express-zod-api 10.3.1 → 10.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,12 +2,35 @@
2
2
 
3
3
  ## Version 10
4
4
 
5
+ ### v10.4.0
6
+
7
+ - For the future features and improvements the following entities are renamed:
8
+ - ~~`Client`~~ class becomes the `Integration`.
9
+ - ~~`OpenAPI`~~ class becomes the `Documentation`.
10
+ - For backward compatibility the previously assigned names are still supported until the next major release.
11
+ - Developers are advised to adjust their implementation accordingly.
12
+
13
+ ```ts
14
+ // before
15
+ new Client(/*...*/);
16
+ new OpenAPI(/*...*/);
17
+ // after
18
+ new Integration(/*...*/);
19
+ new Documentation(/*...*/);
20
+ ```
21
+
22
+ ### v10.3.2
23
+
24
+ - Hotfix on fixing the previously mentioned issue #952.
25
+ - The following interfaces are now exported from the index file directly:
26
+ - `ZodFileDef`, `ZodUploadDef`, `ZodDateInDef`, `ZodDateOutDef`.
27
+
5
28
  ### v10.3.1
6
29
 
7
- - Fixed issue of the insufficient exports of the proprietary schema definitions.
30
+ - Attempted to fix the issue #952 of the insufficient exports of the proprietary schema definitions.
8
31
  - The issue introduced in version 10.0.0-beta1 due to changing the compiler to `tsup`.
9
- - The issue manifested only when `declaration` is enabled in your `tsconfig.json`.
10
- - The issue caused following error:
32
+ - The issue manifests only when `declaration` is enabled in your `tsconfig.json`.
33
+ - The issue causes following error:
11
34
  - `TS4023: Exported variable '' has or is using name 'ZodFileDef' from external module "" but cannot be named.`
12
35
  - The following interfaces are now available within the exported `ez` namespace:
13
36
  - `ez.ZodFileDef`, `ez.ZodUploadDef`, `ez.ZodDateInDef`, `ez.ZodDateOutDef`.
package/README.md CHANGED
@@ -279,7 +279,7 @@ import { createMiddleware, createHttpError } from "express-zod-api";
279
279
 
