express-zod-api 10.0.0-beta1 → 10.0.0-beta2
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 +40 -0
- package/SECURITY.md +14 -13
- package/dist/esm/index.js +8 -8
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/package.json +1 -1
- package/dist/index.js +9 -9
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 10
|
|
4
4
|
|
|
5
|
+
### v10.0.0-beta2
|
|
6
|
+
|
|
7
|
+
- **BREAKING** changes to the behavior of a public method.
|
|
8
|
+
- The feature method `withMeta` _(introduced in v2.1.0)_ used to mutate its argument (`zod` schema) in order to
|
|
9
|
+
extend it with additional methods.
|
|
10
|
+
- If you're using this feature _within_ the call of `EndpointsFactory::build()`, there is no issue.
|
|
11
|
+
- However, if you're using a schema assignment (to some const) along with this method, this might lead to unexpected
|
|
12
|
+
results.
|
|
13
|
+
- The following case is reported by [@McMerph](https://github.com/McMerph) in issue #827.
|
|
14
|
+
- Reusing a schema assigned to a const for its several wrappings by `withMeta` and setting different examples.
|
|
15
|
+
- In this case all examples were set to the original const.
|
|
16
|
+
- This release fixes that behavior by making `withMeta` immutable: it returns a new copy of its argument.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// the example case
|
|
20
|
+
const originalSchema = z.string();
|
|
21
|
+
const schemaA = withMeta(originalSchema).example("A");
|
|
22
|
+
const schemaB = withMeta(originalSchema).example("B");
|
|
23
|
+
// BEFORE: all three const have both examples "A" and "B"
|
|
24
|
+
// AFTER:
|
|
25
|
+
// - originalSchema remains intact
|
|
26
|
+
// - schemaA has example "A"
|
|
27
|
+
// - schemaB has example "B"
|
|
28
|
+
```
|
|
29
|
+
|
|
5
30
|
### v10.0.0-beta1
|
|
6
31
|
|
|
7
32
|
- **BREAKING** changes to the concept of dependencies.
|
|
@@ -22,6 +47,21 @@
|
|
|
22
47
|
- `/dist/esm/index.js` — ESM bundle;
|
|
23
48
|
- `/dist/index.d.ts` — types declaration bundle.
|
|
24
49
|
|
|
50
|
+
```ts
|
|
51
|
+
// before
|
|
52
|
+
import { z } from "express-zod-api";
|
|
53
|
+
const stringSchema = z.string();
|
|
54
|
+
const uploadSchema = z.upload();
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
// after
|
|
59
|
+
import { z } from "zod"; // module changed
|
|
60
|
+
import { ez } from "express-zod-api"; // new namespace
|
|
61
|
+
const stringSchema = z.string(); // remains the same
|
|
62
|
+
const uploadSchema = ez.upload(); // namespace changed
|
|
63
|
+
```
|
|
64
|
+
|
|
25
65
|
## Version 9
|
|
26
66
|
|
|
27
67
|
### v9.2.1
|
package/SECURITY.md
CHANGED
|
@@ -2,24 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
## Supported Versions
|
|
4
4
|
|
|
5
|
-
| Version |
|
|
6
|
-
|
|
|
7
|
-
|
|
|
8
|
-
|
|
|
9
|
-
|
|
|
10
|
-
|
|
|
11
|
-
|
|
|
12
|
-
|
|
|
13
|
-
|
|
|
14
|
-
|
|
|
15
|
-
|
|
|
16
|
-
|
|
|
5
|
+
| Version | Supported |
|
|
6
|
+
| ------: | :----------------: |
|
|
7
|
+
| 10.x.x | :white_check_mark: |
|
|
8
|
+
| 9.x.x | :white_check_mark: |
|
|
9
|
+
| 8.x.x | :white_check_mark: |
|
|
10
|
+
| 7.x.x | :x: |
|
|
11
|
+
| 6.x.x | :x: |
|
|
12
|
+
| 5.x.x | :x: |
|
|
13
|
+
| 4.x.x | :x: |
|
|
14
|
+
| 3.x.x | :x: |
|
|
15
|
+
| 2.x.x | :x: |
|
|
16
|
+
| 1.x.x | :x: |
|
|
17
|
+
| 0.x.x | :x: |
|
|
17
18
|
|
|
18
19
|
## Reporting a Vulnerability
|
|
19
20
|
|
|
20
21
|
Found a vulnerability or other security issue?
|
|
21
22
|
|
|
22
23
|
Please urgently inform me privately by
|
|
23
|
-
[email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#
|
|
24
|
+
[email](https://github.com/RobinTail/express-zod-api/blob/master/package.json#L121).
|
|
24
25
|
|
|
25
26
|
I will try to fix it as soon as possible.
|
package/dist/esm/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Or=(e,r,t)=>{if(!r.has(e))throw TypeError("Cannot "+t)};var A=(e,r,t)=>{if(r.has(e))throw TypeError("Cannot add the same private member more than once");r instanceof WeakSet?r.add(e):r.set(e,t)};var E=(e,r,t)=>(Or(e,r,"access private method"),t);var Rt={silent:!0,warn:!0,debug:!0},br=e=>e;import{z as N}from"zod";import{HttpError as zr}from"http-errors";import{z as T}from"zod";import{clone as Pr,mergeDeepRight as Er}from"ramda";var O="expressZodApiMeta",Zr=e=>{let r=e.constructor,t=Pr(e._def);return t[O]=t[O]||{examples:[]},new r(t)},$=e=>{let r=Zr(e);return Object.defineProperties(r,{example:{get:()=>t=>{let o=$(r);return o._def[O].examples.push(t),o}}}),r},At=e=>O in e._def?typeof e._def[O]=="object"&&e._def[O]!==null:!1;function Se(e,r){if(!At(e))return;let t=e._def;return r in t[O]?t[O][r]:void 0}var Oe=(e,r)=>{if(!At(e))return r;let t=$(r),o=te(t._def[O].examples,e._def[O].examples);if(t._def[O].examples=[],o.type==="single")t._def[O].examples=o.value;else for(let[n,i]of o.value)t._def[O].examples.push(Er({...n},{...i}));return t};import Rr from"mime";var j=Rr.getType("json")||"application/json",re="multipart/form-data";import{INVALID as Ar,OK as Ir,ZodIssueCode as Cr,ZodParsedType as Mr,ZodType as Nr,addIssueToContext as wr}from"zod";var Dr="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",Ge=class extends Nr{_parse(r){let{ctx:t}=this._processInputParams(r);return t.parsedType!==Mr.object||!vr(t.data)?(wr(t,{code:Cr.custom,message:`Expected file upload, received ${t.parsedType}`}),Ar):Ir(t.data)}},L=Ge;L.create=()=>new Ge({typeName:Dr});var qe=/:([A-Za-z0-9_]+)/g;function jr(e){let t=(e.header("content-type")||"").slice(0,re.length).toLowerCase()===re;return"files"in e&&t}var be={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Lr=["body","query","params"],Ve=e=>e.method.toLowerCase();function It(e,r){let t=Ve(e);if(t==="options")return{};let o=Lr;return t in be&&(o=be[t]),r&&t in r&&(o=r[t]||o),o.filter(n=>n==="files"?jr(e):!0).reduce((n,i)=>({...n,...e[i]}),{})}function Be(e){return typeof e=="object"&&"level"in e&&"color"in e&&Object.keys(Rt).includes(e.level)&&typeof e.color=="boolean"}function Pe(e){return!isNaN(e.getTime())}function ne(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:r,message:t})=>(r.length?[r.join("/")]:[]).concat(t).join(": ")).join("; "):e instanceof U?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message}function Ye(e){return e instanceof zr?e.statusCode:e instanceof C?400:500}var Ee=(e,r)=>{let t=Se(e,"examples");return t===void 0?[]:t.reduce((o,n)=>{let i=e.safeParse(n);return o.concat(i.success?r?i.data:n:[])},[])},te=(e,r)=>{if(e.length===0)return{type:"single",value:r};if(r.length===0)return{type:"single",value:e};let t=[];for(let o of e)for(let n of r)t.push([o,n]);return{type:"tuple",value:t}};function Je(e){let r=e.match(qe);return r?r.map(t=>t.slice(1)):[]}var oe=e=>e.reduce((r,t)=>r||t,!1);function I(e){return e instanceof T.ZodEffects&&e._def.effect.type!=="refinement"?!0:e instanceof T.ZodUnion?oe(e.options.map(I)):e instanceof T.ZodIntersection?oe([e._def.left,e._def.right].map(I)):!1}function Z(e){return e instanceof L?!0:e instanceof T.ZodObject?oe(Object.values(e.shape).map(Z)):e instanceof T.ZodUnion?oe(e.options.map(Z)):e instanceof T.ZodIntersection?oe([e._def.left,e._def.right].map(Z)):e instanceof T.ZodOptional||e instanceof T.ZodNullable?Z(e.unwrap()):e instanceof T.ZodEffects||e instanceof T.ZodTransformer?Z(e._def.schema):e instanceof T.ZodRecord?Z(e._def.valueType):e instanceof T.ZodArray?Z(e._def.type):e instanceof T.ZodDefault?Z(e._def.innerType):!1}var ie=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,se=(e,r,t)=>[r].concat(e.split("/")).concat(t||[]).flatMap(o=>o.split(/[^A-Z0-9]/gi)).map(o=>o.slice(0,1).toUpperCase()+o.slice(1).toLowerCase()).join(""),Ze=({effect:e,sample:r})=>{try{return typeof e.transform(r,{addIssue:()=>{},path:[]})}catch{return}},We=e=>typeof e=="string"?{message:e}:e||{};var G=class extends Error{constructor(){super(...arguments);this.name="RoutingError"}},ae=class extends G{constructor(){super(...arguments);this.name="DependsOnMethodError"}},b=class extends Error{constructor(){super(...arguments);this.name="OpenAPIError"}},M=class extends Error{constructor(){super(...arguments);this.name="IOSchemaError"}},U=class extends M{constructor(t){super(k(t));this.name="OutputValidationError";this.originalError=t}},C=class extends M{constructor(t){super(k(t));this.name="InputValidationError";this.originalError=t}},q=class extends Error{constructor(t,o){super(t);this.name="ResultHandlerError";this.originalError=o||void 0}};var R=e=>typeof e=="object"&&e!==null,Re=e=>({and:e.reduce((r,t)=>r.concat(R(t)&&"and"in t?t.and:t),[])}),Ae=(e,r)=>{if(R(e)){if("and"in e)return{and:e.and.map(t=>R(t)&&"or"in t?{or:t.or.map(r)}:r(t))};if("or"in e)return{or:e.or.map(t=>R(t)&&"and"in t?{and:t.and.map(r)}:r(t))}}return r(e)},Qe=e=>e.and.reduce((r,t)=>{let o=te(r.or,R(t)&&"or"in t?t.or:[t]);return o.type==="single"?r.or.push(...o.value):r.or=o.value.map(Re),r},{or:[]}),V=(e,r)=>{if(R(e)){if("and"in e){if(R(r)){if("and"in r)return Re([e,r]);if("or"in r)return V(Qe(e),r)}return Re([e,r])}if("or"in e){if(R(r)){if("and"in r)return V(r,e);if("or"in r){let t=te(e.or,r.or);return{or:t.type==="single"?t.value:t.value.map(Re)}}}return V(e,{and:[r]})}}return R(r)&&("and"in r||"or"in r)?V(r,e):{and:[e,r]}};import{z as B}from"zod";var Y={positive:200,negative:400},Ct=e=>e,J=Ct({getPositiveResponse:e=>{let r=Se(e,"examples")||[],t=$(B.object({status:B.literal("success"),data:e}));return r.reduce((o,n)=>o.example({status:"success",data:n}),t)},getNegativeResponse:()=>$(B.object({status:B.literal("error"),error:B.object({message:B.string()})})).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:r,output:t,request:o,response:n,logger:i})=>{if(!e){n.status(Y.positive).json({status:"success",data:t});return}let a=Ye(e);a===500&&i.error(`Internal server error
|
|
2
2
|
${e.stack}
|
|
3
3
|
`,{url:o.url,payload:r}),n.status(a).json({status:"error",error:{message:k(e)}})}}),Ie=({error:e,logger:r,response:t})=>{r.error(`Result handler failure: ${e.message}.`),t.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
4
|
-
Original error: ${e.originalError.message}.`:""))};var
|
|
4
|
+
Original error: ${e.originalError.message}.`:""))};var Mt=(e,r=[j])=>{if(e instanceof N.ZodType)return r;let{mimeTypes:t,mimeType:o}=e;return o?[o]:t||r},W=class{},Me,Nt,Ne,wt,we,Dt,De,vt,ve,zt,Ce=class extends W{constructor({middlewares:t,inputSchema:o,outputSchema:n,handler:i,resultHandler:a,description:d,shortDescription:l,...c}){super();A(this,Me);A(this,Ne);A(this,we);A(this,De);A(this,ve);this.methods=[];this.siblingMethods=[];this.middlewares=[];this.scopes=[];this.tags=[];[{name:"input schema",schema:o},{name:"output schema",schema:n}].forEach(({name:u,schema:g})=>{if(I(g))throw new M(`Using transformations on the top level of endpoint ${u} is not allowed.`)}),this.middlewares=t;let p={positive:a.getPositiveResponse(n),negative:a.getNegativeResponse()};this.mimeTypes={input:Z(o)?[re]:[j],positive:Mt(p.positive),negative:Mt(p.negative)},this.schemas={input:o,output:n,positive:p.positive instanceof N.ZodType?p.positive:p.positive.schema,negative:p.negative instanceof N.ZodType?p.negative:p.negative.schema},this.statusCodes={positive:p.positive instanceof N.ZodType?Y.positive:p.positive.statusCode||Y.positive,negative:p.negative instanceof N.ZodType?Y.negative:p.negative.statusCode||Y.negative},this.handler=i,this.resultHandler=a,this.descriptions={long:d,short:l},"scopes"in c&&c.scopes&&this.scopes.push(...c.scopes),"scope"in c&&c.scope&&this.scopes.push(c.scope),"tags"in c&&c.tags&&this.tags.push(...c.tags),"tag"in c&&c.tag&&this.tags.push(c.tag),"methods"in c?this.methods=c.methods:this.methods=[c.method]}_setSiblingMethods(t){this.siblingMethods=t}getDescription(t){return this.descriptions[t]}getMethods(){return this.methods}getSchema(t){return this.schemas[t]}getMimeTypes(t){return this.mimeTypes[t]}getStatusCode(t){return this.statusCodes[t]}getSecurity(){return this.middlewares.reduce((t,o)=>o.security?V(t,o.security):t,{and:[]})}getScopes(){return this.scopes}getTags(){return this.tags}async execute({request:t,response:o,logger:n,config:i}){let a=Ve(t),d,l=null;if(i.cors){let p=E(this,Me,Nt).call(this);typeof i.cors=="function"&&(p=await i.cors({request:t,logger:n,endpoint:this,defaultHeaders:p}));for(let u in p)o.set(u,p[u])}let c=It(t,i.inputSources);try{let{options:p,isStreamClosed:u}=await E(this,we,Dt).call(this,{method:a,input:c,request:t,response:o,logger:n});if(u)return;if(a==="options"){o.status(200).end();return}d=await E(this,Ne,wt).call(this,await E(this,De,vt).call(this,{input:c,options:p,logger:n}))}catch(p){l=ne(p)}await E(this,ve,zt).call(this,{input:c,output:d,request:t,response:o,error:l,logger:n})}};Me=new WeakSet,Nt=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"}},Ne=new WeakSet,wt=async function(t){try{return await this.schemas.output.parseAsync(t)}catch(o){throw o instanceof N.ZodError?new U(o):o}},we=new WeakSet,Dt=async function({method:t,input:o,request:n,response:i,logger:a}){let d={},l=!1;for(let c of this.middlewares){if(t==="options"&&c.type==="proprietary")continue;let p;try{p=await c.input.parseAsync(o)}catch(u){throw u instanceof N.ZodError?new C(u):u}if(Object.assign(d,await c.middleware({input:p,options:d,request:n,response:i,logger:a})),l="writableEnded"in i&&i.writableEnded,l){a.warn(`The middleware ${c.middleware.name} has closed the stream. Accumulated options:`,d);break}}return{options:d,isStreamClosed:l}},De=new WeakSet,vt=async function({input:t,options:o,logger:n}){let i;try{i=await this.schemas.input.parseAsync(t)}catch(a){throw a instanceof N.ZodError?new C(a):a}return this.handler({input:i,options:o,logger:n})},ve=new WeakSet,zt=async function({error:t,request:o,response:n,logger:i,input:a,output:d}){try{await this.resultHandler.handler({error:t,output:d,request:o,response:n,logger:i,input:a})}catch(l){Ie({logger:i,response:n,error:new q(ne(l).message,t)})}};var jt=["get","post","put","delete","patch"];import{z as kt}from"zod";var Lt=(e,r)=>{let t=e.map(({input:n})=>n).concat(r),o=t.reduce((n,i)=>n.and(i));return t.reduce((n,i)=>Oe(i,n),o)};var Xe=e=>{if(I(e.input))throw new M("Using transformations on the top level of middleware input schema is not allowed.");return{...e,type:"proprietary"}};var X,ze,Q=class{constructor(r){this.middlewares=[];this.use=this.addExpressMiddleware;this.resultHandler="resultHandler"in r?r.resultHandler:r}addMiddleware(r){var t;return E(t=Q,X,ze).call(t,this.middlewares.concat(r),this.resultHandler)}addExpressMiddleware(r,t){var a;let o=t?.transformer||(d=>d),n=t?.provider||(()=>({})),i={type:"express",input:kt.object({}),middleware:async({request:d,response:l})=>new Promise((c,p)=>{r(d,l,g=>{if(g&&g instanceof Error)return p(o(g));c(n(d,l))})})};return E(a=Q,X,ze).call(a,this.middlewares.concat(i),this.resultHandler)}addOptions(r){var t;return E(t=Q,X,ze).call(t,this.middlewares.concat(Xe({input:kt.object({}),middleware:async()=>r})),this.resultHandler)}build({input:r,handler:t,output:o,...n}){let{middlewares:i,resultHandler:a}=this;return new Ce({handler:t,middlewares:i,outputSchema:o,resultHandler:a,inputSchema:Lt(i,r),...n})}},de=Q;X=new WeakSet,ze=function(r,t){let o=new Q(t);return o.middlewares=r,o},A(de,X);var kr=new de(J);import{inspect as Ur}from"util";import{LEVEL as Hr,MESSAGE as Kr,SPLAT as Fr}from"triple-beam";import je from"winston";var{combine:_r,colorize:$r,timestamp:Gr,printf:qr}=je.format;function Le(e){let r=i=>{let{[Hr]:a,[Kr]:d,[Fr]:l,...c}=i;return Ur(c,!1,1,e.color)},t=i=>qr(({timestamp:a,message:d,level:l,durationMs:c,...p})=>(typeof d=="object"&&(p={...p,...d},d="[No message]"),`${a} ${l}: ${d}`+(c===void 0?"":` duration: ${c}ms`)+(Object.keys(p).length===0?"":" "+(i?r(p):JSON.stringify(p))))),o=[Gr()],n={handleExceptions:!0};switch(e.color&&o.push($r()),e.level){case"debug":n.level="debug",o.push(t(!0));break;case"silent":case"warn":default:n.level="warn",o.push(t())}return n.format=_r(...o),je.createLogger({silent:e.level==="silent",levels:je.config.npm.levels,transports:[new je.transports.Console(n)],exitOnError:!1})}var pe=class{constructor(r){this.methods=r;Object.keys(r).forEach(t=>{if(t in r&&!(r[t]?.getMethods()||[]).includes(t))throw new ae(`The endpoint assigned to the '${t}' 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
|
|
16
|
-
The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let
|
|
15
|
+
`)})}};import Vr from"express";var ce=class{constructor(...r){this.params=r}apply(r,t){return t(r,Vr.static(...this.params))}};var H=({routing:e,onEndpoint:r,onStatic:t,parentPath:o,hasCors:n})=>{Object.entries(e).forEach(([i,a])=>{if(i=i.trim(),i.match(/\//))throw new G(`Routing elements should not contain '/' character.
|
|
16
|
+
The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let d=`${o||""}${i?`/${i}`:""}`;if(a instanceof W){let l=a.getMethods().slice();n&&l.push("options"),l.forEach(c=>{r(a,d,c)})}else if(a instanceof ce)t&&a.apply(d,t);else if(a instanceof pe){if(Object.entries(a.methods).forEach(([l,c])=>{r(c,d,l)}),n&&Object.keys(a.methods).length>0){let[l,...c]=Object.keys(a.methods),p=a.methods[l];p._setSiblingMethods(c),r(p,d,"options")}}else H({onEndpoint:r,onStatic:t,hasCors:n,routing:a,parentPath:d})})};var Ut=()=>`
|
|
17
17
|
\x1B[94m\x1B[39m
|
|
18
18
|
\x1B[94m\x1B[39m
|
|
19
19
|
\x1B[94m8888888888 8888888888P 888 d8888 8888888b. 8888888 \x1B[39m
|
|
@@ -26,11 +26,11 @@ The error caused by ${o?`'${o}' route that has a '${i}'`:`'${i}'`} entry.`);let
|
|
|
26
26
|
\x1B[95m8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P' d8888888888 "Y88P" "Y88888 d88P 888 888 8888888\x1B[39m\x1B[94m\x1B[39m
|
|
27
27
|
\x1B[94m 888\x1B[39m
|
|
28
28
|
\x1B[94m 888\x1B[3m Proudly supports transgender community.\x1B[23m\x1B[39m
|
|
29
|
-
\x1B[94m\x1B[3mfor
|
|
29
|
+
\x1B[94m\x1B[3mfor Gisberta \x1B[23m 888\x1B[3m Start your API server with I/O schema validation and custom middlewares in minutes.\x1B[23m\x1B[39m\x1B[90m\x1B[39m
|
|
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 et=({app:e,logger:r,config:t,routing:o})=>{t.startupLogo!==!1&&console.log(Ht()),H({routing:o,hasCors:!!t.cors,onEndpoint:(n,i,a)=>{e[a](i,async(p,l)=>{r.info(`${p.method}: ${i}`),await n.execute({request:p,response:l,logger:r,config:t})})},onStatic:(n,i)=>{e.use(n,i)}})};import qr,{json as Vr}from"express";import Br from"compression";import Yr from"express-fileupload";import Jr from"https";import Wr from"http-errors";var Qr=(e,r)=>(t,o,n,i)=>{if(!t)return i();e.handler({error:t,request:o,response:n,logger:r,input:o.body,output:null})},Kt=(e,r)=>(t,o)=>{let n=Wr(404,`Can not ${t.method} ${t.path}`);try{e.handler({request:t,response:o,logger:r,error:n,input:null,output:null})}catch(i){Ie({response:o,logger:r,error:new G(ie(i).message,n)})}};function Xr(e,r){let t=Be(e.logger)?Le(e.logger):e.logger;et({app:e.app,routing:r,logger:t,config:e});let o=e.errorHandler||Y;return{notFoundHandler:Kt(o,t),logger:t}}function eo(e,r){let t=Be(e.logger)?Le(e.logger):e.logger,o=qr();o.disable("x-powered-by");let n=e.errorHandler||Y,i=e.server.compression?Br({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||Vr(),p=e.server.upload?Yr({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,l=[].concat(i||[]).concat(a).concat(p||[]);o.use(l),o.use(Qr(n,t)),et({app:o,routing:r,logger:t,config:e}),o.use(Kt(n,t));let c=o.listen(e.server.listen,()=>{t.info(`Listening ${e.server.listen}`)}),d;return e.https&&(d=Jr.createServer(e.https.options,o).listen(e.https.listen,()=>{t.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:c,httpsServer:d,logger:t}}import{OpenApiBuilder as Ho}from"openapi3-ts";import{omit as fe}from"ramda";import{z as h}from"zod";import{INVALID as Ft,ZodIssueCode as tt,ZodParsedType as _t,ZodType as to,addIssueToContext as rt}from"zod";var ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,ro="ZodDateIn",nt=class extends to{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);if(o.parsedType!==_t.string)return rt(o,{code:tt.invalid_type,expected:_t.string,received:o.parsedType}),Ft;ot.test(o.data)||(rt(o,{code:tt.invalid_string,validation:"regex"}),t.dirty());let n=new Date(o.data);return Pe(n)?{status:t.value,value:n}:(rt(o,{code:tt.invalid_date}),Ft)}},me=nt;me.create=()=>new nt({typeName:ro});var K=({schema:e,onEach:r,rules:t,onMissing:o,...n})=>{let i=r&&r({schema:e,...n}),a="typeName"in e._def?t[e._def.typeName]:void 0,l=a?a({schema:e,...n,next:c=>K({...c,...n,onEach:r,rules:t,onMissing:o})}):o(e);return i?{...l,...i}:l};var $t=50,qt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",oo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vt=e=>e.replace(qe,r=>`{${r.slice(1)}}`),no=({schema:{_def:{innerType:e,defaultValue:r}},next:t})=>({...t({schema:e}),default:r()}),io=({schema:{_def:{innerType:e}},next:r})=>r({schema:e}),so=()=>({format:"any"}),ao=({isResponse:e})=>{if(e)throw new b("Please use z.upload() only for input.");return{type:"string",format:"binary"}},po=({schema:{isBinary:e,isBase64:r},isResponse:t})=>{if(!t)throw new b("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":r?"byte":"file"}},co=({schema:{options:e},next:r})=>({oneOf:e.map(t=>r({schema:t}))}),lo=({schema:{options:e,discriminator:r},next:t})=>({discriminator:{propertyName:r},oneOf:Array.from(e.values()).map(o=>t({schema:o}))}),mo=({schema:{_def:{left:e,right:r}},next:t})=>({allOf:[e,r].map(o=>t({schema:o}))}),uo=({schema:e,next:r})=>r({schema:e.unwrap()}),fo=({schema:e,next:r})=>({nullable:!0,...r({schema:e.unwrap()})}),Gt=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),yo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),go=({schema:e,isResponse:r,next:t})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(r&&se(i)?i instanceof h.ZodOptional:i.isOptional())});return{type:"object",properties:ke({schema:e,isResponse:r,next:t}),...o.length?{required:o}:{}}},xo=()=>({type:"string",nullable:!0,format:"null"}),ho=({isResponse:e})=>{if(e)throw new b("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ot.source,externalDocs:{url:qt}}},To=({isResponse:e})=>{if(!e)throw new b("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:qt}}},So=({isResponse:e})=>{throw new b(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},Oo=()=>({type:"boolean"}),bo=()=>({type:"integer",format:"bigint"}),Po=({schema:{keySchema:e,valueSchema:r},isResponse:t,next:o})=>{if(e instanceof h.ZodEnum||e instanceof h.ZodNativeEnum){let n=Object.values(e.enum),i=n.reduce((a,p)=>({...a,[p]:r}),{});return{type:"object",properties:ke({schema:h.object(i),isResponse:t,next:o}),...n.length?{required:n}:{}}}if(e instanceof h.ZodLiteral)return{type:"object",properties:ke({schema:h.object({[e.value]:r}),isResponse:t,next:o}),required:[e.value]};if(e instanceof h.ZodUnion&&e.options.reduce((i,a)=>i&&a instanceof h.ZodLiteral,!0)){let i=e.options.reduce((a,p)=>({...a,[p.value]:r}),{});return{type:"object",properties:ke({schema:h.object(i),isResponse:t,next:o}),required:e.options.map(a=>a.value)}}return{type:"object",additionalProperties:o({schema:r})}},Eo=({schema:{_def:e,element:r},next:t})=>({type:"array",items:t({schema:r}),...e.minLength!==null&&{minItems:e.minLength.value},...e.maxLength!==null&&{maxItems:e.maxLength.value}}),Zo=({schema:{items:e},next:r})=>{let t=e.map(o=>r({schema:o}));return{type:"array",minItems:t.length,maxItems:t.length,items:{oneOf:t,format:"tuple",...t.length>0&&{description:t.map((o,n)=>`${n}: ${o.type}`).join(", ")}}}},Ro=({schema:{isEmail:e,isURL:r,minLength:t,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:d,_def:{checks:u}}})=>{let g=u.find(O=>O.kind==="regex"),y=u.find(O=>O.kind==="datetime"),T=g?g.regex:y?y.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",...d&&{format:"date-time"},...e&&{format:"email"},...r&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...p&&{format:"ulid"},...l&&{format:"ip"},...c&&{format:"emoji"},...t!==null&&{minLength:t},...o!==null&&{maxLength:o},...T&&{pattern:`/${T.source}/${T.flags}`}}},Ao=({schema:e})=>{let r=e._def.checks.find(({kind:i})=>i==="min"),t=r?r.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:!t,maximum:e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,exclusiveMaximum:!n}},ke=({schema:{shape:e},next:r})=>Object.keys(e).reduce((t,o)=>({...t,[o]:r({schema:e[o]})}),{}),Io=e=>{let r=Array.isArray(e.type)?e.type[0]:e.type;return oo?.[r]},Co=({schema:e,isResponse:r,next:t})=>{let o=t({schema:e.innerType()}),{effect:n}=e._def;if(r&&n.type==="transform"){let i=Ze({effect:n,sample:Io(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:t({schema:h.any()})}if(!r&&n.type==="preprocess"){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Mo=({schema:e,isResponse:r,next:t})=>t({schema:e._def[r?"out":"in"]}),No=({schema:e,next:r})=>r({schema:e.unwrap()}),Bt=(e,r,t=[])=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:fe(t,i)}}),{})}},wo=(e,r,t)=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>t in i?{...n,[`example${a+1}`]:{value:i[t]}}:n,{})}};function ue(e){if(e instanceof h.ZodObject)return e;let r;if(e instanceof h.ZodUnion||e instanceof h.ZodDiscriminatedUnion)r=Array.from(e.options.values()).map(t=>ue(t)).reduce((t,o)=>t.merge(o.partial()),h.object({}));else if(e instanceof h.ZodEffects){if(I(e))throw new b("Using transformations on the top level of input schema is not allowed.");r=ue(e._def.schema)}else r=ue(e._def.left).merge(ue(e._def.right));return te(e,r)}var Yt=({path:e,method:r,endpoint:t,inputSources:o})=>{let n=t.getSchema("input"),i=ue(n).shape,a=Je(e),p=o.includes("query"),l=o.includes("params"),c=d=>l&&a.includes(d);return Object.keys(i).filter(d=>p||c(d)).map(d=>({name:d,in:c(d)?"path":"query",required:!i[d].isOptional(),schema:{description:`${r.toUpperCase()} ${e} parameter`,...K({schema:i[d],isResponse:!1,rules:st,onEach:at,onMissing:pt})},...wo(n,!1,d)}))},st={ZodString:Ro,ZodNumber:Ao,ZodBigInt:bo,ZodBoolean:Oo,ZodDateIn:ho,ZodDateOut:To,ZodNull:xo,ZodArray:Eo,ZodTuple:Zo,ZodRecord:Po,ZodObject:go,ZodLiteral:yo,ZodIntersection:mo,ZodUnion:co,ZodFile:po,ZodUpload:ao,ZodAny:so,ZodDefault:no,ZodEnum:Gt,ZodNativeEnum:Gt,ZodEffects:Co,ZodOptional:uo,ZodNullable:fo,ZodDiscriminatedUnion:lo,ZodBranded:No,ZodDate:So,ZodCatch:io,ZodPipeline:Mo},at=({schema:e,isResponse:r})=>{let{description:t}=e,o=Ee(e,r);return{...t&&{description:t},...e.isNullable()&&!(r&&se(e))&&{nullable:!0},...o.length>0&&{example:o[0]}}},pt=e=>{throw new b(`Zod type ${e.constructor.name} is unsupported`)},it=(e,r)=>{let t=e.properties?fe(r,e.properties):void 0,o=e.example?fe(r,e.example):void 0,n=e.required?e.required.filter(p=>!r.includes(p)):void 0,i=e.allOf?e.allOf.map(p=>it(p,r)):void 0,a=e.oneOf?e.oneOf.map(p=>it(p,r)):void 0;return fe(Object.entries({properties:t,required:n,example:o,allOf:i,oneOf:a}).filter(([{},p])=>p===void 0).map(([p])=>p),{...e,properties:t,required:n,example:o,allOf:i,oneOf:a})},Jt=e=>fe(["example"],e),dt=({method:e,path:r,description:t,endpoint:o,isPositive:n})=>{let i=n?o.getSchema("positive"):o.getSchema("negative"),a=n?o.getMimeTypes("positive"):o.getMimeTypes("negative"),p=Jt(K({schema:i,isResponse:!0,rules:st,onEach:at,onMissing:pt})),l=Bt(i,!0);return{description:`${e.toUpperCase()} ${r} ${t}`,content:a.reduce((c,d)=>({...c,[d]:{schema:p,...l}}),{})}},Do=()=>({type:"http",scheme:"basic"}),vo=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),zo=({name:e})=>({type:"apiKey",in:"query",name:e}),jo=({name:e})=>({type:"apiKey",in:"header",name:e}),Lo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ko=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Uo=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((r,t)=>{let o=e[t];if(!o)return r;let{scopes:n={},...i}=o;return{...r,[t]:{...i,scopes:n}}},{})}),Wt=e=>{let r={basic:Do,bearer:vo,input:zo,header:jo,cookie:Lo,openid:ko,oauth2:Uo};return Ae(e,t=>r[t.type](t))},Ue=e=>{if(typeof e=="object"){if("or"in e)return e.or.map(r=>("and"in r?r.and:[r]).reduce((t,{name:o,scopes:n})=>({...t,[o]:n}),{}));if("and"in e)return Ue(Qe(e))}return Ue({or:[e]})},Qt=({method:e,path:r,endpoint:t})=>{let o=Je(r),n=Jt(it(K({schema:t.getSchema("input"),isResponse:!1,rules:st,onEach:at,onMissing:pt}),o)),i=Bt(t.getSchema("input"),!1,o);return{content:t.getMimeTypes("input").reduce((a,p)=>({...a,[p]:{schema:{description:`${e.toUpperCase()} ${r} request body`,...n},...i}}),{})}},Xt=e=>Object.keys(e).map(r=>{let t=e[r];return{name:r,description:typeof t=="string"?t:t.description,...typeof t=="object"&&t.url&&{externalDocs:{url:t.url}}}}),ct=e=>e.length<=$t?e:e.slice(0,$t-1)+"\u2026";var lt=class extends Ho{constructor({routing:t,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:p="Successful response",errorResponseDescription:l="Error response",hasSummaryFromDescription:c=!0}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:i}).addServer({url:a}),H({routing:t,onEndpoint:(u,g,y)=>{let T=y,O={path:g,method:T,endpoint:u},[F,_]=["short","long"].map(u.getDescription.bind(u)),he=o.inputSources?.[T]||be[T],Te=Yt({...O,inputSources:he}),P={operationId:this.ensureUniqOperationId(g,T),responses:{[u.getStatusCode("positive")]:dt({...O,description:p,isPositive:!0}),[u.getStatusCode("negative")]:dt({...O,description:l,isPositive:!1})}};_&&(P.description=_,c&&F===void 0&&(P.summary=ct(_))),F&&(P.summary=ct(F)),u.getTags().length>0&&(P.tags=u.getTags()),Te.length>0&&(P.parameters=Te),he.includes("body")&&(P.requestBody=Qt(O));let Se=Ue(Ae(Wt(u.getSecurity()),$e=>{let Zt=this.ensureUniqSecuritySchemaName($e),Or=["oauth2","openIdConnect"].includes($e.type)?u.getScopes():[];return this.addSecurityScheme(Zt,$e),{name:Zt,scopes:Or}}));Se.length>0&&(P.security=Se);let Sr=Vt(g);this.addPath(Sr,{[T]:P})}}),this.rootDoc.tags=o.tags?Xt(o.tags):[]}ensureUniqOperationId(t,o){let n=ae(t,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(t){for(let o in this.rootDoc.components?.securitySchemes||{})if(JSON.stringify(t)===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}};import er from"http";var Ko=e=>({method:"GET",header:jest.fn(()=>j),...e}),Fo=e=>{let r={writableEnded:!1,statusCode:200,statusMessage:er.STATUS_CODES[200],set:jest.fn(()=>r),status:jest.fn(t=>(r.statusCode=t,r.statusMessage=er.STATUS_CODES[t],r)),json:jest.fn(()=>r),end:jest.fn(()=>(r.writableEnded=!0,r)),...e};return r},_o=async({endpoint:e,requestProps:r,responseProps:t,configProps:o,loggerProps:n,__noJest:i})=>{if(!jest||i)throw new Error("You need to install Jest in order to use testEndpoint().");let a=Ko(r),p=Fo(t),l={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},c={cors:!1,logger:l,...o};return await e.execute({request:a,response:p,config:c,logger:l}),{requestMock:a,responseMock:p,loggerMock:l}};import z from"typescript";import w from"typescript";var s=w.factory,X=[s.createModifier(w.SyntaxKind.ExportKeyword)],$o=[s.createModifier(w.SyntaxKind.PublicKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],tr=[s.createModifier(w.SyntaxKind.ProtectedKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],Go=s.createTemplateHead(""),qo=s.createTemplateTail(""),Vo=s.createTemplateMiddle(" "),mt=e=>s.createTemplateLiteralType(Go,e.map((r,t)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(r),t===e.length-1?qo:Vo))),ut=mt(["M","P"]),He=(e,r,t)=>s.createParameterDeclaration(t,void 0,e,void 0,r),Ke=(e,r)=>Object.keys(e).reduce((t,o)=>t.concat(He(o,e[o],r)),[]),ft=(e,r)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(r)]),rr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yt=(e,r)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(r)),or=(e,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,r)],w.NodeFlags.Const),gt=(e,r)=>s.createTypeAliasDeclaration(X,e,void 0,s.createUnionTypeNode(r.map(t=>s.createLiteralTypeNode(s.createStringLiteral(t))))),Fe=(e,r)=>s.createTypeAliasDeclaration(X,e,void 0,r),nr=(e,r,t)=>s.createPropertyDeclaration($o,e,void 0,r,t),ir=(e,r,t=[])=>s.createClassDeclaration(X,e,void 0,void 0,[r,...t]),sr=(e,r)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),r)]),ar=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(w.SyntaxKind.AnyKeyword)]),xt=(e,r,t)=>s.createInterfaceDeclaration(X,e,void 0,r,t),pr=e=>Object.keys(e).reduce((r,t)=>r.concat(s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(e[t]))),[]),dr=(e,r)=>s.createArrowFunction(void 0,void 0,e.map(t=>He(t)),void 0,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),"implementation"),void 0,r)),ht=(e,r,t)=>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,Ke({acc:void 0,key:void 0}),void 0,void 0,r),t]);import f from"typescript";import{z as Yo}from"zod";import D from"typescript";var{factory:_e}=D,Tt=(e,r)=>{D.addSyntheticLeadingComment(e,D.SyntaxKind.MultiLineCommentTrivia,`* ${r} `,!0)},St=(e,r,t)=>{let o=_e.createTypeAliasDeclaration(void 0,_e.createIdentifier(r),void 0,e);return t&&Tt(o,t),o},cr=(e,r)=>{let t=D.createSourceFile("print.ts","",D.ScriptTarget.Latest,!1,D.ScriptKind.TS);return D.createPrinter(r).printNode(D.EmitHint.Unspecified,e,t)},Bo=/^[A-Za-z_$][A-Za-z0-9_$]*$/,lr=e=>Bo.test(e)?_e.createIdentifier(e):_e.createStringLiteral(e);var{factory:m}=f,Jo={[f.SyntaxKind.AnyKeyword]:"",[f.SyntaxKind.BigIntKeyword]:BigInt(0),[f.SyntaxKind.BooleanKeyword]:!1,[f.SyntaxKind.NumberKeyword]:0,[f.SyntaxKind.ObjectKeyword]:{},[f.SyntaxKind.StringKeyword]:"",[f.SyntaxKind.UndefinedKeyword]:void 0},Wo=({schema:{value:e}})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),Qo=({schema:{shape:e},isResponse:r,next:t})=>{let o=Object.entries(e).map(([n,i])=>{let a=r&&se(i)?i instanceof Yo.ZodOptional:i.isOptional(),p=m.createPropertySignature(void 0,lr(n),a?m.createToken(f.SyntaxKind.QuestionToken):void 0,t({schema:i}));return i.description&&Tt(p,i.description),p});return m.createTypeLiteralNode(o)},Xo=({schema:{element:e},next:r})=>m.createArrayTypeNode(r({schema:e})),en=({schema:{options:e}})=>m.createUnionTypeNode(e.map(r=>m.createLiteralTypeNode(m.createStringLiteral(r)))),mr=({schema:{options:e},next:r})=>m.createUnionTypeNode(e.map(t=>r({schema:t}))),tn=e=>Jo?.[e.kind],rn=({schema:e,next:r,isResponse:t})=>{let o=r({schema:e.innerType()}),n=e._def.effect;if(t&&n.type==="transform"){let i=Ze({effect:n,sample:tn(o)}),a={number:f.SyntaxKind.NumberKeyword,bigint:f.SyntaxKind.BigIntKeyword,boolean:f.SyntaxKind.BooleanKeyword,string:f.SyntaxKind.StringKeyword,undefined:f.SyntaxKind.UndefinedKeyword,object:f.SyntaxKind.ObjectKeyword};return m.createKeywordTypeNode(i&&a[i]||f.SyntaxKind.AnyKeyword)}return o},on=({schema:e})=>m.createUnionTypeNode(Object.values(e.enum).map(r=>m.createLiteralTypeNode(typeof r=="number"?m.createNumericLiteral(r):m.createStringLiteral(r)))),nn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createKeywordTypeNode(f.SyntaxKind.UndefinedKeyword)]),sn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createLiteralTypeNode(m.createNull())]),an=({next:e,schema:{items:r}})=>m.createTupleTypeNode(r.map(t=>e({schema:t}))),pn=({next:e,schema:{keySchema:r,valueSchema:t}})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e({schema:r}),e({schema:t})]),dn=({next:e,schema:r})=>m.createIntersectionTypeNode([r._def.left,r._def.right].map(t=>e({schema:t}))),cn=({next:e,schema:r})=>e({schema:r._def.innerType}),v=e=>()=>m.createKeywordTypeNode(e),ln=({next:e,schema:r})=>e({schema:r.unwrap()}),mn=({next:e,schema:r})=>e({schema:r._def.innerType}),un=({schema:e,next:r,isResponse:t})=>r({schema:e._def[t?"out":"in"]}),fn=()=>m.createLiteralTypeNode(m.createNull()),yn={ZodString:v(f.SyntaxKind.StringKeyword),ZodNumber:v(f.SyntaxKind.NumberKeyword),ZodBigInt:v(f.SyntaxKind.BigIntKeyword),ZodBoolean:v(f.SyntaxKind.BooleanKeyword),ZodDateIn:v(f.SyntaxKind.StringKeyword),ZodDateOut:v(f.SyntaxKind.StringKeyword),ZodNull:fn,ZodArray:Xo,ZodTuple:an,ZodRecord:pn,ZodObject:Qo,ZodLiteral:Wo,ZodIntersection:dn,ZodUnion:mr,ZodFile:v(f.SyntaxKind.StringKeyword),ZodAny:v(f.SyntaxKind.AnyKeyword),ZodDefault:cn,ZodEnum:en,ZodNativeEnum:on,ZodEffects:rn,ZodOptional:nn,ZodNullable:sn,ZodDiscriminatedUnion:mr,ZodBranded:ln,ZodCatch:mn,ZodPipeline:un},Ot=({schema:e,...r})=>K({schema:e,rules:yn,onMissing:()=>m.createKeywordTypeNode(f.SyntaxKind.AnyKeyword),...r});var bt=class{constructor(r){this.agg=[];this.registry={};this.paths=[];H({routing:r,onEndpoint:(y,T,O)=>{let F=ae(T,O,"input"),_=ae(T,O,"response"),he=Ot({schema:y.getSchema("input"),isResponse:!1}),Te=Ot({isResponse:!0,schema:y.getSchema("positive").or(y.getSchema("negative"))}),P=St(he,F),Se=St(Te,_);this.agg.push(P),this.agg.push(Se),O!=="options"&&(this.paths.push(T),this.registry[`${O} ${T}`]={in:F,out:_,isJson:y.getMimeTypes("positive").includes(j)})}});let t=gt("Path",this.paths),o=gt("Method",Lt),n=Fe("MethodPath",mt([o.name,t.name])),i=[s.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[ft(n.name,z.SyntaxKind.AnyKeyword)])],a=xt("Input",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].in))),p=xt("Response",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].out))),l=s.createVariableStatement(X,or("jsonEndpoints",s.createObjectLiteralExpression(Object.keys(this.registry).filter(y=>this.registry[y].isJson).map(y=>s.createPropertyAssignment(`"${y}"`,s.createTrue()))))),c=Fe("Provider",s.createFunctionTypeNode(pr({M:o.name,P:t.name}),Ke({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(a.name),ut)}),sr(p.name,ut))),d=Fe("Implementation",s.createFunctionTypeNode(void 0,Ke({method:s.createTypeReferenceNode(o.name),path:s.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:ft(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),ar())),u=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),g=ir("ExpressZodAPIClient",rr([He("implementation",s.createTypeReferenceNode(d.name),tr)]),[nr("provide",s.createTypeReferenceNode(c.name),dr(["method","path","params"],[s.createIdentifier("method"),ht("params",s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("acc"),"replace"),void 0,[u,s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key"))]),s.createIdentifier("path")),ht("params",s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("path"),"indexOf"),void 0,[u]),z.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())]))]);z.addSyntheticLeadingComment(g,z.SyntaxKind.MultiLineCommentTrivia,`
|
|
33
|
+
`.trim();var et=({app:e,logger:r,config:t,routing:o})=>{t.startupLogo!==!1&&console.log(Ut()),H({routing:o,hasCors:!!t.cors,onEndpoint:(n,i,a)=>{e[a](i,async(d,l)=>{r.info(`${d.method}: ${i}`),await n.execute({request:d,response:l,logger:r,config:t})})},onStatic:(n,i)=>{e.use(n,i)}})};import Br,{json as Yr}from"express";import Jr from"compression";import Wr from"express-fileupload";import Qr from"https";import Xr from"http-errors";var eo=(e,r)=>(t,o,n,i)=>{if(!t)return i();e.handler({error:t,request:o,response:n,logger:r,input:o.body,output:null})},Ht=(e,r)=>(t,o)=>{let n=Xr(404,`Can not ${t.method} ${t.path}`);try{e.handler({request:t,response:o,logger:r,error:n,input:null,output:null})}catch(i){Ie({response:o,logger:r,error:new q(ne(i).message,n)})}};function to(e,r){let t=Be(e.logger)?Le(e.logger):e.logger;et({app:e.app,routing:r,logger:t,config:e});let o=e.errorHandler||J;return{notFoundHandler:Ht(o,t),logger:t}}function ro(e,r){let t=Be(e.logger)?Le(e.logger):e.logger,o=Br();o.disable("x-powered-by");let n=e.errorHandler||J,i=e.server.compression?Jr({...typeof e.server.compression=="object"?e.server.compression:{}}):void 0,a=e.server.jsonParser||Yr(),d=e.server.upload?Wr({...typeof e.server.upload=="object"?e.server.upload:{},abortOnLimit:!1,parseNested:!0}):void 0,l=[].concat(i||[]).concat(a).concat(d||[]);o.use(l),o.use(eo(n,t)),et({app:o,routing:r,logger:t,config:e}),o.use(Ht(n,t));let c=o.listen(e.server.listen,()=>{t.info(`Listening ${e.server.listen}`)}),p;return e.https&&(p=Qr.createServer(e.https.options,o).listen(e.https.listen,()=>{t.info(`Listening ${e.https.listen}`)})),{app:o,httpServer:c,httpsServer:p,logger:t}}import{OpenApiBuilder as Fo}from"openapi3-ts";import{omit as ue}from"ramda";import{z as x}from"zod";import{INVALID as Kt,ZodIssueCode as tt,ZodParsedType as Ft,ZodType as oo,addIssueToContext as rt}from"zod";var ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/,no="ZodDateIn",nt=class extends oo{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);if(o.parsedType!==Ft.string)return rt(o,{code:tt.invalid_type,expected:Ft.string,received:o.parsedType}),Kt;ot.test(o.data)||(rt(o,{code:tt.invalid_string,validation:"regex"}),t.dirty());let n=new Date(o.data);return Pe(n)?{status:t.value,value:n}:(rt(o,{code:tt.invalid_date}),Kt)}},le=nt;le.create=()=>new nt({typeName:no});var K=({schema:e,onEach:r,rules:t,onMissing:o,...n})=>{let i=r&&r({schema:e,...n}),a="typeName"in e._def?t[e._def.typeName]:void 0,l=a?a({schema:e,...n,next:c=>K({...c,...n,onEach:r,rules:t,onMissing:o})}):o(e);return i?{...l,...i}:l};var _t=50,Gt="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",io={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},qt=e=>e.replace(qe,r=>`{${r.slice(1)}}`),so=({schema:{_def:{innerType:e,defaultValue:r}},next:t})=>({...t({schema:e}),default:r()}),ao=({schema:{_def:{innerType:e}},next:r})=>r({schema:e}),po=()=>({format:"any"}),co=({isResponse:e})=>{if(e)throw new b("Please use z.upload() only for input.");return{type:"string",format:"binary"}},lo=({schema:{isBinary:e,isBase64:r},isResponse:t})=>{if(!t)throw new b("Please use z.file() only within ResultHandler.");return{type:"string",format:e?"binary":r?"byte":"file"}},mo=({schema:{options:e},next:r})=>({oneOf:e.map(t=>r({schema:t}))}),uo=({schema:{options:e,discriminator:r},next:t})=>({discriminator:{propertyName:r},oneOf:Array.from(e.values()).map(o=>t({schema:o}))}),fo=({schema:{_def:{left:e,right:r}},next:t})=>({allOf:[e,r].map(o=>t({schema:o}))}),yo=({schema:e,next:r})=>r({schema:e.unwrap()}),go=({schema:e,next:r})=>({nullable:!0,...r({schema:e.unwrap()})}),$t=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),xo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),ho=({schema:e,isResponse:r,next:t})=>{let o=Object.keys(e.shape).filter(n=>{let i=e.shape[n];return!(r&&ie(i)?i instanceof x.ZodOptional:i.isOptional())});return{type:"object",properties:ke({schema:e,isResponse:r,next:t}),...o.length?{required:o}:{}}},To=()=>({type:"string",nullable:!0,format:"null"}),So=({isResponse:e})=>{if(e)throw new b("Please use z.dateOut() for output.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ot.source,externalDocs:{url:Gt}}},Oo=({isResponse:e})=>{if(!e)throw new b("Please use z.dateIn() for input.");return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Gt}}},bo=({isResponse:e})=>{throw new b(`Using z.date() within ${e?"output":"input"} schema is forbidden. Please use z.date${e?"Out":"In"}() instead. Check out the documentation for details.`)},Po=()=>({type:"boolean"}),Eo=()=>({type:"integer",format:"bigint"}),Zo=({schema:{keySchema:e,valueSchema:r},isResponse:t,next:o})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let n=Object.values(e.enum),i=n.reduce((a,d)=>({...a,[d]:r}),{});return{type:"object",properties:ke({schema:x.object(i),isResponse:t,next:o}),...n.length?{required:n}:{}}}if(e instanceof x.ZodLiteral)return{type:"object",properties:ke({schema:x.object({[e.value]:r}),isResponse:t,next:o}),required:[e.value]};if(e instanceof x.ZodUnion&&e.options.reduce((i,a)=>i&&a instanceof x.ZodLiteral,!0)){let i=e.options.reduce((a,d)=>({...a,[d.value]:r}),{});return{type:"object",properties:ke({schema:x.object(i),isResponse:t,next:o}),required:e.options.map(a=>a.value)}}return{type:"object",additionalProperties:o({schema:r})}},Ro=({schema:{_def:e,element:r},next:t})=>({type:"array",items:t({schema:r}),...e.minLength!==null&&{minItems:e.minLength.value},...e.maxLength!==null&&{maxItems:e.maxLength.value}}),Ao=({schema:{items:e},next:r})=>{let t=e.map(o=>r({schema:o}));return{type:"array",minItems:t.length,maxItems:t.length,items:{oneOf:t,format:"tuple",...t.length>0&&{description:t.map((o,n)=>`${n}: ${o.type}`).join(", ")}}}},Io=({schema:{isEmail:e,isURL:r,minLength:t,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:d,isIP:l,isEmoji:c,isDatetime:p,_def:{checks:u}}})=>{let g=u.find(S=>S.kind==="regex"),y=u.find(S=>S.kind==="datetime"),h=g?g.regex:y?y.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",...p&&{format:"date-time"},...e&&{format:"email"},...r&&{format:"url"},...n&&{format:"uuid"},...i&&{format:"cuid"},...a&&{format:"cuid2"},...d&&{format:"ulid"},...l&&{format:"ip"},...c&&{format:"emoji"},...t!==null&&{minLength:t},...o!==null&&{maxLength:o},...h&&{pattern:`/${h.source}/${h.flags}`}}},Co=({schema:e})=>{let r=e._def.checks.find(({kind:i})=>i==="min"),t=r?r.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:!t,maximum:e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,exclusiveMaximum:!n}},ke=({schema:{shape:e},next:r})=>Object.keys(e).reduce((t,o)=>({...t,[o]:r({schema:e[o]})}),{}),Mo=e=>{let r=Array.isArray(e.type)?e.type[0]:e.type;return io?.[r]},No=({schema:e,isResponse:r,next:t})=>{let o=t({schema:e.innerType()}),{effect:n}=e._def;if(r&&n.type==="transform"){let i=Ze({effect:n,sample:Mo(o)});return i&&["number","string","boolean"].includes(i)?{type:i}:t({schema:x.any()})}if(!r&&n.type==="preprocess"){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},wo=({schema:e,isResponse:r,next:t})=>t({schema:e._def[r?"out":"in"]}),Do=({schema:e,next:r})=>r({schema:e.unwrap()}),Vt=(e,r,t=[])=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>({...n,[`example${a+1}`]:{value:ue(t,i)}}),{})}},vo=(e,r,t)=>{let o=Ee(e,r);return o.length===0?{}:{examples:o.reduce((n,i,a)=>t in i?{...n,[`example${a+1}`]:{value:i[t]}}:n,{})}};function me(e){if(e instanceof x.ZodObject)return e;let r;if(e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion)r=Array.from(e.options.values()).map(t=>me(t)).reduce((t,o)=>t.merge(o.partial()),x.object({}));else if(e instanceof x.ZodEffects){if(I(e))throw new b("Using transformations on the top level of input schema is not allowed.");r=me(e._def.schema)}else r=me(e._def.left).merge(me(e._def.right));return Oe(e,r)}var Bt=({path:e,method:r,endpoint:t,inputSources:o})=>{let n=t.getSchema("input"),i=me(n).shape,a=Je(e),d=o.includes("query"),l=o.includes("params"),c=p=>l&&a.includes(p);return Object.keys(i).filter(p=>d||c(p)).map(p=>({name:p,in:c(p)?"path":"query",required:!i[p].isOptional(),schema:{description:`${r.toUpperCase()} ${e} parameter`,...K({schema:i[p],isResponse:!1,rules:st,onEach:at,onMissing:dt})},...vo(n,!1,p)}))},st={ZodString:Io,ZodNumber:Co,ZodBigInt:Eo,ZodBoolean:Po,ZodDateIn:So,ZodDateOut:Oo,ZodNull:To,ZodArray:Ro,ZodTuple:Ao,ZodRecord:Zo,ZodObject:ho,ZodLiteral:xo,ZodIntersection:fo,ZodUnion:mo,ZodFile:lo,ZodUpload:co,ZodAny:po,ZodDefault:so,ZodEnum:$t,ZodNativeEnum:$t,ZodEffects:No,ZodOptional:yo,ZodNullable:go,ZodDiscriminatedUnion:uo,ZodBranded:Do,ZodDate:bo,ZodCatch:ao,ZodPipeline:wo},at=({schema:e,isResponse:r})=>{let{description:t}=e,o=Ee(e,r);return{...t&&{description:t},...e.isNullable()&&!(r&&ie(e))&&{nullable:!0},...o.length>0&&{example:o[0]}}},dt=e=>{throw new b(`Zod type ${e.constructor.name} is unsupported`)},it=(e,r)=>{let t=e.properties?ue(r,e.properties):void 0,o=e.example?ue(r,e.example):void 0,n=e.required?e.required.filter(d=>!r.includes(d)):void 0,i=e.allOf?e.allOf.map(d=>it(d,r)):void 0,a=e.oneOf?e.oneOf.map(d=>it(d,r)):void 0;return ue(Object.entries({properties:t,required:n,example:o,allOf:i,oneOf:a}).filter(([{},d])=>d===void 0).map(([d])=>d),{...e,properties:t,required:n,example:o,allOf:i,oneOf:a})},Yt=e=>ue(["example"],e),pt=({method:e,path:r,description:t,endpoint:o,isPositive:n})=>{let i=n?o.getSchema("positive"):o.getSchema("negative"),a=n?o.getMimeTypes("positive"):o.getMimeTypes("negative"),d=Yt(K({schema:i,isResponse:!0,rules:st,onEach:at,onMissing:dt})),l=Vt(i,!0);return{description:`${e.toUpperCase()} ${r} ${t}`,content:a.reduce((c,p)=>({...c,[p]:{schema:d,...l}}),{})}},zo=()=>({type:"http",scheme:"basic"}),jo=({format:e})=>({type:"http",scheme:"bearer",...e&&{bearerFormat:e}}),Lo=({name:e})=>({type:"apiKey",in:"query",name:e}),ko=({name:e})=>({type:"apiKey",in:"header",name:e}),Uo=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ho=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ko=({flows:e={}})=>({type:"oauth2",flows:Object.keys(e).reduce((r,t)=>{let o=e[t];if(!o)return r;let{scopes:n={},...i}=o;return{...r,[t]:{...i,scopes:n}}},{})}),Jt=e=>{let r={basic:zo,bearer:jo,input:Lo,header:ko,cookie:Uo,openid:Ho,oauth2:Ko};return Ae(e,t=>r[t.type](t))},Ue=e=>{if(typeof e=="object"){if("or"in e)return e.or.map(r=>("and"in r?r.and:[r]).reduce((t,{name:o,scopes:n})=>({...t,[o]:n}),{}));if("and"in e)return Ue(Qe(e))}return Ue({or:[e]})},Wt=({method:e,path:r,endpoint:t})=>{let o=Je(r),n=Yt(it(K({schema:t.getSchema("input"),isResponse:!1,rules:st,onEach:at,onMissing:dt}),o)),i=Vt(t.getSchema("input"),!1,o);return{content:t.getMimeTypes("input").reduce((a,d)=>({...a,[d]:{schema:{description:`${e.toUpperCase()} ${r} request body`,...n},...i}}),{})}},Qt=e=>Object.keys(e).map(r=>{let t=e[r];return{name:r,description:typeof t=="string"?t:t.description,...typeof t=="object"&&t.url&&{externalDocs:{url:t.url}}}}),ct=e=>e.length<=_t?e:e.slice(0,_t-1)+"\u2026";var lt=class extends Fo{constructor({routing:t,config:o,title:n,version:i,serverUrl:a,successfulResponseDescription:d="Successful response",errorResponseDescription:l="Error response",hasSummaryFromDescription:c=!0}){super();this.lastSecuritySchemaIds={};this.lastOperationIdSuffixes={};this.addInfo({title:n,version:i}).addServer({url:a}),H({routing:t,onEndpoint:(u,g,y)=>{let h=y,S={path:g,method:h,endpoint:u},[F,_]=["short","long"].map(u.getDescription.bind(u)),xe=o.inputSources?.[h]||be[h],he=Bt({...S,inputSources:xe}),P={operationId:this.ensureUniqOperationId(g,h),responses:{[u.getStatusCode("positive")]:pt({...S,description:d,isPositive:!0}),[u.getStatusCode("negative")]:pt({...S,description:l,isPositive:!1})}};_&&(P.description=_,c&&F===void 0&&(P.summary=ct(_))),F&&(P.summary=ct(F)),u.getTags().length>0&&(P.tags=u.getTags()),he.length>0&&(P.parameters=he),xe.includes("body")&&(P.requestBody=Wt(S));let Te=Ue(Ae(Jt(u.getSecurity()),$e=>{let Zt=this.ensureUniqSecuritySchemaName($e),Sr=["oauth2","openIdConnect"].includes($e.type)?u.getScopes():[];return this.addSecurityScheme(Zt,$e),{name:Zt,scopes:Sr}}));Te.length>0&&(P.security=Te);let Tr=qt(g);this.addPath(Tr,{[h]:P})}}),this.rootDoc.tags=o.tags?Qt(o.tags):[]}ensureUniqOperationId(t,o){let n=se(t,o);return n in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[n]++,`${n}${this.lastOperationIdSuffixes[n]}`):(this.lastOperationIdSuffixes[n]=1,n)}ensureUniqSecuritySchemaName(t){for(let o in this.rootDoc.components?.securitySchemes||{})if(JSON.stringify(t)===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}};import Xt from"http";var _o=e=>({method:"GET",header:jest.fn(()=>j),...e}),$o=e=>{let r={writableEnded:!1,statusCode:200,statusMessage:Xt.STATUS_CODES[200],set:jest.fn(()=>r),status:jest.fn(t=>(r.statusCode=t,r.statusMessage=Xt.STATUS_CODES[t],r)),json:jest.fn(()=>r),end:jest.fn(()=>(r.writableEnded=!0,r)),...e};return r},Go=async({endpoint:e,requestProps:r,responseProps:t,configProps:o,loggerProps:n,__noJest:i})=>{if(!jest||i)throw new Error("You need to install Jest in order to use testEndpoint().");let a=_o(r),d=$o(t),l={info:jest.fn(),warn:jest.fn(),error:jest.fn(),debug:jest.fn(),...n},c={cors:!1,logger:l,...o};return await e.execute({request:a,response:d,config:c,logger:l}),{requestMock:a,responseMock:d,loggerMock:l}};import z from"typescript";import w from"typescript";var s=w.factory,ee=[s.createModifier(w.SyntaxKind.ExportKeyword)],qo=[s.createModifier(w.SyntaxKind.PublicKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],er=[s.createModifier(w.SyntaxKind.ProtectedKeyword),s.createModifier(w.SyntaxKind.ReadonlyKeyword)],Vo=s.createTemplateHead(""),Bo=s.createTemplateTail(""),Yo=s.createTemplateMiddle(" "),mt=e=>s.createTemplateLiteralType(Vo,e.map((r,t)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(r),t===e.length-1?Bo:Yo))),ut=mt(["M","P"]),He=(e,r,t)=>s.createParameterDeclaration(t,void 0,e,void 0,r),Ke=(e,r)=>Object.keys(e).reduce((t,o)=>t.concat(He(o,e[o],r)),[]),ft=(e,r)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(r)]),tr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),yt=(e,r)=>s.createPropertySignature(void 0,`"${e}"`,void 0,s.createTypeReferenceNode(r)),rr=(e,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,void 0,r)],w.NodeFlags.Const),gt=(e,r)=>s.createTypeAliasDeclaration(ee,e,void 0,s.createUnionTypeNode(r.map(t=>s.createLiteralTypeNode(s.createStringLiteral(t))))),Fe=(e,r)=>s.createTypeAliasDeclaration(ee,e,void 0,r),or=(e,r,t)=>s.createPropertyDeclaration(qo,e,void 0,r,t),nr=(e,r,t=[])=>s.createClassDeclaration(ee,e,void 0,void 0,[r,...t]),ir=(e,r)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),r)]),sr=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(w.SyntaxKind.AnyKeyword)]),xt=(e,r,t)=>s.createInterfaceDeclaration(ee,e,void 0,r,t),ar=e=>Object.keys(e).reduce((r,t)=>r.concat(s.createTypeParameterDeclaration([],t,s.createTypeReferenceNode(e[t]))),[]),dr=(e,r)=>s.createArrowFunction(void 0,void 0,e.map(t=>He(t)),void 0,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),"implementation"),void 0,r)),ht=(e,r,t)=>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,Ke({acc:void 0,key:void 0}),void 0,void 0,r),t]);import f from"typescript";import{z as Wo}from"zod";import D from"typescript";var{factory:_e}=D,Tt=(e,r)=>{D.addSyntheticLeadingComment(e,D.SyntaxKind.MultiLineCommentTrivia,`* ${r} `,!0)},St=(e,r,t)=>{let o=_e.createTypeAliasDeclaration(void 0,_e.createIdentifier(r),void 0,e);return t&&Tt(o,t),o},pr=(e,r)=>{let t=D.createSourceFile("print.ts","",D.ScriptTarget.Latest,!1,D.ScriptKind.TS);return D.createPrinter(r).printNode(D.EmitHint.Unspecified,e,t)},Jo=/^[A-Za-z_$][A-Za-z0-9_$]*$/,cr=e=>Jo.test(e)?_e.createIdentifier(e):_e.createStringLiteral(e);var{factory:m}=f,Qo={[f.SyntaxKind.AnyKeyword]:"",[f.SyntaxKind.BigIntKeyword]:BigInt(0),[f.SyntaxKind.BooleanKeyword]:!1,[f.SyntaxKind.NumberKeyword]:0,[f.SyntaxKind.ObjectKeyword]:{},[f.SyntaxKind.StringKeyword]:"",[f.SyntaxKind.UndefinedKeyword]:void 0},Xo=({schema:{value:e}})=>m.createLiteralTypeNode(typeof e=="number"?m.createNumericLiteral(e):typeof e=="boolean"?e?m.createTrue():m.createFalse():m.createStringLiteral(e)),en=({schema:{shape:e},isResponse:r,next:t})=>{let o=Object.entries(e).map(([n,i])=>{let a=r&&ie(i)?i instanceof Wo.ZodOptional:i.isOptional(),d=m.createPropertySignature(void 0,cr(n),a?m.createToken(f.SyntaxKind.QuestionToken):void 0,t({schema:i}));return i.description&&Tt(d,i.description),d});return m.createTypeLiteralNode(o)},tn=({schema:{element:e},next:r})=>m.createArrayTypeNode(r({schema:e})),rn=({schema:{options:e}})=>m.createUnionTypeNode(e.map(r=>m.createLiteralTypeNode(m.createStringLiteral(r)))),lr=({schema:{options:e},next:r})=>m.createUnionTypeNode(e.map(t=>r({schema:t}))),on=e=>Qo?.[e.kind],nn=({schema:e,next:r,isResponse:t})=>{let o=r({schema:e.innerType()}),n=e._def.effect;if(t&&n.type==="transform"){let i=Ze({effect:n,sample:on(o)}),a={number:f.SyntaxKind.NumberKeyword,bigint:f.SyntaxKind.BigIntKeyword,boolean:f.SyntaxKind.BooleanKeyword,string:f.SyntaxKind.StringKeyword,undefined:f.SyntaxKind.UndefinedKeyword,object:f.SyntaxKind.ObjectKeyword};return m.createKeywordTypeNode(i&&a[i]||f.SyntaxKind.AnyKeyword)}return o},sn=({schema:e})=>m.createUnionTypeNode(Object.values(e.enum).map(r=>m.createLiteralTypeNode(typeof r=="number"?m.createNumericLiteral(r):m.createStringLiteral(r)))),an=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createKeywordTypeNode(f.SyntaxKind.UndefinedKeyword)]),dn=({next:e,schema:r})=>m.createUnionTypeNode([e({schema:r.unwrap()}),m.createLiteralTypeNode(m.createNull())]),pn=({next:e,schema:{items:r}})=>m.createTupleTypeNode(r.map(t=>e({schema:t}))),cn=({next:e,schema:{keySchema:r,valueSchema:t}})=>m.createExpressionWithTypeArguments(m.createIdentifier("Record"),[e({schema:r}),e({schema:t})]),ln=({next:e,schema:r})=>m.createIntersectionTypeNode([r._def.left,r._def.right].map(t=>e({schema:t}))),mn=({next:e,schema:r})=>e({schema:r._def.innerType}),v=e=>()=>m.createKeywordTypeNode(e),un=({next:e,schema:r})=>e({schema:r.unwrap()}),fn=({next:e,schema:r})=>e({schema:r._def.innerType}),yn=({schema:e,next:r,isResponse:t})=>r({schema:e._def[t?"out":"in"]}),gn=()=>m.createLiteralTypeNode(m.createNull()),xn={ZodString:v(f.SyntaxKind.StringKeyword),ZodNumber:v(f.SyntaxKind.NumberKeyword),ZodBigInt:v(f.SyntaxKind.BigIntKeyword),ZodBoolean:v(f.SyntaxKind.BooleanKeyword),ZodDateIn:v(f.SyntaxKind.StringKeyword),ZodDateOut:v(f.SyntaxKind.StringKeyword),ZodNull:gn,ZodArray:tn,ZodTuple:pn,ZodRecord:cn,ZodObject:en,ZodLiteral:Xo,ZodIntersection:ln,ZodUnion:lr,ZodFile:v(f.SyntaxKind.StringKeyword),ZodAny:v(f.SyntaxKind.AnyKeyword),ZodDefault:mn,ZodEnum:rn,ZodNativeEnum:sn,ZodEffects:nn,ZodOptional:an,ZodNullable:dn,ZodDiscriminatedUnion:lr,ZodBranded:un,ZodCatch:fn,ZodPipeline:yn},Ot=({schema:e,...r})=>K({schema:e,rules:xn,onMissing:()=>m.createKeywordTypeNode(f.SyntaxKind.AnyKeyword),...r});var bt=class{constructor(r){this.agg=[];this.registry={};this.paths=[];H({routing:r,onEndpoint:(y,h,S)=>{let F=se(h,S,"input"),_=se(h,S,"response"),xe=Ot({schema:y.getSchema("input"),isResponse:!1}),he=Ot({isResponse:!0,schema:y.getSchema("positive").or(y.getSchema("negative"))}),P=St(xe,F),Te=St(he,_);this.agg.push(P),this.agg.push(Te),S!=="options"&&(this.paths.push(h),this.registry[`${S} ${h}`]={in:F,out:_,isJson:y.getMimeTypes("positive").includes(j)})}});let t=gt("Path",this.paths),o=gt("Method",jt),n=Fe("MethodPath",mt([o.name,t.name])),i=[s.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[ft(n.name,z.SyntaxKind.AnyKeyword)])],a=xt("Input",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].in))),d=xt("Response",i,Object.keys(this.registry).map(y=>yt(y,this.registry[y].out))),l=s.createVariableStatement(ee,rr("jsonEndpoints",s.createObjectLiteralExpression(Object.keys(this.registry).filter(y=>this.registry[y].isJson).map(y=>s.createPropertyAssignment(`"${y}"`,s.createTrue()))))),c=Fe("Provider",s.createFunctionTypeNode(ar({M:o.name,P:t.name}),Ke({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(a.name),ut)}),ir(d.name,ut))),p=Fe("Implementation",s.createFunctionTypeNode(void 0,Ke({method:s.createTypeReferenceNode(o.name),path:s.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:ft(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),sr())),u=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(s.createIdentifier("key"),s.createTemplateTail(""))]),g=nr("ExpressZodAPIClient",tr([He("implementation",s.createTypeReferenceNode(p.name),er)]),[or("provide",s.createTypeReferenceNode(c.name),dr(["method","path","params"],[s.createIdentifier("method"),ht("params",s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("acc"),"replace"),void 0,[u,s.createElementAccessExpression(s.createIdentifier("params"),s.createIdentifier("key"))]),s.createIdentifier("path")),ht("params",s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("path"),"indexOf"),void 0,[u]),z.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())]))]);z.addSyntheticLeadingComment(g,z.SyntaxKind.MultiLineCommentTrivia,`
|
|
34
34
|
export const exampleImplementation: Implementation = async (
|
|
35
35
|
method,
|
|
36
36
|
path,
|
|
@@ -52,7 +52,7 @@ export const exampleImplementation: Implementation = async (
|
|
|
52
52
|
|
|
53
53
|
const client = new ExpressZodAPIClient(exampleImplementation);
|
|
54
54
|
client.provide("get", "/v1/user/retrieve", { id: "10" });
|
|
55
|
-
`,!0),this.agg.push(t,o,n,a,
|
|
55
|
+
`,!0),this.agg.push(t,o,n,a,d,l,c,p,g)}print(r){return this.agg.map(t=>pr(t,r)).join(`
|
|
56
56
|
|
|
57
|
-
`)}};import{INVALID as
|
|
57
|
+
`)}};import{INVALID as mr,ZodIssueCode as ur,ZodParsedType as fr,ZodType as hn,addIssueToContext as yr}from"zod";var Tn="ZodDateOut",Pt=class extends hn{_parse(r){let{status:t,ctx:o}=this._processInputParams(r);return o.parsedType!==fr.date?(yr(o,{code:ur.invalid_type,expected:fr.date,received:o.parsedType}),mr):Pe(o.data)?{status:t.value,value:o.data.toISOString()}:(yr(o,{code:ur.invalid_date}),mr)}},fe=Pt;fe.create=()=>new Pt({typeName:Tn});import{INVALID as Sn,ZodIssueCode as gr,ZodParsedType as xr,ZodType as On,addIssueToContext as hr}from"zod";var bn="ZodFile",Pn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ge=class extends On{constructor(){super(...arguments);this.binary=t=>new ge({...this._def,checks:[...this._def.checks,{kind:"binary",...We(t)}]});this.base64=t=>new ge({...this._def,checks:[...this._def.checks,{kind:"base64",...We(t)}]})}_parse(t){let{status:o,ctx:n}=this._processInputParams(t);if(n.parsedType!==xr.string)return hr(n,{code:gr.invalid_type,expected:xr.string,received:n.parsedType}),Sn;for(let i of this._def.checks)i.kind==="base64"&&(Pn.test(n.data)||(hr(n,{code:gr.custom,message:i.message}),o.dirty()));return{status:o.value,value:n.data}}get isBinary(){return!!this._def.checks.find(t=>t.kind==="binary")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}},ye=ge;ye.create=()=>new ge({checks:[],typeName:bn});var Et;(n=>(n.file=ye.create,n.upload=L.create,n.dateIn=le.create,n.dateOut=fe.create))(Et||(Et={}));import Ua from"http-errors";export{W as AbstractEndpoint,bt as Client,pe as DependsOnMethod,ae as DependsOnMethodError,de as EndpointsFactory,C as InputValidationError,lt as OpenAPI,b as OpenAPIError,U as OutputValidationError,G as RoutingError,ce as ServeStatic,to as attachRouting,br as createConfig,Ua as createHttpError,Le as createLogger,Xe as createMiddleware,Ct as createResultHandler,ro as createServer,kr as defaultEndpointsFactory,J as defaultResultHandler,Et as ez,k as getMessageFromError,Ye as getStatusCodeFromError,Go as testEndpoint,$ as withMeta};
|
|
58
58
|
//# sourceMappingURL=index.js.map
|