express-zod-api 23.5.0 → 24.0.0-beta.2

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/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as U from"ramda";import{z as Ae}from"zod";import*as L from"ramda";import{z as hr}from"zod";var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var de=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},$=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.`}},tt=class extends Error{name="IOSchemaError"},me=class extends tt{constructor(r){super(le(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends tt{constructor(r){super(le(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(le(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},De=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ct=/:([A-Za-z0-9_]+)/g,rt=e=>e.match(Ct)?.map(t=>t.slice(1))||[],Vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},jt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Go=["body","query","params"],Nt=e=>e.method.toLowerCase(),ot=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||jt[r]||Go).filter(o=>o==="files"?Vo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),le=e=>e instanceof hr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof me?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Jo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return ue(t,(n[g]?.examples||[]).map(L.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof hr.ZodObject&&(n=Jo(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},ue=(e,t,r)=>e.length&&t.length?L.xprod(e,t).map(r):e.concat(t),Mt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=L.chain(o=>o.split(/[^A-Z0-9]/gi),e);return L.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Mt).join("")},nt=L.tryCatch((e,t)=>typeof e.parse(t),L.always(void 0)),fe=e=>typeof e=="object"&&e!==null,ye=L.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as st from"ramda";var g=Symbol.for("express-zod-api"),Ke=e=>{let t=e.describe(e.description);return t._def[g]=st.clone(t._def[g])||{examples:[]},t},br=(e,t)=>{if(!(g in e._def))return t;let r=Ke(t);return r._def[g].examples=ue(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?st.mergeDeepRight({...o},{...n}):n),r};var Wo=function(e){let t=Ke(this);return t._def[g].examples.push(e),t},Yo=function(){let e=Ke(this);return e._def[g].isDeprecated=!0,e},Qo=function(e){let t=Ke(this);return t._def[g].defaultLabel=e,t},Xo=function(e){return new Ae.ZodBranded({typeName:Ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...U.clone(this._def[g]),brand:e}})},en=function(e){let t=typeof e=="function"?e:U.pipe(U.toPairs,U.map(([n,s])=>U.pair(e[String(n)]||n,s)),U.fromPairs),r=t(U.clone(this.shape)),o=Ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Ae.ZodType.prototype,{example:{get(){return Wo.bind(this)}},deprecated:{get(){return Yo.bind(this)}},brand:{set(){},get(){return Xo.bind(this)}}}),Object.defineProperty(Ae.ZodDefault.prototype,"label",{get(){return Qo.bind(this)}}),Object.defineProperty(Ae.ZodObject.prototype,"remap",{get(){return en.bind(this)}}));function tn(e){return e}import{z as Lr}from"zod";import*as ve from"ramda";import{z as jr}from"zod";import{fail as N}from"node:assert/strict";import{z as Fe}from"zod";var it=e=>!isNaN(e.getTime());var ge=Symbol("DateIn"),xr=()=>Fe.union([Fe.string().date(),Fe.string().datetime(),Fe.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Fe.date().refine(it)).brand(ge);import{z as rn}from"zod";var he=Symbol("DateOut"),Sr=()=>rn.date().refine(it).transform(e=>e.toISOString()).brand(he);import{z as at}from"zod";var G=Symbol("File"),Rr=at.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),on={buffer:()=>Rr.brand(G),string:()=>at.string().brand(G),binary:()=>Rr.or(at.string()).brand(G),base64:()=>at.string().base64().brand(G)};function pt(e){return on[e||"string"]()}import{z as Tr}from"zod";var ct=Symbol("Form"),Or=e=>(e instanceof Tr.ZodObject?e:Tr.object(e)).brand(ct);import{z as nn}from"zod";var ie=Symbol("Raw"),Pr=nn.object({raw:pt("buffer")});function wr(e){return(e?Pr.extend(e):Pr).brand(ie)}import{z as sn}from"zod";var Ee=Symbol("Upload"),Ar=()=>sn.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ee);var Er=(e,{next:t})=>e.options.some(t),an=({_def:e},{next:t})=>[e.left,e.right].some(t),dt=(e,{next:t})=>t(e.unwrap()),mt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Er,ZodDiscriminatedUnion:Er,ZodIntersection:an,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:dt,ZodNullable:dt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},qe=(e,{condition:t,rules:r=mt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>qe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},zr=e=>qe(e,{condition:t=>t._def[g]?.brand===Ee,rules:{...mt,[ct]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Zr=e=>qe(e,{condition:t=>t._def[g]?.brand===ie,maxDepth:3}),Ir=e=>qe(e,{condition:t=>t._def[g]?.brand===ct,maxDepth:3}),vr=(e,t)=>{let r=new WeakSet;return qe(e,{maxDepth:300,rules:{...mt,ZodBranded:dt,ZodReadonly:dt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:mt.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[he]:()=>t==="in"&&N("ez.dateOut()"),[ge]:()=>t==="out"&&N("ez.dateIn()"),[ie]:()=>t==="out"&&N("ez.raw()"),[Ee]:()=>t==="out"&&N("ez.upload()"),[G]:()=>!1}})};import dn,{isHttpError as mn}from"http-errors";import kr,{isHttpError as pn}from"http-errors";import{z as cn}from"zod";var Lt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof cn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},Be=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ze=e=>pn(e)?e:kr(e instanceof ee?400:500,le(e),{cause:e.cause||e}),be=e=>ye()&&!e.expose?kr(e.statusCode).message:e.message;var lt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=be(dn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:mn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Cr}from"zod";var Ut=class{},J=class extends Ut{#e;#t;#r;constructor({input:t=Cr.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 Cr.ZodError?new ee(o):o}}},Ze=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var $e=class extends Ie{},ut=class e extends $e{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){return zr(this.#e.inputSchema)?"upload":Zr(this.#e.inputSchema)?"raw":Ir(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ve.pluck("security",this.#e.middlewares||[]);return ve.reject(ve.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof jr.ZodError?new me(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ze))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof jr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){lt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),a={},c=null,m=null,p=ot(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import*as Nr from"ramda";import{z as xe}from"zod";var Mr=(e,t)=>{let r=Nr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>br(s,n),o)},_=e=>e instanceof xe.ZodObject?e:e instanceof xe.ZodBranded?_(e.unwrap()):e instanceof xe.ZodUnion||e instanceof xe.ZodDiscriminatedUnion?e.options.map(t=>_(t)).reduce((t,r)=>t.merge(r.partial()),xe.object({})):e instanceof xe.ZodEffects?_(e._def.schema):e instanceof xe.ZodPipeline?_(e._def.in):_(e._def.left).merge(_(e._def.right));import{z as W}from"zod";var ke={positive:200,negative:400},Ce=Object.keys(ke);var Ht=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Ht{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Lt(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[Z.json]})}getNegativeResponse(){return Lt(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[Z.json]})}},Re=new Se({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=ze(e);return Be(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:be(a)}})}n.status(ke.positive).json({status:"success",data:r})}}),Dt=new Se({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>fe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);return Be(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(be(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Te=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=Lr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,h=typeof o=="function"?o:()=>o,y=typeof n=="string"?[n]:n||[],R=typeof s=="string"?[s]:s||[];return new ut({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:y,tags:R,methods:l,getOperationId:h,inputSchema:Mr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Lr.object({}),handler:async o=>(await t(o),{})})}},ln=new Te(Re),un=new Te(Dt);import Sn from"ansis";import{inspect as Rn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as fn,green as yn,hex as gn,red as hn,cyanBright as bn}from"ansis";import*as Ur from"ramda";var Kt={debug:fn,info:yn,warn:gn("#FFA500"),error:hn,ctx:bn},ft={debug:10,info:20,warn:30,error:40},Hr=e=>fe(e)&&Object.keys(ft).some(t=>t in e),Dr=e=>e in ft,Kr=(e,t)=>ft[e]<ft[t],xn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),je=Ur.memoizeWith((e,t)=>`${e}${t}`,xn),Fr=e=>e<1e-6?je("nanosecond",3).format(e/1e-6):e<.001?je("nanosecond").format(e/1e-6):e<1?je("microsecond").format(e/.001):e<1e3?je("millisecond").format(e):e<6e4?je("second",2).format(e/1e3):je("minute",2).format(e/6e4);var _e=class e{config;constructor({color:t=Sn.isSupported(),level:r=ye()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return Rn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Kr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Kt.ctx(s):s),m.push(c?`${Kt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:a=Fr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as Br from"ramda";var Ve=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Tn from"express";var Ge=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Tn.static(...this.#e))}};import ht from"express";import Nn from"node:http";import Mn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new De(e)};import An from"http-errors";import*as $r from"ramda";var yt=class{constructor(t){this.logger=t}#e=$r.tryCatch(vr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of Ce){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(Z.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=rt(t);if(s.length===0)return;let{shape:a}=n||_(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Ft=["get","post","put","delete","patch"],_r=e=>Ft.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&_r(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),Vr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=On(r);return[[t||""].concat(Pn(n)||[]).join("/"),o,s]}),wn=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},Gr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},qt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},Me=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Vr(e),n=new Set;for(;o.length;){let[s,a,c]=o.shift();if(a instanceof $e)if(c)qt(c,s,n),Gr(c,s,a.methods),t(a,s,c);else{let{methods:m=["get"]}=a;for(let p of m)qt(p,s,n),t(a,s,p)}else if(c&&wn(c,s),a instanceof Ge)r&&a.apply(s,r);else if(a instanceof Ve)for(let[m,p]of a.entries){let{methods:l}=p;qt(m,s,n),Gr(m,s,l),t(p,s,m)}else o.unshift(...Vr(a,s))}};import*as Jr from"ramda";var Wr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=Wr(e);r.set({Allow:n});let s=An(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},zn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Wr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ye()?void 0:new yt(t()),a=new Map;Me({routing:o,onEndpoint:(p,l,h)=>{ye()||(s?.checkJsonCompat(p,{path:l,method:h}),s?.checkPathParams(l,p,{method:h}));let y=n?.[p.requestType]||[],R=Jr.pair(y,p);a.has(l)||a.set(l,new Map(r.cors?[["options",R]]:[])),a.get(l)?.set(h,R)},onStatic:e.use.bind(e)}),s=void 0;let m=new Map;for(let[p,l]of a){let h=Array.from(l.keys());for(let[y,[R,x]]of l){let P=async(S,D)=>{let C=t(S);if(r.cors){let T=zn(h),I=typeof r.cors=="function"?await r.cors({request:S,endpoint:x,logger:C,defaultHeaders:T}):T;D.set(I)}return x.execute({request:S,response:D,logger:C,config:r})};e[y](p,...R,P)}r.wrongMethodBehavior!==404&&m.set(p,En(h))}for(let[p,l]of m)e.all(p,l)};import In from"http-errors";import{setInterval as Zn}from"node:timers/promises";var Yr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Qr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Xr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,eo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),to=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var ro=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Yr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",eo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Xr(p)||Qr(p))&&a(p);for await(let p of Zn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(to))};return{sockets:n,shutdown:()=>o??=m()}};var oo=({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(),no=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=In(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){lt({response:o,logger:s,error:new re(oe(a),n)})}},vn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},kn=e=>({log:e.debug.bind(e)}),so=async({getLogger:e,config:t})=>{let r=await Ne("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:kn(l)})(c,m,p)}),o&&a.push(vn(o)),a},io=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ao=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[g]={logger:a}),s()},po=e=>t=>t?.res?.locals[g]?.logger||e,co=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),mo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=ro(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as Cn,hex as lo,italic as gt,whiteBright as jn}from"ansis";var uo=e=>{if(e.columns<132)return;let t=gt("Proudly supports transgender community.".padStart(109)),r=gt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=gt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=gt("for Sonia".padEnd(20)),s=lo("#F5A9B8"),a=lo("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(jn,5,7).fill(s,7,9).fill(a,9,12).fill(Cn,12,13),m=`
1
+ import*as L from"ramda";import{z as Y}from"zod/v4";import*as z from"ramda";import{globalRegistry as Bo,z as At}from"zod/v4";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var de=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},$e=class extends Error{name="IOSchemaError"},et=class extends $e{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},me=class extends $e{constructor(r){super(te(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends $e{constructor(r){super(te(r),{cause:r});this.cause=r}name="InputValidationError"},ee=class extends Error{constructor(r,o){super(te(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},He=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ct=/:([A-Za-z0-9_]+)/g,tt=e=>e.match(Ct)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},It={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Uo=["body","query","params"],Nt=e=>e.method.toLowerCase(),rt=(e,t={})=>{let r=Nt(e);return r==="options"?{}:(t[r]||It[r]||Uo).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof At.ZodError?new Error(te(e),{cause:e}):new Error(String(e)),te=e=>e instanceof At.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof me?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,$=(e,t)=>e._zod.def.type===t,ot=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=Bo.get(o)||{};return le(t,n.map(z.objOf(r)),([s,i])=>({...s,...i}))},[]),le=(e,t,r)=>e.length&&t.length?z.xprod(e,t).map(r):e.concat(t),zt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),oe=(...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(zt).join("")},nt=z.tryCatch((e,t)=>typeof At.parse(e,t),z.always(void 0)),st=({_zod:{optin:e,optout:t}},{isResponse:r})=>(r?t:e)==="optional",j=e=>typeof e=="object"&&e!==null,ue=z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as gr from"ramda";var Pe=Symbol.for("express-zod-api"),hr=(e,t)=>{let{examples:r=$(e,"object")?ot(e):void 0}=e.meta()||{};if(!r?.length)return t;let{examples:o=[]}=t.meta()||{},n=le(o,r,([s,i])=>typeof s=="object"&&typeof i=="object"&&s&&i?gr.mergeDeepRight(s,i):i);return t.meta({examples:n})},W=e=>{let{brand:t}=e._zod.bag;if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Do=Y.core.$constructor("$EZBrandCheck",(e,t)=>{Y.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),_o=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Vo=function(){return this.meta({deprecated:!0})},Jo=function(e){return this.meta({default:e})},Go=function(e){return this.check(new Do({brand:e,check:"$EZBrandCheck"}))},Wo=function(e){let t=typeof e=="function"?e:L.pipe(L.toPairs,L.map(([s,i])=>L.pair(e[String(s)]||s,i)),L.fromPairs),r=t(L.map(L.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof Y.ZodUnknown?Y.looseObject:Y.object)(r);return this.transform(t).pipe(n)};if(!(Pe in globalThis)){globalThis[Pe]=!0;for(let e of Object.keys(Y)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=Y[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return _o.bind(this)}},deprecated:{get(){return Vo.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}})}Object.defineProperty(Y.ZodDefault.prototype,"label",{get(){return Jo.bind(this)}}),Object.defineProperty(Y.ZodObject.prototype,"remap",{get(){return Wo.bind(this)}})}function Yo(e){return e}import{z as Lr}from"zod/v4";import*as ke from"ramda";import{z as Nr}from"zod/v4";import*as ie from"ramda";import{z as Er}from"zod/v4";import{z as Ke}from"zod/v4";var fe=Symbol("DateIn"),br=()=>Ke.union([Ke.iso.date(),Ke.iso.datetime(),Ke.iso.datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ke.date()).brand(fe);import{z as Qo}from"zod/v4";var ye=Symbol("DateOut"),xr=()=>Qo.date().transform(e=>e.toISOString()).brand(ye);import{z as Sr}from"zod/v4";var qe=Symbol("Form"),Rr=e=>(e instanceof Sr.ZodObject?e:Sr.object(e)).brand(qe);import{z as Xo}from"zod/v4";var ne=Symbol("Upload"),Or=()=>Xo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ne);import{z as tn}from"zod/v4";import{z as it}from"zod/v4";var se=Symbol("File"),Tr=it.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),en={buffer:()=>Tr.brand(se),string:()=>it.string().brand(se),binary:()=>Tr.or(it.string()).brand(se),base64:()=>it.base64().brand(se)};function at(e){return en[e||"string"]()}var H=Symbol("Raw"),Pr=tn.object({raw:at("buffer")}),rn=e=>Pr.extend(e).brand(H);function wr(e){return e?rn(e):Pr.brand(H)}var vr=(e,{io:t,condition:r})=>ie.tryCatch(()=>{Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new et(o)}})},o=>o.cause)(),kr=(e,{io:t})=>{let o=[Er.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(ie.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ie.values(n))}ie.is(Array,n)&&o.push(...ie.values(n))}return!1},Ar=e=>vr(e,{condition:t=>{let r=W(t);return typeof r=="symbol"&&[ne,H,qe].includes(r)},io:"input"}),on=["nan","symbol","map","set","bigint","void","promise","never"],jt=(e,t)=>vr(e,{io:t,condition:r=>{let o=W(r),{type:n}=r._zod.def;return!!(on.includes(n)||t==="input"&&(n==="date"||o===ye)||t==="output"&&(o===fe||o===H||o===ne))}});import an,{isHttpError as pn}from"http-errors";import Cr,{isHttpError as nn}from"http-errors";import{z as sn}from"zod/v4";var Lt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof sn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ee(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}))},Be=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>nn(e)?e:Cr(e instanceof G?400:500,te(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?Cr(e.statusCode).message:e.message;var pt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(an(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:pn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod/v4";var Mt=class{},U=class extends Mt{#e;#t;#r;constructor({input:t=Ir.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 Ir.ZodError?new G(o):o}}},Ee=class extends U{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 ve=class{nest(t){return Object.assign(t,{"":this})}};var Fe=class extends ve{},ct=class e extends Fe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}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.#e.outputSchema}get requestType(){let t=Ar(this.#e.inputSchema);if(t){let r=W(t);if(r===ne)return"upload";if(r===H)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ke.pluck("security",this.#e.middlewares||[]);return ke.reject(ke.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#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new me(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){pt({...t,error:new ee(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),i={},p={output:{},error:null},d=rt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as zr from"ramda";var jr=(e,t)=>{let r=zr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>hr(s,n),o)};import{globalRegistry as dt,z as K}from"zod/v4";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends Zt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Lt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Lt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},be=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{};!t.length&&$(e,"object")&&t.push(...ot(e)),t.length&&!dt.has(e)&&dt.add(e,{examples:t});let r=K.object({status:K.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=we(e);return Be(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ge(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),$t=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{},r=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());return t.reduce((o,n)=>j(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Be(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ge(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ae.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof U?t:new U(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new U({handler:t})),this.resultHandler)}build({input:t=Lr.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new ct({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Lr.object({}),handler:async o=>(await t(o),{})})}},cn=new xe(be),dn=new xe($t);import hn from"ansis";import{inspect as bn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as Mr from"ramda";var Ht={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},mt={debug:10,info:20,warn:30,error:40},Zr=e=>j(e)&&Object.keys(mt).some(t=>t in e),$r=e=>e in mt,Hr=(e,t)=>mt[e]<mt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=Mr.memoizeWith((e,t)=>`${e}${t}`,gn),Kr=e=>e<1e-6?Ie("nanosecond",3).format(e/1e-6):e<.001?Ie("nanosecond").format(e/1e-6):e<1?Ie("microsecond").format(e/.001):e<1e3?Ie("millisecond").format(e):e<6e4?Ie("second",2).format(e/1e3):Ie("minute",2).format(e/6e4);var Ue=class e{config;constructor({color:t=hn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return bn(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"||Hr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Ht.ctx(s):s),d.push(p?`${Ht[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=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:i=Kr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Br from"ramda";var De=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import xn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,xn.static(...this.#e))}};import ft from"express";import Ln from"node:http";import Mn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new He(e)};import En from"http-errors";import{z as Ur}from"zod/v4";import*as S from"ramda";var Sn=e=>e.type==="object",Rn=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")}),On=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),Fr=S.pair(!0),ze=(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"&&On(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Fr,i.anyOf)),i.oneOf&&r.push(...S.map(Fr,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(j)||[],i.examples.filter(j),([p,d])=>S.mergeDeepRight(p,d))),!!Sn(i)&&(i.properties&&(o.properties=(t==="throw"?Rn: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};var lt=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=[Ur.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=jt(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ce)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=jt(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=tt(t);if(s.length===0)return;let i=n?.flat||ze(Ur.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 Kt=["get","post","put","delete","patch"],Dr=e=>Kt.includes(e);var Tn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Dr(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),_r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Tn(r);return[[t||""].concat(Pn(n)||[]).join("/"),o,s]}),wn=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},qt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Fe)if(p)qt(p,s,n),Vr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)qt(c,s,n),t(i,s,c)}else if(p&&wn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;qt(d,s,n),Vr(d,s,m),t(c,s,d)}else o.unshift(..._r(i,s))}};import*as Jr from"ramda";var Gr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=En(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new lt(t()),i=new Map;je({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let h=n?.[c.requestType]||[],y=Jr.pair(h,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[h,[y,v]]of m){let k=async(M,R)=>{let A=t(M);if(r.cors){let C=kn(g),F=typeof r.cors=="function"?await r.cors({request:M,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(F)}return v.execute({request:M,response:R,logger:A,config:r})};e[h](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import Cn from"http-errors";import{setInterval as An}from"node:timers/promises";var Wr=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",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(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",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of An(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Cn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){pt({response:o,logger:s,error:new ee(re(i),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Ne("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:Nn(m)})(p,d,c)}),o&&i.push(In(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Pe]={logger:i}),s()},ao=e=>t=>t?.res?.locals[Pe]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),co=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=to(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let i of o)process.on(i,s)};import{gray as zn,hex as mo,italic as ut,whiteBright as jn}from"ansis";var lo=e=>{if(e.columns<132)return;let t=ut("Proudly supports transgender community.".padStart(109)),r=ut("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=ut("Thank you for choosing Express Zod API for your project.".padStart(132)),n=ut("for Ashley".padEnd(20)),s=mo("#F5A9B8"),i=mo("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(jn,5,7).fill(s,7,9).fill(i,9,12).fill(zn,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
@@ -13,11 +13,11 @@ Original error: ${e.handled.message}.`:""),{expose:mn(e.cause)?e.cause.expose:!1
13
13
  888${t}
14
14
  ${n}888${r}
15
15
  ${o}
16
- `;e.write(m.split(`
17
- `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||Re,r=Hr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v23.5.0 (ESM)",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},a=no(s),c=oo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return Bt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Un=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=fo(e),c=ht().disable("x-powered-by").use(a);if(e.compression){let y=await Ne("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ht.json()],raw:[e.rawParser||ht.raw(),io],form:[e.formParser||ht.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};Bt({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(y,R)=>()=>y.listen(R,()=>r.info("Listening",R)),h=[];if(e.http){let y=Nn.createServer(c);p.push(y),h.push(l(y,e.http.listen))}if(e.https){let y=Mn.createServer(e.https.options,c);p.push(y),h.push(l(y,e.https.listen))}return e.gracefulShutdown&&mo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(y=>y())}};import{OpenApiBuilder as Cs}from"openapi3-ts/oas31";import*as Lo from"ramda";import*as O from"ramda";var yo=e=>fe(e)&&"or"in e,go=e=>fe(e)&&"and"in e,$t=e=>!go(e)&&!yo(e),ho=e=>{let t=O.filter($t,e),r=O.chain(O.prop("and"),O.filter(go,e)),[o,n]=O.partition($t,r),s=O.concat(t,o),a=O.filter(yo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>ue(m,O.map(l=>$t(l)?[l]:l.and,p),([l,h])=>O.concat(l,h)),O.reject(O.isEmpty,[s]))};import{isReferenceObject as _t,isSchemaObject as xt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as F}from"zod";var Oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Oe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var 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 xo=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dn=/^\d{4}-\d{2}-\d{2}$/,Kn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Fn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Oo=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Bn=({_def:{innerType:e}},{next:t})=>t(e),$n=()=>({format:"any"}),_n=({},e)=>{if(e.isResponse)throw new $("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Vn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Gn=({options:e},{next:t})=>({oneOf:e.map(t)}),Jn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Wn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Po={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Wn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>ue(e,t,([r,o])=>d.mergeDeepRight(r,o))},Yn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Po)),d.isEmpty)),Qn=d.tryCatch(e=>{let[t,r]=e.filter(xt).filter(Yn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Po);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Xn=({_def:{left:e,right:t}},{next:r})=>Qn([e,t].map(r)),es=(e,{next:t})=>t(e.unwrap()),ts=(e,{next:t})=>t(e.unwrap()),rs=(e,{next:t})=>{let r=t(e.unwrap());return xt(r)&&(r.type=Ao(r)),r},os=e=>e in To,wo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":os(t)?t:void 0},So=e=>({type:wo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ns=({value:e})=>({type:wo(e),const:e}),ss=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=bt(e,r)),s.length&&(a.required=s),a},is=()=>({type:"null"}),as=({},e)=>{if(e.isResponse)throw new $("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}}},ps=({},e)=>{if(!e.isResponse)throw new $("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}}},cs=({},e)=>{throw new $(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ds=()=>({type:"boolean"}),ms=()=>({type:"integer",format:"bigint"}),ls=e=>e.every(t=>t instanceof F.ZodLiteral),us=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof F.ZodEnum||e instanceof F.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=bt(F.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:bt(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&ls(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:bt(F.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},fs=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ys=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),gs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:y,isTime:R,isBase64:x,isNANOID:P,isBase64url:S,isDuration:D,_def:{checks:C}})=>{let T=C.find(k=>k.kind==="regex"),I=C.find(k=>k.kind==="datetime"),K=C.some(k=>k.kind==="jwt"),M=C.find(k=>k.kind==="length"),w={type:"string"},B={"date-time":l,byte:x,base64url:S,date:y,time:R,duration:D,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:P,jwt:K,ip:m,cidr:h,emoji:p};for(let k in B)if(B[k]){w.format=k;break}return M&&([w.minLength,w.maxLength]=[M.value,M.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),y&&(w.pattern=Dn.source),R&&(w.pattern=Kn.source),l&&(w.pattern=Fn(I?.offset).source),T&&(w.pattern=T.regex.source),w},hs=2**32-1,bs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(S=>S.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(S=>S.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,y=l?l.inclusive:!0,R=s?s[1]-s[0]<=hs?"int32":"int64":void 0,P={type:e?"integer":"number",format:e?R:"double"};return p?P.minimum=m:P.exclusiveMinimum=m,y?P.maximum=h:P.exclusiveMaximum=h,P},bt=({shape:e},t)=>d.map(t,e),xs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},Ao=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&xt(o)){let s=nt(e,xs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&&xt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Rs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ts=(e,{next:t})=>t(e.unwrap()),Os=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ps=(e,{next:t})=>t(e.unwrap().shape.raw),Eo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,zo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Eo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ws=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Eo)({schema:e,variant:"original",validate:!0,pullProps:!0}),As=(e,t)=>t?.includes(e)||e.startsWith("x-")||bo.includes(e),Zo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=_(r),y=rt(e),R=o.includes("query"),x=o.includes("params"),P=o.includes("headers"),S=T=>x&&y.includes(T),D=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),C=T=>P&&(c?.(T,t,e)??As(T,D));return Object.entries(h.shape).reduce((T,[I,K])=>{let M=S(I)?"path":C(I)?"header":R?"query":void 0;if(!M)return T;let w=Oe(K,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),B=s==="components"?n(K,w,se(l,I)):w,{_def:k}=K;return T.concat({name:I,in:M,deprecated:k[g]?.isDeprecated,required:!K.isOptional(),description:w.description||l,schema:B,examples:ws(h,I)})},[])},Vt={ZodString:gs,ZodNumber:bs,ZodBigInt:ms,ZodBoolean:ds,ZodNull:is,ZodArray:fs,ZodTuple:ys,ZodRecord:us,ZodObject:ss,ZodLiteral:ns,ZodIntersection:Xn,ZodUnion:Gn,ZodAny:$n,ZodDefault:qn,ZodEnum:So,ZodNativeEnum:So,ZodEffects:Ss,ZodOptional:es,ZodNullable:rs,ZodDiscriminatedUnion:Jn,ZodBranded:Ts,ZodDate:cs,ZodCatch:Bn,ZodPipeline:Rs,ZodLazy:Os,ZodReadonly:ts,[G]:Vn,[Ee]:_n,[he]:ps,[ge]:as,[ie]:Ps},Gt=(e,{isResponse:t,prev:r})=>{if(_t(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[g]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Ao(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},Jt=(e,t)=>{throw new $(`Zod type ${e.constructor.name} is unsupported.`,t)},Io=(e,t)=>{if(_t(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Io(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},vo=e=>_t(e)?e:d.omit(["examples"],e),ko=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Mt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let y=vo(Oe(r,{rules:{...p,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,y,se(h)):y,examples:zo(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[R]))}},Es=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},zs=({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},Zs=({name:e})=>({type:"apiKey",in:"header",name:e}),Is=({name:e})=>({type:"apiKey",in:"cookie",name:e}),vs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ks=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Es(o):o.type==="input"?zs(o,t):o.type==="header"?Zs(o):o.type==="cookie"?Is(o):o.type==="openid"?vs(o):ks(o);return e.map(o=>o.map(r))},jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),No=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=Io(Oe(r,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),y=vo(l),R={schema:s==="components"?n(r,y,se(p)):y,examples:zo(_(r),!1,c)},x={description:p,content:{[o]:R}};return(h||o===Z.raw)&&(x.required=!0),x},Mo=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)},[]),Wt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Yt=class extends Cs{#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),typeof r=="function"&&(r=r())),typeof r=="object"&&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 $(`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:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});Me({routing:t,onEndpoint:(x,P,S)=>{let D={path:P,method:S,endpoint:x,composition:y,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:C,shortDescription:T,scopes:I,inputSchema:K}=x,M=T?Wt(T):h&&C?Wt(C):void 0,w=r.inputSources?.[S]||jt[S],B=this.#n(P,S,x.getOperationId(S)),k=ho(x.security),pe=Zo({...D,inputSources:w,isHeader:p,security:k,schema:K,description:a?.requestParameter?.call(null,{method:S,path:P,operationId:B})}),Ye={};for(let te of Ce){let ce=x.getResponses(te);for(let{mimeTypes:vt,schema:Xe,statusCodes:et}of ce)for(let kt of et)Ye[kt]=ko({...D,variant:te,schema:Xe,mimeTypes:vt,statusCode:kt,hasMultipleStatusCodes:ce.length>1||et.length>1,description:a?.[`${te}Response`]?.call(null,{method:S,path:P,operationId:B,statusCode:kt})})}let Zt=w.includes("body")?No({...D,paramNames:Lo.pluck("name",pe),schema:K,mimeType:Z[x.requestType],description:a?.requestBody?.call(null,{method:S,path:P,operationId:B})}):void 0,Qe=jo(Co(k,w),I,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),It={operationId:B,summary:M,description:C,deprecated:x.isDeprecated||void 0,tags:St(x.tags),parameters:St(pe),requestBody:Zt,security:St(Qe),responses:Ye};this.addPath(Oo(P),{[S]:It})}}),m&&(this.rootDoc.tags=Mo(m))}};import{createRequest as js,createResponse as Ns}from"node-mocks-http";var Ms=e=>js({...e,headers:{"content-type":Z.json,...e?.headers}}),Ls=e=>Ns(e),Us=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Uo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ms(e),s=Ls({req:n,...t});s.req=t?.req||n,n.res=s;let a=Us(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Uo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ds=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Re}}=Uo(r),m=ot(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Bo from"ramda";import zt from"typescript";import{z as fi}from"zod";import*as Fo from"ramda";import X from"typescript";import*as Y from"ramda";import u from"typescript";var i=u.factory,Rt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Ks=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Je={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Qt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Xt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Fs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,er=e=>typeof e=="string"&&Fs.test(e)?i.createIdentifier(e):z(e),Tt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Ot=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>Ot(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),tr=(e,t=[])=>i.createConstructorDeclaration(Je.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,rr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Pe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,er(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Qt(s,a.join(" ")):s},or=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),nr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Rt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),sr=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Rt:void 0,e,n&&cr(n),t);return o?Qt(s,o):s},Ho=(e,t)=>i.createPropertyDeclaration(Je.public,e,void 0,f(t),void 0),ir=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Je.public,void 0,e,void 0,o&&cr(o),t,n,i.createBlock(r)),ar=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Rt,e,r&&cr(r),void 0,t),pr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Qt(n,o):n},cr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ks:void 0,void 0,Array.isArray(e)?Y.map(Ot,e):Le(e),void 0,void 0,t),A=e=>e,We=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ue=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),At=(e,t)=>f("Extract",[e,t]),dr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),V=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Do=e=>i.createUnionTypeNode([f(e),Pt(e)]),mr=(e,t)=>i.createFunctionTypeNode(void 0,Le(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),H=e=>i.createLiteralTypeNode(z(e)),qs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Ko=e=>qs.includes(e.kind);var Et=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=sr("Method",Ft);someOfType=Q("SomeOf",V("T",pr("T")),{params:["T"]});requestType=Q("Request",pr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Pe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(er(t),i.createArrayLiteralExpression(Fo.map(z,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,mr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Pt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,we({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,we({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([dr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(Tt(":",[this.#e.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ir(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:V(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(nr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Pt(V(this.interfaces.response,"K"))});makeClientClass=t=>ar(t,[tr([Ot(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Je.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Tt("?",[Ue(URLSearchParams.name,t)]);#o=()=>Ue(URL.name,Tt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),We(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(Z.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),We(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,We(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(Z.json))),l=i.createReturnStatement(E(this.#e.responseConst,We(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return j(this.#e.defaultImplementationConst,we([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>tr(Le({request:"K",params:V(this.interfaces.input,"K")}),[j(nr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),dr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Ue("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Pe(A("event"),t)]);#i=()=>ir(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:mr({[this.#e.dataParameter.text]:V(At("R",or(this.#s("E"))),H(A("data")))},Do(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,we([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:V("R",H(A("event")))}});makeSubscriptionClass=t=>ar(t,[Ho(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:At(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:At(V(this.interfaces.positive,"K"),or(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Ue(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Ue(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),we(["time"],i.createBlock([])))]};import*as v from"ramda";import b from"typescript";import{z as ur}from"zod";var{factory:q}=b,Bs={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},lr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},$s=({value:e})=>H(e),_s=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof ur.ZodOptional:a.isOptional();return Pe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return q.createTypeLiteralNode(n)},Vs=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),Gs=({options:e})=>q.createUnionTypeNode(e.map(H)),qo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Ko(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Js=e=>Bs?.[e.kind],Ws=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=nt(e,Js(o)),s={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(n&&s[n]||b.SyntaxKind.AnyKeyword)}return o},Ys=e=>q.createUnionTypeNode(Object.values(e.enum).map(H)),Qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(b.SyntaxKind.UndefinedKeyword)]):o},Xs=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),H(null)]),ei=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),ti=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),ri=v.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(lr.name,...o))return!1;if(v.both(v.eqBy(lr.type),v.eqBy(lr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),oi=({_def:{left:e,right:t}},{next:r})=>ri([e,t].map(r)),ni=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),si=(e,{next:t})=>t(e.unwrap()),ii=(e,{next:t})=>t(e.unwrap()),ai=({_def:e},{next:t})=>t(e.innerType),pi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ci=()=>H(null),di=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),mi=e=>{let t=e.unwrap(),r=f(b.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof ur.ZodString?r:t instanceof ur.ZodUnion?n:o},li=(e,{next:t})=>t(e.unwrap().shape.raw),ui={ZodString:ae(b.SyntaxKind.StringKeyword),ZodNumber:ae(b.SyntaxKind.NumberKeyword),ZodBigInt:ae(b.SyntaxKind.BigIntKeyword),ZodBoolean:ae(b.SyntaxKind.BooleanKeyword),ZodAny:ae(b.SyntaxKind.AnyKeyword),ZodUndefined:ae(b.SyntaxKind.UndefinedKeyword),[ge]:ae(b.SyntaxKind.StringKeyword),[he]:ae(b.SyntaxKind.StringKeyword),ZodNull:ci,ZodArray:Vs,ZodTuple:ei,ZodRecord:ti,ZodObject:_s,ZodLiteral:$s,ZodIntersection:oi,ZodUnion:qo,ZodDefault:ni,ZodEnum:Gs,ZodNativeEnum:Ys,ZodEffects:Ws,ZodOptional:Qs,ZodNullable:Xs,ZodDiscriminatedUnion:qo,ZodBranded:si,ZodCatch:ai,ZodPipeline:pi,ZodLazy:di,ZodReadonly:ii,[G]:mi,[ie]:li},fr=(e,{brandHandling:t,ctx:r})=>Oe(e,{rules:{...t,...ui},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var yr=class extends Et{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=H(null);this.#t.set(t,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:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=fi.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(R,x,P)=>{let S=se.bind(null,P,x),{isDeprecated:D,inputSchema:C,tags:T}=R,I=`${P} ${x}`,K=Q(S("input"),fr(C,l),{comment:I});this.#e.push(K);let M=Ce.reduce((k,pe)=>{let Ye=R.getResponses(pe),Zt=Bo.chain(([It,{schema:te,mimeTypes:ce,statusCodes:vt}])=>{let Xe=Q(S(pe,"variant",`${It+1}`),fr(ce?te:m,h),{comment:I});return this.#e.push(Xe),vt.map(et=>Pe(et,Xe.name))},Array.from(Ye.entries())),Qe=wt(S(pe,"response","variants"),Zt,{comment:I});return this.#e.push(Qe),Object.assign(k,{[pe]:Qe})},{});this.paths.add(x);let w=H(I),B={input:f(K.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([V(this.interfaces.positive,w),V(this.interfaces.negative,w)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(I,{isDeprecated:D,store:B}),this.tags.set(I,T)}}),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:Xt(r,t)).join(`
19
- `):void 0}print(t){let r=this.#n(t),o=r&&zt.addSyntheticLeadingComment(zt.addSyntheticLeadingComment(i.createEmptyStatement(),zt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),zt.SyntaxKind.MultiLineCommentTrivia,`
20
- ${r}`);return this.#e.concat(o||[]).map((n,s)=>Xt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
16
+ `;e.write(d.split(`
17
+ `).map((c,m)=>p[m]?p[m](c):c).join(`
18
+ `))};var uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||be,r=Zr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.2 (ESM)",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Bt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},$n=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=ft().disable("x-powered-by").use(i);if(e.compression){let h=await Ne("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ft.json()],raw:[e.rawParser||ft.raw(),so],form:[e.formParser||ft.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Bt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,y)=>()=>h.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let h=Ln.createServer(p);c.push(h),g.push(m(h,e.http.listen))}if(e.https){let h=Mn.createServer(e.https.options,p);c.push(h),g.push(m(h,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as ms}from"openapi3-ts/oas31";import*as zo from"ramda";import*as x from"ramda";var fo=e=>j(e)&&"or"in e,yo=e=>j(e)&&"and"in e,Ft=e=>!yo(e)&&!fo(e),go=e=>{let t=x.filter(Ft,e),r=x.chain(x.prop("and"),x.filter(yo,e)),[o,n]=x.partition(Ft,r),s=x.concat(t,o),i=x.filter(fo,e);return x.map(x.prop("or"),x.concat(i,n)).reduce((d,c)=>le(d,x.map(m=>Ft(m)?[m]:m.and,c),([m,g])=>x.concat(m,g)),x.reject(x.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as yt}from"openapi3-ts/oas31";import*as l from"ramda";import{globalRegistry as Kn,z as bo}from"zod/v4";var ho=["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 xo=50,Oo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Bn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Fn=({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}}},Un=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Dn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:es(t.type)})},So=e=>e in To,_n=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Vn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Jn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!$(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!st(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},Se=({$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(So):t&&So(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Se));return s&&(p.not=Se(s)),p},Gn=({zodSchema:e},t)=>{if(t.isResponse)throw new J("Please use ez.dateOut() for output.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}},o=Kn.get(e)?.examples?.filter(n=>n instanceof Date).map(n=>n.toISOString());return o?.length&&(r.examples=o),r},Wn=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new J("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(r.examples=e),r},Yn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Qn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},es=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ts=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!$(o,"transform"))return t;let s=Se(_t(n,{ctx:r}));if(yt(s))if(r.isResponse){let i=nt(o,Xn(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},rs=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Ut=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,os=(e,t)=>t?.includes(e)||e.startsWith("x-")||ho.includes(e),wo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=ze(r),m=tt(e),g=o.includes("query"),h=o.includes("params"),y=o.includes("headers"),v=R=>h&&m.includes(R),k=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),M=R=>y&&(i?.(R,t,e)??os(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let F=v(A)?"path":M(A)?"header":g?"query":void 0;if(!F)return R;let N=Se(C),Q=s==="components"?n(C,N,oe(d,A)):N;return R.concat({name:A,in:F,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Q,examples:Ut(yt(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(j,l.has(A)))||[]))})},[])},Dt={nullable:Dn,union:Fn,bigint:Yn,intersection:Un,tuple:Qn,pipe:ts,literal:Vn,enum:_n,object:Jn,[fe]:Gn,[ye]:Wn,[ne]:qn,[se]:Bn,[H]:rs},ns=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(Ro(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,Se(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},_t=(e,{ctx:t,rules:r=Dt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(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 ns(n.subject,o,t)},Eo=(e,t)=>{if(Ro(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Eo(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]},vo=({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} ${zt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Se(_t(r,{rules:{...c,...Dt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];yt(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,oe(m)):g,examples:Ut(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ss=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},is=({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},as=({name:e})=>({type:"apiKey",in:"header",name:e}),ps=({name:e})=>({type:"apiKey",in:"cookie",name:e}),cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ds=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),ko=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ss(o):o.type==="input"?is(o,t):o.type==="header"?as(o):o.type==="cookie"?ps(o):o.type==="openid"?cs(o):ds(o);return e.map(o=>o.map(r))},Ao=(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:[]})},{})),Co=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>_t(e,{rules:{...t,...Dt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({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]=Eo(Se(o),p),g=[];yt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,oe(d)):c,examples:Ut(g.length?g:ze(o).examples?.filter(v=>j(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:h}};return(m||n===w.raw)&&(y.required=!0),y},No=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Vt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",gt=e=>e.length?e.slice():void 0;var Jt=class extends ms{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});je({routing:t,onEndpoint:(y,v,k)=>{let M={path:v,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:C,inputSchema:F}=y,N=A?Vt(A):m&&R?Vt(R):void 0,Q=r.inputSources?.[k]||It[k],Te=this.#n(v,k,y.getOperationId(k)),Ge=Co({...M,schema:F}),pe=go(y.security),We=wo({...M,inputSources:Q,isHeader:c,security:pe,request:Ge,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Te})}),Ye={};for(let X of Ce){let ce=y.getResponses(X);for(let{mimeTypes:Xe,schema:vt,statusCodes:yr}of ce)for(let kt of yr)Ye[kt]=vo({...M,variant:X,schema:vt,mimeTypes:Xe,statusCode:kt,hasMultipleStatusCodes:ce.length>1||yr.length>1,description:i?.[`${X}Response`]?.call(null,{method:k,path:v,operationId:Te,statusCode:kt})})}let Qe=Q.includes("body")?Io({...M,request:Ge,paramNames:zo.pluck("name",We),schema:F,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Te})}):void 0,wt=Ao(ko(pe,Q),C,X=>{let ce=this.#s(X);return this.addSecurityScheme(ce,X),ce}),Et={operationId:Te,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:gt(y.tags),parameters:gt(We),requestBody:Qe,security:gt(wt),responses:Ye};this.addPath(Po(v),{[k]:Et})}}),d&&(this.rootDoc.tags=No(d))}};import{createRequest as ls,createResponse as us}from"node-mocks-http";var fs=e=>ls({...e,headers:{"content-type":w.json,...e?.headers}}),ys=e=>us(e),gs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let i=gs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},bs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=jo(r),d=rt(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:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import Pt from"typescript";import{z as Bs}from"zod/v4";import*as $o from"ramda";import V from"typescript";import*as D from"ramda";import u from"typescript";var a=u.factory,ht=[a.createModifier(u.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Gt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Wt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Ss=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&Ss.test(e)?a.createIdentifier(e):P(e),bt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),xt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ve.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&D.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Yt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=D.reject(D.isNil,[o?"@deprecated":void 0,n]);return p.length?Gt(i,p.join(" ")):i},er=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),tr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&ht,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>_(e,a.createUnionTypeNode(D.map(Z,t)),{expose:!0}),_=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?ht:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},Lo=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(ht,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),St=e=>f(Promise.name,[e]),Rt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?ht:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>D.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?D.map(xt,e):Le(e),void 0,void 0,t),O=e=>e,Je=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Me=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ot=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Mo=e=>a.createUnionTypeNode([f(e),St(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),P=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),Z=e=>a.createLiteralTypeNode(P(e)),Rs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Zo=e=>Rs.includes(e.kind);var Tt=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=rr("Method",Kt);someOfType=_("SomeOf",q("T",sr("T")),{params:["T"]});requestType=_("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>rr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Rt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression($o.map(P,r))))),{expose:!0});makeImplementationType=()=>_(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},St(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>I(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([I(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ar(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(bt(":",[this.#e.keyParameter]),Oe([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>or(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(tr(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:St(q(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>bt("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,bt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),Je(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Je(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=I(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=I(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=I(this.#e.searchParamsConst,Je(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=I(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=I(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Je(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Oe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Qt(Le({request:"K",params:q(this.interfaces.input,"K")}),[I(tr(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),I(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>or(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:q(Ot("R",er(this.#s("E"))),Z(O("data")))},Mo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",Z(O("event")))}});makeSubscriptionClass=t=>nr(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ot(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ot(q(this.interfaces.positive,"K"),er(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(this.#e.clientConst,Me(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Me(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Oe(["time"],a.createBlock([])))]};import*as E from"ramda";import b from"typescript";import{globalRegistry as Os}from"zod/v4";var cr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=W(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>cr(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:B}=b,Ts={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},dr={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Ps=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:B.createUnionTypeNode(t)},ws=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Os.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:st(p,{isResponse:t})})});return B.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},Es=({_zod:{def:e}},{next:t})=>B.createArrayTypeNode(t(e.element)),vs=({_zod:{def:e}})=>B.createUnionTypeNode(Object.values(e.entries).map(Z)),ks=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Zo(n)?n.kind:n,n)}return B.createUnionTypeNode(Array.from(r.values()))},As=e=>Ts?.[e.kind],Cs=({_zod:{def:e}},{next:t})=>t(e.innerType),Is=({_zod:{def:e}},{next:t})=>B.createUnionTypeNode([t(e.innerType),Z(null)]),Ns=({_zod:{def:e}},{next:t})=>B.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:B.createRestTypeNode(t(e.rest)))),zs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=E.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=E.chain(E.prop("members"),e),r=E.uniqWith((...o)=>{if(!E.eqBy(dr.name,...o))return!1;if(E.both(E.eqBy(dr.type),E.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return B.createTypeLiteralNode(r)},(e,t)=>B.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),ae=e=>()=>f(e),mr=({_zod:{def:e}},{next:t})=>t(e.innerType),Ms=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!$(o,"transform"))return t(o);let s=t(n),i=nt(o,As(s)),p={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(i&&p[i]||b.SyntaxKind.AnyKeyword)},Zs=()=>Z(null),$s=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Hs=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=B.createUnionTypeNode([t,r]);return $(e,"string")?t:$(e,"union")?o:r},Ks=(e,{next:t})=>t(e._zod.def.shape.raw),qs={string:ae(b.SyntaxKind.StringKeyword),number:ae(b.SyntaxKind.NumberKeyword),bigint:ae(b.SyntaxKind.BigIntKeyword),boolean:ae(b.SyntaxKind.BooleanKeyword),any:ae(b.SyntaxKind.AnyKeyword),undefined:ae(b.SyntaxKind.UndefinedKeyword),[fe]:ae(b.SyntaxKind.StringKeyword),[ye]:ae(b.SyntaxKind.StringKeyword),null:Zs,array:Es,tuple:Ns,record:zs,object:ws,literal:Ps,intersection:Ls,union:ks,default:mr,enum:vs,optional:Cs,nullable:Is,catch:mr,pipe:Ms,lazy:$s,readonly:mr,[se]:Hs,[H]:Ks},lr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...qs},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var ur=class extends Tt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=Z(null);this.#t.set(t,_(o,n)),this.#t.set(t,_(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=Bs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};je({routing:t,onEndpoint:(h,y,v)=>{let k=oe.bind(null,v,y),{isDeprecated:M,inputSchema:R,tags:A}=h,C=`${v} ${y}`,F=_(k("input"),lr(R,c),{comment:C});this.#e.push(F);let N=Ce.reduce((Ge,pe)=>{let We=h.getResponses(pe),Ye=Ho.chain(([wt,{schema:Et,mimeTypes:X,statusCodes:ce}])=>{let Xe=_(k(pe,"variant",`${wt+1}`),lr(X?Et:p,m),{comment:C});return this.#e.push(Xe),ce.map(vt=>Re(vt,Xe.name))},Array.from(We.entries())),Qe=Rt(k(pe,"response","variants"),Ye,{comment:C});return this.#e.push(Qe),Object.assign(Ge,{[pe]:Qe})},{});this.paths.add(y);let Q=Z(C),Te={input:f(F.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([q(this.interfaces.positive,Q),q(this.interfaces.negative,Q)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:M,store:Te}),this.tags.set(C,A)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
19
+ `):void 0}print(t){let r=this.#n(t),o=r&&Pt.addSyntheticLeadingComment(Pt.addSyntheticLeadingComment(a.createEmptyStatement(),Pt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Pt.SyntaxKind.MultiLineCommentTrivia,`
20
+ ${r}`);return this.#e.concat(o||[]).map((n,s)=>Wt(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 a=(await Ne("prettier")).format;o=c=>a(c,{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}};import{z as He}from"zod";var _o=(e,t)=>He.object({data:t,event:He.literal(e),id:He.string().optional(),retry:He.number().int().positive().optional()}),yi=(e,t,r)=>_o(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),gi=1e4,$o=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":Z.sse,"cache-control":"no-cache"}),hi=e=>new J({handler:async({response:t})=>setTimeout(()=>$o(t),gi)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{$o(t),t.write(yi(e,r,o),"utf-8"),t.flush?.()}}}),bi=e=>new Se({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>_o(o,n));return{mimeType:Z.sse,schema:r.length?He.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:He.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);Be(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(be(a),"utf-8")}t.end()}}),gr=class extends Te{constructor(t){super(bi(t)),this.middlewares=[hi(t)]}};var xi={dateIn:xr,dateOut:Sr,form:Or,file:pt,upload:Ar,raw:wr};export{_e as BuiltinLogger,Ve as DependsOnMethod,Yt as Documentation,$ as DocumentationError,Te as EndpointsFactory,gr as EventStreamFactory,ee as InputValidationError,yr as Integration,J as Middleware,De as MissingPeerError,me as OutputValidationError,Se as ResultHandler,de as RoutingError,Ge as ServeStatic,un as arrayEndpointsFactory,Dt as arrayResultHandler,Ln as attachRouting,tn as createConfig,Un as createServer,ln as defaultEndpointsFactory,Re as defaultResultHandler,ze as ensureHttpError,xi as ez,ne as getExamples,le as getMessageFromError,Hs as testEndpoint,Ds as testMiddleware};
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ne("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}};import{z as Ze}from"zod/v4";var qo=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.int().positive().optional()}),Fs=(e,t,r)=>qo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),Us=1e4,Ko=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Ds=e=>new U({handler:async({response:t})=>setTimeout(()=>Ko(t),Us)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ko(t),t.write(Fs(e,r,o),"utf-8"),t.flush?.()}}}),_s=e=>new he({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>qo(o,n));return{mimeType:w.sse,schema:r.length?Ze.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);Be(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ge(i),"utf-8")}t.end()}}),fr=class extends xe{constructor(t){super(_s(t)),this.middlewares=[Ds(t)]}};var Vs={dateIn:br,dateOut:xr,form:Rr,file:at,upload:Or,raw:wr};export{Ue as BuiltinLogger,De as DependsOnMethod,Jt as Documentation,J as DocumentationError,xe as EndpointsFactory,fr as EventStreamFactory,G as InputValidationError,ur as Integration,U as Middleware,He as MissingPeerError,me as OutputValidationError,he as ResultHandler,de as RoutingError,_e as ServeStatic,dn as arrayEndpointsFactory,$t as arrayResultHandler,Zn as attachRouting,Yo as createConfig,$n as createServer,cn as defaultEndpointsFactory,be as defaultResultHandler,we as ensureHttpError,Vs as ez,te as getMessageFromError,hs as testEndpoint,bs as testMiddleware};
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var g=(n,e)=>{for(var r in e)c(n,r,{get:e[r],enumerable:!0})},S=(n,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of p(e))!l.call(n,o)&&o!==r&&c(n,o,{get:()=>e[o],enumerable:!(s=u(e,o))||s.enumerable});return n};var f=n=>S(c({},"__esModule",{value:!0}),n);var v={};g(v,{default:()=>E});module.exports=f(v);var t=require("@typescript-eslint/utils"),y={headerSecurity:`${t.AST_NODE_TYPES.Identifier}[name='CustomHeaderSecurity']`,createConfig:`${t.AST_NODE_TYPES.CallExpression}[callee.name='createConfig'] > ${t.AST_NODE_TYPES.ObjectExpression}`,testMiddleware:`${t.AST_NODE_TYPES.CallExpression}[callee.name='testMiddleware'] > ${t.AST_NODE_TYPES.ObjectExpression}`},T=n=>Object.keys(n).reduce((e,r)=>Object.assign(e,{[y[r]]:n[r]}),{}),m=t.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"change {{ subject }} from {{ from }} to {{ to }}",add:"add {{ subject }} to {{ to }}",move:"move {{ subject }} to {{ to }}"}},defaultOptions:[],create:n=>T({headerSecurity:e=>n.report({node:e,messageId:"change",data:{subject:"interface",from:e.name,to:"HeaderSecurity"},fix:r=>r.replaceText(e,"HeaderSecurity")}),createConfig:e=>{e.properties.find(s=>s.type===t.AST_NODE_TYPES.Property&&s.key.type===t.AST_NODE_TYPES.Identifier&&s.key.name==="wrongMethodBehavior")||n.report({node:e,messageId:"add",data:{subject:"wrongMethodBehavior property",to:"configuration"},fix:s=>s.insertTextAfterRange([e.range[0],e.range[0]+1],"wrongMethodBehavior: 404,")})},testMiddleware:e=>{let r=e.properties.find(i=>i.type===t.AST_NODE_TYPES.Property&&i.key.type===t.AST_NODE_TYPES.Identifier&&i.key.name==="errorHandler"&&[t.AST_NODE_TYPES.ArrowFunctionExpression,t.AST_NODE_TYPES.FunctionExpression].includes(i.value.type));if(!r)return;let s=n.sourceCode.getTokenAfter(r)?.value===",",{body:o}=r.value,a=e.properties.find(i=>i.type===t.AST_NODE_TYPES.Property&&i.key.type===t.AST_NODE_TYPES.Identifier&&i.key.name==="configProps"&&i.value.type===t.AST_NODE_TYPES.ObjectExpression),d=`errorHandler: new ResultHandler({ positive: [], negative: [], handler: ({ error, response }) => {${n.sourceCode.getText(o)}} }),`;n.report({node:r,messageId:"move",data:{subject:"errorHandler",to:"configProps"},fix:i=>[i.removeRange([r.range[0],r.range[1]+(s?1:0)]),a?i.insertTextAfterRange([a.value.range[0],a.value.range[0]+1],d):i.insertTextAfterRange([e.range[0],e.range[0]+1],`configProps: {${d}},`)]})}})}),E={rules:{v23:m}};
1
+ "use strict";var i=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var y=(t,e)=>{for(var n in e)i(t,n,{get:e[n],enumerable:!0})},g=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of S(e))!d.call(t,o)&&o!==n&&i(t,o,{get:()=>e[o],enumerable:!(s=u(e,o))||s.enumerable});return t};var T=t=>g(i({},"__esModule",{value:!0}),t);var h={};y(h,{default:()=>b});module.exports=T(h);var r=require("@typescript-eslint/utils"),f={numericRange:`${r.AST_NODE_TYPES.NewExpression}[callee.name='Documentation'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='numericRange']`,optionalPropStyle:`${r.AST_NODE_TYPES.NewExpression}[callee.name='Integration'] > ${r.AST_NODE_TYPES.ObjectExpression} > ${r.AST_NODE_TYPES.Property}[key.name='optionalPropStyle']`,depicter:`${r.AST_NODE_TYPES.VariableDeclarator}[id.typeAnnotation.typeAnnotation.typeName.name='Depicter'] > ${r.AST_NODE_TYPES.ArrowFunctionExpression}`,nextCall:`${r.AST_NODE_TYPES.VariableDeclarator}[id.typeAnnotation.typeAnnotation.typeName.name='Depicter'] > ${r.AST_NODE_TYPES.ArrowFunctionExpression} ${r.AST_NODE_TYPES.CallExpression}[callee.name='next']`,zod:`${r.AST_NODE_TYPES.ImportDeclaration}[source.value='zod']`},E=t=>Object.keys(t).reduce((e,n)=>Object.assign(e,{[f[n]]:t[n]}),{}),l=(t,e)=>[t.range[0],t.range[1]+(e.sourceCode.getTokenAfter(t)?.value===","?1:0)],m=t=>e=>t.report({node:e,messageId:"remove",data:{subject:e.key.name},fix:n=>n.removeRange(l(e,t))}),x=r.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"change {{ subject }} from {{ from }} to {{ to }}",add:"add {{ subject }} to {{ to }}",move:"move {{ subject }} to {{ to }}",remove:"remove {{ subject }}"}},defaultOptions:[],create:t=>E({numericRange:m(t),optionalPropStyle:m(t),depicter:e=>{let[n,s]=e.params;if(n?.type!==r.AST_NODE_TYPES.Identifier)return;let o=n.name;if(s?.type!==r.AST_NODE_TYPES.ObjectPattern)return;let p=s.properties.find(a=>a.type===r.AST_NODE_TYPES.Property&&a.key.type===r.AST_NODE_TYPES.Identifier&&a.key.name==="next");t.report({node:e,messageId:"change",data:{subject:"arguments",from:`[${o}, { next, ...rest }]`,to:`[{ zodSchema: ${o}, jsonSchema }, { ...rest }]`},fix:a=>{let c=[a.replaceText(n,`{ zodSchema: ${o}, jsonSchema }`)];return p&&c.push(a.removeRange(l(p,t))),c}})},nextCall:e=>t.report({node:e,messageId:"change",data:{subject:"statement",from:"next()",to:"jsonSchema"},fix:n=>n.replaceText(e,"jsonSchema")}),zod:e=>t.report({node:e.source,messageId:"change",data:{subject:"import",from:"zod",to:"zod/v4"},fix:n=>n.replaceText(e.source,'"zod/v4"')})})}),b={rules:{v24:x}};
@@ -9,12 +9,12 @@ import { ESLintUtils } from '@typescript-eslint/utils';
9
9
  * import migration from "express-zod-api/migration";
10
10
  * export default [
11
11
  * { languageOptions: {parser}, plugins: {migration} },
12
- * { files: ["**\/*.ts"], rules: { "migration/v21": "error" } }
12
+ * { files: ["**\/*.ts"], rules: { "migration/v24": "error" } }
13
13
  * ];
14
14
  * */
15
15
  declare const _default: {
16
16
  rules: {
17
- v23: ESLintUtils.RuleModule<"change" | "add" | "move", [], unknown, ESLintUtils.RuleListener>;
17
+ v24: ESLintUtils.RuleModule<"change" | "add" | "move" | "remove", [], unknown, ESLintUtils.RuleListener>;
18
18
  };
19
19
  };
20
20
 
@@ -9,12 +9,12 @@ import { ESLintUtils } from '@typescript-eslint/utils';
9
9
  * import migration from "express-zod-api/migration";
10
10
  * export default [
11
11
  * { languageOptions: {parser}, plugins: {migration} },
12
- * { files: ["**\/*.ts"], rules: { "migration/v21": "error" } }
12
+ * { files: ["**\/*.ts"], rules: { "migration/v24": "error" } }
13
13
  * ];
14
14
  * */
15
15
  declare const _default: {
16
16
  rules: {
17
- v23: ESLintUtils.RuleModule<"change" | "add" | "move", [], unknown, ESLintUtils.RuleListener>;
17
+ v24: ESLintUtils.RuleModule<"change" | "add" | "move" | "remove", [], unknown, ESLintUtils.RuleListener>;
18
18
  };
19
19
  };
20
20
 
@@ -1 +1 @@
1
- import{ESLintUtils as d,AST_NODE_TYPES as r}from"@typescript-eslint/utils";var u={headerSecurity:`${r.Identifier}[name='CustomHeaderSecurity']`,createConfig:`${r.CallExpression}[callee.name='createConfig'] > ${r.ObjectExpression}`,testMiddleware:`${r.CallExpression}[callee.name='testMiddleware'] > ${r.ObjectExpression}`},p=i=>Object.keys(i).reduce((e,n)=>Object.assign(e,{[u[n]]:i[n]}),{}),l=d.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"change {{ subject }} from {{ from }} to {{ to }}",add:"add {{ subject }} to {{ to }}",move:"move {{ subject }} to {{ to }}"}},defaultOptions:[],create:i=>p({headerSecurity:e=>i.report({node:e,messageId:"change",data:{subject:"interface",from:e.name,to:"HeaderSecurity"},fix:n=>n.replaceText(e,"HeaderSecurity")}),createConfig:e=>{e.properties.find(s=>s.type===r.Property&&s.key.type===r.Identifier&&s.key.name==="wrongMethodBehavior")||i.report({node:e,messageId:"add",data:{subject:"wrongMethodBehavior property",to:"configuration"},fix:s=>s.insertTextAfterRange([e.range[0],e.range[0]+1],"wrongMethodBehavior: 404,")})},testMiddleware:e=>{let n=e.properties.find(t=>t.type===r.Property&&t.key.type===r.Identifier&&t.key.name==="errorHandler"&&[r.ArrowFunctionExpression,r.FunctionExpression].includes(t.value.type));if(!n)return;let s=i.sourceCode.getTokenAfter(n)?.value===",",{body:c}=n.value,o=e.properties.find(t=>t.type===r.Property&&t.key.type===r.Identifier&&t.key.name==="configProps"&&t.value.type===r.ObjectExpression),a=`errorHandler: new ResultHandler({ positive: [], negative: [], handler: ({ error, response }) => {${i.sourceCode.getText(c)}} }),`;i.report({node:n,messageId:"move",data:{subject:"errorHandler",to:"configProps"},fix:t=>[t.removeRange([n.range[0],n.range[1]+(s?1:0)]),o?t.insertTextAfterRange([o.value.range[0],o.value.range[0]+1],a):t.insertTextAfterRange([e.range[0],e.range[0]+1],`configProps: {${a}},`)]})}})}),S={rules:{v23:l}};export{S as default};
1
+ import{ESLintUtils as l,AST_NODE_TYPES as r}from"@typescript-eslint/utils";var u={numericRange:`${r.NewExpression}[callee.name='Documentation'] > ${r.ObjectExpression} > ${r.Property}[key.name='numericRange']`,optionalPropStyle:`${r.NewExpression}[callee.name='Integration'] > ${r.ObjectExpression} > ${r.Property}[key.name='optionalPropStyle']`,depicter:`${r.VariableDeclarator}[id.typeAnnotation.typeAnnotation.typeName.name='Depicter'] > ${r.ArrowFunctionExpression}`,nextCall:`${r.VariableDeclarator}[id.typeAnnotation.typeAnnotation.typeName.name='Depicter'] > ${r.ArrowFunctionExpression} ${r.CallExpression}[callee.name='next']`,zod:`${r.ImportDeclaration}[source.value='zod']`},S=e=>Object.keys(e).reduce((t,n)=>Object.assign(t,{[u[n]]:e[n]}),{}),m=(e,t)=>[e.range[0],e.range[1]+(t.sourceCode.getTokenAfter(e)?.value===","?1:0)],c=e=>t=>e.report({node:t,messageId:"remove",data:{subject:t.key.name},fix:n=>n.removeRange(m(t,e))}),d=l.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"change {{ subject }} from {{ from }} to {{ to }}",add:"add {{ subject }} to {{ to }}",move:"move {{ subject }} to {{ to }}",remove:"remove {{ subject }}"}},defaultOptions:[],create:e=>S({numericRange:c(e),optionalPropStyle:c(e),depicter:t=>{let[n,s]=t.params;if(n?.type!==r.Identifier)return;let a=n.name;if(s?.type!==r.ObjectPattern)return;let i=s.properties.find(o=>o.type===r.Property&&o.key.type===r.Identifier&&o.key.name==="next");e.report({node:t,messageId:"change",data:{subject:"arguments",from:`[${a}, { next, ...rest }]`,to:`[{ zodSchema: ${a}, jsonSchema }, { ...rest }]`},fix:o=>{let p=[o.replaceText(n,`{ zodSchema: ${a}, jsonSchema }`)];return i&&p.push(o.removeRange(m(i,e))),p}})},nextCall:t=>e.report({node:t,messageId:"change",data:{subject:"statement",from:"next()",to:"jsonSchema"},fix:n=>n.replaceText(t,"jsonSchema")}),zod:t=>e.report({node:t.source,messageId:"change",data:{subject:"import",from:"zod",to:"zod/v4"},fix:n=>n.replaceText(t.source,'"zod/v4"')})})}),g={rules:{v24:d}};export{g as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "23.5.0",
3
+ "version": "24.0.0-beta.2",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -76,7 +76,7 @@
76
76
  "express-fileupload": "^1.5.0",
77
77
  "http-errors": "^2.0.0",
78
78
  "typescript": "^5.1.3",
79
- "zod": "^3.23.0"
79
+ "zod": "^3.25.1"
80
80
  },
81
81
  "peerDependenciesMeta": {
82
82
  "@types/compression": {