280
280
  const authMiddleware = createMiddleware({
281
281
  security: {
282
- // this information is optional and used for the generated documentation (OpenAPI)
282
+ // this information is optional and used for generating documentation
283
283
  and: [
284
284
  { type: "input", name: "key" },
285
285
  { type: "header", name: "token" },
@@ -809,11 +809,11 @@ Consuming the generated client requires Typescript version 4.1 or higher.
809
809
  ```typescript
810
810
  // example client-generator.ts
811
811
  import fs from "fs";
812
- import { Client } from "express-zod-api";
812
+ import { Integration } from "express-zod-api";
813
813
 
814
814
  fs.writeFileSync(
815
815
  "./frontend/client.ts",
816
- new Client({
816
+ new Integration({
817
817
  routing,
818
818
  optionalPropStyle: { withQuestionMark: true, withUndefined: true }, // optional
819
819
  }).print(),
@@ -845,9 +845,9 @@ client.provide("post", "/v1/user/:id", { id: "10" }); // it also substitues path
845
845
  You can generate the specification of your API and write it to a `.yaml` file, that can be used as the documentation:
846
846
 
847
847
  ```typescript
848
- import { OpenAPI } from "express-zod-api";
848
+ import { Documentation } from "express-zod-api";
849
849
 
850
- const yamlString = new OpenAPI({
850
+ const yamlString = new Documentation({
851
851
  routing, // the same routing and config that you use to start the server
852
852
  config,
853
853
  version: "1.2.3",
package/dist/esm/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var Zr=Object.defineProperty;var Dr=(e,t)=>{for(var r in t)Zr(e,r,{get:t[r],enumerable:!0})};var Cr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var D=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)};var E=(e,t,r)=>(Cr(e,t,"access private method"),r);var Ct={silent:!0,warn:!0,debug:!0},wr=e=>e;import{z as v}from"zod";import{createHash as qr}from"crypto";import{HttpError as Vr}from"http-errors";import{z as T}from"zod";import{clone as Nr,mergeDeepRight as vr}from"ramda";var S="expressZodApiMeta",Mr=e=>{let t=e.constructor,r=Nr(e._def);return r[S]=r[S]||{examples:[]},new t(r)},_=e=>{let t=Mr(e);return Object.defineProperties(t,{example:{get:()=>r=>{let o=_(t);return o._def[S].examples.push(r),o}}}),t},wt=e=>S in e._def?typeof e._def[S]=="object"&&e._def[S]!==null:!1;function je(e,t){if(!wt(e))return;let r=e._def;return t in r[S]?r[S][t]:void 0}var Re=(e,t)=>{if(!wt(e))return t;let r=_(t),o=ce(r._def[S].examples,e._def[S].examples);if(r._def[S].examples=[],o.type==="single")r._def[S].examples=o.value;else for(let[n,i]of o.value)r._def[S].examples.push(vr({...n},{...i}));return r};import zr from"mime";var U=zr.getType("json")||"application/json",pe="multipart/form-data";import{INVALID as kr,OK as Lr,ZodIssueCode as Ur,ZodParsedType as Hr,ZodType as Kr,addIssueToContext as Fr}from"zod";var Br="ZodUpload",$r=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.mimetype=="string"&&typeof e.data=="object"&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",Je=class extends Kr{_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==Hr.object||!$r(r.data)?(Fr(r,{code:Ur.custom,message:`Expected file upload, received ${r.parsedType}`}),kr):Lr(r.data)}},H=Je;H.create=()=>new Je({typeName:Br});var Qe=/:([A-Za-z0-9_]+)/g;function Gr(e){let r=(e.header("content-type")||"").slice(0,pe.length).toLowerCase()===pe;return"files"in e&&r}var Pe={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},_r=["body","query","params"],We=e=>e.method.toLowerCase();function Nt(e,t){let r=We(e);if(r==="options")return{};let o=_r;return r in Pe&&(o=Pe[r]),t&&r in t&&(o=t[r]||o),o.filter(n=>n==="files"?Gr(e):!0).reduce((n,i)=>({...n,...e[i]}),{})}function Xe(e){return typeof e=="object"&&"level"in e&&"color"in e&&Object.keys(Ct).includes(e.level)&&typeof e.color=="boolean"}function Ee(e){return!isNaN(e.getTime())}function Y(e){return e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`)}function K(e){return e instanceof T.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof F?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message}function et(e){return e instanceof Vr?e.statusCode:e instanceof w?400:500}var Ie=(e,t)=>{let r=[],o=je(e,"examples");for(let n of o||[]){let i=e.safeParse(n);i.success&&r.push(t?i.data:n)}return r},ce=(e,t)=>{if(e.length===0)return{type:"single",value:t};if(t.length===0)return{type:"single",value:e};let r=[];for(let o of e)for(let n of t)r.push([o,n]);return{type:"tuple",value:r}};function tt(e){let t=e.match(Qe);return t?t.map(r=>r.slice(1)):[]}var de=e=>e.reduce((t,r)=>t||r,!1);function C(e){return e instanceof T.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof T.ZodUnion?de(e.options.map(C)):e instanceof T.ZodIntersection?de([e._def.left,e._def.right].map(C)):!1}function I(e){return e instanceof H?!0:e instanceof T.ZodObject?de(Object.values(e.shape).map(I)):e instanceof T.ZodUnion?de(e.options.map(I)):e instanceof T.ZodIntersection?de([e._def.left,e._def.right].map(I)):e instanceof T.ZodOptional||e instanceof T.ZodNullable?I(e.unwrap()):e instanceof T.ZodEffects||e instanceof T.ZodTransformer?I(e._def.schema):e instanceof T.ZodRecord?I(e._def.valueType):e instanceof T.ZodArray?I(e._def.type):e instanceof T.ZodDefault?I(e._def.innerType):!1}var me=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,A=(e,t,r)=>[t].concat(e.split("/")).concat(r||[]).flatMap(o=>o.split(/[^A-Z0-9]/gi)).map(o=>o.slice(0,1).toUpperCase()+o.slice(1).toLowerCase()).join(""),Ae=e=>qr("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ze=({effect:e,sample:t})=>{try{return typeof e.transform(t,{addIssue:()=>{},path:[]})}catch{return}},rt=e=>typeof e=="string"?{message:e}:e||{};var J=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},le=class extends J{constructor(){super(...arguments);this.name="DependsOnMethodError"}},R=class extends Error{constructor(){super(...arguments);this.name="OpenAPIError"}},N=class extends Error{constructor(){super(...arguments);this.name="IOSchemaError"}},F=class extends N{constructor(r){super(K(r));this.name="OutputValidationError";this.originalError=r}},w=class extends N{constructor(r){super(K(r));this.name="InputValidationError";this.originalError=r}},Q=class extends Error{constructor(r,o){super(r);this.name="ResultHandlerError";this.originalError=o||void 0}};var Z=e=>typeof e=="object"&&e!==null,De=e=>({and:e.reduce((t,r)=>t.concat(Z(r)&&"and"in r?r.and:r),[])}),Ce=(e,t)=>{if(Z(e)){if("and"in e)return{and:e.and.map(r=>Z(r)&&"or"in r?{or:r.or.map(t)}:t(r))};if("or"in e)return{or:e.or.map(r=>Z(r)&&"and"in r?{and:r.and.map(t)}:t(r))}}return t(e)},ot=e=>e.and.reduce((t,r)=>{let o=ce(t.or,Z(r)&&"or"in r?r.or:[r]);return o.type==="single"?t.or.push(...o.value):t.or=o.value.map(De),t},{or:[]}),W=(e,t)=>{if(Z(e)){if("and"in e){if(Z(t)){if("and"in t)return De([e,t]);if("or"in t)return W(ot(e),t)}return De([e,t])}if("or"in e){if(Z(t)){if("and"in t)return W(t,e);if("or"in t){let r=ce(e.or,t.or);return{or:r.type==="single"?r.value:r.value.map(De)}}}return W(e,{and:[t]})}}return Z(t)&&("and"in t||"or"in t)?W(t,e):{and:[e,t]}};import{z as X}from"zod";var ee={positive:200,negative:400},vt=e=>e,te=vt({getPositiveResponse:e=>{let t=je(e,"examples")||[],r=_(X.object({status:X.literal("success"),data:e}));return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},getNegativeResponse:()=>_(X.object({status:X.literal("error"),error:X.object({message:X.string()})})).example({status:"error",error:{message:K(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(ee.positive).json({status:"success",data:r});return}let a=et(e);a===500&&i.error(`Internal server error
1
+ var Cr=Object.defineProperty;var wr=(e,t)=>{for(var r in t)Cr(e,r,{get:t[r],enumerable:!0})};var Nr=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var D=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)};var E=(e,t,r)=>(Nr(e,t,"access private method"),r);var Nt={silent:!0,warn:!0,debug:!0},vr=e=>e;import{z as v}from"zod";import{createHash as _r}from"crypto";import{HttpError as Gr}from"http-errors";import{z as T}from"zod";import{clone as Mr,mergeDeepRight as zr}from"ramda";var S="expressZodApiMeta",kr=e=>{let t=e.constructor,r=Mr(e._def);return r[S]=r[S]||{examples:[]},new t(r)},G=e=>{let t=kr(e);return Object.defineProperties(t,{example:{get:()=>r=>{let o=G(t);return o._def[S].examples.push(r),o}}}),t},vt=e=>S in e._def?typeof e._def[S]=="object"&&e._def[S]!==null:!1;function je(e,t){if(!vt(e))return;let r=e._def;return t in r[S]?r[S][t]:void 0}var Re=(e,t)=>{if(!vt(e))return t;let r=G(t),o=ce(r._def[S].examples,e._def[S].examples);if(r._def[S].examples=[],o.type==="single")r._def[S].examples=o.value;else for(let[n,i]of o.value)r._def[S].examples.push(zr({...n},{...i}));return r};import Lr from"mime";var U=Lr.getType("json")||"application/json",pe="multipart/form-data";import{INVALID as Ur,OK as Hr,ZodIssueCode as Kr,ZodParsedType as Fr,ZodType as Br,addIssueToContext as $r}from"zod";var qr="ZodUpload",Vr=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.mimetype=="string"&&typeof e.data=="object"&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",We=class extends Br{_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==Fr.object||!Vr(r.data)?($r(r,{code:Kr.custom,message:`Expected file upload, received ${r.parsedType}`}),Ur):Hr(r.data)}},H=We;H.create=()=>new We({typeName:qr});var Xe=/:([A-Za-z0-9_]+)/g;function Yr(e){let r=(e.header("content-type")||"").slice(0,pe.length).toLowerCase()===pe;return"files"in e&&r}var Pe={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Jr=["body","query","params"],et=e=>e.method.toLowerCase();function Mt(e,t){let r=et(e);if(r==="options")return{};let o=Jr;return r in Pe&&(o=Pe[r]),t&&r in t&&(o=t[r]||o),o.filter(n=>n==="files"?Yr(e):!0).reduce((n,i)=>({...n,...e[i]}),{})}function tt(e){return typeof e=="object"&&"level"in e&&"color"in e&&Object.keys(Nt).includes(e.level)&&typeof e.color=="boolean"}function Ee(e){return!isNaN(e.getTime())}function Y(e){return e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`)}function K(e){return e instanceof T.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof F?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message}function rt(e){return e instanceof Gr?e.statusCode:e instanceof w?400:500}var Ie=(e,t)=>{let r=[],o=je(e,"examples");for(let n of o||[]){let i=e.safeParse(n);i.success&&r.push(t?i.data:n)}return r},ce=(e,t)=>{if(e.length===0)return{type:"single",value:t};if(t.length===0)return{type:"single",value:e};let r=[];for(let o of e)for(let n of t)r.push([o,n]);return{type:"tuple",value:r}};function ot(e){let t=e.match(Xe);return t?t.map(r=>r.slice(1)):[]}var de=e=>e.reduce((t,r)=>t||r,!1);function C(e){return e instanceof T.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof T.ZodUnion?de(e.options.map(C)):e instanceof T.ZodIntersection?de([e._def.left,e._def.right].map(C)):!1}function I(e){return e instanceof H?!0:e instanceof T.ZodObject?de(Object.values(e.shape).map(I)):e instanceof T.ZodUnion?de(e.options.map(I)):e instanceof T.ZodIntersection?de([e._def.left,e._def.right].map(I)):e instanceof T.ZodOptional||e instanceof T.ZodNullable?I(e.unwrap()):e instanceof T.ZodEffects||e instanceof T.ZodTransformer?I(e._def.schema):e instanceof T.ZodRecord?I(e._def.valueType):e instanceof T.ZodArray?I(e._def.type):e instanceof T.ZodDefault?I(e._def.innerType):!1}var me=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,A=(e,t,r)=>[t].concat(e.split("/")).concat(r||[]).flatMap(o=>o.split(/[^A-Z0-9]/gi)).map(o=>o.slice(0,1).toUpperCase()+o.slice(1).toLowerCase()).join(""),Ae=e=>_r("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ze=({effect:e,sample:t})=>{try{return typeof e.transform(t,{addIssue:()=>{},path:[]})}catch{return}},nt=e=>typeof e=="string"?{message:e}:e||{};var J=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},le=class extends J{constructor(){super(...arguments);this.name="DependsOnMethodError"}},R=class extends Error{constructor(){super(...arguments);this.name="OpenAPIError"}},N=class extends Error{constructor(){super(...arguments);this.name="IOSchemaError"}},F=class extends N{constructor(r){super(K(r));this.name="OutputValidationError";this.originalError=r}},w=class extends N{constructor(r){super(K(r));this.name="InputValidationError";this.originalError=r}},Q=class extends Error{constructor(r,o){super(r);this.name="ResultHandlerError";this.originalError=o||void 0}};var Z=e=>typeof e=="object"&&e!==null,De=e=>({and:e.reduce((t,r)=>t.concat(Z(r)&&"and"in r?r.and:r),[])}),Ce=(e,t)=>{if(Z(e)){if("and"in e)return{and:e.and.map(r=>Z(r)&&"or"in r?{or:r.or.map(t)}:t(r))};if("or"in e)return{or:e.or.map(r=>Z(r)&&"and"in r?{and:r.and.map(t)}:t(r))}}return t(e)},it=e=>e.and.reduce((t,r)=>{let o=ce(t.or,Z(r)&&"or"in r?r.or:[r]);return o.type==="single"?t.or.push(...o.value):t.or=o.value.map(De),t},{or:[]}),W=(e,t)=>{if(Z(e)){if("and"in e){if(Z(t)){if("and"in t)return De([e,t]);if("or"in t)return W(it(e),t)}return De([e,t])}if("or"in e){if(Z(t)){if("and"in t)return W(t,e);if("or"in t){let r=ce(e.or,t.or);return{or:r.type==="single"?r.value:r.value.map(De)}}}return W(e,{and:[t]})}}return Z(t)&&("and"in t||"or"in t)?W(t,e):{and:[e,t]}};import{z as X}from"zod";var ee={positive:200,negative:400},zt=e=>e,te=zt({getPositiveResponse:e=>{let t=je(e,"examples")||[],r=G(X.object({status:X.literal("success"),data:e}));return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},getNegativeResponse:()=>G(X.object({status:X.literal("error"),error:X.object({message:X.string()})})).example({status:"error",error:{message:K(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(ee.positive).json({status:"success",data:r});return}let a=rt(e);a===500&&i.error(`Internal server error
2
2
  ${e.stack}
3
3
  `,{url:o.url,payload:t}),n.status(a).json({status:"error",error:{message:K(e)}})}}),we=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
4
- Original error: ${e.originalError.message}.`:""))};var Mt=(e,t=[U])=>{if(e instanceof v.ZodType)return t;let{mimeTypes:r,mimeType:o}=e;return o?[o]:r||t},re=class{},ve,zt,Me,kt,ze,Lt,ke,Ut,Le,Ht,Ne=class extends re{constructor({middlewares:r,inputSchema:o,outputSchema:n,handler:i,resultHandler:a,description:c,shortDescription:d,...p}){super();D(this,ve);D(this,Me);D(this,ze);D(this,ke);D(this,Le);this.methods=[];this.siblingMethods=[];this.middlewares=[];this.scopes=[];this.tags=[];[{name:"input schema",schema:o},{name:"output schema",schema:n}].forEach(({name:f,schema:h})=>{if(C(h))throw new N(`Using transformations on the top level of endpoint ${f} is not allowed.`)}),this.middlewares=r;let m={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:I(o)?[pe]:[U],positive:Mt(m.positive),negative:Mt(m.negative)},this.schemas={input:o,output:n,positive:m.positive instanceof v.ZodType?m.positive:m.positive.schema,negative:m.negative instanceof v.ZodType?m.negative:m.negative.schema},this.statusCodes={positive:m.positive instanceof v.ZodType?ee.positive:m.positive.statusCode||ee.positive,negative:m.negative instanceof v.ZodType?ee.negative:m.negative.statusCode||ee.negative},this.handler=i,this.resultHandler=a,this.descriptions={long:c,short:d},"scopes"in p&&p.scopes&&this.scopes.push(...p.scopes),"scope"in p&&p.scope&&this.scopes.push(p.scope),"tags"in p&&p.tags&&this.tags.push(...p.tags),"tag"in p&&p.tag&&this.tags.push(p.tag),"methods"in p?this.methods=p.methods:this.methods=[p.method]}_setSiblingMethods(r){this.siblingMethods=r}getDescription(r){return this.descriptions[r]}getMethods(){return this.methods}getSchema(r){return this.schemas[r]}getMimeTypes(r){return this.mimeTypes[r]}getStatusCode(r){return this.statusCodes[r]}getSecurity(){return this.middlewares.reduce((r,o)=>o.security?W(r,o.security):r,{and:[]})}getScopes(){return this.scopes}getTags(){return this.tags}async execute({request:r,response:o,logger:n,config:i}){let a=We(r),c,d=null;if(i.cors){let m=E(this,ve,zt).call(this);typeof i.cors=="function"&&(m=await i.cors({request:r,logger:n,endpoint:this,defaultHeaders:m}));for(let f in m)o.set(f,m[f])}let p=Nt(r,i.inputSources);try{let{options:m,isStreamClosed:f}=await E(this,ze,Lt).call(this,{method:a,input:p,request:r,response:o,logger:n});if(f)return;if(a==="options"){o.status(200).end();return}c=await E(this,Me,kt).call(this,await E(this,ke,Ut).call(this,{input:p,options:m,logger:n}))}catch(m){d=Y(m)}await E(this,Le,Ht).call(this,{input:p,output:c,request:r,response:o,error:d,logger:n})}};ve=new WeakSet,zt=function(){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.methods.concat(this.siblingMethods).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}},Me=new WeakSet,kt=async function(r){try{return await this.schemas.output.parseAsync(r)}catch(o){throw o instanceof v.ZodError?new F(o):o}},ze=new WeakSet,Lt=async function({method:r,input:o,request:n,response:i,logger:a}){let c={},d=!1;for(let p of this.middlewares){if(r==="options"&&p.type==="proprietary")continue;let m;try{m=await p.input.parseAsync(o)}catch(f){throw f instanceof v.ZodError?new w(f):f}if(Object.assign(c,await p.middleware({input:m,options:c,request:n,response:i,logger:a})),d="writableEnded"in i&&i.writableEnded,d){a.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,c);break}}return{options:c,isStreamClosed:d}},ke=new WeakSet,Ut=async function({input:r,options:o,logger:n}){let i;try{i=await this.schemas.input.parseAsync(r)}catch(a){throw a instanceof v.ZodError?new w(a):a}return this.handler({input:i,options:o,logger:n})},Le=new WeakSet,Ht=async function({error:r,request:o,response:n,logger:i,input:a,output:c}){try{await this.resultHandler.handler({error:r,output:c,request:o,response:n,logger:i,input:a})}catch(d){we({logger:i,response:n,error:new Q(Y(d).message,r)})}};var Kt=["get","post","put","delete","patch"];import{z as Bt}from"zod";var Ft=(e,t)=>{let r=e.map(({input:n})=>n).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>Re(i,n),o)};var nt=e=>{if(C(e.input))throw new N("Using transformations on the top level of middleware input schema is not allowed.");return{...e,type:"proprietary"}};var ne,Ue,oe=class{constructor(t){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in t?t.resultHandler:t}addMiddleware(t){var r;return E(r=oe,ne,Ue).call(r,this.middlewares.concat(t),this.resultHandler)}addExpressMiddleware(t,r){var a;let o=r?.transformer||(c=>c),n=r?.provider||(()=>({})),i={type:"express",input:Bt.object({}),middleware:async({request:c,response:d})=>new Promise((p,m)=>{t(c,d,h=>{if(h&&h instanceof Error)return m(o(h));p(n(c,d))})})};return E(a=oe,ne,Ue).call(a,this.middlewares.concat(i),this.resultHandler)}addOptions(t){var r;return E(r=oe,ne,Ue).call(r,this.middlewares.concat(nt({input:Bt.object({}),middleware:async()=>t})),this.resultHandler)}build({input:t,handler:r,output:o,...n}){let{middlewares:i,resultHandler:a}=this;return new Ne({handler:r,middlewares:i,outputSchema:o,resultHandler:a,inputSchema:Ft(i,t),...n})}},ue=oe;ne=new WeakSet,Ue=function(t,r){let o=new oe(r);return o.middlewares=t,o},D(ue,ne);var Yr=new ue(te);import{inspect as Jr}from"util";import{LEVEL as Qr,MESSAGE as Wr,SPLAT as Xr}from"triple-beam";import He from"winston";var{combine:eo,colorize:to,timestamp:ro,printf:oo}=He.format;function Ke(e){let t=i=>{let{[Qr]:a,[Wr]:c,[Xr]:d,...p}=i;return Jr(p,!1,1,e.color)},r=i=>oo(({timestamp:a,message:c,level:d,durationMs:p,...m})=>(typeof c=="object"&&(m={...m,...c},c="[No message]"),`${a} ${d}: ${c}`+(p===void 0?"":` duration: ${p}ms`)+(Object.keys(m).length===0?"":" "+(i?t(m):JSON.stringify(m))))),o=[ro()],n={handleExceptions:!0};switch(e.color&&o.push(to()),e.level){case"debug":n.level="debug",o.push(r(!0));break;case"silent":case"warn":default:n.level="warn",o.push(r())}return n.format=eo(...o),He.createLogger({silent:e.level==="silent",levels:He.config.npm.levels,transports:[new He.transports.Console(n)],exitOnError:!1})}var fe=class{constructor(t){this.methods=t;Object.keys(t).forEach(r=>{if(r in t&&!(t[r]?.getMethods()||[]).includes(r))throw new le(`The endpoint assigned to the '${r}' parameter must have at least this method in its specification.
4
+ Original error: ${e.originalError.message}.`:""))};var kt=(e,t=[U])=>{if(e instanceof v.ZodType)return t;let{mimeTypes:r,mimeType:o}=e;return o?[o]:r||t},re=class{},ve,Lt,Me,Ut,ze,Ht,ke,Kt,Le,Ft,Ne=class extends re{constructor({middlewares:r,inputSchema:o,outputSchema:n,handler:i,resultHandler:a,description:c,shortDescription:d,...p}){super();D(this,ve);D(this,Me);D(this,ze);D(this,ke);D(this,Le);this.methods=[];this.siblingMethods=[];this.middlewares=[];this.scopes=[];this.tags=[];[{name:"input schema",schema:o},{name:"output schema",schema:n}].forEach(({name:f,schema:h})=>{if(C(h))throw new N(`Using transformations on the top level of endpoint ${f} is not allowed.`)}),this.middlewares=r;let m={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:I(o)?[pe]:[U],positive:kt(m.positive),negative:kt(m.negative)},this.schemas={input:o,output:n,positive:m.positive instanceof v.ZodType?m.positive:m.positive.schema,negative:m.negative instanceof v.ZodType?m.negative:m.negative.schema},this.statusCodes={positive:m.positive instanceof v.ZodType?ee.positive:m.positive.statusCode||ee.positive,negative:m.negative instanceof v.ZodType?ee.negative:m.negative.statusCode||ee.negative},this.handler=i,this.resultHandler=a,this.descriptions={long:c,short:d},"scopes"in p&&p.scopes&&this.scopes.push(...p.scopes),"scope"in p&&p.scope&&this.scopes.push(p.scope),"tags"in p&&p.tags&&this.tags.push(...p.tags),"tag"in p&&p.tag&&this.tags.push(p.tag),"methods"in p?this.methods=p.methods:this.methods=[p.method]}_setSiblingMethods(r){this.siblingMethods=r}getDescription(r){return this.descriptions[r]}getMethods(){return this.methods}getSchema(r){return this.schemas[r]}getMimeTypes(r){return this.mimeTypes[r]}getStatusCode(r){return this.statusCodes[r]}getSecurity(){return this.middlewares.reduce((r,o)=>o.security?W(r,o.security):r,{and:[]})}getScopes(){return this.scopes}getTags(){return this.tags}async execute({request:r,response:o,logger:n,config:i}){let a=et(r),c,d=null;if(i.cors){let m=E(this,ve,Lt).call(this);typeof i.cors=="function"&&(m=await i.cors({request:r,logger:n,endpoint:this,defaultHeaders:m}));for(let f in m)o.set(f,m[f])}let p=Mt(r,i.inputSources);try{let{options:m,isStreamClosed:f}=await E(this,ze,Ht).call(this,{method:a,input:p,request:r,response:o,logger:n});if(f)return;if(a==="options"){o.status(200).end();return}c=await E(this,Me,Ut).call(this,await E(this,ke,Kt).call(this,{input:p,options:m,logger:n}))}catch(m){d=Y(m)}await E(this,Le,Ft).call(this,{input:p,output:c,request:r,response:o,error:d,logger:n})}};ve=new WeakSet,Lt=function(){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.methods.concat(this.siblingMethods).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}},Me=new WeakSet,Ut=async function(r){try{return await this.schemas.output.parseAsync(r)}catch(o){throw o instanceof v.ZodError?new F(o):o}},ze=new WeakSet,Ht=async function({method:r,input:o,request:n,response:i,logger:a}){let c={},d=!1;for(let p of this.middlewares){if(r==="options"&&p.type==="proprietary")continue;let m;try{m=await p.input.parseAsync(o)}catch(f){throw f instanceof v.ZodError?new w(f):f}if(Object.assign(c,await p.middleware({input:m,options:c,request:n,response:i,logger:a})),d="writableEnded"in i&&i.writableEnded,d){a.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,c);break}}return{options:c,isStreamClosed:d}},ke=new WeakSet,Kt=async function({input:r,options:o,logger:n}){let i;try{i=await this.schemas.input.parseAsync(r)}catch(a){throw a instanceof v.ZodError?new w(a):a}return this.handler({input:i,options:o,logger:n})},Le=new WeakSet,Ft=async function({error:r,request:o,response:n,logger:i,input:a,output:c}){try{await this.resultHandler.handler({error:r,output:c,request:o,response:n,logger:i,input:a})}catch(d){we({logger:i,response:n,error:new Q(Y(d).message,r)})}};var Bt=["get","post","put","delete","patch"];import{z as qt}from"zod";var $t=(e,t)=>{let r=e.map(({input:n})=>n).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>Re(i,n),o)};var st=e=>{if(C(e.input))throw new N("Using transformations on the top level of middleware input schema is not allowed.");return{...e,type:"proprietary"}};var ne,Ue,oe=class{constructor(t){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in t?t.resultHandler:t}addMiddleware(t){var r;return E(r=oe,ne,Ue).call(r,this.middlewares.concat(t),this.resultHandler)}addExpressMiddleware(t,r){var a;let o=r?.transformer||(c=>c),n=r?.provider||(()=>({})),i={type:"express",input:qt.object({}),middleware:async({request:c,response:d})=>new Promise((p,m)=>{t(c,d,h=>{if(h&&h instanceof Error)return m(o(h));p(n(c,d))})})};return E(a=oe,ne,Ue).call(a,this.middlewares.concat(i),this.resultHandler)}addOptions(t){var r;return E(r=oe,ne,Ue).call(r,this.middlewares.concat(st({input:qt.object({}),middleware:async()=>t})),this.resultHandler)}build({input:t,handler:r,output:o,...n}){let{middlewares:i,resultHandler:a}=this;return new Ne({handler:r,middlewares:i,outputSchema:o,resultHandler:a,inputSchema:$t(i,t),...n})}},ue=oe;ne=new WeakSet,Ue=function(t,r){let o=new oe(r);return o.middlewares=t,o},D(ue,ne);var Qr=new ue(te);import{inspect as Wr}from"util";import{LEVEL as Xr,MESSAGE as eo,SPLAT as to}from"triple-beam";import He from"winston";var{combine:ro,colorize:oo,timestamp:no,printf:io}=He.format;function Ke(e){let t=i=>{let{[Xr]:a,[eo]:c,[to]:d,...p}=i;return Wr(p,!1,1,e.color)},r=i=>io(({timestamp:a,message:c,level:d,durationMs:p,...m})=>(typeof c=="object"&&(m={...m,...c},c="[No message]"),`${a} ${d}: ${c}`+(p===void 0?"":` duration: ${p}ms`)+(Object.keys(m).length===0?"":" "+(i?t(m):JSON.stringify(m))))),o=[no()],n={handleExceptions:!0};switch(e.color&&o.push(oo()),e.level){case"debug":n.level="debug",o.push(r(!0));break;case"silent":case"warn":default:n.level="warn",o.push(r())}return n.format=ro(...o),He.createLogger({silent:e.level==="silent",levels:He.config.npm.levels,transports:[new He.transports.Console(n)],exitOnError:!1})}var fe=class{constructor(t){this.methods=t;Object.keys(t).forEach(r=>{if(r in t&&!(t[r]?.getMethods()||[]).includes(r))throw new le(`The endpoint assigned to the '${r}' parameter must have at least this method in its specification.
5
5
  This error should prevent mistakes during the development process.
6
6
  Example:
7
7
 
@@ -12,8 +12,8 @@ new ${this.constructor.name}({
12
12
  ...
13
13
  })
14
14
  });
15
- `)})}};import no from"express";var ye=class{constructor(...t){this.params=t}apply(t,r){return r(t,no.static(...this.params))}};var B=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{Object.entries(e).forEach(([i,a])=>{if(i=i.trim(),i.match(/\//))throw new J(`Routing elements should not contain '/' character.
16
- The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let c=`${o||""}${i?`/${i}`:""}`;if(a instanceof re){let d=a.getMethods().slice();n&&d.push("options"),d.forEach(p=>{t(a,c,p)})}else if(a instanceof ye)r&&a.apply(c,r);else if(a instanceof fe){if(Object.entries(a.methods).forEach(([d,p])=>{t(p,c,d)}),n&&Object.keys(a.methods).length>0){let[d,...p]=Object.keys(a.methods),m=a.methods[d];m._setSiblingMethods(p),t(m,c,"options")}}else B({onEndpoint:t,onStatic:r,hasCors:n,routing:a,parentPath:c})})};var $t=()=>`
15
+ `)})}};import so from"express";var ye=class{constructor(...t){this.params=t}apply(t,r){return r(t,so.static(...this.params))}};var B=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{Object.entries(e).forEach(([i,a])=>{if(i=i.trim(),i.match(/\//))throw new J(`Routing elements should not contain '/' character.
16
+ The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let c=`${o||""}${i?`/${i}`:""}`;if(a instanceof re){let d=a.getMethods().slice();n&&d.push("options"),d.forEach(p=>{t(a,c,p)})}else if(a instanceof ye)r&&a.apply(c,r);else if(a instanceof fe){if(Object.entries(a.methods).forEach(([d,p])=>{t(p,c,d)}),n&&Object.keys(a.methods).length>0){let[d,...p]=Object.keys(a.methods),m=a.methods[d];m._setSiblingMethods(p),t(m,c,"options")}}else B({onEndpoint:t,onStatic:r,hasCors:n,routing:a,parentPath:c})})};var Vt=()=>`
17
17
  \x1B[94m\x1B[39m
18
18
  \x1B[94m\x1B[39m
19
19
  \x1B[94m8888888888 8888888888P 888 d8888 8888888b. 8888888 \x1B[39m
@@ -30,7 +30,7 @@ The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let
30
30
  \x1B[90m\x1B[3m Thank you for choosing Express Zod API for your project.\x1B[23m\x1B[39m\x1B[0m\x1B[0m
31
31
  \x1B[0m\x1B[0m
32
32
  \x1B[0m\x1B[0m
33
- `.trim();var it=({app:e,logger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log($t()),B({routing:o,hasCors:!!r.cors,onEndpoint:(n,i,a)=>{e[a](i,async(c,d)=>{t.info(`${c.method}: ${i}`),await n.execute({request:c,response:d,logger:t,config:r})})},onStatic:(n,i)=>{e.use(n,i)}})};import io,{json as so}from"express";import ao from"compression";import co from"express-fileupload";import po from"https";import qt from"http-errors";var mo=(e,t)=>(r,o,n,i)=>{if(!r)return i();e.handler({error:qt(400,Y(r).message),request:o,response:n,logger:t,input:o.body,output:null})},Vt=(e,t)=>(r,o)=>{let n=qt(404,`Can not ${r.method} ${r.path}`);try{e.handler({request:r,response:o,logger:t,error:n,input:null,output:null})}catch(i){we({response:o,logger:t,error:new Q(Y(i).message,n)})}};function lo(e,t){let r=Xe(e.logger)?Ke(e.logger):e.logger;it({app:e.app,routing:t,logger:r,config:e});let o=e.errorHandler||te;return{notFoundHandler:Vt(o,r),logger:r}}function uo(e,t){let r=Xe(e.logger)?Ke(e.logger):e.logger,o=io();o.disable("x-powered-by");let n=e.errorHandler||te,i=e.server.compression?ao({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||so(),c=e.server.upload?co({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,d=[].concat(i||[]).concat(a).concat(c||[]);o.use(d),o.use(mo(n,r)),it({app:o,routing:t,logger:r,config:e}),o.use(Vt(n,r));let p=o.listen(e.server.listen,()=>{r.info(`Listening ${e.server.listen}`)}),m;return e.https&&(m=po.createServer(e.https.options,o).listen(e.https.listen,()=>{r.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:p,httpsServer:m,logger:r}}import*as Gt from"yaml";var $=class{static create(t){return new $(t)}constructor(t){this.rootDoc=t||{openapi:"3.0.0",info:{title:"app",version:"version"},paths:{},components:{schemas:{},responses:{},parameters:{},examples:{},requestBodies:{},headers:{},securitySchemes:{},links:{},callbacks:{}},tags:[],servers:[]}}getSpec(){return this.rootDoc}getSpecAsJson(t,r){return JSON.stringify(this.rootDoc,t,r)}getSpecAsYaml(){return Gt.stringify(this.rootDoc)}static isValidOpenApiVersion(t){t=t||"";let r=/(\d+)\.(\d+).(\d+)/.exec(t);return!!(r&&parseInt(r[1],10)>=3)}addOpenApiVersion(t){if(!$.isValidOpenApiVersion(t))throw new Error("Invalid OpenApi version: "+t+". Follow convention: 3.x.y");return this.rootDoc.openapi=t,this}addInfo(t){return this.rootDoc.info=t,this}addContact(t){return this.rootDoc.info.contact=t,this}addLicense(t){return this.rootDoc.info.license=t,this}addTitle(t){return this.rootDoc.info.title=t,this}addDescription(t){return this.rootDoc.info.description=t,this}addTermsOfService(t){return this.rootDoc.info.termsOfService=t,this}addVersion(t){return this.rootDoc.info.version=t,this}addPath(t,r){return this.rootDoc.paths[t]={...this.rootDoc.paths[t]||{},...r},this}addSchema(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.schemas=this.rootDoc.components.schemas||{},this.rootDoc.components.schemas[t]=r,this}addResponse(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.responses=this.rootDoc.components.responses||{},this.rootDoc.components.responses[t]=r,this}addParameter(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.parameters=this.rootDoc.components.parameters||{},this.rootDoc.components.parameters[t]=r,this}addExample(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.examples=this.rootDoc.components.examples||{},this.rootDoc.components.examples[t]=r,this}addRequestBody(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.requestBodies=this.rootDoc.components.requestBodies||{},this.rootDoc.components.requestBodies[t]=r,this}addHeader(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.headers=this.rootDoc.components.headers||{},this.rootDoc.components.headers[t]=r,this}addSecurityScheme(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.securitySchemes=this.rootDoc.components.securitySchemes||{},this.rootDoc.components.securitySchemes[t]=r,this}addLink(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.links=this.rootDoc.components.links||{},this.rootDoc.components.links[t]=r,this}addCallback(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.callbacks=this.rootDoc.components.callbacks||{},this.rootDoc.components.callbacks[t]=r,this}addServer(t){return this.rootDoc.servers=this.rootDoc.servers||[],this.rootDoc.servers.push(t),this}addTag(t){return this.rootDoc.tags=this.rootDoc.tags||[],this.rootDoc.tags.push(t),this}addExternalDocs(t){return this.rootDoc.externalDocs=t,this}};import{omit as xe}from"ramda";import{z as x}from"zod";import{INVALID as _t,ZodIssueCode as st,ZodParsedType as Yt,ZodType as fo,addIssueToContext as at}from"zod";var ct=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,yo="ZodDateIn",pt=class extends fo{_parse(t){let{status:r,ctx:o}=this._processInputParams(t);if(o.parsedType!==Yt.string)return at(o,{code:st.invalid_type,expected:Yt.string,received:o.parsedType}),_t;ct.test(o.data)||(at(o,{code:st.invalid_string,validation:"regex"}),r.dirty());let n=new Date(o.data);return Ee(n)?{status:r.value,value:n}:(at(o,{code:st.invalid_date}),_t)}},ge=pt;ge.create=()=>new pt({typeName:yo});function dt(e){return Object.prototype.hasOwnProperty.call(e,"$ref")}function ie(e){return!Object.prototype.hasOwnProperty.call(e,"$ref")}var q=({schema:e,onEach:t,rules:r,onMissing:o,...n})=>{let i="typeName"in e._def?r[e._def.typeName]:void 0,c=i?i({schema:e,...n,next:p=>q({...p,...n,onEach:t,rules:r,onMissing:o})}):o(e),d=t&&t({schema:e,prev:c,...n});return d?{...c,...d}:c};var Jt=50,Wt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",go={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Xt=e=>e.replace(Qe,t=>`{${t.slice(1)}}`),ho=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r({schema:e}),default:t()}),xo=({schema:{_def:{innerType:e}},next:t})=>t({schema:e}),Oo=()=>({format:"any"}),bo=({isResponse:e})=>{if(e)throw new R("Please use z.upload() only for input.");return{type:"string",format:"binary"}},To=({schema:{isBinary:e,isBase64:t},isResponse:r})=>{if(!r)throw new R("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":t?"byte":"file"}},So=({schema:{options:e},next:t})=>({oneOf:e.map(r=>t({schema:r}))}),jo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(o=>r({schema:o}))}),Ro=({schema:{_def:{left:e,right:t}},next:r})=>({allOf:[e,t].map(o=>r({schema:o}))}),Po=({schema:e,next:t})=>t({schema:e.unwrap()}),Eo=({schema:e,next:t})=>({nullable:!0,...t({schema:e.unwrap()})}),Qt=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),Io=({schema:{value:e}})=>({type:typeof e,enum:[e]}),Ao=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(t&&me(i)?i instanceof x.ZodOptional:i.isOptional())});return{type:"object",properties:Fe({schema:e,isResponse:t,...r}),...o.length?{required:o}:{}}},Zo=()=>({type:"string",nullable:!0,format:"null"}),Do=({isResponse:e})=>{if(e)throw new R("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ct.source,externalDocs:{url:Wt}}},Co=({isResponse:e})=>{if(!e)throw new R("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Wt}}},wo=({isResponse:e})=>{throw new R(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},No=()=>({type:"boolean"}),vo=()=>({type:"integer",format:"bigint"}),Mo=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),n=o.reduce((i,a)=>({...i,[a]:t}),{});return{type:"object",properties:Fe({schema:x.object(n),...r}),...o.length?{required:o}:{}}}if(e instanceof x.ZodLiteral)return{type:"object",properties:Fe({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&e.options.reduce((n,i)=>n&&i instanceof x.ZodLiteral,!0)){let n=e.options.reduce((i,a)=>({...i,[a.value]:t}),{});return{type:"object",properties:Fe({schema:x.object(n),...r}),required:e.options.map(i=>i.value)}}return{type:"object",additionalProperties:r.next({schema:t})}},zo=({schema:{_def:e,element:t},next:r})=>({type:"array",items:r({schema:t}),...e.minLength!==null&&{minItems:e.minLength.value},...e.maxLength!==null&&{maxItems:e.maxLength.value}}),ko=({schema:{items:e},next:t})=>{let r=e.map(o=>t({schema:o}));return{type:"array",minItems:r.length,maxItems:r.length,items:{oneOf:r,format:"tuple",...r.length>0&&{description:r.map((o,n)=>`${n}: ${ie(o)?o.type:o.$ref}`).join(", ")}}}},Lo=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,_def:{checks:f}}})=>{let h=f.find(l=>l.kind==="regex"),g=f.find(l=>l.kind==="datetime"),O=h?h.regex:g?g.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0;return{type:"string",...m&&{format:"date-time"},...e&&{format:"email"},...t&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...c&&{format:"ulid"},...d&&{format:"ip"},...p&&{format:"emoji"},...r!==null&&{minLength:r},...o!==null&&{maxLength:o},...O&&{pattern:`/${O.source}/${O.flags}`}}},Uo=({schema:e})=>{let t=e._def.checks.find(({kind:i})=>i==="min"),r=t?t.inclusive:!0,o=e._def.checks.find(({kind:i})=>i==="max"),n=o?o.inclusive:!0;return{type:e.isInt?"integer":"number",format:e.isInt?"int64":"double",minimum:e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:Number.MIN_VALUE:e.minValue,exclusiveMinimum:!r,maximum:e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,exclusiveMaximum:!n}},Fe=({schema:{shape:e},next:t})=>Object.keys(e).reduce((r,o)=>({...r,[o]:t({schema:e[o]})}),{}),Ho=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return go?.[t]},Ko=({schema:e,isResponse:t,next:r})=>{let o=r({schema:e.innerType()}),{effect:n}=e._def;if(t&&n.type==="transform"&&ie(o)){let i=Ze({effect:n,sample:Ho(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:r({schema:x.any()})}if(!t&&n.type==="preprocess"&&ie(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Fo=({schema:e,isResponse:t,next:r})=>r({schema:e._def[t?"out":"in"]}),Bo=({schema:e,next:t})=>t({schema:e.unwrap()}),$o=({next:e,schema:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(t.schema);return o(i)||(()=>(n(i,{}),n(i,e({schema:t.schema}))))()},er=(e,t,r=[])=>{let o=Ie(e,t);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:xe(r,i)}}),{})}},qo=(e,t,r)=>{let o=Ie(e,t);return o.length===0?{}:{examples:o.reduce((n,i,a)=>r in i?{...n,[`example${a+1}`]:{value:i[r]}}:n,{})}};function he(e){if(e instanceof x.ZodObject)return e;let t;if(e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion)t=Array.from(e.options.values()).map(r=>he(r)).reduce((r,o)=>r.merge(o.partial()),x.object({}));else if(e instanceof x.ZodEffects){if(C(e))throw new R("Using transformations on the top level of input schema is not allowed.");t=he(e._def.schema)}else t=he(e._def.left).merge(he(e._def.right));return Re(e,t)}var tr=({path:e,method:t,endpoint:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:c,clue:d="parameter"})=>{let p=r.getSchema("input"),m=he(p).shape,f=tt(e),h=o.includes("query"),g=o.includes("params"),O=l=>g&&f.includes(l);return Object.keys(m).filter(l=>h||O(l)).map(l=>{let b=q({schema:m[l],isResponse:!1,rules:lt,onEach:ut,onMissing:ft,serializer:n,getRef:i,makeRef:a}),j=c==="components"?a(A(e,t,`${d} ${l}`),b):b;return{name:l,in:O(l)?"path":"query",required:!m[l].isOptional(),description:ie(b)&&b.description||`${t.toUpperCase()} ${e} ${d}`,schema:j,...qo(p,!1,l)}})},lt={ZodString:Lo,ZodNumber:Uo,ZodBigInt:vo,ZodBoolean:No,ZodDateIn:Do,ZodDateOut:Co,ZodNull:Zo,ZodArray:zo,ZodTuple:ko,ZodRecord:Mo,ZodObject:Ao,ZodLiteral:Io,ZodIntersection:Ro,ZodUnion:So,ZodFile:To,ZodUpload:bo,ZodAny:Oo,ZodDefault:ho,ZodEnum:Qt,ZodNativeEnum:Qt,ZodEffects:Ko,ZodOptional:Po,ZodNullable:Eo,ZodDiscriminatedUnion:jo,ZodBranded:Bo,ZodDate:wo,ZodCatch:xo,ZodPipeline:Fo,ZodLazy:$o},ut=({schema:e,isResponse:t,prev:r})=>{if(dt(r))return{};let{description:o}=e,n=e instanceof x.ZodLazy,i=r.type!==void 0,a=t&&me(e),c=!n&&i&&!a&&e.isNullable(),d=n?[]:Ie(e,t);return{...o&&{description:o},...c&&{nullable:!0},...d.length>0&&{example:d[0]}}},ft=e=>{throw new R(`Zod type ${e.constructor.name} is unsupported`)},mt=(e,t)=>{if(dt(e))return e;let r=e.properties?xe(t,e.properties):void 0,o=e.example?xe(t,e.example):void 0,n=e.required?e.required.filter(c=>!t.includes(c)):void 0,i=e.allOf?e.allOf.map(c=>mt(c,t)):void 0,a=e.oneOf?e.oneOf.map(c=>mt(c,t)):void 0;return xe(Object.entries({properties:r,required:n,example:o,allOf:i,oneOf:a}).filter(([{},c])=>c===void 0).map(([c])=>c),{...e,properties:r,required:n,example:o,allOf:i,oneOf:a})},rr=e=>ie(e)?xe(["example"],e):e,yt=({method:e,path:t,endpoint:r,isPositive:o,serializer:n,getRef:i,makeRef:a,composition:c,clue:d="response"})=>{let p=r.getSchema(o?"positive":"negative"),m=r.getMimeTypes(o?"positive":"negative"),f=rr(q({schema:p,isResponse:!0,rules:lt,onEach:ut,onMissing:ft,serializer:n,getRef:i,makeRef:a})),h=er(p,!0),g=c==="components"?a(A(t,e,d),f):f;return{description:`${e.toUpperCase()} ${t} ${d}`,content:m.reduce((O,l)=>({...O,[l]:{schema:g,...h}}),{})}},Vo=()=>({type:"http",scheme:"basic"}),Go=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),_o=({name:e})=>({type:"apiKey",in:"query",name:e}),Yo=({name:e})=>({type:"apiKey",in:"header",name:e}),Jo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Qo=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Wo=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((t,r)=>{let o=e[r];if(!o)return t;let{scopes:n={},...i}=o;return{...t,[r]:{...i,scopes:n}}},{})}),or=e=>{let t={basic:Vo,bearer:Go,input:_o,header:Yo,cookie:Jo,openid:Qo,oauth2:Wo};return Ce(e,r=>t[r.type](r))},Be=e=>{if(typeof e=="object"){if("or"in e)return e.or.map(t=>("and"in t?t.and:[t]).reduce((r,{name:o,scopes:n})=>({...r,[o]:n}),{}));if("and"in e)return Be(ot(e))}return Be({or:[e]})},nr=({method:e,path:t,endpoint:r,serializer:o,getRef:n,makeRef:i,composition:a,clue:c="request body"})=>{let d=tt(t),p=rr(mt(q({schema:r.getSchema("input"),isResponse:!1,rules:lt,onEach:ut,onMissing:ft,serializer:o,getRef:n,makeRef:i}),d)),m=er(r.getSchema("input"),!1,d),f=a==="components"?i(A(t,e,c),p):p;return{description:`${e.toUpperCase()} ${t} ${c}`,content:r.getMimeTypes("input").reduce((h,g)=>({...h,[g]:{schema:f,...m}}),{})}},ir=e=>Object.keys(e).map(t=>{let r=e[t];return{name:t,description:typeof r=="string"?r:r.description,...typeof r=="object"&&r.url&&{externalDocs:{url:r.url}}}}),gt=e=>e.length<=Jt?e:e.slice(0,Jt-1)+"\u2026";var ht=class extends ${constructor({routing:r,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:c="Successful response",errorResponseDescription:d="Error response",hasSummaryFromDescription:p=!0,composition:m="inline",serializer:f=Ae}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:i}).addServer({url:a}),B({routing:r,onEndpoint:(g,O,l)=>{let b=l,j={path:O,method:b,endpoint:g,composition:m,serializer:f,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[V,G]=["short","long"].map(g.getDescription.bind(g)),ae=o.inputSources?.[b]||Pe[b],Se=tr({...j,inputSources:ae}),P={operationId:this.ensureUniqOperationId(O,b),responses:{[g.getStatusCode("positive")]:yt({...j,clue:c,isPositive:!0}),[g.getStatusCode("negative")]:yt({...j,clue:d,isPositive:!1})}};G&&(P.description=G,p&&V===void 0&&(P.summary=gt(G))),V&&(P.summary=gt(V)),g.getTags().length>0&&(P.tags=g.getTags()),Se.length>0&&(P.parameters=Se),ae.includes("body")&&(P.requestBody=nr(j));let Zt=Be(Ce(or(g.getSecurity()),Ye=>{let Dt=this.ensureUniqSecuritySchemaName(Ye),Ar=["oauth2","openIdConnect"].includes(Ye.type)?g.getScopes():[];return this.addSecurityScheme(Dt,Ye),{name:Dt,scopes:Ar}}));Zt.length>0&&(P.security=Zt);let Ir=Xt(O);this.addPath(Ir,{[b]:P})}}),this.rootDoc.tags=o.tags?ir(o.tags):[]}makeRef(r,o){return this.addSchema(r,o),this.getRef(r)}getRef(r){return r in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${r}`}:void 0}ensureUniqOperationId(r,o){let n=A(r,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(r){let o=JSON.stringify(r);for(let n in this.rootDoc.components?.securitySchemes||{})if(o===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;return this.lastSecuritySchemaIds[r.type]=(this.lastSecuritySchemaIds?.[r.type]||0)+1,`${r.type.toUpperCase()}_${this.lastSecuritySchemaIds[r.type]}`}};import sr from"http";var Xo=e=>({method:"GET",header:jest.fn(()=>U),...e}),en=e=>{let t={writableEnded:!1,statusCode:200,statusMessage:sr.STATUS_CODES[200],set:jest.fn(()=>t),status:jest.fn(r=>(t.statusCode=r,t.statusMessage=sr.STATUS_CODES[r],t)),json:jest.fn(()=>t),end:jest.fn(()=>(t.writableEnded=!0,t)),...e};return t},tn=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:n,__noJest:i})=>{if(!jest||i)throw new Error("You need to install Jest in order to use testEndpoint().");let a=Xo(t),c=en(r),d={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},p={cors:!1,logger:d,...o};return await e.execute({request:a,response:c,config:p,logger:d}),{requestMock:a,responseMock:c,loggerMock:d}};import L from"typescript";import M from"typescript";var s=M.factory,se=[s.createModifier(M.SyntaxKind.ExportKeyword)],rn=[s.createModifier(M.SyntaxKind.PublicKeyword),s.createModifier(M.SyntaxKind.ReadonlyKeyword)],ar=[s.createModifier(M.SyntaxKind.ProtectedKeyword),s.createModifier(M.SyntaxKind.ReadonlyKeyword)],on=s.createTemplateHead(""),nn=s.createTemplateTail(""),sn=s.createTemplateMiddle(" "),xt=e=>s.createTemplateLiteralType(on,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?nn:sn))),Ot=xt(["M","P"]),$e=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t),qe=(e,t)=>Object.keys(e).reduce((r,o)=>r.concat($e(o,e[o],t)),[]),bt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),cr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Tt=(e,t)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(t)),pr=(e,t)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,t)],M.NodeFlags.Const),St=(e,t)=>s.createTypeAliasDeclaration(se,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),Ve=(e,t)=>s.createTypeAliasDeclaration(se,e,void 0,t),dr=(e,t,r)=>s.createPropertyDeclaration(rn,e,void 0,t,r),mr=(e,t,r=[])=>s.createClassDeclaration(se,e,void 0,void 0,[t,...r]),lr=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),ur=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(M.SyntaxKind.AnyKeyword)]),jt=(e,t,r)=>s.createInterfaceDeclaration(se,e,void 0,t,r),fr=e=>Object.keys(e).reduce((t,r)=>t.concat(s.createTypeParameterDeclaration([],r,s.createTypeReferenceNode(e[r]))),[]),yr=(e,t)=>s.createArrowFunction(void 0,void 0,e.map(r=>$e(r)),void 0,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),"implementation"),void 0,t)),Rt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[s.createIdentifier(e)]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,qe({acc:void 0,key:void 0}),void 0,void 0,t),r]);import y from"typescript";import{z as cn}from"zod";import z from"typescript";var{factory:Ge}=z,Pt=(e,t)=>{z.addSyntheticLeadingComment(e,z.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},_e=(e,t,r)=>{let o=Ge.createTypeAliasDeclaration(void 0,Ge.createIdentifier(t),void 0,e);return r&&Pt(o,r),o},gr=(e,t)=>{let r=z.createSourceFile("print.ts","",z.ScriptTarget.Latest,!1,z.ScriptKind.TS);return z.createPrinter(t).printNode(z.EmitHint.Unspecified,e,r)},an=/^[A-Za-z_$][A-Za-z0-9_$]*$/,hr=e=>an.test(e)?Ge.createIdentifier(e):Ge.createStringLiteral(e);var{factory:u}=y,pn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},dn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),mn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&me(a)?a instanceof cn.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,hr(i),c&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r({schema:a}));return a.description&&Pt(d,a.description),d});return u.createTypeLiteralNode(n)},ln=({schema:{element:e},next:t})=>u.createArrayTypeNode(t({schema:e})),un=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),xr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(r=>t({schema:r}))),fn=e=>pn?.[e.kind],yn=({schema:e,next:t,isResponse:r})=>{let o=t({schema:e.innerType()}),n=e._def.effect;if(r&&n.type==="transform"){let i=Ze({effect:n,sample:fn(o)}),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(i&&a[i]||y.SyntaxKind.AnyKeyword)}return o},gn=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),hn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e({schema:t.unwrap()});return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},xn=({next:e,schema:t})=>u.createUnionTypeNode([e({schema:t.unwrap()}),u.createLiteralTypeNode(u.createNull())]),On=({next:e,schema:{items:t}})=>u.createTupleTypeNode(t.map(r=>e({schema:r}))),bn=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e({schema:t}),e({schema:r})]),Tn=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(r=>e({schema:r}))),Sn=({next:e,schema:t})=>e({schema:t._def.innerType}),k=e=>()=>u.createKeywordTypeNode(e),jn=({next:e,schema:t})=>e({schema:t.unwrap()}),Rn=({next:e,schema:t})=>e({schema:t._def.innerType}),Pn=({schema:e,next:t,isResponse:r})=>t({schema:e._def[r?"out":"in"]}),En=()=>u.createLiteralTypeNode(u.createNull()),In=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:n})=>{let i=`Type${o(n.schema)}`;return e(i)||(()=>(t(i,u.createLiteralTypeNode(u.createNull())),t(i,r({schema:n.schema}))))()},An={ZodString:k(y.SyntaxKind.StringKeyword),ZodNumber:k(y.SyntaxKind.NumberKeyword),ZodBigInt:k(y.SyntaxKind.BigIntKeyword),ZodBoolean:k(y.SyntaxKind.BooleanKeyword),ZodDateIn:k(y.SyntaxKind.StringKeyword),ZodDateOut:k(y.SyntaxKind.StringKeyword),ZodNull:En,ZodArray:ln,ZodTuple:On,ZodRecord:bn,ZodObject:mn,ZodLiteral:dn,ZodIntersection:Tn,ZodUnion:xr,ZodFile:k(y.SyntaxKind.StringKeyword),ZodAny:k(y.SyntaxKind.AnyKeyword),ZodDefault:Sn,ZodEnum:un,ZodNativeEnum:gn,ZodEffects:yn,ZodOptional:hn,ZodNullable:xn,ZodDiscriminatedUnion:xr,ZodBranded:jn,ZodCatch:Rn,ZodPipeline:Pn,ZodLazy:In},Et=({schema:e,...t})=>q({schema:e,rules:An,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var It=class{constructor({routing:t,serializer:r=Ae,optionalPropStyle:o={withQuestionMark:!0,withUndefined:!0}}){this.agg=[];this.registry={};this.paths=[];this.aliases={};B({routing:t,onEndpoint:(l,b,j)=>{let V=A(b,j,"input"),G=A(b,j,"response"),ae={serializer:r,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:o},Se=Et({...ae,schema:l.getSchema("input"),isResponse:!1}),P=Et({...ae,isResponse:!0,schema:l.getSchema("positive").or(l.getSchema("negative"))});this.agg.push(_e(Se,V),_e(P,G)),j!=="options"&&(this.paths.push(b),this.registry[`${j} ${b}`]={in:V,out:G,isJson:l.getMimeTypes("positive").includes(U)})}}),this.agg=Object.values(this.aliases).concat(this.agg);let n=St("Path",this.paths),i=St("Method",Kt),a=Ve("MethodPath",xt([i.name,n.name])),c=[s.createHeritageClause(L.SyntaxKind.ExtendsKeyword,[bt(a.name,L.SyntaxKind.AnyKeyword)])],d=jt("Input",c,Object.keys(this.registry).map(l=>Tt(l,this.registry[l].in))),p=jt("Response",c,Object.keys(this.registry).map(l=>Tt(l,this.registry[l].out))),m=s.createVariableStatement(se,pr("jsonEndpoints",s.createObjectLiteralExpression(Object.keys(this.registry).filter(l=>this.registry[l].isJson).map(l=>s.createPropertyAssignment(`"${l}"`,s.createTrue()))))),f=Ve("Provider",s.createFunctionTypeNode(fr({M:i.name,P:n.name}),qe({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(d.name),Ot)}),lr(p.name,Ot))),h=Ve("Implementation",s.createFunctionTypeNode(void 0,qe({method:s.createTypeReferenceNode(i.name),path:s.createKeywordTypeNode(L.SyntaxKind.StringKeyword),params:bt(L.SyntaxKind.StringKeyword,L.SyntaxKind.AnyKeyword)}),ur())),g=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),O=mr("ExpressZodAPIClient",cr([$e("implementation",s.createTypeReferenceNode(h.name),ar)]),[dr("provide",s.createTypeReferenceNode(f.name),yr(["method","path","params"],[s.createIdentifier("method"),Rt("params",s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("acc"),"replace"),void 0,[g,s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key"))]),s.createIdentifier("path")),Rt("params",s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("path"),"indexOf"),void 0,[g]),L.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,s.createIdentifier("acc"),void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(s.createIdentifier("acc")),s.createPropertyAssignment("[key]",s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key")))])),s.createObjectLiteralExpression())]))]);L.addSyntheticLeadingComment(O,L.SyntaxKind.MultiLineCommentTrivia,`
33
+ `.trim();var at=({app:e,logger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(Vt()),B({routing:o,hasCors:!!r.cors,onEndpoint:(n,i,a)=>{e[a](i,async(c,d)=>{t.info(`${c.method}: ${i}`),await n.execute({request:c,response:d,logger:t,config:r})})},onStatic:(n,i)=>{e.use(n,i)}})};import ao,{json as co}from"express";import po from"compression";import mo from"express-fileupload";import lo from"https";import _t from"http-errors";var uo=(e,t)=>(r,o,n,i)=>{if(!r)return i();e.handler({error:_t(400,Y(r).message),request:o,response:n,logger:t,input:o.body,output:null})},Gt=(e,t)=>(r,o)=>{let n=_t(404,`Can not ${r.method} ${r.path}`);try{e.handler({request:r,response:o,logger:t,error:n,input:null,output:null})}catch(i){we({response:o,logger:t,error:new Q(Y(i).message,n)})}};function fo(e,t){let r=tt(e.logger)?Ke(e.logger):e.logger;at({app:e.app,routing:t,logger:r,config:e});let o=e.errorHandler||te;return{notFoundHandler:Gt(o,r),logger:r}}function yo(e,t){let r=tt(e.logger)?Ke(e.logger):e.logger,o=ao();o.disable("x-powered-by");let n=e.errorHandler||te,i=e.server.compression?po({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||co(),c=e.server.upload?mo({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,d=[].concat(i||[]).concat(a).concat(c||[]);o.use(d),o.use(uo(n,r)),at({app:o,routing:t,logger:r,config:e}),o.use(Gt(n,r));let p=o.listen(e.server.listen,()=>{r.info(`Listening ${e.server.listen}`)}),m;return e.https&&(m=lo.createServer(e.https.options,o).listen(e.https.listen,()=>{r.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:p,httpsServer:m,logger:r}}import*as Yt from"yaml";var $=class{static create(t){return new $(t)}constructor(t){this.rootDoc=t||{openapi:"3.0.0",info:{title:"app",version:"version"},paths:{},components:{schemas:{},responses:{},parameters:{},examples:{},requestBodies:{},headers:{},securitySchemes:{},links:{},callbacks:{}},tags:[],servers:[]}}getSpec(){return this.rootDoc}getSpecAsJson(t,r){return JSON.stringify(this.rootDoc,t,r)}getSpecAsYaml(){return Yt.stringify(this.rootDoc)}static isValidOpenApiVersion(t){t=t||"";let r=/(\d+)\.(\d+).(\d+)/.exec(t);return!!(r&&parseInt(r[1],10)>=3)}addOpenApiVersion(t){if(!$.isValidOpenApiVersion(t))throw new Error("Invalid OpenApi version: "+t+". Follow convention: 3.x.y");return this.rootDoc.openapi=t,this}addInfo(t){return this.rootDoc.info=t,this}addContact(t){return this.rootDoc.info.contact=t,this}addLicense(t){return this.rootDoc.info.license=t,this}addTitle(t){return this.rootDoc.info.title=t,this}addDescription(t){return this.rootDoc.info.description=t,this}addTermsOfService(t){return this.rootDoc.info.termsOfService=t,this}addVersion(t){return this.rootDoc.info.version=t,this}addPath(t,r){return this.rootDoc.paths[t]={...this.rootDoc.paths[t]||{},...r},this}addSchema(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.schemas=this.rootDoc.components.schemas||{},this.rootDoc.components.schemas[t]=r,this}addResponse(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.responses=this.rootDoc.components.responses||{},this.rootDoc.components.responses[t]=r,this}addParameter(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.parameters=this.rootDoc.components.parameters||{},this.rootDoc.components.parameters[t]=r,this}addExample(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.examples=this.rootDoc.components.examples||{},this.rootDoc.components.examples[t]=r,this}addRequestBody(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.requestBodies=this.rootDoc.components.requestBodies||{},this.rootDoc.components.requestBodies[t]=r,this}addHeader(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.headers=this.rootDoc.components.headers||{},this.rootDoc.components.headers[t]=r,this}addSecurityScheme(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.securitySchemes=this.rootDoc.components.securitySchemes||{},this.rootDoc.components.securitySchemes[t]=r,this}addLink(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.links=this.rootDoc.components.links||{},this.rootDoc.components.links[t]=r,this}addCallback(t,r){return this.rootDoc.components=this.rootDoc.components||{},this.rootDoc.components.callbacks=this.rootDoc.components.callbacks||{},this.rootDoc.components.callbacks[t]=r,this}addServer(t){return this.rootDoc.servers=this.rootDoc.servers||[],this.rootDoc.servers.push(t),this}addTag(t){return this.rootDoc.tags=this.rootDoc.tags||[],this.rootDoc.tags.push(t),this}addExternalDocs(t){return this.rootDoc.externalDocs=t,this}};import{omit as xe}from"ramda";import{z as x}from"zod";import{INVALID as Jt,ZodIssueCode as ct,ZodParsedType as Qt,ZodType as go,addIssueToContext as pt}from"zod";var dt=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,ho="ZodDateIn",mt=class extends go{_parse(t){let{status:r,ctx:o}=this._processInputParams(t);if(o.parsedType!==Qt.string)return pt(o,{code:ct.invalid_type,expected:Qt.string,received:o.parsedType}),Jt;dt.test(o.data)||(pt(o,{code:ct.invalid_string,validation:"regex"}),r.dirty());let n=new Date(o.data);return Ee(n)?{status:r.value,value:n}:(pt(o,{code:ct.invalid_date}),Jt)}},ge=mt;ge.create=()=>new mt({typeName:ho});function lt(e){return Object.prototype.hasOwnProperty.call(e,"$ref")}function ie(e){return!Object.prototype.hasOwnProperty.call(e,"$ref")}var q=({schema:e,onEach:t,rules:r,onMissing:o,...n})=>{let i="typeName"in e._def?r[e._def.typeName]:void 0,c=i?i({schema:e,...n,next:p=>q({...p,...n,onEach:t,rules:r,onMissing:o})}):o(e),d=t&&t({schema:e,prev:c,...n});return d?{...c,...d}:c};var Wt=50,er="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",xo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},tr=e=>e.replace(Xe,t=>`{${t.slice(1)}}`),Oo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r({schema:e}),default:t()}),bo=({schema:{_def:{innerType:e}},next:t})=>t({schema:e}),To=()=>({format:"any"}),So=({isResponse:e})=>{if(e)throw new R("Please use z.upload() only for input.");return{type:"string",format:"binary"}},jo=({schema:{isBinary:e,isBase64:t},isResponse:r})=>{if(!r)throw new R("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":t?"byte":"file"}},Ro=({schema:{options:e},next:t})=>({oneOf:e.map(r=>t({schema:r}))}),Po=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(o=>r({schema:o}))}),Eo=({schema:{_def:{left:e,right:t}},next:r})=>({allOf:[e,t].map(o=>r({schema:o}))}),Io=({schema:e,next:t})=>t({schema:e.unwrap()}),Ao=({schema:e,next:t})=>({nullable:!0,...t({schema:e.unwrap()})}),Xt=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),Zo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),Do=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(t&&me(i)?i instanceof x.ZodOptional:i.isOptional())});return{type:"object",properties:Fe({schema:e,isResponse:t,...r}),...o.length?{required:o}:{}}},Co=()=>({type:"string",nullable:!0,format:"null"}),wo=({isResponse:e})=>{if(e)throw new R("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:dt.source,externalDocs:{url:er}}},No=({isResponse:e})=>{if(!e)throw new R("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:er}}},vo=({isResponse:e})=>{throw new R(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},Mo=()=>({type:"boolean"}),zo=()=>({type:"integer",format:"bigint"}),ko=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),n=o.reduce((i,a)=>({...i,[a]:t}),{});return{type:"object",properties:Fe({schema:x.object(n),...r}),...o.length?{required:o}:{}}}if(e instanceof x.ZodLiteral)return{type:"object",properties:Fe({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&e.options.reduce((n,i)=>n&&i instanceof x.ZodLiteral,!0)){let n=e.options.reduce((i,a)=>({...i,[a.value]:t}),{});return{type:"object",properties:Fe({schema:x.object(n),...r}),required:e.options.map(i=>i.value)}}return{type:"object",additionalProperties:r.next({schema:t})}},Lo=({schema:{_def:e,element:t},next:r})=>({type:"array",items:r({schema:t}),...e.minLength!==null&&{minItems:e.minLength.value},...e.maxLength!==null&&{maxItems:e.maxLength.value}}),Uo=({schema:{items:e},next:t})=>{let r=e.map(o=>t({schema:o}));return{type:"array",minItems:r.length,maxItems:r.length,items:{oneOf:r,format:"tuple",...r.length>0&&{description:r.map((o,n)=>`${n}: ${ie(o)?o.type:o.$ref}`).join(", ")}}}},Ho=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,_def:{checks:f}}})=>{let h=f.find(l=>l.kind==="regex"),g=f.find(l=>l.kind==="datetime"),O=h?h.regex:g?g.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0;return{type:"string",...m&&{format:"date-time"},...e&&{format:"email"},...t&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...c&&{format:"ulid"},...d&&{format:"ip"},...p&&{format:"emoji"},...r!==null&&{minLength:r},...o!==null&&{maxLength:o},...O&&{pattern:`/${O.source}/${O.flags}`}}},Ko=({schema:e})=>{let t=e._def.checks.find(({kind:i})=>i==="min"),r=t?t.inclusive:!0,o=e._def.checks.find(({kind:i})=>i==="max"),n=o?o.inclusive:!0;return{type:e.isInt?"integer":"number",format:e.isInt?"int64":"double",minimum:e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:Number.MIN_VALUE:e.minValue,exclusiveMinimum:!r,maximum:e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,exclusiveMaximum:!n}},Fe=({schema:{shape:e},next:t})=>Object.keys(e).reduce((r,o)=>({...r,[o]:t({schema:e[o]})}),{}),Fo=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return xo?.[t]},Bo=({schema:e,isResponse:t,next:r})=>{let o=r({schema:e.innerType()}),{effect:n}=e._def;if(t&&n.type==="transform"&&ie(o)){let i=Ze({effect:n,sample:Fo(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:r({schema:x.any()})}if(!t&&n.type==="preprocess"&&ie(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},$o=({schema:e,isResponse:t,next:r})=>r({schema:e._def[t?"out":"in"]}),qo=({schema:e,next:t})=>t({schema:e.unwrap()}),Vo=({next:e,schema:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(t.schema);return o(i)||(()=>(n(i,{}),n(i,e({schema:t.schema}))))()},rr=(e,t,r=[])=>{let o=Ie(e,t);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:xe(r,i)}}),{})}},_o=(e,t,r)=>{let o=Ie(e,t);return o.length===0?{}:{examples:o.reduce((n,i,a)=>r in i?{...n,[`example${a+1}`]:{value:i[r]}}:n,{})}};function he(e){if(e instanceof x.ZodObject)return e;let t;if(e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion)t=Array.from(e.options.values()).map(r=>he(r)).reduce((r,o)=>r.merge(o.partial()),x.object({}));else if(e instanceof x.ZodEffects){if(C(e))throw new R("Using transformations on the top level of input schema is not allowed.");t=he(e._def.schema)}else t=he(e._def.left).merge(he(e._def.right));return Re(e,t)}var or=({path:e,method:t,endpoint:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:c,clue:d="parameter"})=>{let p=r.getSchema("input"),m=he(p).shape,f=ot(e),h=o.includes("query"),g=o.includes("params"),O=l=>g&&f.includes(l);return Object.keys(m).filter(l=>h||O(l)).map(l=>{let b=q({schema:m[l],isResponse:!1,rules:ft,onEach:yt,onMissing:gt,serializer:n,getRef:i,makeRef:a}),j=c==="components"?a(A(e,t,`${d} ${l}`),b):b;return{name:l,in:O(l)?"path":"query",required:!m[l].isOptional(),description:ie(b)&&b.description||`${t.toUpperCase()} ${e} ${d}`,schema:j,..._o(p,!1,l)}})},ft={ZodString:Ho,ZodNumber:Ko,ZodBigInt:zo,ZodBoolean:Mo,ZodDateIn:wo,ZodDateOut:No,ZodNull:Co,ZodArray:Lo,ZodTuple:Uo,ZodRecord:ko,ZodObject:Do,ZodLiteral:Zo,ZodIntersection:Eo,ZodUnion:Ro,ZodFile:jo,ZodUpload:So,ZodAny:To,ZodDefault:Oo,ZodEnum:Xt,ZodNativeEnum:Xt,ZodEffects:Bo,ZodOptional:Io,ZodNullable:Ao,ZodDiscriminatedUnion:Po,ZodBranded:qo,ZodDate:vo,ZodCatch:bo,ZodPipeline:$o,ZodLazy:Vo},yt=({schema:e,isResponse:t,prev:r})=>{if(lt(r))return{};let{description:o}=e,n=e instanceof x.ZodLazy,i=r.type!==void 0,a=t&&me(e),c=!n&&i&&!a&&e.isNullable(),d=n?[]:Ie(e,t);return{...o&&{description:o},...c&&{nullable:!0},...d.length>0&&{example:d[0]}}},gt=e=>{throw new R(`Zod type ${e.constructor.name} is unsupported`)},ut=(e,t)=>{if(lt(e))return e;let r=e.properties?xe(t,e.properties):void 0,o=e.example?xe(t,e.example):void 0,n=e.required?e.required.filter(c=>!t.includes(c)):void 0,i=e.allOf?e.allOf.map(c=>ut(c,t)):void 0,a=e.oneOf?e.oneOf.map(c=>ut(c,t)):void 0;return xe(Object.entries({properties:r,required:n,example:o,allOf:i,oneOf:a}).filter(([{},c])=>c===void 0).map(([c])=>c),{...e,properties:r,required:n,example:o,allOf:i,oneOf:a})},nr=e=>ie(e)?xe(["example"],e):e,ht=({method:e,path:t,endpoint:r,isPositive:o,serializer:n,getRef:i,makeRef:a,composition:c,clue:d="response"})=>{let p=r.getSchema(o?"positive":"negative"),m=r.getMimeTypes(o?"positive":"negative"),f=nr(q({schema:p,isResponse:!0,rules:ft,onEach:yt,onMissing:gt,serializer:n,getRef:i,makeRef:a})),h=rr(p,!0),g=c==="components"?a(A(t,e,d),f):f;return{description:`${e.toUpperCase()} ${t} ${d}`,content:m.reduce((O,l)=>({...O,[l]:{schema:g,...h}}),{})}},Go=()=>({type:"http",scheme:"basic"}),Yo=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),Jo=({name:e})=>({type:"apiKey",in:"query",name:e}),Qo=({name:e})=>({type:"apiKey",in:"header",name:e}),Wo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xo=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),en=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((t,r)=>{let o=e[r];if(!o)return t;let{scopes:n={},...i}=o;return{...t,[r]:{...i,scopes:n}}},{})}),ir=e=>{let t={basic:Go,bearer:Yo,input:Jo,header:Qo,cookie:Wo,openid:Xo,oauth2:en};return Ce(e,r=>t[r.type](r))},Be=e=>{if(typeof e=="object"){if("or"in e)return e.or.map(t=>("and"in t?t.and:[t]).reduce((r,{name:o,scopes:n})=>({...r,[o]:n}),{}));if("and"in e)return Be(it(e))}return Be({or:[e]})},sr=({method:e,path:t,endpoint:r,serializer:o,getRef:n,makeRef:i,composition:a,clue:c="request body"})=>{let d=ot(t),p=nr(ut(q({schema:r.getSchema("input"),isResponse:!1,rules:ft,onEach:yt,onMissing:gt,serializer:o,getRef:n,makeRef:i}),d)),m=rr(r.getSchema("input"),!1,d),f=a==="components"?i(A(t,e,c),p):p;return{description:`${e.toUpperCase()} ${t} ${c}`,content:r.getMimeTypes("input").reduce((h,g)=>({...h,[g]:{schema:f,...m}}),{})}},ar=e=>Object.keys(e).map(t=>{let r=e[t];return{name:t,description:typeof r=="string"?r:r.description,...typeof r=="object"&&r.url&&{externalDocs:{url:r.url}}}}),xt=e=>e.length<=Wt?e:e.slice(0,Wt-1)+"\u2026";var $e=class extends ${constructor({routing:r,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:c="Successful response",errorResponseDescription:d="Error response",hasSummaryFromDescription:p=!0,composition:m="inline",serializer:f=Ae}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:i}).addServer({url:a}),B({routing:r,onEndpoint:(g,O,l)=>{let b=l,j={path:O,method:b,endpoint:g,composition:m,serializer:f,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[V,_]=["short","long"].map(g.getDescription.bind(g)),ae=o.inputSources?.[b]||Pe[b],Se=or({...j,inputSources:ae}),P={operationId:this.ensureUniqOperationId(O,b),responses:{[g.getStatusCode("positive")]:ht({...j,clue:c,isPositive:!0}),[g.getStatusCode("negative")]:ht({...j,clue:d,isPositive:!1})}};_&&(P.description=_,p&&V===void 0&&(P.summary=xt(_))),V&&(P.summary=xt(V)),g.getTags().length>0&&(P.tags=g.getTags()),Se.length>0&&(P.parameters=Se),ae.includes("body")&&(P.requestBody=sr(j));let Ct=Be(Ce(ir(g.getSecurity()),Qe=>{let wt=this.ensureUniqSecuritySchemaName(Qe),Dr=["oauth2","openIdConnect"].includes(Qe.type)?g.getScopes():[];return this.addSecurityScheme(wt,Qe),{name:wt,scopes:Dr}}));Ct.length>0&&(P.security=Ct);let Zr=tr(O);this.addPath(Zr,{[b]:P})}}),this.rootDoc.tags=o.tags?ar(o.tags):[]}makeRef(r,o){return this.addSchema(r,o),this.getRef(r)}getRef(r){return r in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${r}`}:void 0}ensureUniqOperationId(r,o){let n=A(r,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(r){let o=JSON.stringify(r);for(let n in this.rootDoc.components?.securitySchemes||{})if(o===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;return this.lastSecuritySchemaIds[r.type]=(this.lastSecuritySchemaIds?.[r.type]||0)+1,`${r.type.toUpperCase()}_${this.lastSecuritySchemaIds[r.type]}`}},Ot=class extends $e{};import cr from"http";var tn=e=>({method:"GET",header:jest.fn(()=>U),...e}),rn=e=>{let t={writableEnded:!1,statusCode:200,statusMessage:cr.STATUS_CODES[200],set:jest.fn(()=>t),status:jest.fn(r=>(t.statusCode=r,t.statusMessage=cr.STATUS_CODES[r],t)),json:jest.fn(()=>t),end:jest.fn(()=>(t.writableEnded=!0,t)),...e};return t},on=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:n,__noJest:i})=>{if(!jest||i)throw new Error("You need to install Jest in order to use testEndpoint().");let a=tn(t),c=rn(r),d={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},p={cors:!1,logger:d,...o};return await e.execute({request:a,response:c,config:p,logger:d}),{requestMock:a,responseMock:c,loggerMock:d}};import L from"typescript";import M from"typescript";var s=M.factory,se=[s.createModifier(M.SyntaxKind.ExportKeyword)],nn=[s.createModifier(M.SyntaxKind.PublicKeyword),s.createModifier(M.SyntaxKind.ReadonlyKeyword)],pr=[s.createModifier(M.SyntaxKind.ProtectedKeyword),s.createModifier(M.SyntaxKind.ReadonlyKeyword)],sn=s.createTemplateHead(""),an=s.createTemplateTail(""),cn=s.createTemplateMiddle(" "),bt=e=>s.createTemplateLiteralType(sn,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?an:cn))),Tt=bt(["M","P"]),qe=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t),Ve=(e,t)=>Object.keys(e).reduce((r,o)=>r.concat(qe(o,e[o],t)),[]),St=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),dr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),jt=(e,t)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(t)),mr=(e,t)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,t)],M.NodeFlags.Const),Rt=(e,t)=>s.createTypeAliasDeclaration(se,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),_e=(e,t)=>s.createTypeAliasDeclaration(se,e,void 0,t),lr=(e,t,r)=>s.createPropertyDeclaration(nn,e,void 0,t,r),ur=(e,t,r=[])=>s.createClassDeclaration(se,e,void 0,void 0,[t,...r]),fr=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),yr=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(M.SyntaxKind.AnyKeyword)]),Pt=(e,t,r)=>s.createInterfaceDeclaration(se,e,void 0,t,r),gr=e=>Object.keys(e).reduce((t,r)=>t.concat(s.createTypeParameterDeclaration([],r,s.createTypeReferenceNode(e[r]))),[]),hr=(e,t)=>s.createArrowFunction(void 0,void 0,e.map(r=>qe(r)),void 0,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),"implementation"),void 0,t)),Et=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[s.createIdentifier(e)]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,Ve({acc:void 0,key:void 0}),void 0,void 0,t),r]);import y from"typescript";import{z as dn}from"zod";import z from"typescript";var{factory:Ge}=z,It=(e,t)=>{z.addSyntheticLeadingComment(e,z.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ye=(e,t,r)=>{let o=Ge.createTypeAliasDeclaration(void 0,Ge.createIdentifier(t),void 0,e);return r&&It(o,r),o},xr=(e,t)=>{let r=z.createSourceFile("print.ts","",z.ScriptTarget.Latest,!1,z.ScriptKind.TS);return z.createPrinter(t).printNode(z.EmitHint.Unspecified,e,r)},pn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Or=e=>pn.test(e)?Ge.createIdentifier(e):Ge.createStringLiteral(e);var{factory:u}=y,mn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},ln=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),un=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let c=t&&me(a)?a instanceof dn.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Or(i),c&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r({schema:a}));return a.description&&It(d,a.description),d});return u.createTypeLiteralNode(n)},fn=({schema:{element:e},next:t})=>u.createArrayTypeNode(t({schema:e})),yn=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),br=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(r=>t({schema:r}))),gn=e=>mn?.[e.kind],hn=({schema:e,next:t,isResponse:r})=>{let o=t({schema:e.innerType()}),n=e._def.effect;if(r&&n.type==="transform"){let i=Ze({effect:n,sample:gn(o)}),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(i&&a[i]||y.SyntaxKind.AnyKeyword)}return o},xn=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),On=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e({schema:t.unwrap()});return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},bn=({next:e,schema:t})=>u.createUnionTypeNode([e({schema:t.unwrap()}),u.createLiteralTypeNode(u.createNull())]),Tn=({next:e,schema:{items:t}})=>u.createTupleTypeNode(t.map(r=>e({schema:r}))),Sn=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e({schema:t}),e({schema:r})]),jn=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(r=>e({schema:r}))),Rn=({next:e,schema:t})=>e({schema:t._def.innerType}),k=e=>()=>u.createKeywordTypeNode(e),Pn=({next:e,schema:t})=>e({schema:t.unwrap()}),En=({next:e,schema:t})=>e({schema:t._def.innerType}),In=({schema:e,next:t,isResponse:r})=>t({schema:e._def[r?"out":"in"]}),An=()=>u.createLiteralTypeNode(u.createNull()),Zn=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:n})=>{let i=`Type${o(n.schema)}`;return e(i)||(()=>(t(i,u.createLiteralTypeNode(u.createNull())),t(i,r({schema:n.schema}))))()},Dn={ZodString:k(y.SyntaxKind.StringKeyword),ZodNumber:k(y.SyntaxKind.NumberKeyword),ZodBigInt:k(y.SyntaxKind.BigIntKeyword),ZodBoolean:k(y.SyntaxKind.BooleanKeyword),ZodDateIn:k(y.SyntaxKind.StringKeyword),ZodDateOut:k(y.SyntaxKind.StringKeyword),ZodNull:An,ZodArray:fn,ZodTuple:Tn,ZodRecord:Sn,ZodObject:un,ZodLiteral:ln,ZodIntersection:jn,ZodUnion:br,ZodFile:k(y.SyntaxKind.StringKeyword),ZodAny:k(y.SyntaxKind.AnyKeyword),ZodDefault:Rn,ZodEnum:yn,ZodNativeEnum:xn,ZodEffects:hn,ZodOptional:On,ZodNullable:bn,ZodDiscriminatedUnion:br,ZodBranded:Pn,ZodCatch:En,ZodPipeline:In,ZodLazy:Zn},At=({schema:e,...t})=>q({schema:e,rules:Dn,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Je=class{constructor({routing:t,serializer:r=Ae,optionalPropStyle:o={withQuestionMark:!0,withUndefined:!0}}){this.agg=[];this.registry={};this.paths=[];this.aliases={};B({routing:t,onEndpoint:(l,b,j)=>{let V=A(b,j,"input"),_=A(b,j,"response"),ae={serializer:r,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:o},Se=At({...ae,schema:l.getSchema("input"),isResponse:!1}),P=At({...ae,isResponse:!0,schema:l.getSchema("positive").or(l.getSchema("negative"))});this.agg.push(Ye(Se,V),Ye(P,_)),j!=="options"&&(this.paths.push(b),this.registry[`${j} ${b}`]={in:V,out:_,isJson:l.getMimeTypes("positive").includes(U)})}}),this.agg=Object.values(this.aliases).concat(this.agg);let n=Rt("Path",this.paths),i=Rt("Method",Bt),a=_e("MethodPath",bt([i.name,n.name])),c=[s.createHeritageClause(L.SyntaxKind.ExtendsKeyword,[St(a.name,L.SyntaxKind.AnyKeyword)])],d=Pt("Input",c,Object.keys(this.registry).map(l=>jt(l,this.registry[l].in))),p=Pt("Response",c,Object.keys(this.registry).map(l=>jt(l,this.registry[l].out))),m=s.createVariableStatement(se,mr("jsonEndpoints",s.createObjectLiteralExpression(Object.keys(this.registry).filter(l=>this.registry[l].isJson).map(l=>s.createPropertyAssignment(`"${l}"`,s.createTrue()))))),f=_e("Provider",s.createFunctionTypeNode(gr({M:i.name,P:n.name}),Ve({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(d.name),Tt)}),fr(p.name,Tt))),h=_e("Implementation",s.createFunctionTypeNode(void 0,Ve({method:s.createTypeReferenceNode(i.name),path:s.createKeywordTypeNode(L.SyntaxKind.StringKeyword),params:St(L.SyntaxKind.StringKeyword,L.SyntaxKind.AnyKeyword)}),yr())),g=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),O=ur("ExpressZodAPIClient",dr([qe("implementation",s.createTypeReferenceNode(h.name),pr)]),[lr("provide",s.createTypeReferenceNode(f.name),hr(["method","path","params"],[s.createIdentifier("method"),Et("params",s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("acc"),"replace"),void 0,[g,s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key"))]),s.createIdentifier("path")),Et("params",s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("path"),"indexOf"),void 0,[g]),L.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,s.createIdentifier("acc"),void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(s.createIdentifier("acc")),s.createPropertyAssignment("[key]",s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key")))])),s.createObjectLiteralExpression())]))]);L.addSyntheticLeadingComment(O,L.SyntaxKind.MultiLineCommentTrivia,`
34
34
  export const exampleImplementation: Implementation = async (
35
35
  method,
36
36
  path,
@@ -51,7 +51,7 @@ export const exampleImplementation: Implementation = async (
51
51
 
52
52
  const client = new ExpressZodAPIClient(exampleImplementation);
53
53
  client.provide("get", "/v1/user/retrieve", { id: "10" });
54
- `,!0),this.agg.push(n,i,a,d,p,m,f,h,O)}getAlias(t){return t in this.aliases?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=_e(r,t),this.getAlias(t)}print(t){return this.agg.map(r=>gr(r,t)).join(`
54
+ `,!0),this.agg.push(n,i,a,d,p,m,f,h,O)}getAlias(t){return t in this.aliases?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=Ye(r,t),this.getAlias(t)}print(t){return this.agg.map(r=>xr(r,t)).join(`
55
55
 
56
- `)}};var Er={};Dr(Er,{dateIn:()=>kn,dateOut:()=>Ln,file:()=>Mn,upload:()=>zn});import{INVALID as Or,ZodIssueCode as br,ZodParsedType as Tr,ZodType as Zn,addIssueToContext as Sr}from"zod";var Dn="ZodDateOut",At=class extends Zn{_parse(t){let{status:r,ctx:o}=this._processInputParams(t);return o.parsedType!==Tr.date?(Sr(o,{code:br.invalid_type,expected:Tr.date,received:o.parsedType}),Or):Ee(o.data)?{status:r.value,value:o.data.toISOString()}:(Sr(o,{code:br.invalid_date}),Or)}},Oe=At;Oe.create=()=>new At({typeName:Dn});import{INVALID as Cn,ZodIssueCode as jr,ZodParsedType as Rr,ZodType as wn,addIssueToContext as Pr}from"zod";var Nn="ZodFile",vn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Te=class extends wn{constructor(){super(...arguments);this.binary=r=>new Te({...this._def,checks:[...this._def.checks,{kind:"binary",...rt(r)}]});this.base64=r=>new Te({...this._def,checks:[...this._def.checks,{kind:"base64",...rt(r)}]})}_parse(r){let{status:o,ctx:n}=this._processInputParams(r);if(n.parsedType!==Rr.string)return Pr(n,{code:jr.invalid_type,expected:Rr.string,received:n.parsedType}),Cn;for(let i of this._def.checks)i.kind==="base64"&&(vn.test(n.data)||(Pr(n,{code:jr.custom,message:i.message}),o.dirty()));return{status:o.value,value:n.data}}get isBinary(){return!!this._def.checks.find(r=>r.kind==="binary")}get isBase64(){return!!this._def.checks.find(r=>r.kind==="base64")}},be=Te;be.create=()=>new Te({checks:[],typeName:Nn});var Mn=be.create,zn=H.create,kn=ge.create,Ln=Oe.create;import fc from"http-errors";export{re as AbstractEndpoint,It as Client,fe as DependsOnMethod,le as DependsOnMethodError,ue as EndpointsFactory,w as InputValidationError,ht as OpenAPI,R as OpenAPIError,F as OutputValidationError,J as RoutingError,ye as ServeStatic,lo as attachRouting,wr as createConfig,fc as createHttpError,Ke as createLogger,nt as createMiddleware,vt as createResultHandler,uo as createServer,Yr as defaultEndpointsFactory,te as defaultResultHandler,Er as ez,K as getMessageFromError,et as getStatusCodeFromError,tn as testEndpoint,_ as withMeta};
56
+ `)}},Zt=class extends Je{};var Ar={};wr(Ar,{dateIn:()=>Un,dateOut:()=>Hn,file:()=>kn,upload:()=>Ln});import{INVALID as Tr,ZodIssueCode as Sr,ZodParsedType as jr,ZodType as Cn,addIssueToContext as Rr}from"zod";var wn="ZodDateOut",Dt=class extends Cn{_parse(t){let{status:r,ctx:o}=this._processInputParams(t);return o.parsedType!==jr.date?(Rr(o,{code:Sr.invalid_type,expected:jr.date,received:o.parsedType}),Tr):Ee(o.data)?{status:r.value,value:o.data.toISOString()}:(Rr(o,{code:Sr.invalid_date}),Tr)}},Oe=Dt;Oe.create=()=>new Dt({typeName:wn});import{INVALID as Nn,ZodIssueCode as Pr,ZodParsedType as Er,ZodType as vn,addIssueToContext as Ir}from"zod";var Mn="ZodFile",zn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Te=class extends vn{constructor(){super(...arguments);this.binary=r=>new Te({...this._def,checks:[...this._def.checks,{kind:"binary",...nt(r)}]});this.base64=r=>new Te({...this._def,checks:[...this._def.checks,{kind:"base64",...nt(r)}]})}_parse(r){let{status:o,ctx:n}=this._processInputParams(r);if(n.parsedType!==Er.string)return Ir(n,{code:Pr.invalid_type,expected:Er.string,received:n.parsedType}),Nn;for(let i of this._def.checks)i.kind==="base64"&&(zn.test(n.data)||(Ir(n,{code:Pr.custom,message:i.message}),o.dirty()));return{status:o.value,value:n.data}}get isBinary(){return!!this._def.checks.find(r=>r.kind==="binary")}get isBase64(){return!!this._def.checks.find(r=>r.kind==="base64")}},be=Te;be.create=()=>new Te({checks:[],typeName:Mn});var kn=be.create,Ln=H.create,Un=ge.create,Hn=Oe.create;import gc from"http-errors";export{re as AbstractEndpoint,Zt as Client,fe as DependsOnMethod,le as DependsOnMethodError,$e as Documentation,ue as EndpointsFactory,w as InputValidationError,Je as Integration,Ot as OpenAPI,R as OpenAPIError,F as OutputValidationError,J as RoutingError,ye as ServeStatic,fo as attachRouting,vr as createConfig,gc as createHttpError,Ke as createLogger,st as createMiddleware,zt as createResultHandler,yo as createServer,Qr as defaultEndpointsFactory,te as defaultResultHandler,Ar as ez,K as getMessageFromError,rt as getStatusCodeFromError,on as testEndpoint,G as withMeta};
57
57
  //# sourceMappingURL=index.js.map