express-zod-api 24.0.0-beta.9 → 24.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -3
- package/README.md +185 -198
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +10 -5
- package/dist/index.d.ts +10 -5
- package/dist/index.js +6 -6
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,gt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod/v4");var Jt=class{},q=class extends Jt{#e;#t;#r;constructor({input:t=_t.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 _t.z.ZodError?new G(o):o}}},Le=class extends q{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 Me=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Me{},bt=class e extends Xe{#e;#t=de.once(()=>{let t=this.#e.outputSchema.meta();if(t?.examples?.length||!Ne(this.#e.outputSchema,"object"))return;let r=Ur(this.#e.outputSchema);r.length&&Qe.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:r})});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=qr(this.#e.inputSchema);if(t){let r=ee(t);if(r===pe)return"upload";if(r===K)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=de.pluck("security",this.#e.middlewares||[]);return de.reject(de.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 je(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 G(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ht({...t,error:new ae(oe(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ht(t),i={},p={output:{},error:null},d=lt(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:oe(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Dr=y(require("ramda"),1),_r=(e,t)=>Dr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var A=require("zod/v4");var Ze={positive:200,negative:400},$e=Object.keys(Ze);var Vt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends Vt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},le=new me({positive:e=>{let t=A.z.object({status:A.z.literal("success"),data:e}),{examples:r=[]}=A.globalRegistry.get(e)||{};return r.length&&A.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:A.z.object({status:A.z.literal("error"),error:A.z.object({message:A.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=Oe(e);return Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Te(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),xt=new me({positive:e=>{let t=e instanceof A.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof A.z.ZodArray?e.shape.items:A.z.array(A.z.any()),r=t.meta();if(r?.examples?.length)return t;let o=(A.globalRegistry.get(e)?.examples||[]).filter(n=>M(n)&&"items"in n&&Array.isArray(n.items)).map(n=>n.items);return o.length&&A.globalRegistry.remove(t).add(t,{...r,examples:o}),t},negative:A.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Oe(r);return Ye(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Te(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ze.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ue=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(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 q({handler:t})),this.resultHandler)}build({input:t=Gt.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,x=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:g,methods:m,getOperationId:h,inputSchema:_r(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Gt.z.object({}),handler:async o=>(await t(o),{})})}},Jr=new ue(le),Vr=new ue(xt);var eo=y(require("ansis"),1),to=require("node:util"),Yt=require("node:perf_hooks");var W=require("ansis"),Gr=y(require("ramda"),1);var Wt={debug:W.blue,info:W.green,warn:(0,W.hex)("#FFA500"),error:W.red,ctx:W.cyanBright},St={debug:10,info:20,warn:30,error:40},Wr=e=>M(e)&&Object.keys(St).some(t=>t in e),Yr=e=>e in St,Qr=(e,t)=>St[e]<St[t],In=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Be=Gr.memoizeWith((e,t)=>`${e}${t}`,In),Xr=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=eo.default.isSupported(),level:r=Re()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,to.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"||Qr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Wt.ctx(s):s),d.push(p?`${Wt[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=Yt.performance.now();return()=>{let o=Yt.performance.now()-r,{message:n,severity:s="debug",formatter:i=Xr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var ro=y(require("ramda"),1);var Ke=class e extends Me{#e;constructor(t){super(),this.#e=t}get entries(){let t=ro.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 oo=y(require("express"),1),qe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,oo.default.static(...this.#e))}};var et=y(require("express"),1),Co=y(require("node:http"),1),Ao=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new ze(e)};var po=y(require("http-errors"),1);var Qt=require("zod/v4");var S=y(require("ramda"),1);var Nn=e=>e.type==="object",jn=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}})}),zn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),no=S.pair(!0),Ue=(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"&&zn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(no,i.anyOf)),i.oneOf&&r.push(...S.map(no,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Se(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>S.mergeDeepRight(p,d))),!!Nn(i)&&(r.push([s,{examples:Ln(i)}]),i.properties&&(o.properties=(t==="throw"?jn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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},Ln=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>Se(t,o.map(S.objOf(r)),([n,s])=>({...n,...s})),[]);var Rt=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=[Qt.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=Ut(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 $e)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Ut(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=mt(t);if(s.length===0)return;let i=n?.flat||Ue(Qt.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 Xt=["get","post","put","delete","patch"],so=e=>Xt.includes(e);var Mn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&so(t)?[r,t]:[e]},Zn=e=>e.trim().split("/").filter(Boolean).join("/"),io=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Mn(r);return[[t||""].concat(Zn(n)||[]).join("/"),o,s]}),$n=(e,t)=>{throw new ie("Route with explicit method can only be assigned with Endpoint",e,t)},ao=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ie(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},er=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ie("Route has a duplicate",e,t);r.add(o)},De=({routing:e,onEndpoint:t,onStatic:r})=>{let o=io(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)er(p,s,n),ao(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)er(c,s,n),t(i,s,c)}else if(p&&$n(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;er(d,s,n),ao(d,s,m),t(c,s,d)}else o.unshift(...io(i,s))}};var co=y(require("ramda"),1),mo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Bn=e=>({method:t},r,o)=>{let n=mo(e);r.set({Allow:n});let s=(0,po.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Hn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":mo(e),"Access-Control-Allow-Headers":"content-type"}),tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new Rt(t()),i=new Map;De({routing:o,onEndpoint:(c,m,h)=>{Re()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let x=n?.[c.requestType]||[],g=co.pair(x,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[x,[g,k]]of m){let C=async(Z,O)=>{let N=t(Z);if(r.cors){let I=Hn(h),_=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:N,defaultHeaders:I}):I;O.set(_)}return k.execute({request:Z,response:O,logger:N,config:r})};e[x](c,...g,C)}r.wrongMethodBehavior!==404&&d.set(c,Bn(h))}for(let[c,m]of d)e.all(c,m)};var xo=y(require("http-errors"),1);var ho=require("node:timers/promises");var lo=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",uo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),go=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var bo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(lo(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",yo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(fo(c)||uo(c))&&i(c);for await(let c of(0,ho.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(go))};return{sockets:n,shutdown:()=>o??=d()}};var So=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:oe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Ro=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,xo.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){ht({response:o,logger:s,error:new ae(oe(i),n)})}},Kn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},qn=e=>({log:e.debug.bind(e)}),Oo=async({getLogger:e,config:t})=>{let r=await Fe("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:qn(m)})(p,d,c)}),o&&i.push(Kn(o)),i},To=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Po=({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()},wo=e=>t=>t?.res?.locals[Ce]?.logger||e,Eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
"use strict";var gn=Object.create;var dt=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)dt(e,r,{get:t[r],enumerable:!0})},vr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xn(t))!Sn.call(e,n)&&n!==r&&dt(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)):{},vr(t||!e||!e.__esModule?dt(r,"default",{value:e,enumerable:!0}):r,e)),On=e=>vr(dt({},"__esModule",{value:!0}),e);var Ds={};Rn(Ds,{BuiltinLogger:()=>Ke,DependsOnMethod:()=>qe,Documentation:()=>Tt,DocumentationError:()=>W,EndpointsFactory:()=>ye,EventStreamFactory:()=>jt,InputValidationError:()=>Y,Integration:()=>Nt,Middleware:()=>F,MissingPeerError:()=>Le,OutputValidationError:()=>ze,ResultHandler:()=>ue,RoutingError:()=>pe,ServeStatic:()=>Ue,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>bt,attachRouting:()=>zo,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 $=y(require("ramda"),1),G=require("zod/v4");var kr=require("zod/v4"),Ie=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}=kr.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})},vn=function(e){return this.check(new Tn({brand:e,check:"$EZBrandCheck"}))},kn=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 G.z.ZodUnknown?G.z.looseObject:G.z.object)(r);return this.transform(t).pipe(n)};if(!(Ie in globalThis)){globalThis[Ie]=!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 vn.bind(this)}}})}Object.defineProperty(G.z.ZodDefault.prototype,"label",{value:En,writable:!1}),Object.defineProperty(G.z.ZodObject.prototype,"remap",{value:kn,writable:!1})}function Ar(e){return e}var Gt=require("zod/v4");var le=y(require("ramda"),1),Xe=require("zod/v4");var me=y(require("ramda"),1),Ut=require("zod/v4");var Cr=require("zod/v4"),be=Symbol("Buffer"),mt=()=>Cr.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(be);var Ne=require("zod/v4"),Se=Symbol("DateIn"),Ir=({examples:e,...t}={})=>Ne.z.union([Ne.z.iso.date(),Ne.z.iso.datetime(),Ne.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ne.z.date()).brand(Se).meta(t);var Nr=require("zod/v4"),Re=Symbol("DateOut"),jr=(e={})=>Nr.z.date().transform(t=>t.toISOString()).brand(Re).meta(e);var zr=require("zod/v4");var Z=y(require("ramda"),1),je=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 Zt=/:([A-Za-z0-9_]+)/g,lt=e=>e.match(Zt)?.map(t=>t.slice(1))||[],An=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Cn=["body","query","params"],Ht=e=>e.method.toLowerCase(),ut=(e,t={})=>{let r=Ht(e);return r==="options"?{}:(t[r]||Bt[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 je.z.ZodError?new je.z.ZodRealError(e.issues):new Error(String(e)),se=e=>e instanceof je.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${je.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,ie=(e,t)=>L(e)&&"_zod"in e&&(t?Z.path(["_zod","def","type"],e)===t:!0),Oe=(e,t,r)=>e.length&&t.length?Z.xprod(e,t).map(r):e.concat(t),Kt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ae=(...e)=>{let t=Z.chain(o=>o.split(/[^A-Z0-9]/gi),e);return Z.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Kt).join("")},ft=Z.tryCatch((e,t)=>typeof je.z.parse(e,t),Z.always(void 0)),L=e=>typeof e=="object"&&e!==null,Te=Z.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.`}},Ge=class extends Error{name="IOSchemaError"},yt=class extends Ge{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ze=class extends Ge{constructor(r){let o=new zr.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 Ge{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"},Le=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var qt=require("zod/v4"),We=Symbol("Form"),Lr=e=>(e instanceof qt.z.ZodObject?e:qt.z.object(e)).brand(We);var Mr=require("zod/v4"),de=Symbol("Upload"),$r=()=>Mr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(de);var Zr=require("zod/v4");var U=Symbol("Raw"),Br=Zr.z.object({raw:mt()}),In=e=>Br.extend(e).brand(U);function Hr(e){return e?In(e):Br.brand(U)}var Kr=(e,{io:t,condition:r})=>me.tryCatch(()=>{Ut.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new yt(o)}})},o=>o.cause)(),qr=(e,{io:t})=>{let o=[Ut.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];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,U,We].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===U||o===de))}});var gt=y(require("http-errors"),1);var Ye=y(require("http-errors"),1),Fr=y(require("ramda"),1),Dr=require("zod/v4");var Dt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Dr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new 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}))},Qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Pe=e=>(0,Ye.isHttpError)(e)?e:(0,Ye.default)(e instanceof Y?400:500,se(e),{cause:e.cause||e}),we=e=>Te()&&!e.expose?(0,Ye.default)(e.statusCode).message:e.message,_r=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>Oe(t,K(o).map(Fr.objOf(r)),([n,s])=>({...n,...s})),[]);var ht=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=we((0,gt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,gt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod/v4");var Jt=class{},F=class extends Jt{#e;#t;#r;constructor({input:t=_t.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 _t.z.ZodError?new Y(o):o}}},Me=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 et=class extends $e{},xt=class e extends et{#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();Xe.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===U)return"raw";if(r===We)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 Xe.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 Me))&&(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 Xe.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){ht({...t,error:new ce(ne(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ht(t),i={},p={output:{},error:null},d=ut(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 N=require("zod/v4");var Ze={positive:200,negative:400},Be=Object.keys(Ze);var Vt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ue=class extends Vt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},fe=new ue({positive:e=>{let t=N.z.object({status:N.z.literal("success"),data:e}),r=K(e);return r.length&&N.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:N.z.object({status:N.z.literal("error"),error:N.z.object({message:N.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 Qe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:we(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),bt=new ue({positive:e=>{let t=e instanceof N.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof N.z.ZodArray?e.shape.items:N.z.array(N.z.any());if(K(t).length)return t;let r=K(e).filter(o=>L(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r.length){let o=t.meta();N.globalRegistry.remove(t).add(t,{...o,examples:r})}return t},negative:N.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 Qe(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(Ze.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 Me(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Gt.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 xt({...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:Gt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new ye(fe),Wr=new ye(bt);var ro=y(require("ansis"),1),oo=require("node:util"),Yt=require("node:perf_hooks");var Q=require("ansis"),Yr=y(require("ramda"),1);var Wt={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},St={debug:10,info:20,warn:30,error:40},Qr=e=>L(e)&&Object.keys(St).some(t=>t in e),Xr=e=>e in St,eo=(e,t)=>St[e]<St[t],jn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),He=Yr.memoizeWith((e,t)=>`${e}${t}`,jn),to=e=>e<1e-6?He("nanosecond",3).format(e/1e-6):e<.001?He("nanosecond").format(e/1e-6):e<1?He("microsecond").format(e/.001):e<1e3?He("millisecond").format(e):e<6e4?He("second",2).format(e/1e3):He("minute",2).format(e/6e4);var Ke=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?Wt.ctx(s):s),d.push(p?`${Wt[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=Yt.performance.now();return()=>{let o=Yt.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 qe=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),Ue=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var tt=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new Le(e)};var mo=y(require("http-errors"),1);var Qt=require("zod/v4");var S=y(require("ramda"),1);var zn=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}})}),Mn=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"&&Mn(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(L)||[],i.examples.filter(L),([p,d])=>S.mergeDeepRight(p,d))),!!zn(i)&&(r.push([s,{examples:$n(i)}]),i.properties&&(o.properties=(t==="throw"?Ln:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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},$n=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>Oe(t,o.map(S.objOf(r)),([n,s])=>({...n,...s})),[]);var Rt=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=[Qt.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 Be)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=lt(t);if(s.length===0)return;let i=n?.flat||De(Qt.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 Xt=["get","post","put","delete","patch"],ao=e=>Xt.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)},er=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new pe("Route has a duplicate",e,t);r.add(o)},_e=({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 et)if(p)er(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)er(c,s,n),t(i,s,c)}else if(p&&Hn(p,s),i instanceof Ue)r&&i.apply(s,r);else if(i instanceof qe)for(let[d,c]of i.entries){let{methods:m}=c;er(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"}),tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Te()?void 0:new Rt(t()),i=new Map;_e({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,k]]of m){let A=async(H,O)=>{let I=t(H);if(r.cors){let C=qn(h),V=typeof r.cors=="function"?await r.cors({request:H,endpoint:k,logger:I,defaultHeaders:C}):C;O.set(V)}return k.execute({request:H,response:O,logger:I,config:r})};e[b](c,...g,A)}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){ht({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()},Fn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await Fe("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:Fn(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[Ie]={logger:i}),s()},vo=e=>t=>t?.res?.locals[Ie]?.logger||e,ko=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,9 +15,9 @@ ${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 Io=e=>{e.startupLogo!==!1&&ko(process.stdout);let t=e.errorHandler||le,r=Wr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.0.0-beta.9 (CJS)",env:process.env.NODE_ENV||"development"}),Eo(r);let o=Po({logger:r,config:e}),s={getLogger:wo(r),errorHandler:t},i=Ro(s),p=So(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},No=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Io(e);return tr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},jo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=Io(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let x=await Fe("compression");p.use(x(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(),To],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Oo({config:e,getLogger:o}):[]};tr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,g)=>()=>x.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let x=Co.default.createServer(p);c.push(x),h.push(m(x,e.http.listen))}if(e.https){let x=Ao.default.createServer(e.https.options,p);c.push(x),h.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&vo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(x=>x())}};var Yo=require("openapi3-ts/oas31"),Qo=y(require("ramda"),1);var R=y(require("ramda"),1);var zo=e=>M(e)&&"or"in e,Lo=e=>M(e)&&"and"in e,rr=e=>!Lo(e)&&!zo(e),Mo=e=>{let t=R.filter(rr,e),r=R.chain(R.prop("and"),R.filter(Lo,e)),[o,n]=R.partition(rr,r),s=R.concat(t,o),i=R.filter(zo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Se(d,R.map(m=>rr(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var fe=require("openapi3-ts/oas31"),l=y(require("ramda"),1),or=require("zod/v4");var Zo=["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 $o=50,Ho="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ko={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},qo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new V("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Dn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),_n=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Vn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:rs(t.type)})},Bo=e=>e in Ko,Gn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Wn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Pe=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(Bo):t&&Bo(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Pe));return s&&(p.not=Pe(s)),p},Yn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new V("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:Ho}};return e?.length&&(o.examples=e),o},Qn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new V("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ho}};return e?.length&&(o.examples=e),o},Xn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),es=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Ko?.[t]},rs=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],os=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!Ne(o,"transform"))return t;let s=Pe(ir(n,{ctx:r}));if((0,fe.isSchemaObject)(s))if(r.isResponse){let i=ut(o,ts(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},ns=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},nr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ss=(e,t)=>t?.includes(e)||e.startsWith("x-")||Zo.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=Ue(r),m=mt(e),h=o.includes("query"),x=o.includes("params"),g=o.includes("headers"),k=O=>x&&m.includes(O),C=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),Z=O=>g&&(i?.(O,t,e)??ss(O,C));return Object.entries(c.properties).reduce((O,[N,I])=>{let _=k(N)?"path":Z(N)?"header":h?"query":void 0;if(!_)return O;let z=Pe(I),te=s==="components"?n(I.id||JSON.stringify(I),z,se(d,N)):z;return O.concat({name:N,in:_,deprecated:I.deprecated,required:c.required?.includes(N)||!1,description:z.description||d,schema:te,examples:nr((0,fe.isSchemaObject)(z)&&z.examples?.length?z.examples:l.pluck(N,c.examples?.filter(l.both(M,l.has(N)))||[]))})},[])},sr={nullable:Vn,union:_n,bigint:Xn,intersection:Jn,tuple:es,pipe:os,literal:Wn,enum:Gn,[be]:Yn,[xe]:Qn,[pe]:Un,[K]:ns,[he]:Dn},is=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,fe.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Pe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ir=(e,{ctx:t,rules:r=sr})=>{let{$defs:o={},properties:n={}}=or.z.toJSONSchema(or.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=ee(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 is(n.subject,o,t)},Uo=(e,t)=>{if((0,fe.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Uo(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]},Do=({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} ${Kt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=Pe(ir(r,{rules:{...c,...sr},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];(0,fe.isSchemaObject)(h)&&h.examples&&(x.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,se(m)):h,examples:nr(x)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},as=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ps=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},cs=({name:e})=>({type:"apiKey",in:"header",name:e}),ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ms=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ls=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),_o=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?as(o):o.type==="input"?ps(o,t):o.type==="header"?cs(o):o.type==="cookie"?ds(o):o.type==="openid"?ms(o):ls(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),Vo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ir(e,{rules:{...t,...sr},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Go=({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]=Uo(Pe(o),p),h=[];(0,fe.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,se(d)):c,examples:nr(h.length?h:Ue(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},g={description:d,content:{[n]:x}};return(m||n===E.raw)&&(g.required=!0),g},Wo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),ar=e=>e.length<=$o?e:e.slice(0,$o-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Tt=class extends Yo.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||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new V(`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});De({routing:t,onEndpoint:(g,k,C)=>{let Z={path:k,method:C,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:N,scopes:I,inputSchema:_}=g,z=N?ar(N):m&&O?ar(O):void 0,te=r.inputSources?.[C]||Bt[C],ke=this.#n(k,C,g.getOperationId(C)),nt=Vo({...Z,schema:_}),ye=Mo(g.security),st=Fo({...Z,inputSources:te,isHeader:c,security:ye,request:nt,description:i?.requestParameter?.call(null,{method:C,path:k,operationId:ke})}),it={};for(let re of $e){let ge=g.getResponses(re);for(let{mimeTypes:pt,schema:Mt,statusCodes:Er}of ge)for(let Zt of Er)it[Zt]=Do({...Z,variant:re,schema:Mt,mimeTypes:pt,statusCode:Zt,hasMultipleStatusCodes:ge.length>1||Er.length>1,description:i?.[`${re}Response`]?.call(null,{method:C,path:k,operationId:ke,statusCode:Zt})})}let at=te.includes("body")?Go({...Z,request:nt,paramNames:Qo.pluck("name",st),schema:_,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:C,path:k,operationId:ke})}):void 0,zt=Jo(_o(ye,te),I,re=>{let ge=this.#s(re);return this.addSecurityScheme(ge,re),ge}),Lt={operationId:ke,summary:z,description:O,deprecated:g.isDeprecated||void 0,tags:Ot(g.tags),parameters:Ot(st),requestBody:at,security:Ot(zt),responses:it};this.addPath(qo(k),{[C]:Lt})}}),d&&(this.rootDoc.tags=Wo(d))}};var Pt=require("node-mocks-http");var us=e=>(0,Pt.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),fs=e=>(0,Pt.createResponse)(e),ys=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Yr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Xo=({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}},en=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Xo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},tn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=le}}=Xo(r),d=lt(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:oe(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var cn=y(require("ramda"),1),ot=y(require("typescript"),1),dn=require("zod/v4");var sn=y(require("ramda"),1),U=y(require("typescript"),1);var Y=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,wt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],gs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],tt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):w(e),Et=(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)),mr=(e,t=[])=>a.createConstructorDeclaration(tt.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&&Y.map(f,t)):e,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),we=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,dr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return p.length?pr(i,p.join(" ")):i},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&wt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>Q(e,a.createUnionTypeNode(Y.map(B,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&xr(n),t);return o?pr(s,o):s},rn=(e,t)=>a.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(tt.public,void 0,e,void 0,o&&xr(o),t,n,a.createBlock(r)),hr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&xr(r),void 0,t),br=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?wt:void 0,e,void 0,void 0,t);return o?pr(n,o):n},xr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Ee=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?Y.map(vt,e):_e(e),void 0,void 0,t),T=e=>e,rt=(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),At=(e,t)=>f("Extract",[e,t]),Sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),F=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),on=e=>a.createUnionTypeNode([f(e),kt(e)]),Rr=(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),B=e=>a.createLiteralTypeNode(w(e)),bs=[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],nn=e=>bs.includes(e.kind);var It=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=yr("Method",Xt);someOfType=Q("SomeOf",F("T",br("T")),{params:["T"]});requestType=Q("Request",br(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(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}])=>we(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(dr(t),a.createArrayLiteralExpression(sn.map(w,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,Rr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},kt(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Ee({[this.#e.requestParameter.text]:U.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=()=>j(this.#e.substituteFn,Ee({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr},a.createBlock([j(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],U.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Sr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[this.#e.keyParameter]),Ee([],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=()=>gr(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:F(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(fr(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:kt(F(this.interfaces.response,"K"))});makeClientClass=t=>hr(t,[mr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:tt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,Et("",[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"),rt(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),rt(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,rt(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=j(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(U.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=j(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,rt(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return j(this.#e.defaultImplementationConst,Ee([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=()=>mr(_e({request:"K",params:F(this.interfaces.input,"K")}),[j(fr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([we(T("event"),t)]);#i=()=>gr(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Rr({[this.#e.dataParameter.text]:F(At("R",ur(this.#s("E"))),B(T("data")))},on(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Ee([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:F("R",B(T("event")))}});makeSubscriptionClass=t=>hr(t,[rn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:At(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:At(F(this.interfaces.positive,"K"),ur(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(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"),Ee(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),b=y(require("typescript"),1),an=require("zod/v4");var Or=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=ee(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Or(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}=b.default,xs={[b.default.SyntaxKind.AnyKeyword]:"",[b.default.SyntaxKind.BigIntKeyword]:BigInt(0),[b.default.SyntaxKind.BooleanKeyword]:!1,[b.default.SyntaxKind.NumberKeyword]:0,[b.default.SyntaxKind.ObjectKeyword]:{},[b.default.SyntaxKind.StringKeyword]:"",[b.default.SyntaxKind.UndefinedKeyword]:void 0},Tr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ss=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.default.SyntaxKind.UndefinedKeyword):B(r));return t.length===1?t[0]:X.createUnionTypeNode(t)},Rs=(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}=an.globalRegistry.get(p)||{};return we(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return X.createTypeLiteralNode(s)};return Kr(e,{io:t?"output":"input"})?o(e,n):n()},Os=({_zod:{def:e}},{next:t})=>X.createArrayTypeNode(t(e.element)),Ts=({_zod:{def:e}})=>X.createUnionTypeNode(Object.values(e.entries).map(B)),Ps=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(nn(n)?n.kind:n,n)}return X.createUnionTypeNode(Array.from(r.values()))},ws=e=>xs?.[e.kind],Es=({_zod:{def:e}},{next:t})=>t(e.innerType),vs=({_zod:{def:e}},{next:t})=>X.createUnionTypeNode([t(e.innerType),B(null)]),ks=({_zod:{def:e}},{next:t})=>X.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:X.createRestTypeNode(t(e.rest)))),Cs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),As=v.tryCatch(e=>{if(!e.every(b.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Tr.name,...o))return!1;if(v.both(v.eqBy(Tr.type),v.eqBy(Tr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return X.createTypeLiteralNode(r)},(e,t)=>X.createIntersectionTypeNode(t)),Is=({_zod:{def:e}},{next:t})=>As([e.left,e.right].map(t)),D=e=>()=>f(e),Pr=({_zod:{def:e}},{next:t})=>t(e.innerType),pn=e=>f(e?b.default.SyntaxKind.UnknownKeyword:b.default.SyntaxKind.AnyKeyword),Ns=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!Ne(o,"transform"))return t(o);let s=t(n),i=ut(o,ws(s)),p={number:b.default.SyntaxKind.NumberKeyword,bigint:b.default.SyntaxKind.BigIntKeyword,boolean:b.default.SyntaxKind.BooleanKeyword,string:b.default.SyntaxKind.StringKeyword,undefined:b.default.SyntaxKind.UndefinedKeyword,object:b.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||pn(r))},js=()=>B(null),zs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ls=()=>f("Buffer"),Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:D(b.default.SyntaxKind.StringKeyword),number:D(b.default.SyntaxKind.NumberKeyword),bigint:D(b.default.SyntaxKind.BigIntKeyword),boolean:D(b.default.SyntaxKind.BooleanKeyword),any:D(b.default.SyntaxKind.AnyKeyword),undefined:D(b.default.SyntaxKind.UndefinedKeyword),[be]:D(b.default.SyntaxKind.StringKeyword),[xe]:D(b.default.SyntaxKind.StringKeyword),never:D(b.default.SyntaxKind.NeverKeyword),void:D(b.default.SyntaxKind.UndefinedKeyword),unknown:D(b.default.SyntaxKind.UnknownKeyword),null:js,array:Os,tuple:ks,record:Cs,object:Rs,literal:Ss,intersection:Is,union:Ps,default:Pr,enum:Ts,optional:Es,nullable:vs,catch:Pr,pipe:Ns,lazy:zs,readonly:Pr,[he]:Ls,[K]:Ms},wr=(e,{brandHandling:t,ctx:r})=>Or(e,{rules:{...t,...Zs},onMissing:({},{isResponse:o})=>pn(o),ctx:r});var Nt=class extends It{#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=B(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(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=dn.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}};De({routing:t,onEndpoint:(x,g,k)=>{let C=se.bind(null,k,g),{isDeprecated:Z,inputSchema:O,tags:N}=x,I=`${k} ${g}`,_=Q(C("input"),wr(O,c),{comment:I});this.#e.push(_);let z=$e.reduce((nt,ye)=>{let st=x.getResponses(ye),it=cn.chain(([zt,{schema:Lt,mimeTypes:re,statusCodes:ge}])=>{let pt=Q(C(ye,"variant",`${zt+1}`),wr(re?Lt:p,m),{comment:I});return this.#e.push(pt),ge.map(Mt=>we(Mt,pt.name))},Array.from(st.entries())),at=Ct(C(ye,"response","variants"),it,{comment:I});return this.#e.push(at),Object.assign(nt,{[ye]:at})},{});this.paths.add(g);let te=B(I),ke={input:f(_.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:a.createUnionTypeNode([F(this.interfaces.positive,te),F(this.interfaces.negative,te)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(I,{isDeprecated:Z,store:ke}),this.tags.set(I,N)}}),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:cr(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.#n(t),o=r&&
|
|
18
|
+
`))};var jo=e=>{e.startupLogo!==!1&&Co(process.stdout);let t=e.errorHandler||fe,r=Qr(e.logger)?e.logger:new Ke(e.logger);r.debug("Running",{build:"v24.1.0 (CJS)",env:process.env.NODE_ENV||"development"}),ko(r);let o=Eo({logger:r,config:e}),s={getLogger:vo(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=jo(e);return tr({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}=jo(e),p=(0,tt.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Fe("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||tt.default.json()],raw:[e.rawParser||tt.default.raw(),wo],form:[e.formParser||tt.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};tr({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 R=y(require("ramda"),1);var Mo=e=>L(e)&&"or"in e,$o=e=>L(e)&&"and"in e,rr=e=>!$o(e)&&!Mo(e),Zo=e=>{let t=R.filter(rr,e),r=R.chain(R.prop("and"),R.filter($o,e)),[o,n]=R.partition(rr,r),s=R.concat(t,o),i=R.filter(Mo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Oe(d,R.map(m=>rr(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var ge=require("openapi3-ts/oas31"),l=y(require("ramda"),1),or=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,qo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Uo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Fo=e=>e.replace(Zt,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)})},Ko=e=>e in Uo,Yn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Qn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Ee=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(Ko):t&&Ko(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Ee));return s&&(p.not=Ee(s)),p},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:qo}};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:qo}};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 Uo?.[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=Ee(ir(n,{ctx:r}));if((0,ge.isSchemaObject)(s))if(r.isResponse){let i=ft(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)?e:t.properties.raw},nr=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),Do=({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=lt(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),k=O=>b&&m.includes(O),A=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),H=O=>g&&(i?.(O,t,e)??as(O,A));return Object.entries(c.properties).reduce((O,[I,C])=>{let V=k(I)?"path":H(I)?"header":h?"query":void 0;if(!V)return O;let M=Ee(C),re=s==="components"?n(C.id||JSON.stringify(C),M,ae(d,I)):M;return O.concat({name:I,in:V,deprecated:C.deprecated,required:c.required?.includes(I)||!1,description:M.description||d,schema:re,examples:nr((0,ge.isSchemaObject)(M)&&M.examples?.length?M.examples:l.pluck(I,c.examples?.filter(l.both(L,l.has(I)))||[]))})},[])},sr={nullable:Wn,union:Vn,bigint:ts,intersection:Gn,tuple:rs,pipe:ss,literal:Qn,enum:Yn,[Se]:Xn,[Re]:es,[de]:_n,[U]: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,Ee(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ir=(e,{ctx:t,rules:r=sr})=>{let{$defs:o={},properties:n={}}=or.z.toJSONSchema(or.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(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} ${Kt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=Ee(ir(r,{rules:{...c,...sr},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:nr(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})=>ir(e,{rules:{...t,...sr},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(Ee(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:nr(h.length?h:De(o).examples?.filter(k=>L(k)&&!Array.isArray(k)).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)},[]),ar=e=>e.length<=Ho?e:e.slice(0,Ho-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Tt=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});_e({routing:t,onEndpoint:(g,k,A)=>{let H={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:C,inputSchema:V}=g,M=I?ar(I):m&&O?ar(O):void 0,re=r.inputSources?.[A]||Bt[A],Ce=this.#n(k,A,g.getOperationId(A)),st=Wo({...H,schema:V}),he=Zo(g.security),it=Do({...H,inputSources:re,isHeader:c,security:he,request:st,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Ce})}),at={};for(let oe of Be){let xe=g.getResponses(oe);for(let{mimeTypes:ct,schema:Mt,statusCodes:Er}of xe)for(let $t of Er)at[$t]=Jo({...H,variant:oe,schema:Mt,mimeTypes:ct,statusCode:$t,hasMultipleStatusCodes:xe.length>1||Er.length>1,description:i?.[`${oe}Response`]?.call(null,{method:A,path:k,operationId:Ce,statusCode:$t})})}let pt=re.includes("body")?Yo({...H,request:st,paramNames:en.pluck("name",it),schema:V,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Ce})}):void 0,zt=Go(Vo(he,re),C,oe=>{let xe=this.#s(oe);return this.addSecurityScheme(xe,oe),xe}),Lt={operationId:Ce,summary:M,description:O,deprecated:g.isDeprecated||void 0,tags:Ot(g.tags),parameters:Ot(it),requestBody:pt,security:Ot(zt),responses:at};this.addPath(Fo(k),{[A]:Lt})}}),d&&(this.rootDoc.tags=Qo(d))}};var Pt=require("node-mocks-http");var ys=e=>(0,Pt.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),gs=e=>(0,Pt.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=ut(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),nt=y(require("typescript"),1),ln=require("zod/v4");var pn=y(require("ramda"),1),_=y(require("typescript"),1);var X=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,wt=[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)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):w(e),Et=(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),Je=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),mr=(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,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),ve=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,dr(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?pr(i,p.join(" ")):i},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&wt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>ee(e,a.createUnionTypeNode(X.map(B,t)),{expose:!0}),ee=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&br(n),t);return o?pr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(rt.public,void 0,e,void 0,o&&br(o),t,n,a.createBlock(r)),hr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&br(r),void 0,t),xr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?wt:void 0,e,void 0,void 0,t);return o?pr(n,o):n},br=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):Je(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),Ve=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),D=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),kt(e)]),Rr=(e,t)=>a.createFunctionTypeNode(void 0,Je(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),B=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 It=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=yr("Method",Xt);someOfType=ee("SomeOf",D("T",xr("T")),{params:["T"]});requestType=ee("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(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}])=>ve(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(dr(t),a.createArrayLiteralExpression(pn.map(w,r))))),{expose:!0});makeImplementationType=()=>ee(this.#e.implementationType,Rr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:_.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},kt(_.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,ke({[this.#e.requestParameter.text]:_.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=()=>j(this.#e.substituteFn,ke({[this.#e.pathParameter.text]:_.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr},a.createBlock([j(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],_.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Sr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[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=()=>gr(this.#e.provideMethod,Je({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:D(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(fr(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:kt(D(this.interfaces.response,"K"))});makeClientClass=t=>hr(t,[mr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[Ve(URLSearchParams.name,t)]);#o=()=>Ve(URL.name,Et("",[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=j(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=j(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(_.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=j(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 j(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=()=>mr(Je({request:"K",params:D(this.interfaces.input,"K")}),[j(fr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ve("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([ve(T("event"),t)]);#i=()=>gr(this.#e.onMethod,Je({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Rr({[this.#e.dataParameter.text]:D(Ct("R",ur(this.#s("E"))),B(T("data")))},sn(_.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:D("R",B(T("event")))}});makeSubscriptionClass=t=>hr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ct(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(_.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ct(D(this.interfaces.positive,"K"),ur(this.#s(_.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Ve(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Ve(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ke(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Or=(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=>Or(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:z}=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},Tr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):B(r));return t.length===1?t[0]:z.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=z.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?z.createTemplateMiddle:z.createTemplateTail;s.push(z.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?z.createTemplateLiteralType(n,s):B(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 ve(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return z.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},ws=({_zod:{def:e}},{next:t})=>z.createArrayTypeNode(t(e.element)),Es=({_zod:{def:e}})=>z.createUnionTypeNode(Object.values(e.entries).map(B)),vs=({_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 z.createUnionTypeNode(Array.from(r.values()))},ks=e=>Rs?.[e.kind],As=({_zod:{def:e}},{next:t})=>t(e.innerType),Cs=({_zod:{def:e}},{next:t})=>z.createUnionTypeNode([t(e.innerType),B(null)]),Is=({_zod:{def:e}},{next:t})=>z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:z.createRestTypeNode(t(e.rest)))),Ns=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Tr.name,...o))return!1;if(v.both(v.eqBy(Tr.type),v.eqBy(Tr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return z.createTypeLiteralNode(r)},(e,t)=>z.createIntersectionTypeNode(t)),zs=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),J=e=>()=>f(e),Pr=({_zod:{def:e}},{next:t})=>t(e.innerType),dn=e=>f(e?x.default.SyntaxKind.UnknownKeyword:x.default.SyntaxKind.AnyKeyword),Ls=({_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=ft(o,ks(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))},Ms=()=>B(null),$s=({_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:J(x.default.SyntaxKind.StringKeyword),number:J(x.default.SyntaxKind.NumberKeyword),bigint:J(x.default.SyntaxKind.BigIntKeyword),boolean:J(x.default.SyntaxKind.BooleanKeyword),any:J(x.default.SyntaxKind.AnyKeyword),undefined:J(x.default.SyntaxKind.UndefinedKeyword),[Se]:J(x.default.SyntaxKind.StringKeyword),[Re]:J(x.default.SyntaxKind.StringKeyword),never:J(x.default.SyntaxKind.NeverKeyword),void:J(x.default.SyntaxKind.UndefinedKeyword),unknown:J(x.default.SyntaxKind.UnknownKeyword),null:Ms,array:ws,tuple:Is,record:Ns,object:Ps,literal:Os,template_literal:Ts,intersection:zs,union:vs,default:Pr,enum:Es,optional:As,nullable:Cs,catch:Pr,pipe:Ls,lazy:$s,readonly:Pr,[be]:Zs,[U]:Bs},wr=(e,{brandHandling:t,ctx:r})=>Or(e,{rules:{...t,...Hs},onMissing:({},{isResponse:o})=>dn(o),ctx:r});var Nt=class extends It{#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=B(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}};_e({routing:t,onEndpoint:(b,g,k)=>{let A=ae.bind(null,k,g),{isDeprecated:H,inputSchema:O,tags:I}=b,C=`${k} ${g}`,V=ee(A("input"),wr(O,c),{comment:C});this.#e.push(V);let M=Be.reduce((st,he)=>{let it=b.getResponses(he),at=mn.chain(([zt,{schema:Lt,mimeTypes:oe,statusCodes:xe}])=>{let ct=ee(A(he,"variant",`${zt+1}`),wr(oe?Lt:p,m),{comment:C});return this.#e.push(ct),xe.map(Mt=>ve(Mt,ct.name))},Array.from(it.entries())),pt=At(A(he,"response","variants"),at,{comment:C});return this.#e.push(pt),Object.assign(st,{[he]:pt})},{});this.paths.add(g);let re=B(C),Ce={input:f(V.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:a.createUnionTypeNode([D(this.interfaces.positive,re),D(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(C,{isDeprecated:H,store:Ce}),this.tags.set(C,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:cr(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.#n(t),o=r&&nt.default.addSyntheticLeadingComment(nt.default.addSyntheticLeadingComment(a.createEmptyStatement(),nt.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),nt.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.#e.concat(o||[]).map((n,s)=>cr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Fe("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Fe("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var Ae=require("zod/v4");var fn=(e,t)=>Ae.z.object({data:t,event:Ae.z.literal(e),id:Ae.z.string().optional(),retry:Ae.z.int().positive().optional()}),Ks=(e,t,r)=>fn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),qs=1e4,un=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Us=e=>new F({handler:async({response:t})=>setTimeout(()=>un(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{un(t),t.write(Ks(e,r,o),"utf-8"),t.flush?.()}}}),Fs=e=>new ue({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>fn(o,n));return{mimeType:E.sse,schema:r.length?Ae.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ae.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Pe(r);Qe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(we(i),"utf-8")}t.end()}}),jt=class extends ye{constructor(t){super(Fs(t)),this.middlewares=[Us(t)]}};var yn={dateIn:Ir,dateOut:jr,form:Lr,upload:$r,raw:Hr,buffer:mt};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
|
package/dist/index.d.cts
CHANGED
|
@@ -578,13 +578,12 @@ type Intact<T, U> = {
|
|
|
578
578
|
|
|
579
579
|
declare module "zod/v4/core" {
|
|
580
580
|
interface GlobalMeta {
|
|
581
|
-
deprecated?: boolean;
|
|
582
581
|
default?: unknown;
|
|
583
582
|
}
|
|
584
583
|
}
|
|
585
584
|
declare module "zod/v4" {
|
|
586
585
|
interface ZodType {
|
|
587
|
-
/** @desc
|
|
586
|
+
/** @desc Alias for .meta({examples}), but argument is typed to ensure the correct placement for transformations */
|
|
588
587
|
example(example: z.output<this>): this;
|
|
589
588
|
deprecated(): this;
|
|
590
589
|
}
|
|
@@ -902,6 +901,12 @@ declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<E
|
|
|
902
901
|
constructor(events: E);
|
|
903
902
|
}
|
|
904
903
|
|
|
904
|
+
/**
|
|
905
|
+
* @since zod 3.25.44
|
|
906
|
+
* @link https://github.com/colinhacks/zod/pull/4586
|
|
907
|
+
* */
|
|
908
|
+
declare const getExamples: (subject: $ZodType) => ReadonlyArray<unknown>;
|
|
909
|
+
|
|
905
910
|
declare const base: z.ZodObject<{
|
|
906
911
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
907
912
|
}, z.core.$strip>;
|
|
@@ -923,12 +928,12 @@ declare function raw(): Base;
|
|
|
923
928
|
declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
924
929
|
|
|
925
930
|
declare const ez: {
|
|
926
|
-
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.
|
|
927
|
-
dateOut: (
|
|
931
|
+
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>;
|
|
932
|
+
dateOut: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
928
933
|
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
|
|
929
934
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
|
930
935
|
raw: typeof raw;
|
|
931
936
|
buffer: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
932
937
|
};
|
|
933
938
|
|
|
934
|
-
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getMessageFromError, testEndpoint, testMiddleware };
|
|
939
|
+
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getExamples, getMessageFromError, testEndpoint, testMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -578,13 +578,12 @@ type Intact<T, U> = {
|
|
|
578
578
|
|
|
579
579
|
declare module "zod/v4/core" {
|
|
580
580
|
interface GlobalMeta {
|
|
581
|
-
deprecated?: boolean;
|
|
582
581
|
default?: unknown;
|
|
583
582
|
}
|
|
584
583
|
}
|
|
585
584
|
declare module "zod/v4" {
|
|
586
585
|
interface ZodType {
|
|
587
|
-
/** @desc
|
|
586
|
+
/** @desc Alias for .meta({examples}), but argument is typed to ensure the correct placement for transformations */
|
|
588
587
|
example(example: z.output<this>): this;
|
|
589
588
|
deprecated(): this;
|
|
590
589
|
}
|
|
@@ -902,6 +901,12 @@ declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<E
|
|
|
902
901
|
constructor(events: E);
|
|
903
902
|
}
|
|
904
903
|
|
|
904
|
+
/**
|
|
905
|
+
* @since zod 3.25.44
|
|
906
|
+
* @link https://github.com/colinhacks/zod/pull/4586
|
|
907
|
+
* */
|
|
908
|
+
declare const getExamples: (subject: $ZodType) => ReadonlyArray<unknown>;
|
|
909
|
+
|
|
905
910
|
declare const base: z.ZodObject<{
|
|
906
911
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
907
912
|
}, z.core.$strip>;
|
|
@@ -923,12 +928,12 @@ declare function raw(): Base;
|
|
|
923
928
|
declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
924
929
|
|
|
925
930
|
declare const ez: {
|
|
926
|
-
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.
|
|
927
|
-
dateOut: (
|
|
931
|
+
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>;
|
|
932
|
+
dateOut: (meta?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
928
933
|
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
|
|
929
934
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
|
930
935
|
raw: typeof raw;
|
|
931
936
|
buffer: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
932
937
|
};
|
|
933
938
|
|
|
934
|
-
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getMessageFromError, testEndpoint, testMiddleware };
|
|
939
|
+
export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getExamples, getMessageFromError, testEndpoint, testMiddleware };
|