express-zod-api 24.4.0 → 24.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/README.md +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
|
@@ -273,7 +273,7 @@ architecture — or even mix them seamlessly.
|
|
|
273
273
|
import { Routing, DependsOnMethod, ServeStatic } from "express-zod-api";
|
|
274
274
|
|
|
275
275
|
const routing: Routing = {
|
|
276
|
-
//
|
|
276
|
+
// flat syntax — /v1/users
|
|
277
277
|
"/v1/users": listUsersEndpoint,
|
|
278
278
|
// nested syntax
|
|
279
279
|
v1: {
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var gn=Object.create;var mt=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var Rn=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xn(t))!Sn.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=hn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?gn(bn(e)):{},kr(t||!e||!e.__esModule?mt(r,"default",{value:e,enumerable:!0}):r,e)),On=e=>kr(mt({},"__esModule",{value:!0}),e);var Ds={};Rn(Ds,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Pt,DocumentationError:()=>W,EndpointsFactory:()=>ye,EventStreamFactory:()=>jt,InputValidationError:()=>Y,Integration:()=>zt,Middleware:()=>F,MissingPeerError:()=>je,OutputValidationError:()=>ze,ResultHandler:()=>ue,RoutingError:()=>pe,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>St,attachRouting:()=>jo,createConfig:()=>
|
|
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 Jt=require("zod/v4");var Vt=class{},F=class extends Vt{#e;#t;#r;constructor({input:t=Jt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 Jt.z.ZodError?new Y(o):o}}},Le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var $e=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends $e{},bt=class e extends Xe{#e;#t=le.once(()=>{if(K(this.#e.outputSchema).length||!ie(this.#e.outputSchema,"object"))return;let t=_r(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();Qe.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Ur(this.#e.inputSchema);if(t){let r=te(t);if(r===de)return"upload";if(r===D)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=le.pluck("security",this.#e.middlewares||[]);return le.reject(le.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Qe.z.ZodError?new ze(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Le))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Qe.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){xt({...t,error:new ce(ne(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),i={},p={output:{},error:null},d=ft(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ne(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Jr=y(require("ramda"),1),Vr=(e,t)=>Jr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var j=require("zod/v4");var Me={positive:200,negative:400},Ze=Object.keys(Me);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ue=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return _t(this.#e,{variant:"positive",args:[t],statusCodes:[Me.positive],mimeTypes:[E.json]})}getNegativeResponse(){return _t(this.#t,{variant:"negative",args:[],statusCodes:[Me.negative],mimeTypes:[E.json]})}},fe=new ue({positive:e=>{let t=j.z.object({status:j.z.literal("success"),data:e}),r=K(e);return r.length&&j.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:j.z.object({status:j.z.literal("error"),error:j.z.object({message:j.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Pe(e);return Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:we(i)}})}n.status(Me.positive).json({status:"success",data:r})}}),St=new ue({positive:e=>{let t=e instanceof j.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof j.z.ZodArray?e.shape.items:j.z.array(j.z.any());if(K(t).length)return t;let r=K(e).filter(o=>k(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();j.globalRegistry.remove(t).add(t,{...o,examples:r})}return t},negative:j.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Pe(r);return Ye(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(we(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Me.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Wt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:Vr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Wt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new ye(fe),Wr=new ye(St);var ro=y(require("ansis"),1),oo=require("node:util"),Qt=require("node:perf_hooks");var Q=require("ansis"),Yr=y(require("ramda"),1);var Yt={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},Rt={debug:10,info:20,warn:30,error:40},Qr=e=>k(e)&&Object.keys(Rt).some(t=>t in e),Xr=e=>e in Rt,eo=(e,t)=>Rt[e]<Rt[t],zn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Be=Yr.memoizeWith((e,t)=>`${e}${t}`,zn),to=e=>e<1e-6?Be("nanosecond",3).format(e/1e-6):e<.001?Be("nanosecond").format(e/1e-6):e<1?Be("microsecond").format(e/.001):e<1e3?Be("millisecond").format(e):e<6e4?Be("second",2).format(e/1e3):Be("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Te()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.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,...i},color:p}=this.config;if(n==="silent"||eo(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Yt.ctx(s):s),d.push(p?`${Yt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=Qt.performance.now();return()=>{let o=Qt.performance.now()-r,{message:n,severity:s="debug",formatter:i=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var no=y(require("ramda"),1);var Ke=class e extends $e{#e;constructor(t){super(),this.#e=t}get entries(){let t=no.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var so=y(require("express"),1),qe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var et=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var Ue=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new je(e)};var mo=y(require("http-errors"),1);var Xt=require("zod/v4");var S=y(require("ramda"),1);var jn=e=>e.type==="object",Ln=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),$n=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),io=S.pair(!0),De=(e,t="coerce")=>{let r=[S.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&$n(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(io,i.anyOf)),i.oneOf&&r.push(...S.map(io,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Oe(o.examples?.filter(k)||[],i.examples.filter(k),([p,d])=>S.mergeDeepRight(p,d))),!!jn(i)&&(r.push([s,{examples:Mn(i)}]),i.properties&&(o.properties=(t==="throw"?Ln:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),k(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Mn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=k(o)?o:{};return Oe(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var Ot=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Xt.z.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Ft(t.inputSchema,"input");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 Ze)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Ft(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=ut(t);if(s.length===0)return;let i=n?.flat||De(Xt.z.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var er=["get","post","put","delete","patch"],ao=e=>er.includes(e);var Zn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},Bn=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Zn(r);return[[t||""].concat(Bn(n)||[]).join("/"),o,s]}),Hn=(e,t)=>{throw new pe("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new pe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},tr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new pe("Route has a duplicate",e,t);r.add(o)},Fe=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)tr(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)tr(c,s,n),t(i,s,c)}else if(p&&Hn(p,s),i instanceof qe)r&&i.apply(s,r);else if(i instanceof Ke)for(let[d,c]of i.entries){let{methods:m}=c;tr(d,s,n),co(d,s,m),t(c,s,d)}else o.unshift(...po(i,s))}};var lo=y(require("ramda"),1),uo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Kn=e=>({method:t},r,o)=>{let n=uo(e);r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},qn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":uo(e),"Access-Control-Allow-Headers":"content-type"}),rr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Te()?void 0:new Ot(t()),i=new Map;Fe({routing:o,onEndpoint:(c,m,h)=>{Te()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=lo.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,A]]of m){let v=g.slice().concat(async(M,R)=>{let I=t(M);return A.execute({request:M,response:R,logger:I,config:r})});r.cors&&v.unshift(async(M,R,I)=>{let N=t(M),U=qn(h),z=typeof r.cors=="function"?await r.cors({request:M,endpoint:A,logger:N,defaultHeaders:U}):U;R.set(z),I()}),e[b](c,...v)}r.wrongMethodBehavior!==404&&d.set(c,Kn(h))}for(let[c,m]of d)e.all(c,m)};var Ro=y(require("http-errors"),1);var bo=require("node:timers/promises");var fo=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",yo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",go=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ho=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xo=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=c=>void n.delete(c.destroy()),i=c=>void(fo(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",ho);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(go(c)||yo(c))&&i(c);for await(let c of(0,bo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(xo))};return{sockets:n,shutdown:()=>o??=d()}};var Oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ne(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),To=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Ro.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){xt({response:o,logger:s,error:new ce(ne(i),n)})}},Un=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Dn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await Ue("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Dn(m)})(p,d,c)}),o&&i.push(Un(o)),i},wo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Eo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Ae]={logger:i}),s()},ko=e=>t=>t?.res?.locals[Ae]?.logger||e,vo=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 gn=Object.create;var mt=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var Rn=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xn(t))!Sn.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=hn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?gn(bn(e)):{},kr(t||!e||!e.__esModule?mt(r,"default",{value:e,enumerable:!0}):r,e)),On=e=>kr(mt({},"__esModule",{value:!0}),e);var Ds={};Rn(Ds,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Pt,DocumentationError:()=>W,EndpointsFactory:()=>ye,EventStreamFactory:()=>jt,InputValidationError:()=>Y,Integration:()=>zt,Middleware:()=>F,MissingPeerError:()=>je,OutputValidationError:()=>ze,ResultHandler:()=>ue,RoutingError:()=>pe,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>St,attachRouting:()=>jo,createConfig:()=>Ar,createServer:()=>Lo,defaultEndpointsFactory:()=>Gr,defaultResultHandler:()=>fe,ensureHttpError:()=>Pe,ez:()=>yn,getExamples:()=>K,getMessageFromError:()=>se,testEndpoint:()=>rn,testMiddleware:()=>on});module.exports=On(Ds);var Z=y(require("ramda"),1),G=require("zod/v4");var vr=require("zod/v4"),Ce=Symbol.for("express-zod-api"),te=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},K=e=>{let{examples:t,example:r}=vr.globalRegistry.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Tn=G.z.core.$constructor("$EZBrandCheck",(e,t)=>{G.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Pn=function(e){let t=K(this).slice();return t.push(e),this.meta({examples:t})},wn=function(){return this.meta({deprecated:!0})},En=function(e){return this.meta({default:e})},kn=function(e){return this.check(new Tn({brand:e,check:"$EZBrandCheck"}))},vn=function(e){let t=typeof e=="function"?e:Z.pipe(Z.toPairs,Z.map(([s,i])=>Z.pair(e[String(s)]||s,i)),Z.fromPairs),r=t(Z.map(Z.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof G.z.ZodUnknown?G.z.looseObject:G.z.object)(r);return this.transform(t).pipe(n)};if(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(G.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=G.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Pn,writable:!1},deprecated:{value:wn,writable:!1},brand:{set(){},get(){return kn.bind(this)}}})}Object.defineProperty(G.z.ZodDefault.prototype,"label",{value:En,writable:!1}),Object.defineProperty(G.z.ZodObject.prototype,"remap",{value:vn,writable:!1})}function Ar(e){return e}var Wt=require("zod/v4");var le=y(require("ramda"),1),Qe=require("zod/v4");var me=y(require("ramda"),1),Dt=require("zod/v4");var Cr=require("zod/v4"),be=Symbol("Buffer"),lt=()=>Cr.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(be);var Ie=require("zod/v4"),Se=Symbol("DateIn"),Ir=({examples:e,...t}={})=>Ie.z.union([Ie.z.iso.date(),Ie.z.iso.datetime(),Ie.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ie.z.date()).brand(Se).meta(t);var Nr=require("zod/v4"),Re=Symbol("DateOut"),zr=(e={})=>Nr.z.date().transform(t=>t.toISOString()).brand(Re).meta(e);var jr=require("zod/v4");var B=y(require("ramda"),1),Ne=require("zod/v4");var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Bt=/:([A-Za-z0-9_]+)/g,ut=e=>e.match(Bt)?.map(t=>t.slice(1))||[],An=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Ht={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Cn=["body","query","params"],Kt=e=>e.method.toLowerCase(),ft=(e,t={})=>{let r=Kt(e);return r==="options"?{}:(t[r]||Ht[r]||Cn).filter(o=>o==="files"?An(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},ne=e=>e instanceof Error?e:e instanceof Ne.z.ZodError?new Ne.z.ZodRealError(e.issues):new Error(String(e)),se=e=>e instanceof Ne.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ne.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,ie=(e,t)=>k(e)&&"_zod"in e&&(t?B.path(["_zod","def","type"],e)===t:!0),Oe=(e,t,r)=>e.length&&t.length?B.xprod(e,t).map(r):e.concat(t),qt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ae=(...e)=>{let t=B.chain(o=>o.split(/[^A-Z0-9]/gi),e);return B.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(qt).join("")},yt=B.tryCatch((e,t)=>typeof Ne.z.parse(e,t),B.always(void 0)),k=e=>typeof e=="object"&&e!==null,Te=B.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var pe=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},W=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ve=class extends Error{name="IOSchemaError"},gt=class extends Ve{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ze=class extends Ve{constructor(r){let o=new jr.z.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(se(o),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends Ve{constructor(r){super(se(r),{cause:r});this.cause=r}name="InputValidationError"},ce=class extends Error{constructor(r,o){super(se(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},je=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ut=require("zod/v4"),Ge=Symbol("Form"),Lr=e=>(e instanceof Ut.z.ZodObject?e:Ut.z.object(e)).brand(Ge);var $r=require("zod/v4"),de=Symbol("Upload"),Mr=()=>$r.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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(de);var Zr=require("zod/v4");var D=Symbol("Raw"),Br=Zr.z.object({raw:lt()}),In=e=>Br.extend(e).brand(D);function Hr(e){return e?In(e):Br.brand(D)}var Kr=(e,{io:t,condition:r})=>me.tryCatch(()=>{Dt.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new gt(o)}})},o=>o.cause)(),qr=(e,{io:t})=>{let o=[Dt.z.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(me.is(Object,n)){if(n.$ref==="#")return!0;o.push(...me.values(n))}me.is(Array,n)&&o.push(...me.values(n))}return!1},Ur=e=>Kr(e,{condition:t=>{let r=te(t);return typeof r=="symbol"&&[de,D,Ge].includes(r)},io:"input"}),Nn=["nan","symbol","map","set","bigint","void","promise","never"],Ft=(e,t)=>Kr(e,{io:t,condition:r=>{let o=te(r),{type:n}=r._zod.def;return!!(Nn.includes(n)||o===be||t==="input"&&(n==="date"||o===Re)||t==="output"&&(o===Se||o===D||o===de))}});var ht=y(require("http-errors"),1);var We=y(require("http-errors"),1),Dr=y(require("ramda"),1),Fr=require("zod/v4");var _t=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Fr.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 ce(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ye=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Pe=e=>(0,We.isHttpError)(e)?e:(0,We.default)(e instanceof Y?400:500,se(e),{cause:e.cause||e}),we=e=>Te()&&!e.expose?(0,We.default)(e.statusCode).message:e.message,_r=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>Oe(t,K(o).map(Dr.objOf(r)),([n,s])=>({...n,...s})),[]);var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=we((0,ht.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,ht.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Jt=require("zod/v4");var Vt=class{},F=class extends Vt{#e;#t;#r;constructor({input:t=Jt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 Jt.z.ZodError?new Y(o):o}}},Le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var $e=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends $e{},bt=class e extends Xe{#e;#t=le.once(()=>{if(K(this.#e.outputSchema).length||!ie(this.#e.outputSchema,"object"))return;let t=_r(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();Qe.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Ur(this.#e.inputSchema);if(t){let r=te(t);if(r===de)return"upload";if(r===D)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=le.pluck("security",this.#e.middlewares||[]);return le.reject(le.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Qe.z.ZodError?new ze(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Le))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Qe.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){xt({...t,error:new ce(ne(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),i={},p={output:{},error:null},d=ft(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ne(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Jr=y(require("ramda"),1),Vr=(e,t)=>Jr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var j=require("zod/v4");var Me={positive:200,negative:400},Ze=Object.keys(Me);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ue=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return _t(this.#e,{variant:"positive",args:[t],statusCodes:[Me.positive],mimeTypes:[E.json]})}getNegativeResponse(){return _t(this.#t,{variant:"negative",args:[],statusCodes:[Me.negative],mimeTypes:[E.json]})}},fe=new ue({positive:e=>{let t=j.z.object({status:j.z.literal("success"),data:e}),r=K(e);return r.length&&j.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:j.z.object({status:j.z.literal("error"),error:j.z.object({message:j.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Pe(e);return Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:we(i)}})}n.status(Me.positive).json({status:"success",data:r})}}),St=new ue({positive:e=>{let t=e instanceof j.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof j.z.ZodArray?e.shape.items:j.z.array(j.z.any());if(K(t).length)return t;let r=K(e).filter(o=>k(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();j.globalRegistry.remove(t).add(t,{...o,examples:r})}return t},negative:j.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Pe(r);return Ye(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(we(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Me.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Wt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:Vr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Wt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new ye(fe),Wr=new ye(St);var ro=y(require("ansis"),1),oo=require("node:util"),Qt=require("node:perf_hooks");var Q=require("ansis"),Yr=y(require("ramda"),1);var Yt={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},Rt={debug:10,info:20,warn:30,error:40},Qr=e=>k(e)&&Object.keys(Rt).some(t=>t in e),Xr=e=>e in Rt,eo=(e,t)=>Rt[e]<Rt[t],zn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Be=Yr.memoizeWith((e,t)=>`${e}${t}`,zn),to=e=>e<1e-6?Be("nanosecond",3).format(e/1e-6):e<.001?Be("nanosecond").format(e/1e-6):e<1?Be("microsecond").format(e/.001):e<1e3?Be("millisecond").format(e):e<6e4?Be("second",2).format(e/1e3):Be("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Te()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.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,...i},color:p}=this.config;if(n==="silent"||eo(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Yt.ctx(s):s),d.push(p?`${Yt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=Qt.performance.now();return()=>{let o=Qt.performance.now()-r,{message:n,severity:s="debug",formatter:i=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var no=y(require("ramda"),1);var Ke=class e extends $e{#e;constructor(t){super(),this.#e=t}get entries(){let t=no.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var so=y(require("express"),1),qe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var et=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var Ue=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new je(e)};var mo=y(require("http-errors"),1);var Xt=require("zod/v4");var S=y(require("ramda"),1);var jn=e=>e.type==="object",Ln=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),$n=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),io=S.pair(!0),De=(e,t="coerce")=>{let r=[S.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&$n(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(io,i.anyOf)),i.oneOf&&r.push(...S.map(io,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Oe(o.examples?.filter(k)||[],i.examples.filter(k),([p,d])=>S.mergeDeepRight(p,d))),!!jn(i)&&(r.push([s,{examples:Mn(i)}]),i.properties&&(o.properties=(t==="throw"?Ln:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),k(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Mn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=k(o)?o:{};return Oe(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var Ot=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Xt.z.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Ft(t.inputSchema,"input");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 Ze)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Ft(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=ut(t);if(s.length===0)return;let i=n?.flat||De(Xt.z.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var er=["get","post","put","delete","patch"],ao=e=>er.includes(e);var Zn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},Bn=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Zn(r);return[[t||""].concat(Bn(n)||[]).join("/"),o,s]}),Hn=(e,t)=>{throw new pe("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new pe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},tr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new pe("Route has a duplicate",e,t);r.add(o)},Fe=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)tr(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)tr(c,s,n),t(i,s,c)}else if(p&&Hn(p,s),i instanceof qe)r&&i.apply(s,r);else if(i instanceof Ke)for(let[d,c]of i.entries){let{methods:m}=c;tr(d,s,n),co(d,s,m),t(c,s,d)}else o.unshift(...po(i,s))}};var lo=y(require("ramda"),1),uo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Kn=e=>({method:t},r,o)=>{let n=uo(e);r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},qn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":uo(e),"Access-Control-Allow-Headers":"content-type"}),rr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Te()?void 0:new Ot(t()),i=new Map;Fe({routing:o,onEndpoint:(c,m,h)=>{Te()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=lo.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,C]]of m){let v=g.slice().concat(async(M,R)=>{let I=t(M);return C.execute({request:M,response:R,logger:I,config:r})});r.cors&&v.unshift(async(M,R,I)=>{let N=t(M),U=qn(h),z=typeof r.cors=="function"?await r.cors({request:M,endpoint:C,logger:N,defaultHeaders:U}):U;R.set(z),I()}),e[b](c,...v)}r.wrongMethodBehavior!==404&&d.set(c,Kn(h))}for(let[c,m]of d)e.all(c,m)};var Ro=y(require("http-errors"),1);var bo=require("node:timers/promises");var fo=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",yo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",go=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ho=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xo=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=c=>void n.delete(c.destroy()),i=c=>void(fo(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",ho);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(go(c)||yo(c))&&i(c);for await(let c of(0,bo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(xo))};return{sockets:n,shutdown:()=>o??=d()}};var Oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ne(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),To=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Ro.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){xt({response:o,logger:s,error:new ce(ne(i),n)})}},Un=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Dn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await Ue("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Dn(m)})(p,d,c)}),o&&i.push(Un(o)),i},wo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Eo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Ce]={logger:i}),s()},ko=e=>t=>t?.res?.locals[Ce]?.logger||e,vo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),Ao=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=So(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};var q=require("ansis"),Co=e=>{if(e.columns<132)return;let t=(0,q.italic)("Proudly supports transgender community.".padStart(109)),r=(0,q.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,q.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,q.italic)("for Ashley".padEnd(20)),s=(0,q.hex)("#F5A9B8"),i=(0,q.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(q.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill(q.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,7 +15,7 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((c,m)=>p[m]?p[m](c):c).join(`
|
|
18
|
-
`))};var zo=e=>{e.startupLogo!==!1&&Ao(process.stdout);let t=e.errorHandler||fe,r=Qr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.4.0 (CJS)",env:process.env.NODE_ENV||"development"}),vo(r);let o=Eo({logger:r,config:e}),s={getLogger:ko(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return rr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Lo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=zo(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Ue("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||et.default.json()],raw:[e.rawParser||et.default.raw(),wo],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};rr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Io.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=No.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&Co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Xo=require("openapi3-ts/oas31"),en=y(require("ramda"),1);var O=y(require("ramda"),1);var $o=e=>k(e)&&"or"in e,Mo=e=>k(e)&&"and"in e,or=e=>!Mo(e)&&!$o(e),Zo=e=>{let t=O.filter(or,e),r=O.chain(O.prop("and"),O.filter(Mo,e)),[o,n]=O.partition(or,r),s=O.concat(t,o),i=O.filter($o,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>Oe(d,O.map(m=>or(m)?[m]:m.and,c),([m,h])=>O.concat(m,h)),O.reject(O.isEmpty,[s]))};var ge=require("openapi3-ts/oas31"),l=y(require("ramda"),1),nr=require("zod/v4");var Bo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Ho=50,Ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Uo=e=>e.replace(Bt,t=>`{${t.slice(1)}}`),_n=({},e)=>{if(e.isResponse)throw new W("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Jn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Vn=({zodSchema:e,jsonSchema:t})=>{if(!ie(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Gn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return De(e,"throw")},(e,{jsonSchema:t})=>t),Wn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ns(t.type)})},Do=e=>e in qo,Yn=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Do(t)&&(e.type=t),e},Qn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Do(t)&&(e.type=t),e},tt=e=>e,Xn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new W("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ko}};return e?.length&&(o.examples=e),o},es=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new W("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ko}};return e?.length&&(o.examples=e),o},ts=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),rs=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},ns=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ss=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ie(o,"transform"))return t;let s=tt(ar(n,{ctx:r}));if((0,ge.isSchemaObject)(s))if(r.isResponse){let i=yt(o,os(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},is=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!k(t.properties.raw)?e:t.properties.raw},sr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,as=(e,t)=>t?.includes(e)||e.startsWith("x-")||Bo.includes(e),Fo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=De(r),m=ut(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),A=R=>b&&m.includes(R),v=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),M=R=>g&&(i?.(R,t,e)??as(R,v));return Object.entries(c.properties).reduce((R,[I,N])=>{if(!k(N))return R;let U=A(I)?"path":M(I)?"header":h?"query":void 0;if(!U)return R;let z=tt(N),re=s==="components"?n(N.id||JSON.stringify(N),z,ae(d,I)):z;return R.concat({name:I,in:U,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:z.description||d,schema:re,examples:sr((0,ge.isSchemaObject)(z)&&z.examples?.length?z.examples:l.pluck(I,c.examples?.filter(l.both(k,l.has(I)))||[]))})},[])},ir={nullable:Wn,union:Vn,bigint:ts,intersection:Gn,tuple:rs,pipe:ss,literal:Qn,enum:Yn,[Se]:Xn,[Re]:es,[de]:_n,[D]:is,[be]:Jn},ps=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ge.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,tt(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ar=(e,{ctx:t,rules:r=ir})=>{let{$defs:o={},properties:n={}}=nr.z.toJSONSchema(nr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=te(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return ps(k(n.subject)?n.subject:{},o,t)},_o=(e,t)=>{if((0,ge.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=_o(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Jo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${qt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=tt(ar(r,{rules:{...c,...ir},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ge.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,ae(m)):h,examples:sr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),fs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):fs(o);return e.map(o=>o.map(r))},Go=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),Wo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ar(e,{rules:{...t,...ir},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Yo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=_o(tt(o),p),h=[];(0,ge.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,ae(d)):c,examples:sr(h.length?h:De(o).examples?.filter(A=>k(A)&&!Array.isArray(A)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===E.raw)&&(g.required=!0),g},Qo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),pr=e=>e.length<=Ho?e:e.slice(0,Ho-1)+"\u2026",Tt=e=>e.length?e.slice():void 0;var Pt=class extends Xo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ae(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new W(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});Fe({routing:t,onEndpoint:(g,A,v)=>{let M={path:A,method:v,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:I,scopes:N,inputSchema:U}=g,z=I?pr(I):m&&R?pr(R):void 0,re=r.inputSources?.[v]||Ht[v],Ce=this.#n(A,v,g.getOperationId(v)),it=Wo({...M,schema:U}),he=Zo(g.security),at=Fo({...M,inputSources:re,isHeader:c,security:he,request:it,description:i?.requestParameter?.call(null,{method:v,path:A,operationId:Ce})}),pt={};for(let oe of Ze){let xe=g.getResponses(oe);for(let{mimeTypes:dt,schema:Mt,statusCodes:Er}of xe)for(let Zt of Er)pt[Zt]=Jo({...M,variant:oe,schema:Mt,mimeTypes:dt,statusCode:Zt,hasMultipleStatusCodes:xe.length>1||Er.length>1,description:i?.[`${oe}Response`]?.call(null,{method:v,path:A,operationId:Ce,statusCode:Zt})})}let ct=re.includes("body")?Yo({...M,request:it,paramNames:en.pluck("name",at),schema:U,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:v,path:A,operationId:Ce})}):void 0,Lt=Go(Vo(he,re),N,oe=>{let xe=this.#s(oe);return this.addSecurityScheme(xe,oe),xe}),$t={operationId:Ce,summary:z,description:R,deprecated:g.isDeprecated||void 0,tags:Tt(g.tags),parameters:Tt(at),requestBody:ct,security:Tt(Lt),responses:pt};this.addPath(Uo(A),{[v]:$t})}}),d&&(this.rootDoc.tags=Qo(d))}};var wt=require("node-mocks-http");var ys=e=>(0,wt.createRequest)({...e,headers:{"content-type":E.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:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},tn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},rn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=tn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},on=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=fe}}=tn(r),d=ft(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:ne(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var mn=y(require("ramda"),1),st=y(require("typescript"),1),ln=require("zod/v4");var pn=y(require("ramda"),1),J=y(require("typescript"),1);var X=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,Et=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):w(e),kt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),vt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>a.createConstructorDeclaration(rt.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&X.map(f,t)):e,ur=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,mr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=X.reject(X.isNil,[o?"@deprecated":void 0,n]);return p.length?cr(i,p.join(" ")):i},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Et,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(e,t)=>ee(e,a.createUnionTypeNode(X.map(H,t)),{expose:!0}),ee=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Et:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Sr(o),t,n,a.createBlock(r)),xr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Et,e,r&&Sr(r),void 0,t),br=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Et:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=e=>(Array.isArray(e)?e.map(t=>X.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ke=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?X.map(vt,e):_e(e),void 0,void 0,t),T=e=>e,ot=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Je=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),It=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),_=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),Ct(e)]),Or=(e,t)=>a.createFunctionTypeNode(void 0,_e(e),f(t)),w=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),H=e=>a.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],an=e=>Ss.includes(e.kind);var Nt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=gr("Method",er);someOfType=ee("SomeOf",_("T",br("T")),{params:["T"]});requestType=ee("Request",br(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(mr(t),a.createArrayLiteralExpression(pn.map(w,r))))),{expose:!0});makeImplementationType=()=>ee(this.#e.implementationType,Or({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:J.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(J.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:J.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ke({[this.#e.requestParameter.text]:J.default.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ke({[this.#e.pathParameter.text]:J.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur},a.createBlock([L(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],J.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Rr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(kt(":",[this.#e.keyParameter]),ke([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>hr(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(yr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(_(this.interfaces.response,"K"))});makeClientClass=t=>xr(t,[lr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),ot(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),ot(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=L(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=L(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(J.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=L(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,ot(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return L(this.#e.defaultImplementationConst,ke([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>lr(_e({request:"K",params:_(this.interfaces.input,"K")}),[L(yr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Rr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>hr(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Or({[this.#e.dataParameter.text]:_(It("R",fr(this.#s("E"))),H(T("data")))},sn(J.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,ke([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:_("R",H(T("event")))}});makeSubscriptionClass=t=>xr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:It(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(J.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:It(_(this.interfaces.positive,"K"),fr(this.#s(J.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Je(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ke(["time"],a.createBlock([])))]};var C=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Tr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=te(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Tr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:$}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Pr={name:C.path(["name","text"]),type:C.path(["type"]),optional:C.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):H(r));return t.length===1?t[0]:$.createUnionTypeNode(t)},Ts=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(ie(p)){r.unshift(p);break}i+=p??""}return i},n=$.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?$.createTemplateMiddle:$.createTemplateTail;s.push($.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?$.createTemplateLiteralType(n,s):H(n.text)},Ps=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=cn.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return $.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},ws=({_zod:{def:e}},{next:t})=>$.createArrayTypeNode(t(e.element)),Es=({_zod:{def:e}})=>$.createUnionTypeNode(Object.values(e.entries).map(H)),ks=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},vs=e=>Rs?.[e.kind],Cs=({_zod:{def:e}},{next:t})=>$.createUnionTypeNode([t(e.innerType),H(null)]),As=({_zod:{def:e}},{next:t})=>$.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:$.createRestTypeNode(t(e.rest)))),Is=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ns=C.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=C.chain(C.prop("members"),e),r=C.uniqWith((...o)=>{if(!C.eqBy(Pr.name,...o))return!1;if(C.both(C.eqBy(Pr.type),C.eqBy(Pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),zs=({_zod:{def:e}},{next:t})=>Ns([e.left,e.right].map(t)),V=e=>()=>f(e),nt=({_zod:{def:e}},{next:t})=>t(e.innerType),dn=e=>f(e?x.default.SyntaxKind.UnknownKeyword:x.default.SyntaxKind.AnyKeyword),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ie(o,"transform"))return t(o);let s=t(n),i=yt(o,vs(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||dn(r))},Ls=()=>H(null),$s=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ms=()=>f("Buffer"),Zs=(e,{next:t})=>t(e._zod.def.shape.raw),Bs={string:V(x.default.SyntaxKind.StringKeyword),number:V(x.default.SyntaxKind.NumberKeyword),bigint:V(x.default.SyntaxKind.BigIntKeyword),boolean:V(x.default.SyntaxKind.BooleanKeyword),any:V(x.default.SyntaxKind.AnyKeyword),undefined:V(x.default.SyntaxKind.UndefinedKeyword),[Se]:V(x.default.SyntaxKind.StringKeyword),[Re]:V(x.default.SyntaxKind.StringKeyword),never:V(x.default.SyntaxKind.NeverKeyword),void:V(x.default.SyntaxKind.UndefinedKeyword),unknown:V(x.default.SyntaxKind.UnknownKeyword),null:Ls,array:ws,tuple:As,record:Is,object:Ps,literal:Os,template_literal:Ts,intersection:zs,union:ks,default:nt,enum:Es,optional:nt,nonoptional:nt,nullable:Cs,catch:nt,pipe:js,lazy:$s,readonly:nt,[be]:Ms,[D]:Zs},wr=(e,{brandHandling:t,ctx:r})=>Tr(e,{rules:{...t,...Bs},onMissing:({},{isResponse:o})=>dn(o),ctx:r});var zt=class extends Nt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=H(null);this.#t.set(t,ee(o,n)),this.#t.set(t,ee(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=ln.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Fe({routing:t,onEndpoint:(b,g,A)=>{let v=ae.bind(null,A,g),{isDeprecated:M,inputSchema:R,tags:I}=b,N=`${A} ${g}`,U=ee(v("input"),wr(R,c),{comment:N});this.#e.push(U);let z=Ze.reduce((it,he)=>{let at=b.getResponses(he),pt=mn.chain(([Lt,{schema:$t,mimeTypes:oe,statusCodes:xe}])=>{let dt=ee(v(he,"variant",`${Lt+1}`),wr(oe?$t:p,m),{comment:N});return this.#e.push(dt),xe.map(Mt=>Ee(Mt,dt.name))},Array.from(at.entries())),ct=At(v(he,"response","variants"),pt,{comment:N});return this.#e.push(ct),Object.assign(it,{[he]:ct})},{});this.paths.add(g);let re=H(N),Ce={input:f(U.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:a.createUnionTypeNode([_(this.interfaces.positive,re),_(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(N,{isDeprecated:M,store:Ce}),this.tags.set(N,I)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:dr(r,t)).join(`
|
|
18
|
+
`))};var zo=e=>{e.startupLogo!==!1&&Co(process.stdout);let t=e.errorHandler||fe,r=Qr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.4.1 (CJS)",env:process.env.NODE_ENV||"development"}),vo(r);let o=Eo({logger:r,config:e}),s={getLogger:ko(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return rr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Lo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=zo(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Ue("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||et.default.json()],raw:[e.rawParser||et.default.raw(),wo],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};rr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Io.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=No.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&Ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Xo=require("openapi3-ts/oas31"),en=y(require("ramda"),1);var O=y(require("ramda"),1);var $o=e=>k(e)&&"or"in e,Mo=e=>k(e)&&"and"in e,or=e=>!Mo(e)&&!$o(e),Zo=e=>{let t=O.filter(or,e),r=O.chain(O.prop("and"),O.filter(Mo,e)),[o,n]=O.partition(or,r),s=O.concat(t,o),i=O.filter($o,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>Oe(d,O.map(m=>or(m)?[m]:m.and,c),([m,h])=>O.concat(m,h)),O.reject(O.isEmpty,[s]))};var ge=require("openapi3-ts/oas31"),l=y(require("ramda"),1),nr=require("zod/v4");var Bo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Ho=50,Ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Uo=e=>e.replace(Bt,t=>`{${t.slice(1)}}`),_n=({},e)=>{if(e.isResponse)throw new W("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Jn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Vn=({zodSchema:e,jsonSchema:t})=>{if(!ie(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Gn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return De(e,"throw")},(e,{jsonSchema:t})=>t),Wn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ns(t.type)})},Do=e=>e in qo,Yn=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Do(t)&&(e.type=t),e},Qn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Do(t)&&(e.type=t),e},tt=e=>e,Xn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new W("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ko}};return e?.length&&(o.examples=e),o},es=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new W("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ko}};return e?.length&&(o.examples=e),o},ts=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),rs=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},ns=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ss=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ie(o,"transform"))return t;let s=tt(ar(n,{ctx:r}));if((0,ge.isSchemaObject)(s))if(r.isResponse){let i=yt(o,os(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},is=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!k(t.properties.raw)?e:t.properties.raw},sr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,as=(e,t)=>t?.includes(e)||e.startsWith("x-")||Bo.includes(e),Fo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=De(r),m=ut(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),C=R=>b&&m.includes(R),v=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),M=R=>g&&(i?.(R,t,e)??as(R,v));return Object.entries(c.properties).reduce((R,[I,N])=>{if(!k(N))return R;let U=C(I)?"path":M(I)?"header":h?"query":void 0;if(!U)return R;let z=tt(N),re=s==="components"?n(N.id||JSON.stringify(N),z,ae(d,I)):z;return R.concat({name:I,in:U,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:z.description||d,schema:re,examples:sr((0,ge.isSchemaObject)(z)&&z.examples?.length?z.examples:l.pluck(I,c.examples?.filter(l.both(k,l.has(I)))||[]))})},[])},ir={nullable:Wn,union:Vn,bigint:ts,intersection:Gn,tuple:rs,pipe:ss,literal:Qn,enum:Yn,[Se]:Xn,[Re]:es,[de]:_n,[D]:is,[be]:Jn},ps=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ge.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,tt(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ar=(e,{ctx:t,rules:r=ir})=>{let{$defs:o={},properties:n={}}=nr.z.toJSONSchema(nr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=te(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return ps(k(n.subject)?n.subject:{},o,t)},_o=(e,t)=>{if((0,ge.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=_o(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Jo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${qt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=tt(ar(r,{rules:{...c,...ir},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ge.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,ae(m)):h,examples:sr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),fs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):fs(o);return e.map(o=>o.map(r))},Go=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),Wo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ar(e,{rules:{...t,...ir},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Yo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=_o(tt(o),p),h=[];(0,ge.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,ae(d)):c,examples:sr(h.length?h:De(o).examples?.filter(C=>k(C)&&!Array.isArray(C)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===E.raw)&&(g.required=!0),g},Qo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),pr=e=>e.length<=Ho?e:e.slice(0,Ho-1)+"\u2026",Tt=e=>e.length?e.slice():void 0;var Pt=class extends Xo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ae(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new W(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});Fe({routing:t,onEndpoint:(g,C,v)=>{let M={path:C,method:v,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:I,scopes:N,inputSchema:U}=g,z=I?pr(I):m&&R?pr(R):void 0,re=r.inputSources?.[v]||Ht[v],Ae=this.#n(C,v,g.getOperationId(v)),it=Wo({...M,schema:U}),he=Zo(g.security),at=Fo({...M,inputSources:re,isHeader:c,security:he,request:it,description:i?.requestParameter?.call(null,{method:v,path:C,operationId:Ae})}),pt={};for(let oe of Ze){let xe=g.getResponses(oe);for(let{mimeTypes:dt,schema:Mt,statusCodes:Er}of xe)for(let Zt of Er)pt[Zt]=Jo({...M,variant:oe,schema:Mt,mimeTypes:dt,statusCode:Zt,hasMultipleStatusCodes:xe.length>1||Er.length>1,description:i?.[`${oe}Response`]?.call(null,{method:v,path:C,operationId:Ae,statusCode:Zt})})}let ct=re.includes("body")?Yo({...M,request:it,paramNames:en.pluck("name",at),schema:U,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:v,path:C,operationId:Ae})}):void 0,Lt=Go(Vo(he,re),N,oe=>{let xe=this.#s(oe);return this.addSecurityScheme(xe,oe),xe}),$t={operationId:Ae,summary:z,description:R,deprecated:g.isDeprecated||void 0,tags:Tt(g.tags),parameters:Tt(at),requestBody:ct,security:Tt(Lt),responses:pt};this.addPath(Uo(C),{[v]:$t})}}),d&&(this.rootDoc.tags=Qo(d))}};var wt=require("node-mocks-http");var ys=e=>(0,wt.createRequest)({...e,headers:{"content-type":E.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:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},tn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},rn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=tn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},on=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=fe}}=tn(r),d=ft(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:ne(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var mn=y(require("ramda"),1),st=y(require("typescript"),1),ln=require("zod/v4");var pn=y(require("ramda"),1),J=y(require("typescript"),1);var X=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,Et=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):w(e),kt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),vt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>a.createConstructorDeclaration(rt.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&X.map(f,t)):e,ur=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,mr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=X.reject(X.isNil,[o?"@deprecated":void 0,n]);return p.length?cr(i,p.join(" ")):i},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Et,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(e,t)=>ee(e,a.createUnionTypeNode(X.map(H,t)),{expose:!0}),ee=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Et:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Sr(o),t,n,a.createBlock(r)),xr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Et,e,r&&Sr(r),void 0,t),br=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),At=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Et:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=e=>(Array.isArray(e)?e.map(t=>X.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ke=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?X.map(vt,e):_e(e),void 0,void 0,t),T=e=>e,ot=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Je=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),It=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),_=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),At(e)]),Or=(e,t)=>a.createFunctionTypeNode(void 0,_e(e),f(t)),w=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),H=e=>a.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],an=e=>Ss.includes(e.kind);var Nt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=gr("Method",er);someOfType=ee("SomeOf",_("T",br("T")),{params:["T"]});requestType=ee("Request",br(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(mr(t),a.createArrayLiteralExpression(pn.map(w,r))))),{expose:!0});makeImplementationType=()=>ee(this.#e.implementationType,Or({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:J.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},At(J.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:J.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ke({[this.#e.requestParameter.text]:J.default.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ke({[this.#e.pathParameter.text]:J.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur},a.createBlock([L(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],J.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Rr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(kt(":",[this.#e.keyParameter]),ke([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>hr(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(yr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:At(_(this.interfaces.response,"K"))});makeClientClass=t=>xr(t,[lr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),ot(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),ot(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=L(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=L(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(J.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=L(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,ot(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return L(this.#e.defaultImplementationConst,ke([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>lr(_e({request:"K",params:_(this.interfaces.input,"K")}),[L(yr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Rr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>hr(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Or({[this.#e.dataParameter.text]:_(It("R",fr(this.#s("E"))),H(T("data")))},sn(J.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,ke([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:_("R",H(T("event")))}});makeSubscriptionClass=t=>xr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:It(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(J.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:It(_(this.interfaces.positive,"K"),fr(this.#s(J.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Je(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ke(["time"],a.createBlock([])))]};var A=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Tr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=te(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Tr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:$}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Pr={name:A.path(["name","text"]),type:A.path(["type"]),optional:A.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):H(r));return t.length===1?t[0]:$.createUnionTypeNode(t)},Ts=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(ie(p)){r.unshift(p);break}i+=p??""}return i},n=$.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?$.createTemplateMiddle:$.createTemplateTail;s.push($.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?$.createTemplateLiteralType(n,s):H(n.text)},Ps=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=cn.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return $.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},ws=({_zod:{def:e}},{next:t})=>$.createArrayTypeNode(t(e.element)),Es=({_zod:{def:e}})=>$.createUnionTypeNode(Object.values(e.entries).map(H)),ks=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},vs=e=>Rs?.[e.kind],As=({_zod:{def:e}},{next:t})=>$.createUnionTypeNode([t(e.innerType),H(null)]),Cs=({_zod:{def:e}},{next:t})=>$.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:$.createRestTypeNode(t(e.rest)))),Is=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ns=A.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=A.chain(A.prop("members"),e),r=A.uniqWith((...o)=>{if(!A.eqBy(Pr.name,...o))return!1;if(A.both(A.eqBy(Pr.type),A.eqBy(Pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),zs=({_zod:{def:e}},{next:t})=>Ns([e.left,e.right].map(t)),V=e=>()=>f(e),nt=({_zod:{def:e}},{next:t})=>t(e.innerType),dn=e=>f(e?x.default.SyntaxKind.UnknownKeyword:x.default.SyntaxKind.AnyKeyword),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ie(o,"transform"))return t(o);let s=t(n),i=yt(o,vs(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||dn(r))},Ls=()=>H(null),$s=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ms=()=>f("Buffer"),Zs=(e,{next:t})=>t(e._zod.def.shape.raw),Bs={string:V(x.default.SyntaxKind.StringKeyword),number:V(x.default.SyntaxKind.NumberKeyword),bigint:V(x.default.SyntaxKind.BigIntKeyword),boolean:V(x.default.SyntaxKind.BooleanKeyword),any:V(x.default.SyntaxKind.AnyKeyword),undefined:V(x.default.SyntaxKind.UndefinedKeyword),[Se]:V(x.default.SyntaxKind.StringKeyword),[Re]:V(x.default.SyntaxKind.StringKeyword),never:V(x.default.SyntaxKind.NeverKeyword),void:V(x.default.SyntaxKind.UndefinedKeyword),unknown:V(x.default.SyntaxKind.UnknownKeyword),null:Ls,array:ws,tuple:Cs,record:Is,object:Ps,literal:Os,template_literal:Ts,intersection:zs,union:ks,default:nt,enum:Es,optional:nt,nonoptional:nt,nullable:As,catch:nt,pipe:js,lazy:$s,readonly:nt,[be]:Ms,[D]:Zs},wr=(e,{brandHandling:t,ctx:r})=>Tr(e,{rules:{...t,...Bs},onMissing:({},{isResponse:o})=>dn(o),ctx:r});var zt=class extends Nt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=H(null);this.#t.set(t,ee(o,n)),this.#t.set(t,ee(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=ln.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Fe({routing:t,onEndpoint:(b,g,C)=>{let v=ae.bind(null,C,g),{isDeprecated:M,inputSchema:R,tags:I}=b,N=`${C} ${g}`,U=ee(v("input"),wr(R,c),{comment:N});this.#e.push(U);let z=Ze.reduce((it,he)=>{let at=b.getResponses(he),pt=mn.chain(([Lt,{schema:$t,mimeTypes:oe,statusCodes:xe}])=>{let dt=ee(v(he,"variant",`${Lt+1}`),wr(oe?$t:p,m),{comment:N});return this.#e.push(dt),xe.map(Mt=>Ee(Mt,dt.name))},Array.from(at.entries())),ct=Ct(v(he,"response","variants"),pt,{comment:N});return this.#e.push(ct),Object.assign(it,{[he]:ct})},{});this.paths.add(g);let re=H(N),Ae={input:f(U.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:a.createUnionTypeNode([_(this.interfaces.positive,re),_(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(N,{isDeprecated:M,store:Ae}),this.tags.set(N,I)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:dr(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.#n(t),o=r&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(a.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.#e.concat(o||[]).map((n,s)=>dr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as zod_v4 from 'zod/v4';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
import * as zod_v4_core from 'zod/v4/core';
|
|
4
|
-
import { $ZodTypeInternals, $ZodType, SomeType, $ZodDefaultInternals, $ZodDefault, $ZodShape, $ZodLooseShape, $ZodObjectConfig, $ZodObjectInternals, $ZodObject, JSONSchema } from 'zod/v4/core';
|
|
4
|
+
import { $ZodTypeInternals, $ZodType, SomeType, $ZodDefaultInternals, $ZodDefault, $ZodShape, $ZodLooseShape, $ZodObjectConfig, $strip, $ZodObjectInternals, $ZodObject, JSONSchema } from 'zod/v4/core';
|
|
5
5
|
import compression from 'compression';
|
|
6
6
|
import * as express from 'express';
|
|
7
7
|
import express__default, { Request, Response, NextFunction, RequestHandler, IRouter } from 'express';
|
|
@@ -50,7 +50,7 @@ declare module "zod/v4" {
|
|
|
50
50
|
/** @desc Change the default value in the generated Documentation to a label, alias for .meta({ default }) */
|
|
51
51
|
label(label: string): this;
|
|
52
52
|
}
|
|
53
|
-
interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $
|
|
53
|
+
interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $strip> extends z._ZodType<$ZodObjectInternals<Shape, Config>>, $ZodObject<Shape, Config> {
|
|
54
54
|
remap<V extends string, U extends {
|
|
55
55
|
[P in keyof Shape]?: V;
|
|
56
56
|
}>(mapping: U): z.ZodPipe<z.ZodPipe<this, z.ZodTransform>, // internal type simplified
|
|
@@ -926,7 +926,7 @@ declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<
|
|
|
926
926
|
declare const ez: {
|
|
927
927
|
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<readonly [zod_v4.ZodISODate, zod_v4.ZodISODateTime, zod_v4.ZodISODateTime]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
928
928
|
dateOut: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
929
|
-
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<
|
|
929
|
+
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<S, zod_v4_core.$strip>, symbol>;
|
|
930
930
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
|
931
931
|
raw: typeof raw;
|
|
932
932
|
buffer: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as zod_v4 from 'zod/v4';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
import * as zod_v4_core from 'zod/v4/core';
|
|
4
|
-
import { $ZodTypeInternals, $ZodType, SomeType, $ZodDefaultInternals, $ZodDefault, $ZodShape, $ZodLooseShape, $ZodObjectConfig, $ZodObjectInternals, $ZodObject, JSONSchema } from 'zod/v4/core';
|
|
4
|
+
import { $ZodTypeInternals, $ZodType, SomeType, $ZodDefaultInternals, $ZodDefault, $ZodShape, $ZodLooseShape, $ZodObjectConfig, $strip, $ZodObjectInternals, $ZodObject, JSONSchema } from 'zod/v4/core';
|
|
5
5
|
import compression from 'compression';
|
|
6
6
|
import * as express from 'express';
|
|
7
7
|
import express__default, { Request, Response, NextFunction, RequestHandler, IRouter } from 'express';
|
|
@@ -50,7 +50,7 @@ declare module "zod/v4" {
|
|
|
50
50
|
/** @desc Change the default value in the generated Documentation to a label, alias for .meta({ default }) */
|
|
51
51
|
label(label: string): this;
|
|
52
52
|
}
|
|
53
|
-
interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $
|
|
53
|
+
interface ZodObject<out Shape extends $ZodShape = $ZodLooseShape, out Config extends $ZodObjectConfig = $strip> extends z._ZodType<$ZodObjectInternals<Shape, Config>>, $ZodObject<Shape, Config> {
|
|
54
54
|
remap<V extends string, U extends {
|
|
55
55
|
[P in keyof Shape]?: V;
|
|
56
56
|
}>(mapping: U): z.ZodPipe<z.ZodPipe<this, z.ZodTransform>, // internal type simplified
|
|
@@ -926,7 +926,7 @@ declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<
|
|
|
926
926
|
declare const ez: {
|
|
927
927
|
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<readonly [zod_v4.ZodISODate, zod_v4.ZodISODateTime, zod_v4.ZodISODateTime]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
928
928
|
dateOut: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
929
|
-
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<
|
|
929
|
+
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<S, zod_v4_core.$strip>, symbol>;
|
|
930
930
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
|
931
931
|
raw: typeof raw;
|
|
932
932
|
buffer: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import*as $ from"ramda";import{z as W}from"zod/v4";import{globalRegistry as Ho}from"zod/v4";var Pe=Symbol.for("express-zod-api"),G=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},H=e=>{let{examples:t,example:r}=Ho.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Ko=W.core.$constructor("$EZBrandCheck",(e,t)=>{W.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),qo=function(e){let t=H(this).slice();return t.push(e),this.meta({examples:t})},Uo=function(){return this.meta({deprecated:!0})},Do=function(e){return this.meta({default:e})},Fo=function(e){return this.check(new Ko({brand:e,check:"$EZBrandCheck"}))},_o=function(e){let t=typeof e=="function"?e:$.pipe($.toPairs,$.map(([s,i])=>$.pair(e[String(s)]||s,i)),$.fromPairs),r=t($.map($.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof W.ZodUnknown?W.looseObject:W.object)(r);return this.transform(t).pipe(n)};if(!(Pe in globalThis)){globalThis[Pe]=!0;for(let e of Object.keys(W)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=W[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:qo,writable:!1},deprecated:{value:Uo,writable:!1},brand:{set(){},get(){return Fo.bind(this)}}})}Object.defineProperty(W.ZodDefault.prototype,"label",{value:Do,writable:!1}),Object.defineProperty(W.ZodObject.prototype,"remap",{value:_o,writable:!1})}function Jo(e){return e}import{z as Nr}from"zod/v4";import*as ae from"ramda";import{z as vr,globalRegistry as pn}from"zod/v4";import*as ie from"ramda";import{z as Sr}from"zod/v4";import{z as Vo}from"zod/v4";var de=Symbol("Buffer"),ot=()=>Vo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(de);import{z as Me}from"zod/v4";var me=Symbol("DateIn"),ur=({examples:e,...t}={})=>Me.union([Me.iso.date(),Me.iso.datetime(),Me.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Me.date()).brand(me).meta(t);import{z as Go}from"zod/v4";var le=Symbol("DateOut"),fr=(e={})=>Go.date().transform(t=>t.toISOString()).brand(le).meta(e);import{z as Qo}from"zod/v4";import*as M from"ramda";import{z as Ze}from"zod/v4";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var vt=/:([A-Za-z0-9_]+)/g,nt=e=>e.match(vt)?.map(t=>t.slice(1))||[],Wo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},
|
|
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 kr}from"zod/v4";var jt=class{},F=class extends jt{#e;#t;#r;constructor({input:t=kr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 kr.ZodError?new Q(o):o}}},Ee=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ke=class{nest(t){return Object.assign(t,{"":this})}};var De=class extends ke{},ct=class e extends De{#e;#t=ae.once(()=>{if(H(this.#e.outputSchema).length||!re(this.#e.outputSchema,"object"))return;let t=Er(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();pn.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Tr(this.#e.inputSchema);if(t){let r=G(t);if(r===se)return"upload";if(r===K)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ae.pluck("security",this.#e.middlewares||[]);return ae.reject(ae.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof vr.ZodError?new He(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof vr.ZodError?new Q(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){pt({...t,error:new ne(te(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=At(t),i={},p={output:{},error:null},d=st(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:te(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Cr from"ramda";var Ar=(e,t)=>Cr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as Ir,z as q}from"zod/v4";var ve={positive:200,negative:400},Ce=Object.keys(ve);var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[ve.positive],mimeTypes:[w.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[ve.negative],mimeTypes:[w.json]})}},be=new xe({positive:e=>{let t=q.object({status:q.literal("success"),data:e}),r=H(e);return r.length&&Ir.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},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 i=we(e);return Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:he(i)}})}n.status(ve.positive).json({status:"success",data:r})}}),$t=new xe({positive:e=>{let t=e instanceof q.ZodObject&&"items"in e.shape&&e.shape.items instanceof q.ZodArray?e.shape.items:q.array(q.any());if(H(t).length)return t;let r=H(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Ir.remove(t).add(t,{...o,examples:r})}return t},negative:q.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(he(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ve.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Se=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 Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Nr.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,x=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new ct({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:y,methods:m,getOperationId:g,inputSchema:Ar(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Nr.object({}),handler:async o=>(await t(o),{})})}},cn=new Se(be),dn=new Se($t);import hn from"ansis";import{inspect as xn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as zr from"ramda";var Mt={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},dt={debug:10,info:20,warn:30,error:40},jr=e=>E(e)&&Object.keys(dt).some(t=>t in e),Lr=e=>e in dt,$r=(e,t)=>dt[e]<dt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=zr.memoizeWith((e,t)=>`${e}${t}`,gn),Mr=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 Fe=class e{config;constructor({color:t=hn.isSupported(),level:r=ye()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return 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,...i},color:p}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Mt.ctx(s):s),d.push(p?`${Mt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var _e=class e extends ke{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import bn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,bn.static(...this.#e))}};import ut from"express";import $n from"node:http";import Mn from"node:https";var Ie=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import kn from"http-errors";import{z as Kr}from"zod/v4";import*as b from"ramda";var Sn=e=>e.type==="object",Rn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),On=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Hr=b.pair(!0),Ne=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&On(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Hr,i.anyOf)),i.oneOf&&r.push(...b.map(Hr,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=fe(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!Sn(i)&&(r.push([s,{examples:Tn(i)}]),i.properties&&(o.properties=(t==="throw"?Rn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Tn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return fe(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var mt=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Kr.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Nt(t.inputSchema,"input");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 Ce)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=Nt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=nt(t);if(s.length===0)return;let i=n?.flat||Ne(Kr.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var Zt=["get","post","put","delete","patch"],qr=e=>Zt.includes(e);var Pn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&qr(t)?[r,t]:[e]},wn=e=>e.trim().split("/").filter(Boolean).join("/"),Ur=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Pn(r);return[[t||""].concat(wn(n)||[]).join("/"),o,s]}),En=(e,t)=>{throw new ge("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ge(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Bt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ge("Route has a duplicate",e,t);r.add(o)},ze=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Ur(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof De)if(p)Bt(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Bt(c,s,n),t(i,s,c)}else if(p&&En(p,s),i instanceof Je)r&&i.apply(s,r);else if(i instanceof _e)for(let[d,c]of i.entries){let{methods:m}=c;Bt(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Ur(i,s))}};import*as Fr from"ramda";var _r=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=_r(e);r.set({Allow:n});let s=kn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Cn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":_r(e),"Access-Control-Allow-Headers":"content-type"}),Ht=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ye()?void 0:new mt(t()),i=new Map;ze({routing:o,onEndpoint:(c,m,g)=>{ye()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let x=n?.[c.requestType]||[],y=Fr.pair(x,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[x,[y,C]]of m){let k=y.slice().concat(async(L,S)=>{let A=t(L);return C.execute({request:L,response:S,logger:A,config:r})});r.cors&&k.unshift(async(L,S,A)=>{let I=t(L),B=Cn(g),N=typeof r.cors=="function"?await r.cors({request:L,endpoint:C,logger:I,defaultHeaders:B}):B;S.set(N),A()}),e[x](c,...k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import In from"http-errors";import{setInterval as An}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",Vr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Wr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Yr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Jr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Wr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Gr(c)||Vr(c))&&i(c);for await(let c of An(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Yr))};return{sockets:n,shutdown:()=>o??=d()}};var Xr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:te(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=In(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){pt({response:o,logger:s,error:new ne(te(i),n)})}},Nn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},zn=e=>({log:e.debug.bind(e)}),to=async({getLogger:e,config:t})=>{let r=await Ie("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:zn(m)})(p,d,c)}),o&&i.push(Nn(o)),i},ro=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},oo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Pe]={logger:i}),s()},no=e=>t=>t?.res?.locals[Pe]?.logger||e,so=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
1
|
+
import*as $ from"ramda";import{z as W}from"zod/v4";import{globalRegistry as Ho}from"zod/v4";var Pe=Symbol.for("express-zod-api"),G=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t},H=e=>{let{examples:t,example:r}=Ho.get(e)||{};return t?Array.isArray(t)?t:Object.values(t).map(({value:o})=>o):r===void 0?[]:[r]};var Ko=W.core.$constructor("$EZBrandCheck",(e,t)=>{W.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),qo=function(e){let t=H(this).slice();return t.push(e),this.meta({examples:t})},Uo=function(){return this.meta({deprecated:!0})},Do=function(e){return this.meta({default:e})},Fo=function(e){return this.check(new Ko({brand:e,check:"$EZBrandCheck"}))},_o=function(e){let t=typeof e=="function"?e:$.pipe($.toPairs,$.map(([s,i])=>$.pair(e[String(s)]||s,i)),$.fromPairs),r=t($.map($.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof W.ZodUnknown?W.looseObject:W.object)(r);return this.transform(t).pipe(n)};if(!(Pe in globalThis)){globalThis[Pe]=!0;for(let e of Object.keys(W)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=W[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:qo,writable:!1},deprecated:{value:Uo,writable:!1},brand:{set(){},get(){return Fo.bind(this)}}})}Object.defineProperty(W.ZodDefault.prototype,"label",{value:Do,writable:!1}),Object.defineProperty(W.ZodObject.prototype,"remap",{value:_o,writable:!1})}function Jo(e){return e}import{z as Nr}from"zod/v4";import*as ae from"ramda";import{z as vr,globalRegistry as pn}from"zod/v4";import*as ie from"ramda";import{z as Sr}from"zod/v4";import{z as Vo}from"zod/v4";var de=Symbol("Buffer"),ot=()=>Vo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(de);import{z as Me}from"zod/v4";var me=Symbol("DateIn"),ur=({examples:e,...t}={})=>Me.union([Me.iso.date(),Me.iso.datetime(),Me.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Me.date()).brand(me).meta(t);import{z as Go}from"zod/v4";var le=Symbol("DateOut"),fr=(e={})=>Go.date().transform(t=>t.toISOString()).brand(le).meta(e);import{z as Qo}from"zod/v4";import*as M from"ramda";import{z as Ze}from"zod/v4";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var vt=/:([A-Za-z0-9_]+)/g,nt=e=>e.match(vt)?.map(t=>t.slice(1))||[],Wo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},At={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Yo=["body","query","params"],Ct=e=>e.method.toLowerCase(),st=(e,t={})=>{let r=Ct(e);return r==="options"?{}:(t[r]||At[r]||Yo).filter(o=>o==="files"?Wo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},te=e=>e instanceof Error?e:e instanceof Ze.ZodError?new Ze.ZodRealError(e.issues):new Error(String(e)),ue=e=>e instanceof Ze.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ze.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,re=(e,t)=>E(e)&&"_zod"in e&&(t?M.path(["_zod","def","type"],e)===t:!0),fe=(e,t,r)=>e.length&&t.length?M.xprod(e,t).map(r):e.concat(t),It=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),oe=(...e)=>{let t=M.chain(o=>o.split(/[^A-Z0-9]/gi),e);return M.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(It).join("")},it=M.tryCatch((e,t)=>typeof Ze.parse(e,t),M.always(void 0)),E=e=>typeof e=="object"&&e!==null,ye=M.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ge=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Y=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.`}},Be=class extends Error{name="IOSchemaError"},at=class extends Be{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},He=class extends Be{constructor(r){let o=new Qo.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ue(o),{cause:r});this.cause=r}name="OutputValidationError"},Q=class extends Be{constructor(r){super(ue(r),{cause:r});this.cause=r}name="InputValidationError"},ne=class extends Error{constructor(r,o){super(ue(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as yr}from"zod/v4";var qe=Symbol("Form"),gr=e=>(e instanceof yr.ZodObject?e:yr.object(e)).brand(qe);import{z as Xo}from"zod/v4";var se=Symbol("Upload"),hr=()=>Xo.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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(se);import{z as en}from"zod/v4";var K=Symbol("Raw"),xr=en.object({raw:ot()}),tn=e=>xr.extend(e).brand(K);function br(e){return e?tn(e):xr.brand(K)}var Rr=(e,{io:t,condition:r})=>ie.tryCatch(()=>{Sr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new at(o)}})},o=>o.cause)(),Or=(e,{io:t})=>{let o=[Sr.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(ie.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ie.values(n))}ie.is(Array,n)&&o.push(...ie.values(n))}return!1},Tr=e=>Rr(e,{condition:t=>{let r=G(t);return typeof r=="symbol"&&[se,K,qe].includes(r)},io:"input"}),rn=["nan","symbol","map","set","bigint","void","promise","never"],Nt=(e,t)=>Rr(e,{io:t,condition:r=>{let o=G(r),{type:n}=r._zod.def;return!!(rn.includes(n)||o===de||t==="input"&&(n==="date"||o===le)||t==="output"&&(o===me||o===K||o===se))}});import sn,{isHttpError as an}from"http-errors";import Pr,{isHttpError as on}from"http-errors";import*as wr from"ramda";import{z as nn}from"zod/v4";var zt=(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 ne(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ue=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>on(e)?e:Pr(e instanceof Q?400:500,ue(e),{cause:e.cause||e}),he=e=>ye()&&!e.expose?Pr(e.statusCode).message:e.message,Er=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>fe(t,H(o).map(wr.objOf(r)),([n,s])=>({...n,...s})),[]);var pt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=he(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 kr}from"zod/v4";var jt=class{},F=class extends jt{#e;#t;#r;constructor({input:t=kr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 kr.ZodError?new Q(o):o}}},Ee=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ke=class{nest(t){return Object.assign(t,{"":this})}};var De=class extends ke{},ct=class e extends De{#e;#t=ae.once(()=>{if(H(this.#e.outputSchema).length||!re(this.#e.outputSchema,"object"))return;let t=Er(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();pn.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Tr(this.#e.inputSchema);if(t){let r=G(t);if(r===se)return"upload";if(r===K)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ae.pluck("security",this.#e.middlewares||[]);return ae.reject(ae.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof vr.ZodError?new He(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof vr.ZodError?new Q(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){pt({...t,error:new ne(te(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ct(t),i={},p={output:{},error:null},d=st(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:te(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Ar from"ramda";var Cr=(e,t)=>Ar.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as Ir,z as q}from"zod/v4";var ve={positive:200,negative:400},Ae=Object.keys(ve);var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[ve.positive],mimeTypes:[w.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[ve.negative],mimeTypes:[w.json]})}},be=new xe({positive:e=>{let t=q.object({status:q.literal("success"),data:e}),r=H(e);return r.length&&Ir.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},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 i=we(e);return Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:he(i)}})}n.status(ve.positive).json({status:"success",data:r})}}),$t=new xe({positive:e=>{let t=e instanceof q.ZodObject&&"items"in e.shape&&e.shape.items instanceof q.ZodArray?e.shape.items:q.array(q.any());if(H(t).length)return t;let r=H(e).filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();Ir.remove(t).add(t,{...o,examples:r})}return t},negative:q.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(he(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ve.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Se=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 Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Nr.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,x=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new ct({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:y,methods:m,getOperationId:g,inputSchema:Cr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Nr.object({}),handler:async o=>(await t(o),{})})}},cn=new Se(be),dn=new Se($t);import hn from"ansis";import{inspect as xn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as zr from"ramda";var Mt={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},dt={debug:10,info:20,warn:30,error:40},jr=e=>E(e)&&Object.keys(dt).some(t=>t in e),Lr=e=>e in dt,$r=(e,t)=>dt[e]<dt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ce=zr.memoizeWith((e,t)=>`${e}${t}`,gn),Mr=e=>e<1e-6?Ce("nanosecond",3).format(e/1e-6):e<.001?Ce("nanosecond").format(e/1e-6):e<1?Ce("microsecond").format(e/.001):e<1e3?Ce("millisecond").format(e):e<6e4?Ce("second",2).format(e/1e3):Ce("minute",2).format(e/6e4);var Fe=class e{config;constructor({color:t=hn.isSupported(),level:r=ye()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return 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,...i},color:p}=this.config;if(n==="silent"||$r(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Mt.ctx(s):s),d.push(p?`${Mt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var _e=class e extends ke{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import bn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,bn.static(...this.#e))}};import ut from"express";import $n from"node:http";import Mn from"node:https";var Ie=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import kn from"http-errors";import{z as Kr}from"zod/v4";import*as b from"ramda";var Sn=e=>e.type==="object",Rn=b.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return b.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),On=b.pipe(Object.keys,b.without(["type","properties","required","examples","description","additionalProperties"]),b.isEmpty),Hr=b.pair(!0),Ne=(e,t="coerce")=>{let r=[b.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&On(p)))throw new Error("Can not merge");return b.pair(s,p)})),i.anyOf&&r.push(...b.map(Hr,i.anyOf)),i.oneOf&&r.push(...b.map(Hr,i.oneOf)),i.examples?.length&&(s?o.examples=b.concat(o.examples||[],i.examples):o.examples=fe(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>b.mergeDeepRight(p,d))),!!Sn(i)&&(r.push([s,{examples:Tn(i)}]),i.properties&&(o.properties=(t==="throw"?Rn:b.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Tn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return fe(t,n.map(b.objOf(r)),([s,i])=>({...s,...i}))},[]);var mt=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Kr.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Nt(t.inputSchema,"input");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 Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=Nt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=nt(t);if(s.length===0)return;let i=n?.flat||Ne(Kr.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var Zt=["get","post","put","delete","patch"],qr=e=>Zt.includes(e);var Pn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&qr(t)?[r,t]:[e]},wn=e=>e.trim().split("/").filter(Boolean).join("/"),Ur=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Pn(r);return[[t||""].concat(wn(n)||[]).join("/"),o,s]}),En=(e,t)=>{throw new ge("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ge(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Bt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ge("Route has a duplicate",e,t);r.add(o)},ze=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Ur(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof De)if(p)Bt(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Bt(c,s,n),t(i,s,c)}else if(p&&En(p,s),i instanceof Je)r&&i.apply(s,r);else if(i instanceof _e)for(let[d,c]of i.entries){let{methods:m}=c;Bt(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Ur(i,s))}};import*as Fr from"ramda";var _r=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=_r(e);r.set({Allow:n});let s=kn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},An=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":_r(e),"Access-Control-Allow-Headers":"content-type"}),Ht=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ye()?void 0:new mt(t()),i=new Map;ze({routing:o,onEndpoint:(c,m,g)=>{ye()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let x=n?.[c.requestType]||[],y=Fr.pair(x,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[x,[y,A]]of m){let k=y.slice().concat(async(L,S)=>{let C=t(L);return A.execute({request:L,response:S,logger:C,config:r})});r.cors&&k.unshift(async(L,S,C)=>{let I=t(L),B=An(g),N=typeof r.cors=="function"?await r.cors({request:L,endpoint:A,logger:I,defaultHeaders:B}):B;S.set(N),C()}),e[x](c,...k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import In from"http-errors";import{setInterval as Cn}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",Vr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Wr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Yr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Jr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Wr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Gr(c)||Vr(c))&&i(c);for await(let c of Cn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Yr))};return{sockets:n,shutdown:()=>o??=d()}};var Xr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:te(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),eo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=In(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){pt({response:o,logger:s,error:new ne(te(i),n)})}},Nn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},zn=e=>({log:e.debug.bind(e)}),to=async({getLogger:e,config:t})=>{let r=await Ie("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:zn(m)})(p,d,c)}),o&&i.push(Nn(o)),i},ro=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},oo=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Pe]={logger:i}),s()},no=e=>t=>t?.res?.locals[Pe]?.logger||e,so=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
3
|
`).slice(1))),io=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Qr(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as jn,hex as ao,italic as lt,whiteBright as Ln}from"ansis";var po=e=>{if(e.columns<132)return;let t=lt("Proudly supports transgender community.".padStart(109)),r=lt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=lt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=lt("for Ashley".padEnd(20)),s=ao("#F5A9B8"),i=ao("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(Ln,5,7).fill(s,7,9).fill(i,9,12).fill(jn,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
@@ -15,7 +15,7 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((c,m)=>p[m]?p[m](c):c).join(`
|
|
18
|
-
`))};var co=e=>{e.startupLogo!==!1&&po(process.stdout);let t=e.errorHandler||be,r=jr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v24.4.0 (ESM)",env:process.env.NODE_ENV||"development"}),so(r);let o=oo({logger:r,config:e}),s={getLogger:no(r),errorHandler:t},i=eo(s),p=Xr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=co(e);return Ht({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Bn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=co(e),p=ut().disable("x-powered-by").use(i);if(e.compression){let x=await Ie("compression");p.use(x(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ut.json()],raw:[e.rawParser||ut.raw(),ro],form:[e.formParser||ut.urlencoded()],upload:e.upload?await to({config:e,getLogger:o}):[]};Ht({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let x=$n.createServer(p);c.push(x),g.push(m(x,e.http.listen))}if(e.https){let x=Mn.createServer(e.https.options,p);c.push(x),g.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&io({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(x=>x())}};import{OpenApiBuilder as ds}from"openapi3-ts/oas31";import*as Ao from"ramda";import*as R from"ramda";var mo=e=>E(e)&&"or"in e,lo=e=>E(e)&&"and"in e,Kt=e=>!lo(e)&&!mo(e),uo=e=>{let t=R.filter(Kt,e),r=R.chain(R.prop("and"),R.filter(lo,e)),[o,n]=R.partition(Kt,r),s=R.concat(t,o),i=R.filter(mo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>fe(d,R.map(m=>Kt(m)?[m]:m.and,c),([m,g])=>R.concat(m,g)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as ft}from"openapi3-ts/oas31";import*as l from"ramda";import{z as yo}from"zod/v4";var fo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var go=50,xo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",bo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},So=e=>e.replace(vt,t=>`{${t.slice(1)}}`),Kn=({},e)=>{if(e.isResponse)throw new Y("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},qn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Un=({zodSchema:e,jsonSchema:t})=>{if(!re(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Dn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ne(e,"throw")},(e,{jsonSchema:t})=>t),Fn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Xn(t.type)})},Ro=e=>e in bo,_n=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Ro(t)&&(e.type=t),e},Jn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Ro(t)&&(e.type=t),e},Ve=e=>e,Vn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Y("Please use ez.dateOut() for output.",r);let o={description:t||"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:xo}};return e?.length&&(o.examples=e),o},Gn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Y("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:xo}};return e?.length&&(o.examples=e),o},Wn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Yn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Qn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return bo?.[t]},Xn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],es=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!re(o,"transform"))return t;let s=Ve(Dt(n,{ctx:r}));if(ft(s))if(r.isResponse){let i=it(o,Qn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},ts=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},qt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,rs=(e,t)=>t?.includes(e)||e.startsWith("x-")||fo.includes(e),Oo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ne(r),m=nt(e),g=o.includes("query"),x=o.includes("params"),y=o.includes("headers"),C=S=>x&&m.includes(S),k=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),L=S=>y&&(i?.(S,t,e)??rs(S,k));return Object.entries(c.properties).reduce((S,[A,I])=>{if(!E(I))return S;let B=C(A)?"path":L(A)?"header":g?"query":void 0;if(!B)return S;let N=Ve(I),X=s==="components"?n(I.id||JSON.stringify(I),N,oe(d,A)):N;return S.concat({name:A,in:B,deprecated:I.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:X,examples:qt(ft(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(E,l.has(A)))||[]))})},[])},Ut={nullable:Fn,union:Un,bigint:Wn,intersection:Dn,tuple:Yn,pipe:es,literal:Jn,enum:_n,[me]:Vn,[le]:Gn,[se]:Kn,[K]:ts,[de]:qn},os=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Ve(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Dt=(e,{ctx:t,rules:r=Ut})=>{let{$defs:o={},properties:n={}}=yo.toJSONSchema(yo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=G(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return os(E(n.subject)?n.subject:{},o,t)},To=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=To(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Po=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${It(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Ve(Dt(r,{rules:{...c,...Ut},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];ft(g)&&g.examples&&(x.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,oe(m)):g,examples:qt(x)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ns=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ss=({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},is=({name:e})=>({type:"apiKey",in:"header",name:e}),as=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ps=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),cs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),wo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ns(o):o.type==="input"?ss(o,t):o.type==="header"?is(o):o.type==="cookie"?as(o):o.type==="openid"?ps(o):cs(o);return e.map(o=>o.map(r))},Eo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Dt(e,{rules:{...t,...Ut},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),vo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=To(Ve(o),p),g=[];ft(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,oe(d)):c,examples:qt(g.length?g:Ne(o).examples?.filter(C=>E(C)&&!Array.isArray(C)).map(l.omit(p))||[])},y={description:d,content:{[n]:x}};return(m||n===w.raw)&&(y.required=!0),y},Co=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)},[]),Ft=e=>e.length<=go?e:e.slice(0,go-1)+"\u2026",yt=e=>e.length?e.slice():void 0;var _t=class extends ds{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Y(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});ze({routing:t,onEndpoint:(y,C,k)=>{let L={path:C,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:A,scopes:I,inputSchema:B}=y,N=A?Ft(A):m&&S?Ft(S):void 0,X=r.inputSources?.[k]||Ct[k],Te=this.#n(C,k,y.getOperationId(k)),Qe=ko({...L,schema:B}),pe=uo(y.security),Xe=Oo({...L,inputSources:X,isHeader:c,security:pe,request:Qe,description:i?.requestParameter?.call(null,{method:k,path:C,operationId:Te})}),et={};for(let ee of Ce){let ce=y.getResponses(ee);for(let{mimeTypes:rt,schema:Et,statusCodes:lr}of ce)for(let kt of lr)et[kt]=Po({...L,variant:ee,schema:Et,mimeTypes:rt,statusCode:kt,hasMultipleStatusCodes:ce.length>1||lr.length>1,description:i?.[`${ee}Response`]?.call(null,{method:k,path:C,operationId:Te,statusCode:kt})})}let tt=X.includes("body")?vo({...L,request:Qe,paramNames:Ao.pluck("name",Xe),schema:B,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:C,operationId:Te})}):void 0,Pt=Eo(wo(pe,X),I,ee=>{let ce=this.#s(ee);return this.addSecurityScheme(ce,ee),ce}),wt={operationId:Te,summary:N,description:S,deprecated:y.isDeprecated||void 0,tags:yt(y.tags),parameters:yt(Xe),requestBody:tt,security:yt(Pt),responses:et};this.addPath(So(C),{[k]:wt})}}),d&&(this.rootDoc.tags=Co(d))}};import{createRequest as ms,createResponse as ls}from"node-mocks-http";var us=e=>ms({...e,headers:{"content-type":w.json,...e?.headers}}),fs=e=>ls(e),ys=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Io=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=fs({req:n,...t});s.req=t?.req||n,n.res=s;let i=ys(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},gs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Io(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},hs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=Io(r),d=st(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:te(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Mo from"ramda";import Tt from"typescript";import{z as Ks}from"zod/v4";import*as Lo from"ramda";import V from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,gt=[a.createModifier(u.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ge={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Jt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Vt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):P(e),ht=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),xt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),je=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(e,t=[])=>a.createConstructorDeclaration(Ge.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,Yt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Gt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Jt(i,p.join(" ")):i},Qt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Xt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&>,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),er=(e,t)=>J(e,a.createUnionTypeNode(_.map(Z,t)),{expose:!0}),J=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?gt:void 0,e,n&&nr(n),t);return o?Jt(s,o):s},No=(e,t)=>a.createPropertyDeclaration(Ge.public,e,void 0,f(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ge.public,void 0,e,void 0,o&&nr(o),t,n,a.createBlock(r)),rr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(gt,e,r&&nr(r),void 0,t),or=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),bt=e=>f(Promise.name,[e]),St=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?gt:void 0,e,void 0,void 0,t);return o?Jt(n,o):n},nr=e=>(Array.isArray(e)?e.map(t=>_.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?_.map(xt,e):je(e),void 0,void 0,t),O=e=>e,We=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Le=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Rt=(e,t)=>f("Extract",[e,t]),sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),U=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),zo=e=>a.createUnionTypeNode([f(e),bt(e)]),ir=(e,t)=>a.createFunctionTypeNode(void 0,je(e),f(t)),P=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),Z=e=>a.createLiteralTypeNode(P(e)),Ss=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],jo=e=>Ss.includes(e.kind);var Ot=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=er("Method",Zt);someOfType=J("SomeOf",U("T",or("T")),{params:["T"]});requestType=J("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>er(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>St(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Gt(t),a.createArrayLiteralExpression(Lo.map(P,r))))),{expose:!0});makeImplementationType=()=>J(this.#e.implementationType,ir({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},bt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([sr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(ht(":",[this.#e.keyParameter]),Oe([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>tr(this.#e.provideMethod,je({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:U(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(Xt(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:bt(U(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ge.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>ht("?",[Le(URLSearchParams.name,t)]);#o=()=>Le(URL.name,ht("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),We(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),We(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,We(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,We(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return z(this.#e.defaultImplementationConst,Oe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Wt(je({request:"K",params:U(this.interfaces.input,"K")}),[z(Xt(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Le("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>tr(this.#e.onMethod,je({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:ir({[this.#e.dataParameter.text]:U(Rt("R",Qt(this.#s("E"))),Z(O("data")))},zo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:U("R",Z(O("event")))}});makeSubscriptionClass=t=>rr(t,[No(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Rt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Rt(U(this.interfaces.positive,"K"),Qt(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Le(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Le(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Oe(["time"],a.createBlock([])))]};import*as v from"ramda";import h from"typescript";import{globalRegistry as Rs}from"zod/v4";var ar=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=G(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ar(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:j}=h,Os={[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:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ts=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:j.createUnionTypeNode(t)},Ps=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(re(p)){r.unshift(p);break}i+=p??""}return i},n=j.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?j.createTemplateMiddle:j.createTemplateTail;s.push(j.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?j.createTemplateLiteralType(n,s):Z(n.text)},ws=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Rs.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return j.createTypeLiteralNode(s)};return Or(e,{io:t?"output":"input"})?o(e,n):n()},Es=({_zod:{def:e}},{next:t})=>j.createArrayTypeNode(t(e.element)),ks=({_zod:{def:e}})=>j.createUnionTypeNode(Object.values(e.entries).map(Z)),vs=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(jo(n)?n.kind:n,n)}return j.createUnionTypeNode(Array.from(r.values()))},Cs=e=>Os?.[e.kind],As=({_zod:{def:e}},{next:t})=>j.createUnionTypeNode([t(e.innerType),Z(null)]),Is=({_zod:{def:e}},{next:t})=>j.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:j.createRestTypeNode(t(e.rest)))),Ns=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),zs=v.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(pr.name,...o))return!1;if(v.both(v.eqBy(pr.type),v.eqBy(pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return j.createTypeLiteralNode(r)},(e,t)=>j.createIntersectionTypeNode(t)),js=({_zod:{def:e}},{next:t})=>zs([e.left,e.right].map(t)),D=e=>()=>f(e),Ye=({_zod:{def:e}},{next:t})=>t(e.innerType),$o=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),Ls=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!re(o,"transform"))return t(o);let s=t(n),i=it(o,Cs(s)),p={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 f(i&&p[i]||$o(r))},$s=()=>Z(null),Ms=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Zs=()=>f("Buffer"),Bs=(e,{next:t})=>t(e._zod.def.shape.raw),Hs={string:D(h.SyntaxKind.StringKeyword),number:D(h.SyntaxKind.NumberKeyword),bigint:D(h.SyntaxKind.BigIntKeyword),boolean:D(h.SyntaxKind.BooleanKeyword),any:D(h.SyntaxKind.AnyKeyword),undefined:D(h.SyntaxKind.UndefinedKeyword),[me]:D(h.SyntaxKind.StringKeyword),[le]:D(h.SyntaxKind.StringKeyword),never:D(h.SyntaxKind.NeverKeyword),void:D(h.SyntaxKind.UndefinedKeyword),unknown:D(h.SyntaxKind.UnknownKeyword),null:$s,array:Es,tuple:Is,record:Ns,object:ws,literal:Ts,template_literal:Ps,intersection:js,union:vs,default:Ye,enum:ks,optional:Ye,nonoptional:Ye,nullable:As,catch:Ye,pipe:Ls,lazy:Ms,readonly:Ye,[de]:Zs,[K]:Bs},cr=(e,{brandHandling:t,ctx:r})=>ar(e,{rules:{...t,...Hs},onMissing:({},{isResponse:o})=>$o(o),ctx:r});var dr=class extends Ot{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=Z(null);this.#t.set(t,J(o,n)),this.#t.set(t,J(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Ks.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};ze({routing:t,onEndpoint:(x,y,C)=>{let k=oe.bind(null,C,y),{isDeprecated:L,inputSchema:S,tags:A}=x,I=`${C} ${y}`,B=J(k("input"),cr(S,c),{comment:I});this.#e.push(B);let N=Ce.reduce((Qe,pe)=>{let Xe=x.getResponses(pe),et=Mo.chain(([Pt,{schema:wt,mimeTypes:ee,statusCodes:ce}])=>{let rt=J(k(pe,"variant",`${Pt+1}`),cr(ee?wt:p,m),{comment:I});return this.#e.push(rt),ce.map(Et=>Re(Et,rt.name))},Array.from(Xe.entries())),tt=St(k(pe,"response","variants"),et,{comment:I});return this.#e.push(tt),Object.assign(Qe,{[pe]:tt})},{});this.paths.add(y);let X=Z(I),Te={input:f(B.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([U(this.interfaces.positive,X),U(this.interfaces.negative,X)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(I,{isDeprecated:L,store:Te}),this.tags.set(I,A)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
|
|
18
|
+
`))};var co=e=>{e.startupLogo!==!1&&po(process.stdout);let t=e.errorHandler||be,r=jr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v24.4.1 (ESM)",env:process.env.NODE_ENV||"development"}),so(r);let o=oo({logger:r,config:e}),s={getLogger:no(r),errorHandler:t},i=eo(s),p=Xr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=co(e);return Ht({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Bn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=co(e),p=ut().disable("x-powered-by").use(i);if(e.compression){let x=await Ie("compression");p.use(x(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ut.json()],raw:[e.rawParser||ut.raw(),ro],form:[e.formParser||ut.urlencoded()],upload:e.upload?await to({config:e,getLogger:o}):[]};Ht({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let x=$n.createServer(p);c.push(x),g.push(m(x,e.http.listen))}if(e.https){let x=Mn.createServer(e.https.options,p);c.push(x),g.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&io({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(x=>x())}};import{OpenApiBuilder as ds}from"openapi3-ts/oas31";import*as Co from"ramda";import*as R from"ramda";var mo=e=>E(e)&&"or"in e,lo=e=>E(e)&&"and"in e,Kt=e=>!lo(e)&&!mo(e),uo=e=>{let t=R.filter(Kt,e),r=R.chain(R.prop("and"),R.filter(lo,e)),[o,n]=R.partition(Kt,r),s=R.concat(t,o),i=R.filter(mo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>fe(d,R.map(m=>Kt(m)?[m]:m.and,c),([m,g])=>R.concat(m,g)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as ft}from"openapi3-ts/oas31";import*as l from"ramda";import{z as yo}from"zod/v4";var fo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var go=50,xo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",bo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},So=e=>e.replace(vt,t=>`{${t.slice(1)}}`),Kn=({},e)=>{if(e.isResponse)throw new Y("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},qn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Un=({zodSchema:e,jsonSchema:t})=>{if(!re(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Dn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ne(e,"throw")},(e,{jsonSchema:t})=>t),Fn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Xn(t.type)})},Ro=e=>e in bo,_n=({jsonSchema:e})=>{let t=typeof e.enum?.[0];return!e.type&&Ro(t)&&(e.type=t),e},Jn=({jsonSchema:e})=>{let t=typeof(e.const||e.enum?.[0]);return!e.type&&Ro(t)&&(e.type=t),e},Ve=e=>e,Vn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Y("Please use ez.dateOut() for output.",r);let o={description:t||"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:xo}};return e?.length&&(o.examples=e),o},Gn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Y("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:xo}};return e?.length&&(o.examples=e),o},Wn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Yn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Qn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return bo?.[t]},Xn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],es=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!re(o,"transform"))return t;let s=Ve(Dt(n,{ctx:r}));if(ft(s))if(r.isResponse){let i=it(o,Qn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},ts=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},qt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,rs=(e,t)=>t?.includes(e)||e.startsWith("x-")||fo.includes(e),Oo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ne(r),m=nt(e),g=o.includes("query"),x=o.includes("params"),y=o.includes("headers"),A=S=>x&&m.includes(S),k=l.chain(l.filter(S=>S.type==="header"),p??[]).map(({name:S})=>S),L=S=>y&&(i?.(S,t,e)??rs(S,k));return Object.entries(c.properties).reduce((S,[C,I])=>{if(!E(I))return S;let B=A(C)?"path":L(C)?"header":g?"query":void 0;if(!B)return S;let N=Ve(I),X=s==="components"?n(I.id||JSON.stringify(I),N,oe(d,C)):N;return S.concat({name:C,in:B,deprecated:I.deprecated,required:c.required?.includes(C)||!1,description:N.description||d,schema:X,examples:qt(ft(N)&&N.examples?.length?N.examples:l.pluck(C,c.examples?.filter(l.both(E,l.has(C)))||[]))})},[])},Ut={nullable:Fn,union:Un,bigint:Wn,intersection:Dn,tuple:Yn,pipe:es,literal:Jn,enum:_n,[me]:Vn,[le]:Gn,[se]:Kn,[K]:ts,[de]:qn},os=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Ve(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Dt=(e,{ctx:t,rules:r=Ut})=>{let{$defs:o={},properties:n={}}=yo.toJSONSchema(yo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=G(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return os(E(n.subject)?n.subject:{},o,t)},To=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=To(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Po=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${It(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Ve(Dt(r,{rules:{...c,...Ut},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];ft(g)&&g.examples&&(x.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,oe(m)):g,examples:qt(x)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ns=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ss=({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},is=({name:e})=>({type:"apiKey",in:"header",name:e}),as=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ps=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),cs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),wo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ns(o):o.type==="input"?ss(o,t):o.type==="header"?is(o):o.type==="cookie"?as(o):o.type==="openid"?ps(o):cs(o);return e.map(o=>o.map(r))},Eo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Dt(e,{rules:{...t,...Ut},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),vo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=To(Ve(o),p),g=[];ft(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,oe(d)):c,examples:qt(g.length?g:Ne(o).examples?.filter(A=>E(A)&&!Array.isArray(A)).map(l.omit(p))||[])},y={description:d,content:{[n]:x}};return(m||n===w.raw)&&(y.required=!0),y},Ao=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Ft=e=>e.length<=go?e:e.slice(0,go-1)+"\u2026",yt=e=>e.length?e.slice():void 0;var _t=class extends ds{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Y(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});ze({routing:t,onEndpoint:(y,A,k)=>{let L={path:A,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:S,shortDescription:C,scopes:I,inputSchema:B}=y,N=C?Ft(C):m&&S?Ft(S):void 0,X=r.inputSources?.[k]||At[k],Te=this.#n(A,k,y.getOperationId(k)),Qe=ko({...L,schema:B}),pe=uo(y.security),Xe=Oo({...L,inputSources:X,isHeader:c,security:pe,request:Qe,description:i?.requestParameter?.call(null,{method:k,path:A,operationId:Te})}),et={};for(let ee of Ae){let ce=y.getResponses(ee);for(let{mimeTypes:rt,schema:Et,statusCodes:lr}of ce)for(let kt of lr)et[kt]=Po({...L,variant:ee,schema:Et,mimeTypes:rt,statusCode:kt,hasMultipleStatusCodes:ce.length>1||lr.length>1,description:i?.[`${ee}Response`]?.call(null,{method:k,path:A,operationId:Te,statusCode:kt})})}let tt=X.includes("body")?vo({...L,request:Qe,paramNames:Co.pluck("name",Xe),schema:B,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:A,operationId:Te})}):void 0,Pt=Eo(wo(pe,X),I,ee=>{let ce=this.#s(ee);return this.addSecurityScheme(ce,ee),ce}),wt={operationId:Te,summary:N,description:S,deprecated:y.isDeprecated||void 0,tags:yt(y.tags),parameters:yt(Xe),requestBody:tt,security:yt(Pt),responses:et};this.addPath(So(A),{[k]:wt})}}),d&&(this.rootDoc.tags=Ao(d))}};import{createRequest as ms,createResponse as ls}from"node-mocks-http";var us=e=>ms({...e,headers:{"content-type":w.json,...e?.headers}}),fs=e=>ls(e),ys=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Lr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Io=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=fs({req:n,...t});s.req=t?.req||n,n.res=s;let i=ys(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},gs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Io(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},hs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=Io(r),d=st(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:te(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Mo from"ramda";import Tt from"typescript";import{z as Ks}from"zod/v4";import*as Lo from"ramda";import V from"typescript";import*as _ from"ramda";import u from"typescript";var a=u.factory,gt=[a.createModifier(u.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ge={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Jt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Vt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):P(e),ht=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),xt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),je=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(e,t=[])=>a.createConstructorDeclaration(Ge.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&_.map(f,t)):e,Yt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Gt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=_.reject(_.isNil,[o?"@deprecated":void 0,n]);return p.length?Jt(i,p.join(" ")):i},Qt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Xt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&>,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),er=(e,t)=>J(e,a.createUnionTypeNode(_.map(Z,t)),{expose:!0}),J=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?gt:void 0,e,n&&nr(n),t);return o?Jt(s,o):s},No=(e,t)=>a.createPropertyDeclaration(Ge.public,e,void 0,f(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ge.public,void 0,e,void 0,o&&nr(o),t,n,a.createBlock(r)),rr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(gt,e,r&&nr(r),void 0,t),or=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),bt=e=>f(Promise.name,[e]),St=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?gt:void 0,e,void 0,void 0,t);return o?Jt(n,o):n},nr=e=>(Array.isArray(e)?e.map(t=>_.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?_.map(xt,e):je(e),void 0,void 0,t),O=e=>e,We=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Le=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Rt=(e,t)=>f("Extract",[e,t]),sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),U=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),zo=e=>a.createUnionTypeNode([f(e),bt(e)]),ir=(e,t)=>a.createFunctionTypeNode(void 0,je(e),f(t)),P=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),Z=e=>a.createLiteralTypeNode(P(e)),Ss=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],jo=e=>Ss.includes(e.kind);var Ot=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=er("Method",Zt);someOfType=J("SomeOf",U("T",or("T")),{params:["T"]});requestType=J("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>er(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>St(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Gt(t),a.createArrayLiteralExpression(Lo.map(P,r))))),{expose:!0});makeImplementationType=()=>J(this.#e.implementationType,ir({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},bt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([sr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(ht(":",[this.#e.keyParameter]),Oe([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>tr(this.#e.provideMethod,je({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:U(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(Xt(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:bt(U(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ge.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>ht("?",[Le(URLSearchParams.name,t)]);#o=()=>Le(URL.name,ht("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),We(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),We(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,We(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,We(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return z(this.#e.defaultImplementationConst,Oe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Wt(je({request:"K",params:U(this.interfaces.input,"K")}),[z(Xt(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Le("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>tr(this.#e.onMethod,je({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:ir({[this.#e.dataParameter.text]:U(Rt("R",Qt(this.#s("E"))),Z(O("data")))},zo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:U("R",Z(O("event")))}});makeSubscriptionClass=t=>rr(t,[No(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Rt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Rt(U(this.interfaces.positive,"K"),Qt(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Le(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Le(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Oe(["time"],a.createBlock([])))]};import*as v from"ramda";import h from"typescript";import{globalRegistry as Rs}from"zod/v4";var ar=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=G(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ar(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:j}=h,Os={[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:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ts=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:j.createUnionTypeNode(t)},Ps=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(re(p)){r.unshift(p);break}i+=p??""}return i},n=j.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?j.createTemplateMiddle:j.createTemplateTail;s.push(j.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?j.createTemplateLiteralType(n,s):Z(n.text)},ws=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Rs.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return j.createTypeLiteralNode(s)};return Or(e,{io:t?"output":"input"})?o(e,n):n()},Es=({_zod:{def:e}},{next:t})=>j.createArrayTypeNode(t(e.element)),ks=({_zod:{def:e}})=>j.createUnionTypeNode(Object.values(e.entries).map(Z)),vs=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(jo(n)?n.kind:n,n)}return j.createUnionTypeNode(Array.from(r.values()))},As=e=>Os?.[e.kind],Cs=({_zod:{def:e}},{next:t})=>j.createUnionTypeNode([t(e.innerType),Z(null)]),Is=({_zod:{def:e}},{next:t})=>j.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:j.createRestTypeNode(t(e.rest)))),Ns=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),zs=v.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(pr.name,...o))return!1;if(v.both(v.eqBy(pr.type),v.eqBy(pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return j.createTypeLiteralNode(r)},(e,t)=>j.createIntersectionTypeNode(t)),js=({_zod:{def:e}},{next:t})=>zs([e.left,e.right].map(t)),D=e=>()=>f(e),Ye=({_zod:{def:e}},{next:t})=>t(e.innerType),$o=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),Ls=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!re(o,"transform"))return t(o);let s=t(n),i=it(o,As(s)),p={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 f(i&&p[i]||$o(r))},$s=()=>Z(null),Ms=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Zs=()=>f("Buffer"),Bs=(e,{next:t})=>t(e._zod.def.shape.raw),Hs={string:D(h.SyntaxKind.StringKeyword),number:D(h.SyntaxKind.NumberKeyword),bigint:D(h.SyntaxKind.BigIntKeyword),boolean:D(h.SyntaxKind.BooleanKeyword),any:D(h.SyntaxKind.AnyKeyword),undefined:D(h.SyntaxKind.UndefinedKeyword),[me]:D(h.SyntaxKind.StringKeyword),[le]:D(h.SyntaxKind.StringKeyword),never:D(h.SyntaxKind.NeverKeyword),void:D(h.SyntaxKind.UndefinedKeyword),unknown:D(h.SyntaxKind.UnknownKeyword),null:$s,array:Es,tuple:Is,record:Ns,object:ws,literal:Ts,template_literal:Ps,intersection:js,union:vs,default:Ye,enum:ks,optional:Ye,nonoptional:Ye,nullable:Cs,catch:Ye,pipe:Ls,lazy:Ms,readonly:Ye,[de]:Zs,[K]:Bs},cr=(e,{brandHandling:t,ctx:r})=>ar(e,{rules:{...t,...Hs},onMissing:({},{isResponse:o})=>$o(o),ctx:r});var dr=class extends Ot{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=Z(null);this.#t.set(t,J(o,n)),this.#t.set(t,J(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Ks.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};ze({routing:t,onEndpoint:(x,y,A)=>{let k=oe.bind(null,A,y),{isDeprecated:L,inputSchema:S,tags:C}=x,I=`${A} ${y}`,B=J(k("input"),cr(S,c),{comment:I});this.#e.push(B);let N=Ae.reduce((Qe,pe)=>{let Xe=x.getResponses(pe),et=Mo.chain(([Pt,{schema:wt,mimeTypes:ee,statusCodes:ce}])=>{let rt=J(k(pe,"variant",`${Pt+1}`),cr(ee?wt:p,m),{comment:I});return this.#e.push(rt),ce.map(Et=>Re(Et,rt.name))},Array.from(Xe.entries())),tt=St(k(pe,"response","variants"),et,{comment:I});return this.#e.push(tt),Object.assign(Qe,{[pe]:tt})},{});this.paths.add(y);let X=Z(I),Te={input:f(B.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([U(this.interfaces.positive,X),U(this.interfaces.negative,X)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(I,{isDeprecated:L,store:Te}),this.tags.set(I,C)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.#n(t),o=r&&Tt.addSyntheticLeadingComment(Tt.addSyntheticLeadingComment(a.createEmptyStatement(),Tt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Tt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.#e.concat(o||[]).map((n,s)=>Vt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
package/package.json
CHANGED