express-zod-api 29.0.0-beta.3 → 29.0.0-beta.5
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 +13 -2
- package/dist/{documentation-helpers-BLgXFiWr.d.ts → documentation-helpers-CwgXjxwT.d.ts} +1 -1
- package/dist/documentation.d.ts +2 -2
- package/dist/documentation.js +1 -1
- package/dist/index.d.ts +29 -50
- package/dist/index.js +4 -4
- package/dist/integration.d.ts +1 -1
- package/dist/integration.js +11 -3
- package/dist/{json-schema-helpers-Bhz0qPT7.js → json-schema-helpers-C1xkaMOk.js} +1 -1
- package/dist/{peer-helpers-eiBZCqrL.js → peer-helpers-BFaGRU7x.js} +1 -1
- package/dist/{routing-walker--qYUjhGi.js → routing-walker-Uax31V_v.js} +1 -1
- package/dist/{routing-C0jFxoT6.d.ts → routing-xQnwfH2D.d.ts} +29 -32
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,15 @@
|
|
|
5
5
|
### v29.0.0
|
|
6
6
|
|
|
7
7
|
- Supported Node.js versions: `^22.19.0 || ^24.11.0 || ^26.0.0`;
|
|
8
|
+
- Major changes to the package distribution:
|
|
9
|
+
- `Documentation` and `Depicter` type moved to the `express-zod-api/documentation` subpath;
|
|
10
|
+
- `Integration` and `Producer` type moved to the `express-zod-api/integration` subpath;
|
|
11
|
+
- Several types and interfaces are no longer exposed:
|
|
12
|
+
- `CommonConfig`, `AppConfig`, `ServerConfig` — use `createConfig()` instead;
|
|
13
|
+
- `ApiResponse` — use `createApiResponse()` instead (new);
|
|
14
|
+
- `CacheControl` and `CachePolicy` — use `createCacheMiddleware()` or `EndpointsFactory::useCacheMiddleware()`;
|
|
15
|
+
- `FlatObject`, `IOSchema` and every type ending with `Security`;
|
|
16
|
+
- The public nature of these types was a workaround for user-side type declarations, but it's solved differently.
|
|
8
17
|
- Breaking change to the `cors` config option:
|
|
9
18
|
- Changed from `boolean | HeadersProvider` to `boolean | RequestHandler`;
|
|
10
19
|
- You can now use the well-known `cors` package or pass a conventional `RequestHandler` directly.
|
|
@@ -23,12 +32,10 @@
|
|
|
23
32
|
- Default input sources for QUERY: `["query", "body", "params"]` (from the lowest priority to highest);
|
|
24
33
|
- Supported by `Integration` and `Documentation` generators.
|
|
25
34
|
- Changes to `Documentation`:
|
|
26
|
-
- Moved to the dedicated subpath `express-zod-api/documentation` along with `Depicter` type;
|
|
27
35
|
- `serverUrl` constructor option renamed to `server` and now also accepts OpenAPI's ServerObject;
|
|
28
36
|
- `title` option and `version` must be wrapped into `info`, assignable with OpenAPI's InfoObject;
|
|
29
37
|
- Now produces OpenAPI 3.2.0 with better SSE support and other features.
|
|
30
38
|
- Changes to `Integration`:
|
|
31
|
-
- Moved to the dedicated subpath `express-zod-api/integration` along with `Producer` type;
|
|
32
39
|
- The static async method `create()` removed — use `new Integration()` instead;
|
|
33
40
|
- Removed `typescript` option from constructor — now imported statically.
|
|
34
41
|
- Consider using [the automated migration](https://www.npmjs.com/package/@express-zod-api/migration).
|
|
@@ -58,6 +65,10 @@
|
|
|
58
65
|
|
|
59
66
|
## Version 28
|
|
60
67
|
|
|
68
|
+
### v28.7.6
|
|
69
|
+
|
|
70
|
+
- Added well-known header, recognized by Documentation generator: `want-unencoded-digest`.
|
|
71
|
+
|
|
61
72
|
### v28.7.5
|
|
62
73
|
|
|
63
74
|
- Small performance improvement for startup and Documentation generator (cache for request type resolution).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as ClientMethod, f as Tag } from "./routing-xQnwfH2D.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { ReferenceObject, SchemaObjectValue, TagObject } from "openapi3-ts/oas32";
|
|
4
4
|
interface ReqResCommons {
|
package/dist/documentation.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as ResponseVariant, g as CommonConfig, t as Routing } from "./routing-xQnwfH2D.js";
|
|
2
2
|
import {
|
|
3
3
|
a as depictTags,
|
|
4
4
|
n as Depicter,
|
|
5
5
|
o as trimSummary,
|
|
6
6
|
r as IsHeader,
|
|
7
7
|
t as BrandHandling,
|
|
8
|
-
} from "./documentation-helpers-
|
|
8
|
+
} from "./documentation-helpers-CwgXjxwT.js";
|
|
9
9
|
import { InfoObject, OpenApiBuilder, ServerObject } from "openapi3-ts/oas32";
|
|
10
10
|
type Component = `${ResponseVariant}Response` | "requestParameter" | "requestBody";
|
|
11
11
|
/** @desc user defined function that creates a component description from its properties */
|
package/dist/documentation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as e,D as t,G as n,H as r,J as i,K as a,M as o,P as s,R as c,V as l,W as u,Z as d,_ as f,a as p,b as m,h,j as g,k as _,n as v,q as y,t as b}from"./routing-walker--qYUjhGi.js";import{t as x}from"./json-schema-helpers-Bhz0qPT7.js";import{z as S}from"zod";import*as C from"ramda";import{OpenApiBuilder as w,isReferenceObject as T,isSchemaObject as E}from"openapi3-ts/oas32";const D=e=>r(e)&&`or`in e,O=e=>r(e)&&`and`in e,k=e=>!O(e)&&!D(e),A=e=>{let t=C.filter(k,e),n=C.chain(C.prop(`and`),C.filter(O,e)),[r,i]=C.partition(k,n),a=C.concat(t,r),o=C.filter(D,e);return C.map(C.prop(`or`),C.concat(o,i)).reduce((e,t)=>s(e,C.map(e=>k(e)?[e]:e.and,t),([e,t])=>C.concat(e,t)),C.reject(C.isEmpty,[a]))},j=(e,t)=>O(e)?C.chain(e=>j(e,t),e.and):D(e)?C.chain(e=>j(e,t),e.or):e.type===t?[e.name]:[],M=(e,t)=>new Set(C.chain(e=>j(e,t),e));let N;const P=()=>N??=new Set(`a-im.accept.accept-additions.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.amp-cache-transform.apply-to-redirect-ref.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cdn-loop.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.dictionary-id.differential-id.digest.dpop.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.incremental.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.want-unencoded-digest.warning.x-content-type-options.x-frame-options`.split(`.`)),ee={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},te=e=>e.replace(a,e=>`{${e.slice(1)}}`),ne=({},e)=>{if(e.isResponse)throw new m(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},re=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),ie=({zodSchema:e,jsonSchema:t})=>{if(!u(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},F=C.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return x(e,`throw`)},(e,{jsonSchema:t})=>t),I=({jsonSchema:e})=>{if(!e.anyOf||!e.anyOf.length)return e;let t=e.anyOf[0];return Object.assign(t,{type:U(t.type)})},L=e=>e,R=({jsonSchema:e},t)=>{if(t.isResponse)throw new m(`Please use ez.dateOut() for output.`,t);return e},z=({jsonSchema:e},t)=>{if(!t.isResponse)throw new m(`Please use ez.dateIn() for input.`,t);return e},B=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),V=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,H=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return ee?.[t]},U=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],W=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!u(r,`transform`))return t;let a=L(X(i,{ctx:n}));if(E(a))if(n.isResponse){let e=l(r,H(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},G=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!r(t.properties.raw)?e:t.properties.raw},K=e=>e.length?C.fromPairs(C.zip(C.times(e=>`example${e+1}`,e.length),C.map(C.objOf(`dataValue`),e))):void 0,q=(e,t)=>t?.has(e)||e.startsWith(`x-`)||P().has(e),J=({path:t,method:i,request:a,inputSources:o,makeRef:s,composition:c,isHeader:l,securityHeaders:u,securityCookies:d,description:f=`${i.toUpperCase()} ${t} Parameter`})=>{let p=x(a),m=e(t),h=o.includes(`query`),g=o.includes(`params`),_=o.includes(`headers`),v=o.includes(`cookies`)||o.includes(`signedCookies`),y=e=>{if(g&&m.includes(e))return`path`;if(v&&d?.has(e))return`cookie`;if(_&&(l?.(e,i,t)??q(e,u)))return`header`;if(h&&i!==`query`)return`query`};return Object.entries(p.properties).reduce((e,[t,i])=>{if(!r(i))return e;let a=y(t);if(!a)return e;let o=L(i),l=c===`components`?s(i.id||JSON.stringify(i),o,i.id||n(f,t)):o;return e.concat({name:t,in:a,deprecated:i.deprecated,required:p.required?.includes(t)||!1,description:o.description||f,schema:l,examples:K(E(o)&&o.examples?.length?o.examples:C.pluck(t,p.examples?.filter(C.both(r,C.has(t)))||[]))})},[])},Y={nullable:I,union:ie,bigint:B,intersection:F,tuple:V,pipe:W,[_]:R,[t]:z,[f]:ne,[h]:G,[g]:re},ae=(e,t,n)=>{let r=[e,t],i=e=>/schema\d+$/.test(e)?void 0:e;for(let e=0;e<r.length;e++){let a=r[e];if(C.is(Object,a)){if(T(a)&&!a.$ref.startsWith(`#/components`)){let e=a.$ref.split(`/`).pop(),r=t[e];r&&(a.$ref=n.makeRef(r.id||r,L(r),r.id||i(e)).$ref);continue}r.push(...C.values(a))}C.is(Array,a)&&r.push(...C.values(a))}return e},X=(e,{ctx:t,rules:n=Y})=>{let{$defs:i={},properties:a={}}=S.toJSONSchema(S.object({subject:e}),{unrepresentable:`any`,io:t.isResponse?`output`:`input`,override:e=>{let r=o(e.zodSchema),i=n[r&&r in n?r:e.zodSchema._zod.def.type];if(i){let n={...i(e,t)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,n)}}});return ae(r(a.subject)?a.subject:{},i,t)},Z=(e,t)=>{if(T(e))return[e,!1];let n=!1,r=C.map(e=>{let[r,i]=Z(e,t);return n||=i,r}),i=C.omit(t),a={properties:i,examples:C.map(i),required:C.without(t),allOf:r,oneOf:r,anyOf:r},o=C.evolve(a,e);return[o,n||!!o.required?.length]},oe=({method:e,path:t,schema:r,mimeTypes:a,variant:o,makeRef:s,composition:c,hasMultipleStatusCodes:l,statusCode:u,brandHandling:f,description:p=`${e.toUpperCase()} ${t} ${i(o)} response ${l?u:``}`.trim()})=>{if(!y(e,a))return{description:p};let m=L(X(r,{rules:{...f,...Y},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];E(m)&&m.examples&&(h.push(...m.examples),delete m.examples);let g=c===`components`?s(r,m,n(p)):m;return{description:p,content:C.fromPairs(a.map(e=>[e,{[e===d.sse?`itemSchema`:`schema`]:g,examples:K(h)}]))}},se=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},ce=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},le=({name:e})=>({type:`apiKey`,in:`header`,name:e}),ue=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),de=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),fe=({flows:e={},oauth2MetadataUrl:t})=>({type:`oauth2`,flows:C.map(e=>({...e,scopes:e.scopes||{}}),C.reject(C.isNil,e)),oauth2MetadataUrl:t}),pe=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?se(e):e.type===`input`?ce(e,t):e.type===`header`?le(e):e.type===`cookie`?ue(e):e.type===`openid`?de(e):fe(e);return e.map(e=>e.map(({deprecated:e,...t})=>({...n(t),deprecated:e})))},me=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Q=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>X(e,{rules:{...t,...Y},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),he=({method:e,path:t,schema:i,request:a,mimeType:o,makeRef:s,composition:c,paramNames:l,description:u=`${e.toUpperCase()} ${t} Request body`})=>{let[f,p]=Z(a,l),m=L(f),h=[];E(m)&&m.examples&&(h.push(...m.examples),delete m.examples);let g={schema:c===`components`?s(i,m,n(u)):m,examples:K(h.length?h:x(a).examples?.filter(e=>r(e)&&!Array.isArray(e)).map(C.omit(l))||[])},_={description:u,content:{[o]:g}};return(p||o===d.raw)&&(_.required=!0),_},ge=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;if(typeof n==`string`)return e.concat({name:t,description:n});let{url:r,...i}=n,a={...i,name:t};return r&&(a.externalDocs={...a.externalDocs,url:r}),e.concat(a)},[]),_e=(e,t=50)=>!e||e.length<=t?e:e.slice(0,Math.max(1,t||0)-1)+`…`,$=e=>e.length?e.slice():void 0,ve=({description:e,summary:t=e,trim:n})=>n(t);var ye=class extends w{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=+!n;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,r){let i=r||n(t,e),a=this.#t.get(i);if(a===void 0)return this.#t.set(i,1),i;if(r)throw new m(`Duplicated operationId: "${r}"`,{method:t,isResponse:!1,path:e});return a++,this.#t.set(i,a),`${i}${a}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}#o({tags:e,server:t,info:n={title:`Generated by Express Zod API`,version:`0.0.0`}}){if(this.addInfo(n),e&&(this.rootDoc.tags=ge(e)),t)for(let e of Array.isArray(t)?t:[t])this.addServer(typeof e==`string`?{url:e}:e)}#s({config:e,descriptions:t,brandHandling:n,isHeader:r,summarizer:i=ve,composition:a=`inline`}){return(o,s,l)=>{let u={path:s,method:o,endpoint:l,composition:a,brandHandling:n,makeRef:this.#r.bind(this)},{description:f,summary:m,scopes:h,inputSchema:g}=l,_=c(o,e.inputSources),v=this.#i(s,o,l.getOperationId(o)),y=Q({...u,schema:g}),b=J({...u,inputSources:_,isHeader:r,securityHeaders:M(l.security,`header`),securityCookies:M(l.security,`cookie`),request:y,description:t?.requestParameter?.({method:o,path:s,operationId:v})}),x={};for(let e of p){let n=l.getResponses(e);for(let{mimeTypes:r,schema:i,statusCodes:a}of n)for(let c of a)x[c]=oe({...u,variant:e,schema:i,mimeTypes:r,statusCode:c,hasMultipleStatusCodes:n.length>1||a.length>1,description:t?.[`${e}Response`]?.({method:o,path:s,operationId:v,statusCode:c})})}let S=_.includes(`body`)?he({...u,request:y,paramNames:C.pluck(`name`,b),schema:g,mimeType:d[l.getProbableRequestType(o)],description:t?.requestBody?.({method:o,path:s,operationId:v})}):void 0,w=me(pe(A(l.security),_),h,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),T={operationId:v,summary:i({summary:m,description:f,trim:_e}),description:f,deprecated:l.isDeprecated||void 0,tags:$(l.tags),parameters:$(b),requestBody:S,security:$(w),responses:x};this.addPath(te(s),{[o]:T})}}constructor({hasHeadMethod:e=!0,...t}){super(),this.#o(t);let n=this.#s(t),r=e?v(n):n;b({...t,onEndpoint:r})}};export{ye as Documentation};
|
|
1
|
+
import{A as e,F as t,G as n,H as r,J as i,K as a,M as o,N as s,O as c,Q as l,U as u,V as d,Y as f,g as p,n as m,o as h,q as g,t as _,v,x as y,z as b}from"./routing-walker-Uax31V_v.js";import{t as x}from"./json-schema-helpers-C1xkaMOk.js";import{z as S}from"zod";import*as C from"ramda";import{OpenApiBuilder as w,isReferenceObject as T,isSchemaObject as E}from"openapi3-ts/oas32";const D=e=>u(e)&&`or`in e,O=e=>u(e)&&`and`in e,k=e=>!O(e)&&!D(e),A=e=>{let n=C.filter(k,e),r=C.chain(C.prop(`and`),C.filter(O,e)),[i,a]=C.partition(k,r),o=C.concat(n,i),s=C.filter(D,e);return C.map(C.prop(`or`),C.concat(s,a)).reduce((e,n)=>t(e,C.map(e=>k(e)?[e]:e.and,n),([e,t])=>C.concat(e,t)),C.reject(C.isEmpty,[o]))},j=(e,t)=>O(e)?C.chain(e=>j(e,t),e.and):D(e)?C.chain(e=>j(e,t),e.or):e.type===t?[e.name]:[],M=(e,t)=>new Set(C.chain(e=>j(e,t),e));let ee;const te=()=>ee??=new Set(`a-im.accept.accept-additions.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.amp-cache-transform.apply-to-redirect-ref.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cdn-loop.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.dictionary-id.differential-id.digest.dpop.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.incremental.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.want-unencoded-digest.warning.x-content-type-options.x-frame-options`.split(`.`)),ne={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},re=e=>e.replace(g,e=>`{${e.slice(1)}}`),ie=({},e)=>{if(e.isResponse)throw new y(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},N=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),P=({zodSchema:e,jsonSchema:t})=>{if(!n(e,`union`)||!(`discriminator`in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},F=C.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return x(e,`throw`)},(e,{jsonSchema:t})=>t),I=({jsonSchema:e})=>{if(!e.anyOf||!e.anyOf.length)return e;let t=e.anyOf[0];return Object.assign(t,{type:U(t.type)})},L=e=>e,R=({jsonSchema:e},t)=>{if(t.isResponse)throw new y(`Please use ez.dateOut() for output.`,t);return e},z=({jsonSchema:e},t)=>{if(!t.isResponse)throw new y(`Please use ez.dateIn() for input.`,t);return e},B=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),V=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,H=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return ne?.[t]},U=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],W=({zodSchema:e,jsonSchema:t},i)=>{let a=e._zod.def[i.isResponse?`out`:`in`],o=e._zod.def[i.isResponse?`in`:`out`];if(!n(a,`transform`))return t;let s=L(X(o,{ctx:i}));if(E(s))if(i.isResponse){let e=r(a,H(s));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=s;return{...t,format:`${t.format||e} (preprocessed)`}}return t},G=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!u(t.properties.raw)?e:t.properties.raw},K=e=>e.length?C.fromPairs(C.zip(C.times(e=>`example${e+1}`,e.length),C.map(C.objOf(`dataValue`),e))):void 0,q=(e,t)=>t?.has(e)||e.startsWith(`x-`)||te().has(e),J=({path:e,method:t,request:n,inputSources:r,makeRef:i,composition:o,isHeader:s,securityHeaders:c,securityCookies:l,description:f=`${t.toUpperCase()} ${e} Parameter`})=>{let p=x(n),m=d(e),h=r.includes(`query`),g=r.includes(`params`),_=r.includes(`headers`),v=r.includes(`cookies`)||r.includes(`signedCookies`),y=n=>{if(g&&m.includes(n))return`path`;if(v&&l?.has(n))return`cookie`;if(_&&(s?.(n,t,e)??q(n,c)))return`header`;if(h&&t!==`query`)return`query`};return Object.entries(p.properties).reduce((e,[t,n])=>{if(!u(n))return e;let r=y(t);if(!r)return e;let s=L(n),c=o===`components`?i(n.id||JSON.stringify(n),s,n.id||a(f,t)):s;return e.concat({name:t,in:r,deprecated:n.deprecated,required:p.required?.includes(t)||!1,description:s.description||f,schema:c,examples:K(E(s)&&s.examples?.length?s.examples:C.pluck(t,p.examples?.filter(C.both(u,C.has(t)))||[]))})},[])},Y={nullable:I,union:P,bigint:B,intersection:F,tuple:V,pipe:W,[e]:R,[c]:z,[v]:ie,[p]:G,[o]:N},ae=(e,t,n)=>{let r=[e,t],i=e=>/schema\d+$/.test(e)?void 0:e;for(let e=0;e<r.length;e++){let a=r[e];if(C.is(Object,a)){if(T(a)&&!a.$ref.startsWith(`#/components`)){let e=a.$ref.split(`/`).pop(),r=t[e];r&&(a.$ref=n.makeRef(r.id||r,L(r),r.id||i(e)).$ref);continue}r.push(...C.values(a))}C.is(Array,a)&&r.push(...C.values(a))}return e},X=(e,{ctx:t,rules:n=Y})=>{let{$defs:r={},properties:i={}}=S.toJSONSchema(S.object({subject:e}),{unrepresentable:`any`,io:t.isResponse?`output`:`input`,override:e=>{let r=s(e.zodSchema),i=n[r&&r in n?r:e.zodSchema._zod.def.type];if(i){let n={...i(e,t)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,n)}}});return ae(u(i.subject)?i.subject:{},r,t)},Z=(e,t)=>{if(T(e))return[e,!1];let n=!1,r=C.map(e=>{let[r,i]=Z(e,t);return n||=i,r}),i=C.omit(t),a={properties:i,examples:C.map(i),required:C.without(t),allOf:r,oneOf:r,anyOf:r},o=C.evolve(a,e);return[o,n||!!o.required?.length]},oe=({method:e,path:t,schema:n,mimeTypes:r,variant:o,makeRef:s,composition:c,hasMultipleStatusCodes:u,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${f(o)} response ${u?d:``}`.trim()})=>{if(!i(e,r))return{description:m};let h=L(X(n,{rules:{...p,...Y},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),g=[];E(h)&&h.examples&&(g.push(...h.examples),delete h.examples);let _=c===`components`?s(n,h,a(m)):h;return{description:m,content:C.fromPairs(r.map(e=>[e,{[e===l.sse?`itemSchema`:`schema`]:_,examples:K(g)}]))}},se=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},ce=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},le=({name:e})=>({type:`apiKey`,in:`header`,name:e}),ue=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),de=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),fe=({flows:e={},oauth2MetadataUrl:t})=>({type:`oauth2`,flows:C.map(e=>({...e,scopes:e.scopes||{}}),C.reject(C.isNil,e)),oauth2MetadataUrl:t}),pe=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?se(e):e.type===`input`?ce(e,t):e.type===`header`?le(e):e.type===`cookie`?ue(e):e.type===`openid`?de(e):fe(e);return e.map(e=>e.map(({deprecated:e,...t})=>({...n(t),deprecated:e})))},me=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Q=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>X(e,{rules:{...t,...Y},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),he=({method:e,path:t,schema:n,request:r,mimeType:i,makeRef:o,composition:s,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[f,p]=Z(r,c),m=L(f),h=[];E(m)&&m.examples&&(h.push(...m.examples),delete m.examples);let g={schema:s===`components`?o(n,m,a(d)):m,examples:K(h.length?h:x(r).examples?.filter(e=>u(e)&&!Array.isArray(e)).map(C.omit(c))||[])},_={description:d,content:{[i]:g}};return(p||i===l.raw)&&(_.required=!0),_},ge=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;if(typeof n==`string`)return e.concat({name:t,description:n});let{url:r,...i}=n,a={...i,name:t};return r&&(a.externalDocs={...a.externalDocs,url:r}),e.concat(a)},[]),_e=(e,t=50)=>!e||e.length<=t?e:e.slice(0,Math.max(1,t||0)-1)+`…`,$=e=>e.length?e.slice():void 0,ve=({description:e,summary:t=e,trim:n})=>n(t);var ye=class extends w{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=+!n;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||a(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new y(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}#o({tags:e,server:t,info:n={title:`Generated by Express Zod API`,version:`0.0.0`}}){if(this.addInfo(n),e&&(this.rootDoc.tags=ge(e)),t)for(let e of Array.isArray(t)?t:[t])this.addServer(typeof e==`string`?{url:e}:e)}#s({config:e,descriptions:t,brandHandling:n,isHeader:r,summarizer:i=ve,composition:a=`inline`}){return(o,s,c)=>{let u={path:s,method:o,endpoint:c,composition:a,brandHandling:n,makeRef:this.#r.bind(this)},{description:d,summary:f,scopes:p,inputSchema:m}=c,g=b(o,e.inputSources),_=this.#i(s,o,c.getOperationId(o)),v=Q({...u,schema:m}),y=J({...u,inputSources:g,isHeader:r,securityHeaders:M(c.security,`header`),securityCookies:M(c.security,`cookie`),request:v,description:t?.requestParameter?.({method:o,path:s,operationId:_})}),x={};for(let e of h){let n=c.getResponses(e);for(let{mimeTypes:r,schema:i,statusCodes:a}of n)for(let c of a)x[c]=oe({...u,variant:e,schema:i,mimeTypes:r,statusCode:c,hasMultipleStatusCodes:n.length>1||a.length>1,description:t?.[`${e}Response`]?.({method:o,path:s,operationId:_,statusCode:c})})}let S=g.includes(`body`)?he({...u,request:v,paramNames:C.pluck(`name`,y),schema:m,mimeType:l[c.getProbableRequestType(o)],description:t?.requestBody?.({method:o,path:s,operationId:_})}):void 0,w=me(pe(A(c.security),g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),T={operationId:_,summary:i({summary:f,description:d,trim:_e}),description:d,deprecated:c.isDeprecated||void 0,tags:$(c.tags),parameters:$(y),requestBody:S,security:$(w),responses:x};this.addPath(re(s),{[o]:T})}}constructor({hasHeadMethod:e=!0,...t}){super(),this.#o(t);let n=this.#s(t),r=e?m(n):n;_({...t,onEndpoint:r})}};export{ye as Documentation};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,45 +1,38 @@
|
|
|
1
1
|
import {
|
|
2
|
-
A as
|
|
3
|
-
C as
|
|
4
|
-
D as
|
|
5
|
-
E as
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
O as arrayResultHandler,
|
|
12
|
-
P as ClientMethod,
|
|
13
|
-
R as LoggerOverrides,
|
|
14
|
-
S as AppConfig,
|
|
15
|
-
T as createConfig,
|
|
16
|
-
_ as EmptySchema,
|
|
2
|
+
A as AbstractLogger,
|
|
3
|
+
C as ensureHttpError,
|
|
4
|
+
D as ClientMethod,
|
|
5
|
+
E as IOSchema,
|
|
6
|
+
N as createApiResponse,
|
|
7
|
+
O as Method,
|
|
8
|
+
S as defaultResultHandler,
|
|
9
|
+
T as FinalInputSchema,
|
|
10
|
+
_ as ServerConfig,
|
|
17
11
|
a as Handler,
|
|
18
|
-
b as
|
|
12
|
+
b as ResultHandler,
|
|
19
13
|
c as Middleware,
|
|
20
|
-
d as
|
|
21
|
-
f as
|
|
22
|
-
g as
|
|
23
|
-
h as
|
|
14
|
+
d as FlatObject,
|
|
15
|
+
f as Tag,
|
|
16
|
+
g as CommonConfig,
|
|
17
|
+
h as AppConfig,
|
|
24
18
|
i as Endpoint,
|
|
25
|
-
j as
|
|
26
|
-
k as
|
|
27
|
-
l as
|
|
28
|
-
m as
|
|
19
|
+
j as LoggerOverrides,
|
|
20
|
+
k as BuiltinLogger,
|
|
21
|
+
l as EmptyObject,
|
|
22
|
+
m as getMessageFromError,
|
|
29
23
|
n as ServeStatic,
|
|
30
24
|
o as AbstractMiddleware,
|
|
31
|
-
p as
|
|
25
|
+
p as TagOverrides,
|
|
32
26
|
r as AbstractEndpoint,
|
|
33
27
|
s as ExpressMiddleware,
|
|
34
28
|
t as Routing,
|
|
35
|
-
u as
|
|
36
|
-
v as
|
|
37
|
-
w as
|
|
38
|
-
x as
|
|
39
|
-
y as
|
|
40
|
-
|
|
41
|
-
} from "./
|
|
42
|
-
import { i as OpenAPIContext } from "./documentation-helpers-BLgXFiWr.js";
|
|
29
|
+
u as EmptySchema,
|
|
30
|
+
v as createConfig,
|
|
31
|
+
w as Extension,
|
|
32
|
+
x as arrayResultHandler,
|
|
33
|
+
y as AbstractResultHandler,
|
|
34
|
+
} from "./routing-xQnwfH2D.js";
|
|
35
|
+
import { i as OpenAPIContext } from "./documentation-helpers-CwgXjxwT.js";
|
|
43
36
|
import { z } from "zod";
|
|
44
37
|
import express, { CookieOptions, Request, Response } from "express";
|
|
45
38
|
import http from "node:http";
|
|
@@ -553,7 +546,7 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
|
|
|
553
546
|
responseMock: import("node-mocks-http").MockResponse<Response<any, Record<string, any>>>;
|
|
554
547
|
loggerMock: AbstractLogger &
|
|
555
548
|
LOG & {
|
|
556
|
-
_getLogs: () => Record<"
|
|
549
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
557
550
|
};
|
|
558
551
|
}>;
|
|
559
552
|
interface MiddlewareLike<RET extends FlatObject> {
|
|
@@ -583,7 +576,7 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
583
576
|
responseMock: import("node-mocks-http").MockResponse<Response<any, Record<string, any>>>;
|
|
584
577
|
loggerMock: AbstractLogger &
|
|
585
578
|
LOG & {
|
|
586
|
-
_getLogs: () => Record<"
|
|
579
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
587
580
|
};
|
|
588
581
|
}>;
|
|
589
582
|
type EventsMap = Record<string, z.ZodType>;
|
|
@@ -770,39 +763,25 @@ declare const ez: {
|
|
|
770
763
|
paginated: typeof paginated;
|
|
771
764
|
};
|
|
772
765
|
export {
|
|
773
|
-
type ApiResponse,
|
|
774
|
-
type AppConfig,
|
|
775
|
-
type BasicSecurity,
|
|
776
|
-
type BearerSecurity,
|
|
777
766
|
BuiltinLogger,
|
|
778
|
-
type CacheControl,
|
|
779
|
-
type CachePolicy,
|
|
780
|
-
type CommonConfig,
|
|
781
|
-
type CookieSecurity,
|
|
782
767
|
DocumentationError,
|
|
783
768
|
EndpointsFactory,
|
|
784
769
|
EventStreamFactory,
|
|
785
|
-
type FlatObject,
|
|
786
|
-
type HeaderSecurity,
|
|
787
|
-
type IOSchema,
|
|
788
|
-
type InputSecurity,
|
|
789
770
|
InputValidationError,
|
|
790
771
|
type LoggerOverrides,
|
|
791
772
|
type Method,
|
|
792
773
|
Middleware,
|
|
793
774
|
MissingPeerError,
|
|
794
|
-
type OAuth2Security,
|
|
795
|
-
type OpenIdSecurity,
|
|
796
775
|
OutputValidationError,
|
|
797
776
|
ResultHandler,
|
|
798
777
|
type Routing,
|
|
799
778
|
RoutingError,
|
|
800
779
|
ServeStatic,
|
|
801
|
-
type ServerConfig,
|
|
802
780
|
type TagOverrides,
|
|
803
781
|
arrayEndpointsFactory,
|
|
804
782
|
arrayResultHandler,
|
|
805
783
|
attachRouting,
|
|
784
|
+
createApiResponse,
|
|
806
785
|
createCacheMiddleware,
|
|
807
786
|
createConfig,
|
|
808
787
|
createCookieMiddleware,
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{A as e,B as t,C as n,E as r,F as i,H as a,I as o,L as s,N as c,O as l,S as u,T as d,U as f,X as p,Z as m,a as ee,b as te,c as h,d as g,f as _,g as ne,i as v,l as y,o as re,p as b,r as ie,s as x,t as ae,u as S,v as oe,w as C,x as se,y as ce,z as le}from"./routing-walker--qYUjhGi.js";import{t as w}from"./peer-helpers-eiBZCqrL.js";import{t as ue}from"./json-schema-helpers-Bhz0qPT7.js";import{globalRegistry as T,z as E}from"zod";import*as de from"ramda";import D,{isHttpError as fe}from"http-errors";import pe,{blue as me,cyanBright as he,green as ge,hex as O,italic as _e,red as ve,whiteBright as k}from"ansis";import{inspect as ye}from"node:util";import{performance as A}from"node:perf_hooks";import j from"express";import be from"node:http";import xe from"node:https";import{setInterval as Se}from"node:timers/promises";import{createRequest as Ce,createResponse as we}from"node-mocks-http";function Te(e){return e}const Ee=(e,t)=>e&&t?e.and(t):e||t,De=(e,t)=>e?e.and(t):t;var Oe=class e{#e;constructor(e){this.#e=e}async execute(...t){try{return await this.#e(...t)}catch(n){let{response:r,logger:i,error:a}=t[0],s=new C(o(n),a||void 0);e.lastResort({response:r,logger:i,error:s})}}static lastResort({error:e,logger:t,response:n}){t.error(`Result handler failure`,e);let r=h(D(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:fe(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)}},M=class extends Oe{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return S(this.#e,{variant:`positive`,args:[e],statusCodes:[v.positive],mimeTypes:[m.json]})}getNegativeResponse(){return S(this.#t,{variant:`negative`,args:[],statusCodes:[v.negative],mimeTypes:[m.json]})}};const N=E.object({status:E.literal(`error`),error:E.object({message:E.string()})});T.add(N,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const P=new M({positive:e=>{let t=E.object({status:E.literal(`success`),data:e}),n=c(e);return n.length&&T.add(t,{examples:n.map(e=>({status:`success`,data:e}))}),t},negative:N,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=x(e);y(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:h(n)}});return}i.status(v.positive).json({status:`success`,data:n})}}),F=E.string();T.add(F,{examples:[`Sample error message`]});const I=new M({positive:e=>{let t=e instanceof E.ZodObject&&`items`in e.shape&&e.shape.items instanceof E.ZodArray?e.shape.items:E.array(E.any());if(c(t).length)return t;let n=c(e).filter(e=>a(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(n?.length){let e=t.meta();T.remove(t).add(t,{...e,examples:n})}return t},negative:{schema:F,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=x(n);y(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(h(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(v.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}}),L=e=>{let t=[];return e.scope&&t.push(e.scope),e.noStore&&t.push(`no-store`),e.noCache&&t.push(`no-cache`),e.maxAge!==void 0&&t.push(`max-age=${e.maxAge}`),e.sMaxAge!==void 0&&t.push(`s-maxage=${e.sMaxAge}`),e.mustRevalidate&&t.push(`must-revalidate`),e.proxyRevalidate&&t.push(`proxy-revalidate`),e.mustUnderstand&&t.push(`must-understand`),e.immutable&&t.push(`immutable`),e.noTransform&&t.push(`no-transform`),e.staleWhileRevalidate!==void 0&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&t.push(`stale-if-error=${e.staleIfError}`),t.join(`, `)},ke={"max-age":`maxAge`,"max-stale":`maxStale`,"min-fresh":`minFresh`,"stale-if-error":`staleIfError`},Ae={"no-cache":`noCache`,"no-store":`noStore`,"no-transform":`noTransform`,"only-if-cached":`onlyIfCached`},je=e=>{if(!e)return;let t={};for(let n of e.toLowerCase().split(`,`)){let[e,r]=n.split(`=`),i=ke[e.trim()];if(i){let e=parseInt(r?.trim()??``,10);isNaN(e)||(t[i]=e);continue}let a=Ae[e.trim()];a&&(t[a]=!0)}return t},R=e=>new _({handler:async({request:t,response:n})=>(e&&n.setHeader(`Cache-Control`,L(e)),{get ifNoneMatch(){let e=t.headers[`if-none-match`];if(!e)return;let n=e.trim();return n===`*`?n:n.split(`,`).map(e=>e.trim().replace(/^(?:W\/)?"/,``).replace(/"$/,``))},get ifModifiedSince(){let e=t.headers[`if-modified-since`];if(!e)return;let n=new Date(e);return isNaN(n.getTime())?void 0:n},get cacheControl(){return je(t.headers[`cache-control`])},addCachePolicy:t=>{n.setHeader(`Cache-Control`,L({...e,...t}))},setETag:e=>{n.setHeader(`ETag`,e.startsWith(`"`)?e:`"${e}"`)},setLastModified:e=>{n.setHeader(`Last-Modified`,e.toUTCString())},setVary:(...e)=>{n.setHeader(`Vary`,e.join(`, `))},setExpires:e=>{n.setHeader(`Expires`,e.toUTCString())},clearSiteData:()=>{n.setHeader(`Clear-Site-Data`,`"cache"`)},notModified:()=>{n.status(304).end()}})}),z=e=>new _({handler:async({request:t,response:n})=>({getCookie:e=>t.signedCookies?.[e]??t.cookies?.[e],setCookie:(t,r,i)=>{n.cookie(t,r,{...e,...i})},clearCookie:(t,r)=>{n.clearCookie(t,{...e,...r})}})}),B=e=>{let t=w(`express-rate-limit`)({...e,handler:(e,t,n,r)=>{n(D(429,r.message))}}),{getKey:n,resetKey:r}=t,i={getKey:n,resetKey:r};return new g(t,{provider:t=>({rateLimit:{...i,...t[e?.requestPropertyName??`rateLimit`]}})})};var V=class e{resultHandler;schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=Ee(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof _?e:new _(e))}useCookies(...e){return this.#e(z(...e))}useCache(...e){return this.#e(R(...e))}useRateLimit(...e){return this.#e(B(...e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new g(...e))}addContext(e){return this.#e(new _({handler:({ctx:t})=>e(t)}))}build({input:e=i,output:t,operationId:n,scope:r,tag:a,method:o,...s}){let{middlewares:c,resultHandler:l}=this,u=typeof o==`string`?[o]:o,d=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,f=typeof r==`string`?[r]:r||[],p=typeof a==`string`?[a]:a||[];return new re({...s,middlewares:c,outputSchema:t,resultHandler:l,scopes:f,tags:p,methods:u,getOperationId:d,inputSchema:De(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:i,handler:async t=>(await e(t),{})})}};const Me=new V(P),Ne=new V(I),H={debug:me,info:ge,warn:O(`#FFA500`),error:ve,ctx:he},U={debug:10,info:20,warn:30,error:40},Pe=e=>a(e)&&Object.keys(U).some(t=>t in e),Fe=e=>e in U,Ie=(e,t)=>U[e]<U[t],W=de.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),Le=e=>e<1e-6?W(`nanosecond`,3).format(e/1e-6):e<.001?W(`nanosecond`).format(e/1e-6):e<1?W(`microsecond`).format(e/.001):e<1e3?W(`millisecond`).format(e):e<6e4?W(`second`,2).format(e/1e3):W(`minute`,2).format(e/6e4);var G=class e{config;constructor({color:e=pe.isSupported(),level:t=f()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return ye(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r!==`debug`||3})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||Ie(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?H.ctx(i):i),s.push(o?`${H[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=A.now();return()=>{let n=A.now()-t,{message:r,severity:i=`debug`,formatter:a=Le}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},Re=class{logger;#e=new WeakMap;constructor(e){this.logger=e}#t(e,t,n){if(!e.isSchemaChecked){for(let e of[`input`,`output`]){let r=[E.toJSONSchema(t[`${e}Schema`],{unrepresentable:`any`})];for(let t of r){t.type&&t.type!==`object`&&this.logger.warn(`Endpoint ${e} schema is not object-based`,n);for(let e of[`allOf`,`oneOf`,`anyOf`])t[e]&&r.push(...t[e])}}if(t.getProbableRequestType()===`json`){let e=b(t.inputSchema,`input`);e&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:e})}for(let e of ee)for(let{mimeTypes:r,schema:i}of t.getResponses(e)){if(!r?.includes(m.json))continue;let t=b(i,`output`);t&&this.logger.warn(`The final ${e} response schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:t})}e.isSchemaChecked=!0}}#n(e,n,r,i){if(e.paths.has(r))return;let a=t(r);if(a.length!==0){e.flat??=ue(E.toJSONSchema(n.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a)t in e.flat.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,{...i,path:r,param:t});e.paths.add(r)}}check=(e,t,n)=>{let r=this.#e.get(n);r||(r={isSchemaChecked:!1,paths:new Set},this.#e.set(n,r)),this.#t(r,n,{method:e,path:t}),this.#n(r,n,t,{method:e})}};const K=e=>e.sort((e,t)=>p(t)-+p(e)||e.localeCompare(t)).join(`, `).toUpperCase(),ze=e=>({method:t},n,r)=>{let i=K(e);n.set({Allow:i}),r(D(405,`${t} is not allowed`,{headers:{Allow:i}}))},Be=({app:e,getLogger:t,config:n,routing:r})=>{let i=f()?void 0:new Re(t()),a=new Map;return ae({routing:r,config:n,onEndpoint:(e,t,r)=>{i?.check(e,t,r),a.has(t)||a.set(t,new Map(n.cors?[[`options`,r]]:[])),a.get(t)?.set(e,r)},onStatic:e.use.bind(e)}),a},q=({app:e,config:t,getLogger:n,...r})=>{let i=Be({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,s]of o){let o=[];t.cors&&o.push((e,t,n)=>{t.set(`Access-Control-Allow-Methods`,K(i)),n()}),o.push(async(e,r)=>{let i=n(e);return s.execute({request:e,response:r,logger:i,config:t})}),e[a]?.(r,...o)}t.hintAllowedMethods!==!1&&a.set(r,ze(i))}for(let[t,n]of a)e.all(t,n)},Ve=e=>`_httpMessage`in e&&typeof e._httpMessage==`object`&&e._httpMessage!==null&&`headersSent`in e._httpMessage&&typeof e._httpMessage.headersSent==`boolean`&&`setHeader`in e._httpMessage&&typeof e._httpMessage.setHeader==`function`,He=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Ue=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,We=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Ge=e=>{let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.close(e=>e?r(e):n()),t},Ke=({timeout:e=1e3,logger:t}={})=>{let n,r=new Set,i=new Set,a=e=>void i.delete(e),o=e=>a(e.destroy()),s=e=>void(Ve(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):o(e)),c=e=>void(n?e.destroy():i.add(e.once(`close`,()=>a(e)).once(`error`,()=>o(e)))),l=async()=>{for(let e of r)e.on(`request`,We);t?.info(`Graceful shutdown`,{sockets:i.size,timeout:e});for(let e of i)(Ue(e)||He(e))&&s(e);for await(let t of Se(10,Date.now()))if(i.size===0||Date.now()-t>=e)break;for(let e of i)o(e);return Promise.allSettled(r.values().map(Ge))},u={sockets:i,add:(...e)=>{for(let t of e)if(!r.has(t)){r.add(t);for(let e of[`connection`,`secureConnection`])t.on(e,c)}return u},shutdown:()=>n??=l(),get isShuttingDown(){return!!n}};return u},J=Symbol.for(`express-zod-api`),qe=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:o(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):a(),Je=({errorHandler:e,getLogger:t})=>async(n,r)=>{let i=D(404,`Can not ${n.method} ${n.path}`),a=t(n);await e.execute({request:n,response:r,logger:a,error:i,input:null,output:null,ctx:{}})},Ye=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},Xe=({config:e})=>{let t=w(`cookie-parser`),{secret:n,...r}={...typeof e.cookies==`object`&&e.cookies};return t(n,Object.keys(r).length?r:void 0)},Y=e=>typeof e==`function`?e:({},e,t)=>{e.set({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Headers":`content-type`}),t()},Ze=e=>({log:t=>{/not eligible/i.test(t)||e.debug(t)}}),Qe=({getLogger:e,config:t})=>{let n=w(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:Ze(s)})(t,r,o)}),r&&o.push(Ye(r)),o},$e=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},et=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[J]={logger:o}),a()},tt=e=>t=>t?.res?.locals[J]?.logger||e;let nt=!1;const rt=e=>{nt||(nt=!0,process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
|
|
2
|
-
`).slice(1))))};let X,Z
|
|
1
|
+
import{B as e,C as t,D as n,E as r,I as i,L as a,P as o,Q as s,R as c,S as l,T as u,U as d,V as f,W as p,Z as ee,_ as te,a as m,b as ne,c as h,d as g,f as _,i as re,j as ie,k as ae,l as v,m as y,o as oe,p as b,r as se,s as ce,t as le,u as x,w as ue,x as de,y as fe}from"./routing-walker-Uax31V_v.js";import{t as S}from"./peer-helpers-BFaGRU7x.js";import{t as pe}from"./json-schema-helpers-C1xkaMOk.js";import{globalRegistry as C,z as w}from"zod";import*as me from"ramda";import T,{isHttpError as he}from"http-errors";import ge,{blue as _e,cyanBright as ve,green as ye,hex as E,italic as be,red as xe,whiteBright as D}from"ansis";import{inspect as Se}from"node:util";import{performance as O}from"node:perf_hooks";import k from"express";import Ce from"node:http";import we from"node:https";import{setInterval as Te}from"node:timers/promises";import{createRequest as Ee,createResponse as De}from"node-mocks-http";function Oe(e){return e}const ke=(e,t)=>e&&t?e.and(t):e||t,Ae=(e,t)=>e?e.and(t):t;var je=class e{#e;constructor(e){this.#e=e}async execute(...t){try{return await this.#e(...t)}catch(n){let{response:r,logger:i,error:o}=t[0],s=new u(a(n),o||void 0);e.lastResort({response:r,logger:i,error:s})}}static lastResort({error:e,logger:t,response:n}){t.error(`Result handler failure`,e);let r=v(T(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:he(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)}},A=class extends je{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return g(this.#e,{variant:`positive`,args:[e],statusCodes:[m.positive],mimeTypes:[s.json]})}getNegativeResponse(){return g(this.#t,{variant:`negative`,args:[],statusCodes:[m.negative],mimeTypes:[s.json]})}};const j=w.object({status:w.literal(`error`),error:w.object({message:w.string()})});C.add(j,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const M=new A({positive:e=>{let t=w.object({status:w.literal(`success`),data:e}),n=o(e);return n.length&&C.add(t,{examples:n.map(e=>({status:`success`,data:e}))}),t},negative:j,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=h(e);x(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:v(n)}});return}i.status(m.positive).json({status:`success`,data:n})}}),N=w.string();C.add(N,{examples:[`Sample error message`]});const P=new A({positive:e=>{let t=e instanceof w.ZodObject&&`items`in e.shape&&e.shape.items instanceof w.ZodArray?e.shape.items:w.array(w.any());if(o(t).length)return t;let n=o(e).filter(e=>d(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(n?.length){let e=t.meta();C.remove(t).add(t,{...e,examples:n})}return t},negative:{schema:N,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=h(n);x(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(v(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(m.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}}),F=e=>{let t=[];return e.scope&&t.push(e.scope),e.noStore&&t.push(`no-store`),e.noCache&&t.push(`no-cache`),e.maxAge!==void 0&&t.push(`max-age=${e.maxAge}`),e.sMaxAge!==void 0&&t.push(`s-maxage=${e.sMaxAge}`),e.mustRevalidate&&t.push(`must-revalidate`),e.proxyRevalidate&&t.push(`proxy-revalidate`),e.mustUnderstand&&t.push(`must-understand`),e.immutable&&t.push(`immutable`),e.noTransform&&t.push(`no-transform`),e.staleWhileRevalidate!==void 0&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&t.push(`stale-if-error=${e.staleIfError}`),t.join(`, `)},Me={"max-age":`maxAge`,"max-stale":`maxStale`,"min-fresh":`minFresh`,"stale-if-error":`staleIfError`},Ne={"no-cache":`noCache`,"no-store":`noStore`,"no-transform":`noTransform`,"only-if-cached":`onlyIfCached`},Pe=e=>{if(!e)return;let t={};for(let n of e.toLowerCase().split(`,`)){let[e,r]=n.split(`=`),i=Me[e.trim()];if(i){let e=parseInt(r?.trim()??``,10);isNaN(e)||(t[i]=e);continue}let a=Ne[e.trim()];a&&(t[a]=!0)}return t},I=e=>new b({handler:async({request:t,response:n})=>(e&&n.setHeader(`Cache-Control`,F(e)),{get ifNoneMatch(){let e=t.headers[`if-none-match`];if(!e)return;let n=e.trim();return n===`*`?n:n.split(`,`).map(e=>e.trim().replace(/^(?:W\/)?"/,``).replace(/"$/,``))},get ifModifiedSince(){let e=t.headers[`if-modified-since`];if(!e)return;let n=new Date(e);return isNaN(n.getTime())?void 0:n},get cacheControl(){return Pe(t.headers[`cache-control`])},addCachePolicy:t=>{n.setHeader(`Cache-Control`,F({...e,...t}))},setETag:e=>{n.setHeader(`ETag`,e.startsWith(`"`)?e:`"${e}"`)},setLastModified:e=>{n.setHeader(`Last-Modified`,e.toUTCString())},setVary:(...e)=>{n.setHeader(`Vary`,e.join(`, `))},setExpires:e=>{n.setHeader(`Expires`,e.toUTCString())},clearSiteData:()=>{n.setHeader(`Clear-Site-Data`,`"cache"`)},notModified:()=>{n.status(304).end()}})}),L=e=>new b({handler:async({request:t,response:n})=>({getCookie:e=>t.signedCookies?.[e]??t.cookies?.[e],setCookie:(t,r,i)=>{n.cookie(t,r,{...e,...i})},clearCookie:(t,r)=>{n.clearCookie(t,{...e,...r})}})}),R=e=>{let t=S(`express-rate-limit`)({...e,handler:(e,t,n,r)=>{n(T(429,r.message))}}),{getKey:n,resetKey:r}=t,i={getKey:n,resetKey:r};return new _(t,{provider:t=>({rateLimit:{...i,...t[e?.requestPropertyName??`rateLimit`]}})})};var z=class e{resultHandler;schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=ke(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof b?e:new b(e))}useCookies(...e){return this.#e(L(...e))}useCache(...e){return this.#e(I(...e))}useRateLimit(...e){return this.#e(R(...e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new _(...e))}addContext(e){return this.#e(new b({handler:({ctx:t})=>e(t)}))}build({input:e=i,output:t,operationId:n,scope:r,tag:a,method:o,...s}){let{middlewares:c,resultHandler:l}=this,u=typeof o==`string`?[o]:o,d=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,f=typeof r==`string`?[r]:r||[],p=typeof a==`string`?[a]:a||[];return new ce({...s,middlewares:c,outputSchema:t,resultHandler:l,scopes:f,tags:p,methods:u,getOperationId:d,inputSchema:Ae(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:i,handler:async t=>(await e(t),{})})}};const Fe=new z(M),Ie=new z(P),B={debug:_e,info:ye,warn:E(`#FFA500`),error:xe,ctx:ve},V={debug:10,info:20,warn:30,error:40},Le=e=>d(e)&&Object.keys(V).some(t=>t in e),Re=e=>e in V,ze=(e,t)=>V[e]<V[t],H=me.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),Be=e=>e<1e-6?H(`nanosecond`,3).format(e/1e-6):e<.001?H(`nanosecond`).format(e/1e-6):e<1?H(`microsecond`).format(e/.001):e<1e3?H(`millisecond`).format(e):e<6e4?H(`second`,2).format(e/1e3):H(`minute`,2).format(e/6e4);var U=class e{config;constructor({color:e=ge.isSupported(),level:t=p()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return Se(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r!==`debug`||3})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||ze(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?B.ctx(i):i),s.push(o?`${B[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=O.now();return()=>{let n=O.now()-t,{message:r,severity:i=`debug`,formatter:a=Be}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},Ve=class{logger;#e=new WeakMap;constructor(e){this.logger=e}#t(e,t,n){if(!e.isSchemaChecked){for(let e of[`input`,`output`]){let r=[w.toJSONSchema(t[`${e}Schema`],{unrepresentable:`any`})];for(let t of r){t.type&&t.type!==`object`&&this.logger.warn(`Endpoint ${e} schema is not object-based`,n);for(let e of[`allOf`,`oneOf`,`anyOf`])t[e]&&r.push(...t[e])}}if(t.getProbableRequestType()===`json`){let e=y(t.inputSchema,`input`);e&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:e})}for(let e of oe)for(let{mimeTypes:r,schema:i}of t.getResponses(e)){if(!r?.includes(s.json))continue;let t=y(i,`output`);t&&this.logger.warn(`The final ${e} response schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:t})}e.isSchemaChecked=!0}}#n(e,t,n,r){if(e.paths.has(n))return;let i=f(n);if(i.length!==0){e.flat??=pe(w.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of i)t in e.flat.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,{...r,path:n,param:t});e.paths.add(n)}}check=(e,t,n)=>{let r=this.#e.get(n);r||(r={isSchemaChecked:!1,paths:new Set},this.#e.set(n,r)),this.#t(r,n,{method:e,path:t}),this.#n(r,n,t,{method:e})}};const W=e=>e.sort((e,t)=>ee(t)-+ee(e)||e.localeCompare(t)).join(`, `).toUpperCase(),He=e=>({method:t},n,r)=>{let i=W(e);n.set({Allow:i}),r(T(405,`${t} is not allowed`,{headers:{Allow:i}}))},Ue=({app:e,getLogger:t,config:n,routing:r})=>{let i=p()?void 0:new Ve(t()),a=new Map;return le({routing:r,config:n,onEndpoint:(e,t,r)=>{i?.check(e,t,r),a.has(t)||a.set(t,new Map(n.cors?[[`options`,r]]:[])),a.get(t)?.set(e,r)},onStatic:e.use.bind(e)}),a},G=({app:e,config:t,getLogger:n,...r})=>{let i=Ue({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,s]of o){let o=[];t.cors&&o.push((e,t,n)=>{t.set(`Access-Control-Allow-Methods`,W(i)),n()}),o.push(async(e,r)=>{let i=n(e);return s.execute({request:e,response:r,logger:i,config:t})}),e[a]?.(r,...o)}t.hintAllowedMethods!==!1&&a.set(r,He(i))}for(let[t,n]of a)e.all(t,n)},We=e=>`_httpMessage`in e&&typeof e._httpMessage==`object`&&e._httpMessage!==null&&`headersSent`in e._httpMessage&&typeof e._httpMessage.headersSent==`boolean`&&`setHeader`in e._httpMessage&&typeof e._httpMessage.setHeader==`function`,Ge=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Ke=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,qe=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Je=e=>{let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.close(e=>e?r(e):n()),t},Ye=({timeout:e=1e3,logger:t}={})=>{let n,r=new Set,i=new Set,a=e=>void i.delete(e),o=e=>a(e.destroy()),s=e=>void(We(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):o(e)),c=e=>void(n?e.destroy():i.add(e.once(`close`,()=>a(e)).once(`error`,()=>o(e)))),l=async()=>{for(let e of r)e.on(`request`,qe);t?.info(`Graceful shutdown`,{sockets:i.size,timeout:e});for(let e of i)(Ke(e)||Ge(e))&&s(e);for await(let t of Te(10,Date.now()))if(i.size===0||Date.now()-t>=e)break;for(let e of i)o(e);return Promise.allSettled(r.values().map(Je))},u={sockets:i,add:(...e)=>{for(let t of e)if(!r.has(t)){r.add(t);for(let e of[`connection`,`secureConnection`])t.on(e,c)}return u},shutdown:()=>n??=l(),get isShuttingDown(){return!!n}};return u},K=Symbol.for(`express-zod-api`),Xe=({errorHandler:e,getLogger:t})=>async(n,r,i,o)=>n?e.execute({error:a(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):o(),Ze=({errorHandler:e,getLogger:t})=>async(n,r)=>{let i=T(404,`Can not ${n.method} ${n.path}`),a=t(n);await e.execute({request:n,response:r,logger:a,error:i,input:null,output:null,ctx:{}})},Qe=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},$e=({config:e})=>{let t=S(`cookie-parser`),{secret:n,...r}={...typeof e.cookies==`object`&&e.cookies};return t(n,Object.keys(r).length?r:void 0)},q=e=>typeof e==`function`?e:({},e,t)=>{e.set({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Headers":`content-type`}),t()},et=e=>({log:t=>{/not eligible/i.test(t)||e.debug(t)}}),tt=({getLogger:e,config:t})=>{let n=S(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:et(s)})(t,r,o)}),r&&o.push(Qe(r)),o},nt=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},rt=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[K]={logger:o}),a()},it=e=>t=>t?.res?.locals[K]?.logger||e;let J=!1;const at=e=>{J||(J=!0,process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
|
|
2
|
+
`).slice(1))))};let Y,X,Z;const ot=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{Y??=Ye({logger:t,timeout:n}),Y.add(...e),r&&(Z??=new Set).add(r),X??=async()=>{Y?.isShuttingDown||(await Y?.shutdown(),Z&&await Promise.allSettled(Z.values().map(async e=>e())),process.exit())};for(let e of i)process.listeners(e).includes(X)||process.on(e,X)},st=e=>{if(e.columns<62)return;let t=be(`for Angie`.padStart(52)),n=E(`#F5A9B8`),r=E(`#5BCEFA`),i=[r`8888888888${t}`,r`888`,r`888`,r`8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b`,n`888 `Y8bd8P' 888 "88b 888P" d8P Y8b 88K 88K`,n`888 X88K 888 888 888 88888888 "Y8888b. "Y8888b.`,n`888 .d8""8b. 888 d88P 888 Y8b. X88 X88`,D`8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P'`,D` 888`,D`8888888888P 888 888 d8888 8888888b. 8888888`,D` d88P 888 d88888 888 Y88b 888`,n` d88P 888 d88P888 888 888 888`,n` d88P .d88b. .d88888 d88P 888 888 d88P 888`,n` d88P d88""88b d88" 888 d88P 888 8888888P" 888`,r` d88P 888 888 888 888 d88P 888 888 888`,r` d88P Y88..88P Y88b 888 d8888888888 888 888`,r`d8888888888 "Y88P" "Y88888 d88P 888 888 8888888`];e.write(`
|
|
3
3
|
`+i.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
|
|
6
|
-
`)},
|
|
7
|
-
`)).parse({event:t,data:n}),
|
|
6
|
+
`)},Q=e=>{e.startupLogo!==!1&&st(process.stdout);let t=e.errorHandler||M,n=Le(e.logger)?e.logger:new U(e.logger);n.debug(`Running`,{build:`v29.0.0-beta.5`,env:process.env.NODE_ENV||`development`}),at(n);let r=rt({logger:n,config:e}),i={getLogger:it(n),errorHandler:t},a=Ze(i),o=Xe(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},ct=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=Q(e),o=e.app.use(a);return e.cors&&o.use(q(e.cors)),G({app:o,routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},lt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=Q(e),s=k().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.beforeParsers?.({app:s,getLogger:r}),e.compression){let t=S(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}return e.cookies&&s.use($e({config:e})),e.cors&&s.use(q(e.cors)),s.use(e.jsonParser||k.json()).use(e.formParser||k.urlencoded()).use(e.rawParser||k.raw(),nt),e.upload&&s.use(...tt({config:e,getLogger:r})),e.beforeRouting?.({app:s,getLogger:r}),G({app:s,routing:t,getLogger:r,config:e}),e.afterRouting?.({app:s,getLogger:r}),s.use(a,i),{app:s,logger:n}},ut=(e,t)=>{let{app:n,logger:r}=lt(e,t),i=[],a=(e,t)=>()=>e.listen(t,()=>r.info(`Listening`,t)),o=[];if(e.http){let t=Ce.createServer(n);i.push(t),o.push(a(t,e.http.listen))}if(e.https){let t=we.createServer(e.https.options,n);i.push(t),o.push(a(t,e.https.listen))}return i.length||r.warn(`No servers configured.`),e.gracefulShutdown&&ot({logger:r,servers:i,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:n,logger:r,servers:o.map(e=>e())}},dt=e=>Ee({...e,headers:{"content-type":s.json,...e?.headers}}),ft=e=>De(e),pt=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:Re(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},mt=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=dt(e),a=ft({req:i,...t});a.req=t?.req||i,i.res=a;let o=pt(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},ht=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=mt(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},gt=async({middleware:e,ctx:t={},...n})=>{let{configMock:{inputSources:r,errorHandler:i=M},...o}=mt(n),s=c(o.requestMock,r),l={request:o.requestMock,response:o.responseMock,logger:o.loggerMock,input:s,ctx:t};try{let t=await e.execute(l);return{...o,output:t}}catch(e){return await i.execute({...l,error:a(e),output:null}),{...o,output:{}}}},_t=(e,t)=>w.object({data:t,event:w.literal(e),id:w.string().optional(),retry:w.int().positive().optional()}),vt=(e,t,n)=>_t(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
|
|
7
|
+
`)).parse({event:t,data:n}),yt=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":s.sse,"cache-control":`no-cache`}),bt=e=>new b({handler:async({request:t,response:n})=>{let r=new AbortController,i=setTimeout(()=>yt(n),1e4);return t.once(`close`,()=>{clearTimeout(i),r.abort()}),{isClosed:()=>n.writableEnded||n.closed,signal:r.signal,emit:(t,r)=>{yt(n),n.write(vt(e,t,r),`utf-8`),n.flush?.()}}}}),xt=e=>new A({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>_t(e,t));if(!t)throw new u(Error(`At least one SSE event is required.`));return{mimeType:s.sse,schema:n.length?w.discriminatedUnion(`event`,[t,...n]):t}},negative:{mimeType:`text/plain`,schema:w.string()},handler:async({response:e,error:t,logger:n,request:r,input:i})=>{if(t){let a=h(t);x(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(v(a),`utf-8`)}e.end()}});var St=class extends z{constructor(e){super(xt(e)),this.middlewares=[bt(e)]}};const Ct=[`total`,`limit`,`offset`],$=[`nextCursor`,`limit`];function wt({style:e,itemSchema:t,itemsName:n=`items`,maxLimit:r=100,defaultLimit:i=20}){if(!Number.isInteger(r)||r<1)throw Error(`ez.paginated: maxLimit must be a positive integer`);if(!Number.isInteger(i)||i<1)throw Error(`ez.paginated: defaultLimit must be a positive integer`);if(i>r)throw Error(`ez.paginated: defaultLimit must not be greater than maxLimit`);if(e===`offset`&&Ct.includes(n))throw Error(`ez.paginated: itemsName must not match reserved keys for offset output (${Ct.join(`, `)})`);if(e===`cursor`&&$.includes(n))throw Error(`ez.paginated: itemsName must not match reserved keys for cursor output (${$.join(`, `)})`);let a=w.coerce.number().int().min(1).max(r).default(i).describe(`Page size (number of ${n} per page)`);if(e===`offset`){let e=w.coerce.number().int().min(0).default(0).describe(`Number of ${n} to skip`);return{input:w.object({limit:a,offset:e}),output:w.object({[n]:w.array(t).describe(`Page of ${n}`),total:w.number().int().min(0).describe(`Total number of ${n}`),limit:w.number().int().min(1).describe(`Page size used`),offset:w.number().int().min(0).describe(`Offset used`)})}}let o=w.string().optional().describe(`Cursor for the next page; omit for first page`);return{input:w.object({cursor:o,limit:a}),output:w.object({[n]:w.array(t).describe(`Page of ${n}`),nextCursor:w.string().nullable().describe(`Cursor for the next page, or null if no more pages`),limit:w.number().int().min(1).describe(`Page size used`)})}}const Tt={dateIn:ae,dateOut:n,form:ne,upload:fe,raw:te,buffer:ie,paginated:wt};export{U as BuiltinLogger,de as DocumentationError,z as EndpointsFactory,St as EventStreamFactory,l as InputValidationError,b as Middleware,t as MissingPeerError,ue as OutputValidationError,A as ResultHandler,r as RoutingError,se as ServeStatic,Ie as arrayEndpointsFactory,P as arrayResultHandler,ct as attachRouting,re as createApiResponse,I as createCacheMiddleware,Oe as createConfig,L as createCookieMiddleware,R as createRateLimitMiddleware,ut as createServer,Fe as defaultEndpointsFactory,M as defaultResultHandler,h as ensureHttpError,Tt as ez,e as getMessageFromError,ht as testEndpoint,gt as testMiddleware};
|
package/dist/integration.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as FlatObject, g as CommonConfig, l as EmptyObject, t as Routing } from "./routing-xQnwfH2D.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import ts, { default as ts$1 } from "typescript";
|
|
4
4
|
interface NextHandlerInc<U> {
|
package/dist/integration.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
import{D as e,G as t,M as n,V as r,W as i,Y as a,Z as o,a as s,h as c,j as l,k as u,m as d,n as f,q as ee,t as p}from"./routing-walker--qYUjhGi.js";import{t as m}from"./peer-helpers-eiBZCqrL.js";import{globalRegistry as h,z as g}from"zod";import*as _ from"ramda";import v from"typescript";const y=v.factory,b=[y.createModifier(v.SyntaxKind.ExportKeyword)],te=[y.createModifier(v.SyntaxKind.AsyncKeyword)],x={public:[y.createModifier(v.SyntaxKind.PublicKeyword)],publicStatic:[y.createModifier(v.SyntaxKind.PublicKeyword),y.createModifier(v.SyntaxKind.StaticKeyword)],protectedReadonly:[y.createModifier(v.SyntaxKind.ProtectedKeyword),y.createModifier(v.SyntaxKind.ReadonlyKeyword)]},ne=/^[A-Za-z_$][A-Za-z0-9_$]*$/,re=[v.SyntaxKind.AnyKeyword,v.SyntaxKind.BigIntKeyword,v.SyntaxKind.BooleanKeyword,v.SyntaxKind.NeverKeyword,v.SyntaxKind.NumberKeyword,v.SyntaxKind.ObjectKeyword,v.SyntaxKind.StringKeyword,v.SyntaxKind.SymbolKeyword,v.SyntaxKind.UndefinedKeyword,v.SyntaxKind.UnknownKeyword,v.SyntaxKind.VoidKeyword],S=e=>e,C=e=>typeof e==`number`?y.createNumericLiteral(e):typeof e==`bigint`?y.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?y.createTrue():y.createFalse():e===null?y.createNull():y.createStringLiteral(e),w=e=>y.createIdentifier(e),T=e=>typeof e==`string`&&ne.test(e)?w(e):C(e),E=(e,t)=>typeof e==`number`?y.createKeywordTypeNode(e):typeof e==`string`||v.isIdentifier(e)?y.createTypeReferenceNode(e,t&&_.map(E,t)):e,ie=()=>E(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),D=e=>{let t=new Map;for(let n of e)t.set(ae(n)?n.kind:n,n);return y.createUnionTypeNode(Array.from(t.values()))},ae=e=>re.includes(e.kind),O=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),oe=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS);return v.createPrinter(t).printNode(v.EmitHint.Unspecified,e,n)},k=(e,...t)=>y.createTemplateExpression(y.createTemplateHead(e),t.map(([e,n=``],r)=>y.createTemplateSpan(typeof e==`string`?w(e):e,r===t.length-1?y.createTemplateTail(n):y.createTemplateMiddle(n)))),A=(e,{type:t,mod:n,initId:r,optional:i}={})=>y.createParameterDeclaration(n,void 0,e,i?y.createToken(v.SyntaxKind.QuestionToken):void 0,t?E(t):void 0,r?w(r):void 0),j=e=>Object.entries(e).map(([e,t])=>A(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),se=(e,t=[])=>y.createConstructorDeclaration(x.public,e,y.createBlock(t)),M=(e,t,{isOptional:n,hasUndefined:r=n,isDeprecated:i,comment:a}={})=>{let o=E(t),s=y.createPropertySignature(void 0,T(e),n?y.createToken(v.SyntaxKind.QuestionToken):void 0,r?D([o,E(v.SyntaxKind.UndefinedKeyword)]):o),c=_.reject(_.isNil,[i?`@deprecated`:void 0,a]);return c.length?O(s,c.join(` `)):s},N=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),ce=(...e)=>y.createArrayBindingPattern(e.map(e=>y.createBindingElement(void 0,void 0,e))),P=(e,t,{type:n,expose:r}={})=>y.createVariableStatement(r&&b,y.createVariableDeclarationList([y.createVariableDeclaration(e,void 0,n?E(n):void 0,t)],v.NodeFlags.Const)),F=(e,t,{expose:n,comment:r,params:i}={})=>{let a=y.createTypeAliasDeclaration(n?b:void 0,e,i&&I(i),t);return r?O(a,r):a},le=(e,t)=>F(e,D(_.map(J,t)),{expose:!0}),I=e=>(Array.isArray(e)?e.map(e=>_.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return y.createTypeParameterDeclaration([],e,n?E(n):void 0,r?E(r):void 0)}),ue=(e,t)=>y.createPropertyDeclaration(x.public,e,void 0,E(t),void 0),L=(e,t,n,{typeParams:r,returns:i,isStatic:a}={})=>y.createMethodDeclaration(a?x.publicStatic:x.public,void 0,e,void 0,r&&I(r),t,i,y.createBlock(n)),R=(e,t,{typeParams:n}={})=>y.createClassDeclaration(b,e,n&&I(n),void 0,t),z=e=>y.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,E(e)),B=e=>E(Promise.name,[e]),V=(e,t,{expose:n,comment:r}={})=>{let i=y.createInterfaceDeclaration(n?b:void 0,e,void 0,void 0,t);return r?O(i,r):i},H=(e,t,{isAsync:n}={})=>y.createArrowFunction(n?te:void 0,void 0,Array.isArray(e)?_.map(A,e):j(e),void 0,void 0,t),U=(...e)=>{let[t,n,r]=e.map(e=>typeof e==`string`?w(e):e);return y.createConditionalExpression(t,y.createToken(v.SyntaxKind.QuestionToken),n,y.createToken(v.SyntaxKind.ColonToken),r)},W=(e,...t)=>(...n)=>y.createCallExpression(t.reduce((e,t)=>typeof t==`string`||v.isIdentifier(t)?y.createPropertyAccessExpression(e,t):y.createElementAccessExpression(e,t),typeof e==`string`?w(e):e),void 0,n.map(e=>typeof e==`string`?w(e):e)),G=(e,...t)=>y.createNewExpression(w(e),void 0,t),K=(e,t)=>E(`Extract`,[e,t]),de=(e,t)=>y.createExpressionStatement(y.createBinaryExpression(typeof e==`string`?w(e):e,y.createToken(v.SyntaxKind.EqualsToken),t)),q=(e,t)=>y.createIndexedAccessTypeNode(E(e),E(t)),fe=e=>D([E(e),B(e)]),pe=(e,t)=>y.createFunctionTypeNode(void 0,j(e),E(t)),J=e=>y.createLiteralTypeNode(C(e));var me=class{serverUrl;paths=new Set;tags=new Map;registry=new Map;constructor(e){this.serverUrl=e}#e={pathType:`Path`,implementationType:`Implementation`,keyParameter:`key`,pathParameter:`path`,paramsArgument:`params`,ctxArgument:`ctx`,methodParameter:`method`,requestParameter:`request`,eventParameter:`event`,dataParameter:`data`,handlerParameter:`handler`,msgParameter:`msg`,parseRequestFn:`parseRequest`,substituteFn:`substitute`,provideMethod:`provide`,onMethod:`on`,implementationArgument:`implementation`,hasBodyConst:`hasBody`,undefinedValue:`undefined`,responseConst:`response`,restConst:`rest`,searchParamsConst:`searchParams`,defaultImplementationConst:`defaultImplementation`,clientConst:`client`,contentTypeConst:`contentType`,isJsonConst:`isJSON`,sourceProp:`source`,methodType:`Method`,someOfType:`SomeOf`,requestType:`Request`,paginationType:`Pagination`};interfaces={input:`Input`,positive:`PositiveResponse`,negative:`NegativeResponse`,encoded:`EncodedResponse`,response:`Response`};makeMethodType=()=>le(this.#e.methodType,a);makeSomeOfType=()=>F(this.#e.someOfType,q(`T`,z(`T`)),{params:[`T`]});makeRequestType=()=>F(this.#e.requestType,z(this.interfaces.input),{expose:!0});someOf=({name:e})=>E(this.#e.someOfType,[e]);makePathType=()=>le(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>V(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>M(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>P(`endpointTags`,y.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>y.createPropertyAssignment(T(e),y.createArrayLiteralExpression(_.map(C,t))))),{expose:!0});makeImplementationType=()=>F(this.#e.implementationType,pe({[this.#e.methodParameter]:this.#e.methodType,[this.#e.pathParameter]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:ie(),[this.#e.ctxArgument]:{optional:!0,type:`T`}},B(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>P(this.#e.parseRequestFn,H({[this.#e.requestParameter]:v.SyntaxKind.StringKeyword},y.createAsExpression(W(this.#e.requestParameter,S(`split`))(y.createRegularExpressionLiteral(`/ (.+)/`),C(2)),y.createTupleTypeNode([E(this.#e.methodType),E(this.#e.pathType)]))));makeSubstituteFn=()=>P(this.#e.substituteFn,H({[this.#e.pathParameter]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:ie()},y.createBlock([P(this.#e.restConst,y.createObjectLiteralExpression([y.createSpreadAssignment(w(this.#e.paramsArgument))])),y.createForInStatement(y.createVariableDeclarationList([y.createVariableDeclaration(this.#e.keyParameter)],v.NodeFlags.Const),w(this.#e.paramsArgument),y.createBlock([de(this.#e.pathParameter,W(this.#e.pathParameter,S(`replace`))(k(`:`,[this.#e.keyParameter]),H([],y.createBlock([y.createExpressionStatement(y.createDeleteExpression(y.createElementAccessExpression(w(this.#e.restConst),w(this.#e.keyParameter)))),y.createReturnStatement(y.createElementAccessExpression(w(this.#e.paramsArgument),w(this.#e.keyParameter)))]))))])),y.createReturnStatement(y.createAsExpression(y.createArrayLiteralExpression([w(this.#e.pathParameter),w(this.#e.restConst)]),E(`const`)))])));makePaginationType=()=>{let e=S(`nextCursor`),t=S(`total`),n=S(`limit`),r=S(`offset`),i=y.createTypeLiteralNode([M(e,D([E(v.SyntaxKind.StringKeyword),J(null)]))]),a=y.createTypeLiteralNode([t,n,r].map(e=>M(e,v.SyntaxKind.NumberKeyword)));return F(this.#e.paginationType,D([i,a]))};#t=()=>{let e=w(this.#e.responseConst),t=S(`nextCursor`),n=S(`total`),r=S(`limit`),i=S(`offset`),a=y.createBinaryExpression(C(t),v.SyntaxKind.InKeyword,e),o=y.createReturnStatement(y.createBinaryExpression(y.createPropertyAccessExpression(e,t),v.SyntaxKind.ExclamationEqualsEqualsToken,C(null))),s=y.createBinaryExpression(y.createPropertyAccessExpression(e,i),v.SyntaxKind.PlusToken,y.createPropertyAccessExpression(e,r)),c=y.createReturnStatement(y.createBinaryExpression(s,v.SyntaxKind.LessThanToken,y.createPropertyAccessExpression(e,n)));return L(`hasMore`,[A(e,{type:this.#e.paginationType})],[y.createIfStatement(a,o),c],{returns:E(v.SyntaxKind.BooleanKeyword),isStatic:!0})};#n=()=>L(this.#e.provideMethod,j({[this.#e.requestParameter]:`K`,[this.#e.paramsArgument]:q(this.interfaces.input,`K`),[this.#e.ctxArgument]:{optional:!0,type:`T`}}),[P(ce(this.#e.methodParameter,this.#e.pathParameter),W(this.#e.parseRequestFn)(this.#e.requestParameter)),y.createReturnStatement(W(y.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,y.createSpreadElement(W(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.#e.requestType},returns:B(q(this.interfaces.response,`K`))});makeClientClass=e=>R(e,[se([A(this.#e.implementationArgument,{type:E(this.#e.implementationType,[`T`]),mod:x.protectedReadonly,initId:this.#e.defaultImplementationConst})]),this.#n(),this.#t()],{typeParams:[`T`]});#r=e=>k(`?`,[G(URLSearchParams.name,w(e))]);#i=()=>G(URL.name,k(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),C(this.serverUrl));makeDefaultImplementation=()=>{let e=y.createPropertyAssignment(S(`method`),W(this.#e.methodParameter,S(`toUpperCase`))()),t=y.createPropertyAssignment(S(`headers`),U(this.#e.hasBodyConst,y.createObjectLiteralExpression([y.createPropertyAssignment(C(`Content-Type`),C(o.json))]),this.#e.undefinedValue)),n=y.createPropertyAssignment(S(`body`),U(this.#e.hasBodyConst,W(JSON[Symbol.toStringTag],S(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=P(this.#e.responseConst,y.createAwaitExpression(W(fetch.name)(this.#i(),y.createObjectLiteralExpression([e,t,n])))),i=P(this.#e.hasBodyConst,y.createLogicalNot(W(y.createArrayLiteralExpression([C(`get`),C(`head`),C(`delete`)]),S(`includes`))(this.#e.methodParameter))),a=P(this.#e.searchParamsConst,U(this.#e.hasBodyConst,C(``),this.#r(this.#e.paramsArgument))),s=P(this.#e.contentTypeConst,W(this.#e.responseConst,S(`headers`),S(`get`))(C(`content-type`))),c=y.createIfStatement(y.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,w(this.#e.contentTypeConst)),y.createReturnStatement()),l=P(this.#e.isJsonConst,W(this.#e.contentTypeConst,S(`startsWith`))(C(o.json))),u=y.createReturnStatement(W(this.#e.responseConst,U(this.#e.isJsonConst,C(S(`json`)),C(S(`text`))))());return P(this.#e.defaultImplementationConst,H([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],y.createBlock([i,a,r,s,c,l,u]),{isAsync:!0}),{type:this.#e.implementationType})};#a=()=>se(j({request:`K`,params:q(this.interfaces.input,`K`)}),[P(ce(this.#e.pathParameter,this.#e.restConst),W(this.#e.substituteFn)(y.createElementAccessExpression(W(this.#e.parseRequestFn)(this.#e.requestParameter),C(1)),this.#e.paramsArgument)),P(this.#e.searchParamsConst,this.#r(this.#e.restConst)),de(y.createPropertyAccessExpression(y.createThis(),this.#e.sourceProp),G(`EventSource`,this.#i()))]);#o=e=>y.createTypeLiteralNode([M(S(`event`),e)]);#s=()=>L(this.#e.onMethod,j({[this.#e.eventParameter]:`E`,[this.#e.handlerParameter]:pe({[this.#e.dataParameter]:q(K(`R`,N(this.#o(`E`))),J(S(`data`)))},fe(v.SyntaxKind.VoidKeyword))}),[y.createExpressionStatement(W(y.createThis(),this.#e.sourceProp,S(`addEventListener`))(this.#e.eventParameter,H([this.#e.msgParameter],W(this.#e.handlerParameter)(W(JSON[Symbol.toStringTag],S(`parse`))(y.createPropertyAccessExpression(y.createParenthesizedExpression(y.createAsExpression(w(this.#e.msgParameter),E(MessageEvent.name))),S(`data`))))))),y.createReturnStatement(y.createThis())],{typeParams:{E:q(`R`,J(S(`event`)))}});makeSubscriptionClass=e=>R(e,[ue(this.#e.sourceProp,`EventSource`),this.#a(),this.#s()],{typeParams:{K:K(this.#e.requestType,y.createTemplateLiteralType(y.createTemplateHead(`get `),[y.createTemplateLiteralTypeSpan(E(v.SyntaxKind.StringKeyword),y.createTemplateTail(``))])),R:K(q(this.interfaces.positive,`K`),N(this.#o(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[P(this.#e.clientConst,G(e)),W(this.#e.clientConst,this.#e.provideMethod)(C(`get /v1/user/retrieve`),y.createObjectLiteralExpression([y.createPropertyAssignment(`id`,C(`10`))])),W(G(t,C(`get /v1/events/stream`),y.createObjectLiteralExpression()),this.#e.onMethod)(C(`time`),H([`time`],y.createBlock([])))]};const he=(e,{rules:t,onMissing:r,ctx:i={}})=>{let a=n(e),o=a&&a in t?t[a]:t[e._zod.def.type],s=e=>he(e,{ctx:i,rules:t,onMissing:r});return o?o(e,{...i,next:s}):r(e,i)},Y={name:_.path([`name`,`text`]),type:_.path([`type`]),optional:_.path([`questionToken`])},ge=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?E(v.SyntaxKind.UndefinedKeyword):J(e));return t.length===1?t[0]:D(t)},_e=({_zod:{def:e}},{next:t})=>{let{parts:n}=e,r=0,a=()=>{let e=``;for(;r<n.length;){let t=n[r];if(i(t))break;r++,e+=t??``}return e},o=y.createTemplateHead(a()),s=[];for(;r<n.length;){let e=t(n[r++]),i=a(),o=r<n.length?y.createTemplateMiddle:y.createTemplateTail;s.push(y.createTemplateLiteralTypeSpan(e,o(i)))}return s.length?y.createTemplateLiteralType(o,s):J(o.text)},ve=(e,{isResponse:t,next:n,makeAlias:r})=>{let i=()=>{let r=Object.entries(e._zod.def.shape).map(([e,r])=>{let{description:i,deprecated:a}=h.get(r)||{},o=(t?r._zod.optout:r._zod.optin)===`optional`,s=o&&!(r instanceof g.core.$ZodExactOptional);return M(e,n(r),{comment:i,isDeprecated:a,isOptional:o,hasUndefined:s})});return y.createTypeLiteralNode(r)};return d(e,{io:t?`output`:`input`})?r(e,i):i()},ye=({_zod:{def:e}},{next:t})=>y.createArrayTypeNode(t(e.element)),be=({_zod:{def:e}})=>D(_.map(J,Object.values(e.entries))),xe=({_zod:{def:e}},{next:t})=>D(e.options.map(t)),Se=({_zod:{def:e}},{next:t})=>D([t(e.innerType),J(null)]),Ce=({_zod:{def:e}},{next:t})=>y.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:y.createRestTypeNode(t(e.rest)))),we=({_zod:{def:e}},{next:t})=>{let[n,r]=[e.keyType,e.valueType].map(t),i=E(`Record`,[n,r]);return e.mode===`loose`?y.createIntersectionTypeNode([i,E(`Record`,[`PropertyKey`,r])]):i},Te=_.tryCatch(e=>{if(!e.every(v.isTypeLiteralNode))throw Error(`Not objects`);let t=_.chain(_.prop(`members`),e),n=_.uniqWith((...e)=>{if(!_.eqBy(Y.name,...e))return!1;if(_.both(_.eqBy(Y.type),_.eqBy(Y.optional))(...e))return!0;throw Error(`Has conflicting prop`)},t);return y.createTypeLiteralNode(n)},(e,t)=>y.createIntersectionTypeNode(t)),Ee=({_zod:{def:e}},{next:t})=>Te([e.left,e.right].map(t)),X=e=>()=>E(e),Z=({_zod:{def:e}},{next:t})=>t(e.innerType),Q=e=>E(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),De=({_zod:{def:e}},{next:t,isResponse:n})=>{let a=e[n?`out`:`in`],o=e[n?`in`:`out`];if(!i(a,`transform`))return t(a);let s=t(o),c={[v.SyntaxKind.AnyKeyword]:``,[v.SyntaxKind.BigIntKeyword]:BigInt(0),[v.SyntaxKind.BooleanKeyword]:!1,[v.SyntaxKind.NumberKeyword]:0,[v.SyntaxKind.ObjectKeyword]:{},[v.SyntaxKind.StringKeyword]:``,[v.SyntaxKind.UndefinedKeyword]:void 0}[s.kind],l=r(a,c),u={number:v.SyntaxKind.NumberKeyword,bigint:v.SyntaxKind.BigIntKeyword,boolean:v.SyntaxKind.BooleanKeyword,string:v.SyntaxKind.StringKeyword,undefined:v.SyntaxKind.UndefinedKeyword,object:v.SyntaxKind.ObjectKeyword};return E(l&&u[l]||Q(n))},Oe=()=>J(null),ke=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),Ae=()=>E(`Buffer`),je=(e,{next:t})=>t(e._zod.def.shape.raw),Me={string:X(v.SyntaxKind.StringKeyword),number:X(v.SyntaxKind.NumberKeyword),bigint:X(v.SyntaxKind.BigIntKeyword),boolean:X(v.SyntaxKind.BooleanKeyword),any:X(v.SyntaxKind.AnyKeyword),undefined:X(v.SyntaxKind.UndefinedKeyword),[u]:X(v.SyntaxKind.StringKeyword),[e]:X(v.SyntaxKind.StringKeyword),never:X(v.SyntaxKind.NeverKeyword),void:X(v.SyntaxKind.UndefinedKeyword),unknown:X(v.SyntaxKind.UnknownKeyword),null:Oe,array:ye,tuple:Ce,record:we,object:ve,literal:ge,template_literal:_e,intersection:Ee,union:xe,default:Z,enum:be,optional:Z,nonoptional:Z,nullable:Se,catch:Z,pipe:De,lazy:ke,readonly:Z,[l]:Ae,[c]:je},$=(e,{brandHandling:t,ctx:n})=>he(e,{rules:{...t,...Me},onMissing:({},{isResponse:e})=>Q(e),ctx:n});var Ne=class extends me{#e=[this.makeSomeOfType()];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=J(null);this.#t.set(e,F(n,r)),this.#t.set(e,F(n,t()))}return E(n)}constructor({routing:e,config:n,brandHandling:r,variant:i=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:c=`https://example.com`,noBodySchema:l=g.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this)},m={brandHandling:r,ctx:{...d,isResponse:!1}},h={brandHandling:r,ctx:{...d,isResponse:!0}},v=(e,n,r)=>{let i=t.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:c}=r,u=`${e} ${n}`,d=F(i(`input`),$(o,m),{comment:u});this.#e.push(d);let f=s.reduce((t,n)=>{let a=r.getResponses(n),o=_.chain(([t,{schema:r,mimeTypes:a,statusCodes:o}])=>{let s=ee(e,a),c=F(i(n,`variant`,`${t+1}`),$(s?r:l,h),{comment:u});return this.#e.push(c),o.map(e=>M(e,c.name))},Array.from(a.entries())),s=V(i(n,`response`,`variants`),o,{comment:u});return this.#e.push(s),Object.assign(t,{[n]:s})},{});this.paths.add(n);let p=J(u),g={input:E(d.name),positive:this.someOf(f.positive),negative:this.someOf(f.negative),response:D([q(this.interfaces.positive,p),q(this.interfaces.negative,p)]),encoded:y.createIntersectionTypeNode([E(f.positive.name),E(f.negative.name)])};this.registry.set(u,{isDeprecated:a,store:g}),this.tags.set(u,c)};p({routing:e,config:n,onEndpoint:u?f(v):v}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.makeMethodType(),...this.makePublicInterfaces(),this.makeRequestType()),i!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makePaginationType(),this.makeDefaultImplementation(),this.makeClientClass(a),this.makeSubscriptionClass(o)),this.#n.push(...this.makeUsageStatements(a,o)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:oe(t,e)).join(`
|
|
2
|
-
|
|
1
|
+
import{A as e,G as t,H as n,J as r,K as i,M as a,N as o,O as s,Q as c,X as l,g as u,h as d,n as f,o as p,t as m}from"./routing-walker-Uax31V_v.js";import{t as h}from"./peer-helpers-BFaGRU7x.js";import{globalRegistry as g,z as _}from"zod";import*as v from"ramda";import y from"typescript";const b={Path:`Path`,Implementation:`Implementation`,key:`key`,path:`path`,params:`params`,ctx:`ctx`,method:`method`,request:`request`,event:`event`,data:`data`,handler:`handler`,msg:`msg`,parseRequest:`parseRequest`,substitute:`substitute`,provide:`provide`,on:`on`,implementation:`implementation`,hasBody:`hasBody`,undefined:`undefined`,response:`response`,rest:`rest`,searchParams:`searchParams`,defaultImplementation:`defaultImplementation`,client:`client`,contentType:`contentType`,isJSON:`isJSON`,source:`source`,Method:`Method`,SomeOf:`SomeOf`,Request:`Request`,Pagination:`Pagination`},x={input:`Input`,positive:`PositiveResponse`,negative:`NegativeResponse`,encoded:`EncodedResponse`,response:`Response`},S=e=>Array.from(e,e=>`"${e}"`),C=e=>e;var w=class{serverUrl;paths=new Set;tags=new Map;registry=new Map;constructor(e){this.serverUrl=e}makeMethodType=()=>{let e=S(l).join(` | `);return`export type ${b.Method} = ${e};`};makeSomeOfType=()=>`type ${b.SomeOf}<T> = T[keyof T];`;makeRequestType=()=>`export type ${b.Request} = keyof ${x.input};`;someOf=e=>`${b.SomeOf}<${e}>`;makePathType=()=>{let e=S(this.paths).join(` | `);return`export type ${b.Path} = ${e};`};makePublicInterfaces=()=>Object.keys(x).map(e=>{let t=Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>` ${r?`/** @deprecated */
|
|
2
|
+
`:``}"${t}": ${n[e]};`).join(`
|
|
3
|
+
`);return`export interface ${x[e]} {\n${t}\n}`});makeEndpointTags=()=>`export const endpointTags = {\n${Array.from(this.tags).map(([e,t])=>` "${e}": [${S(t).join(`, `)}]`).join(`,
|
|
4
|
+
`)}\n}`;makeImplementationType=()=>{let e=[`${b.method}: ${b.Method}`,`${b.path}: string`,`${b.params}: Record<string, any>`,`${b.ctx}?: T`].join(`,`);return`export type ${b.Implementation}<T = unknown> = (${e}) => Promise<any>;`};makeParseRequestFn=()=>{let e=`${b.request}: string`,t=`[${b.Method}, ${b.Path}]`,n=`${b.request}.${C(`split`)}(/ (.+)/, 2) as ${t}`;return`const ${b.parseRequest} = (${e}) => ${n};`};makeSubstituteFn=()=>{let e=`${b.path}: string, ${b.params}: Record<string, any>`,t=`\`:\${${b.key}}\``;return[`const ${b.substitute} = (${e}) => {\n`,` const ${b.rest} = { ...${b.params} };`,` for (const ${b.key} in ${b.params}) {`,` ${b.path} = ${b.path}.${C(`replace`)}(${t}, () => {`,` delete ${b.rest}[${b.key}];`,` return ${b.params}[${b.key}];`,` });`,` }`,` return [${b.path}, ${b.rest}] as const;`,`}`].join(`
|
|
5
|
+
`)};makePaginationType=()=>{let e=C(`nextCursor`),t=C(`total`),n=C(`limit`),r=C(`offset`),i=`{ ${e}: string | null }`,a=`{ ${t}: number; ${n}: number; ${r}: number }`;return`type ${b.Pagination} = ${i} | ${a}`};makeClientClass=e=>{let t=C(`nextCursor`),n=C(`offset`),r=C(`limit`),i=C(`total`),a=`${b.method}, ...${b.substitute}(${b.path}, ${b.params}), ${b.ctx}`;return[`export class ${e}<T> {`,` public constructor(`,` protected readonly ${b.implementation}: ${b.Implementation}<T> = ${b.defaultImplementation},`,` ) {}`,` public ${b.provide}<K extends ${b.Request}>(`,` ${b.request}: K,`,` ${b.params}: ${x.input}[K],`,` ${b.ctx}?: T,`,` ): Promise<${x.response}[K]> {`,` const [${b.method}, ${b.path}] = ${b.parseRequest}(${b.request});`,` return this.${b.implementation}(${a});`,` }`,` public static hasMore(${b.response}: ${b.Pagination}): boolean {`,` if ("${t}" in ${b.response}) return ${b.response}.${t} !== null;`,` return ${b.response}.${n} + ${b.response}.${r} < ${b.response}.${i};`,` }`,`}`].join(`
|
|
6
|
+
`)};makeDefaultImplementation=()=>{let e=`${b.method}, ${b.path}, ${b.params}`,t=S([`get`,`head`,`delete`]).join(`, `),n=`${b.hasBody} ? { "Content-Type": "${c.json}" } : ${b.undefined}`,r=`${b.hasBody} ? JSON.${C(`stringify`)}(${b.params}) : ${b.undefined}`,i=`${b.response}.${C(`headers`)}.${C(`get`)}("content-type")`,a=`${b.isJSON} ? "${C(`json`)}" : "${C(`text`)}"`;return[`const ${b.defaultImplementation}: ${b.Implementation} = async (${e}) => {`,` const ${b.hasBody} = ![${t}].includes(${b.method});`,` const ${b.searchParams} = ${b.hasBody} ? "" : \`?\${new ${URLSearchParams.name}(${b.params})}\`;`,` const ${b.response} = await ${fetch.name}(`,` new ${URL.name}(\`\${${b.path}}\${${b.searchParams}}\`, "${this.serverUrl}"),`,` {`,` ${C(`method`)}: ${b.method}.${C(`toUpperCase`)}(),`,` ${C(`headers`)}: ${n},`,` ${C(`body`)}: ${r},`,` },`,` );`,` const ${b.contentType} = ${i};`,` if (!${b.contentType}) return;`,` const ${b.isJSON} = ${b.contentType}.${C(`startsWith`)}("${c.json}");`,` return ${b.response}[${a}]();`,`};`].join(`
|
|
7
|
+
`)};makeSubscriptionClass=e=>{let t=`${b.substitute}(${b.parseRequest}(${b.request})[1], ${b.params})`,n=`Extract<R, { ${C(`event`)}: E }>["${C(`data`)}"]`,r=`(${b.msg} as ${MessageEvent.name}).${C(`data`)}`;return[`export class ${e}<`,` K extends Extract<${b.Request}, \`get \${string}\`>,`,` R extends Extract<${x.positive}[K], { ${C(`event`)}: string }>,`,`> {`,` public ${b.source}: EventSource;`,` public constructor(${b.request}: K, ${b.params}: ${x.input}[K]) {`,` const [${b.path}, ${b.rest}] = ${t};`,` const ${b.searchParams} = \`?\${new ${URLSearchParams.name}(${b.rest})}\`;`,` this.${b.source} = new EventSource(`,` new URL(\`\${${b.path}}\${${b.searchParams}}\`, "${this.serverUrl}"),`,` );`,` }`,` public ${b.on}<E extends R["${C(`event`)}"]>(`,` ${C(`event`)}: E,`,` ${b.handler}: (${b.data}: ${n}) => void | Promise<void>,`,` ) {`,` this.${b.source}.${C(`addEventListener`)}(${b.event}, (${b.msg}) =>`,` ${b.handler}(JSON.${C(`parse`)}(${r})),`,` );`,` return this;`,` }`,`}`].join(`
|
|
8
|
+
`)};makeUsageStatements=(e,t)=>[`const ${b.client} = new ${e}();`,`${b.client}.${b.provide}("get /v1/user/retrieve", { id: "10" });`,`new ${t}("get /v1/events/stream", {}).${b.on}("time", (time) => {});`].join(`
|
|
9
|
+
`)};const T=y.factory,E=/^[A-Za-z_$][A-Za-z0-9_$]*$/,D=[y.SyntaxKind.AnyKeyword,y.SyntaxKind.BigIntKeyword,y.SyntaxKind.BooleanKeyword,y.SyntaxKind.NeverKeyword,y.SyntaxKind.NumberKeyword,y.SyntaxKind.ObjectKeyword,y.SyntaxKind.StringKeyword,y.SyntaxKind.SymbolKeyword,y.SyntaxKind.UndefinedKeyword,y.SyntaxKind.UnknownKeyword,y.SyntaxKind.VoidKeyword],O=e=>typeof e==`number`?T.createNumericLiteral(e):typeof e==`bigint`?T.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?T.createTrue():T.createFalse():e===null?T.createNull():T.createStringLiteral(e),ee=e=>T.createIdentifier(e),k=e=>typeof e==`string`&&E.test(e)?ee(e):O(e),A=(e,t)=>typeof e==`number`?T.createKeywordTypeNode(e):typeof e==`string`||y.isIdentifier(e)?T.createTypeReferenceNode(e,t&&v.map(A,t)):e,j=e=>{let t=new Map;for(let n of e)t.set(M(n)?n.kind:n,n);return T.createUnionTypeNode(Array.from(t.values()))},M=e=>D.includes(e.kind),N=(e,t)=>y.addSyntheticLeadingComment(e,y.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),P=(e,t)=>{let n=y.createSourceFile(`print.ts`,``,y.ScriptTarget.Latest,!1,y.ScriptKind.TS);return y.createPrinter(t).printNode(y.EmitHint.Unspecified,e,n)},F=(e,t,{isOptional:n,hasUndefined:r=n,isDeprecated:i,comment:a}={})=>{let o=A(t),s=T.createPropertySignature(void 0,k(e),n?T.createToken(y.SyntaxKind.QuestionToken):void 0,r?j([o,A(y.SyntaxKind.UndefinedKeyword)]):o),c=v.reject(v.isNil,[i?`@deprecated`:void 0,a]);return c.length?N(s,c.join(` `)):s},I=e=>T.createLiteralTypeNode(O(e)),L=(e,{rules:t,onMissing:n,ctx:r={}})=>{let i=o(e),a=i&&i in t?t[i]:t[e._zod.def.type],s=e=>L(e,{ctx:r,rules:t,onMissing:n});return a?a(e,{...r,next:s}):n(e,r)},R={name:v.path([`name`,`text`]),type:v.path([`type`]),optional:v.path([`questionToken`])},z=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?A(y.SyntaxKind.UndefinedKeyword):I(e));return t.length===1?t[0]:j(t)},B=({_zod:{def:e}},{next:n})=>{let{parts:r}=e,i=0,a=()=>{let e=``;for(;i<r.length;){let n=r[i];if(t(n))break;i++,e+=n??``}return e},o=T.createTemplateHead(a()),s=[];for(;i<r.length;){let e=n(r[i++]),t=a(),o=i<r.length?T.createTemplateMiddle:T.createTemplateTail;s.push(T.createTemplateLiteralTypeSpan(e,o(t)))}return s.length?T.createTemplateLiteralType(o,s):I(o.text)},V=(e,{isResponse:t,next:n,makeAlias:r})=>{let i=()=>{let r=Object.entries(e._zod.def.shape).map(([e,r])=>{let{description:i,deprecated:a}=g.get(r)||{},o=(t?r._zod.optout:r._zod.optin)===`optional`,s=o&&!(r instanceof _.core.$ZodExactOptional);return F(e,n(r),{comment:i,isDeprecated:a,isOptional:o,hasUndefined:s})});return T.createTypeLiteralNode(r)};return d(e,{io:t?`output`:`input`})?r(e,i):i()},H=({_zod:{def:e}},{next:t})=>T.createArrayTypeNode(t(e.element)),U=({_zod:{def:e}})=>j(v.map(I,Object.values(e.entries))),W=({_zod:{def:e}},{next:t})=>j(e.options.map(t)),G=({_zod:{def:e}},{next:t})=>j([t(e.innerType),I(null)]),K=({_zod:{def:e}},{next:t})=>T.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:T.createRestTypeNode(t(e.rest)))),q=({_zod:{def:e}},{next:t})=>{let[n,r]=[e.keyType,e.valueType].map(t),i=A(`Record`,[n,r]);return e.mode===`loose`?T.createIntersectionTypeNode([i,A(`Record`,[`PropertyKey`,r])]):i},J=v.tryCatch(e=>{if(!e.every(y.isTypeLiteralNode))throw Error(`Not objects`);let t=v.chain(v.prop(`members`),e),n=v.uniqWith((...e)=>{if(!v.eqBy(R.name,...e))return!1;if(v.both(v.eqBy(R.type),v.eqBy(R.optional))(...e))return!0;throw Error(`Has conflicting prop`)},t);return T.createTypeLiteralNode(n)},(e,t)=>T.createIntersectionTypeNode(t)),Y=({_zod:{def:e}},{next:t})=>J([e.left,e.right].map(t)),X=e=>()=>A(e),Z=({_zod:{def:e}},{next:t})=>t(e.innerType),Q=e=>A(e?y.SyntaxKind.UnknownKeyword:y.SyntaxKind.AnyKeyword),te=({_zod:{def:e}},{next:r,isResponse:i})=>{let a=e[i?`out`:`in`],o=e[i?`in`:`out`];if(!t(a,`transform`))return r(a);let s=r(o),c={[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}[s.kind],l=n(a,c),u={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 A(l&&u[l]||Q(i))},ne=()=>I(null),re=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ie=()=>A(`Buffer`),ae=(e,{next:t})=>t(e._zod.def.shape.raw),oe={string:X(y.SyntaxKind.StringKeyword),number:X(y.SyntaxKind.NumberKeyword),bigint:X(y.SyntaxKind.BigIntKeyword),boolean:X(y.SyntaxKind.BooleanKeyword),any:X(y.SyntaxKind.AnyKeyword),undefined:X(y.SyntaxKind.UndefinedKeyword),[e]:X(y.SyntaxKind.StringKeyword),[s]:X(y.SyntaxKind.StringKeyword),never:X(y.SyntaxKind.NeverKeyword),void:X(y.SyntaxKind.UndefinedKeyword),unknown:X(y.SyntaxKind.UnknownKeyword),null:ne,array:H,tuple:K,record:q,object:V,literal:z,template_literal:B,intersection:Y,union:W,default:Z,enum:U,optional:Z,nonoptional:Z,nullable:G,catch:Z,pipe:te,lazy:re,readonly:Z,[a]:ie,[u]:ae},$=(e,{brandHandling:t,ctx:n})=>L(e,{rules:{...t,...oe},onMissing:({},{isResponse:e})=>Q(e),ctx:n});var se=class extends w{#e=[];#t=new Map;#n;#r(e,t){let n=this.#t.get(e);if(!n){n=`Type${this.#t.size+1}`,this.#t.set(e,n);let r=t();this.#e.push(e=>`type ${n} = ${P(r,e)};`)}return A(n)}constructor({routing:e,config:t,brandHandling:n,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noBodySchema:l=_.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this)},h={brandHandling:n,ctx:{...d,isResponse:!1}},g={brandHandling:n,ctx:{...d,isResponse:!0}},v=(e,t,n)=>{let a=i.bind(null,e,t),{isDeprecated:o,inputSchema:s,tags:c}=n,u=`${e} ${t}`,d=a(`input`),f=$(s,h);this.#e.push(e=>`/** ${u} */\ntype ${d} = ${P(f,e)};`);let m=p.reduce((t,i)=>{let o=n.getResponses(i),s=[];for(let[t,{schema:n,mimeTypes:c,statusCodes:d}]of o.entries()){let o=r(e,c),f=a(i,`variant`,`${t+1}`),p=$(o?n:l,g);this.#e.push(e=>`/** ${u} */\ntype ${f} = ${P(p,e)};`);for(let e of d)s.push(` ${e}: ${f};`)}let c=a(i,`response`,`variants`);return this.#e.push(`/** ${u} */\ninterface ${c} {\n${s.join(`
|
|
10
|
+
`)}\n}`),Object.assign(t,{[i]:c})},{});this.paths.add(t);let _={input:d,positive:this.someOf(m.positive),negative:this.someOf(m.negative),response:`${x.positive}["${u}"] | ${x.negative}["${u}"]`,encoded:`${m.positive} & ${m.negative}`};this.registry.set(u,{isDeprecated:o,store:_}),this.tags.set(u,c)};m({routing:e,config:t,onEndpoint:u?f(v):v}),this.#e.push(this.makeSomeOfType(),this.makePathType(),this.makeMethodType(),...this.makePublicInterfaces(),this.makeRequestType()),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makePaginationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n=this.makeUsageStatements(o,s))}print(e){let t=this.#e.map(t=>typeof t==`function`?t(e):t);return this.#n&&t.push(`// Usage example:\n/*\n${this.#n}*/`),t.join(`
|
|
3
11
|
|
|
4
|
-
`)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=
|
|
12
|
+
`)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=h(`prettier`).format;n=t=>e(t,{filepath:`client.ts`})}catch{}this.#n&&n&&(this.#n=await n(this.#n));let r=this.print(e);return n?n(r):r}};export{se as Integration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{F as e,U as t}from"./routing-walker-Uax31V_v.js";import*as n from"ramda";const r=e=>e.type===`object`,i=n.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return n.concat(e,t);if(e===t)return t;throw Error(`Can not flatten properties`,{cause:{a:e,b:t}})}),a=new Set([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),o=e=>{for(let t of Object.keys(e))if(!a.has(t))return!1;return!0},s=n.pair(!0),c=(e,t,r)=>!(`allOf`in e)||!e.allOf?[]:e.allOf.map(e=>{if(t===`throw`&&!(e.type===`object`&&o(e)))throw Error(`Can not merge`);return n.pair(r,e)}),l=e=>{let t=[];return e.anyOf&&t.push(...n.map(s,e.anyOf)),e.oneOf&&t.push(...n.map(s,e.oneOf)),t},u=(e,n,r,i)=>{if(!t(e.propertyNames))return;let a=[];typeof e.propertyNames.const==`string`&&a.push(e.propertyNames.const),e.propertyNames.enum&&a.push(...e.propertyNames.enum.filter(e=>typeof e==`string`));let o={...Object(e.additionalProperties)};for(let e of a)n.properties[e]??=o;i||r.push(...a)},d=(r,i,a)=>{i.examples?.length&&(a?r.examples=n.concat(r.examples||[],i.examples):r.examples=e(r.examples?.filter(t)||[],i.examples.filter(t),([e,t])=>n.mergeDeepRight(e,t)))},f=(e,t=`coerce`)=>{let a=[n.pair(!1,e)],o={type:`object`,properties:{}},s=[];for(let[e,f]of a)f.description&&(o.description??=f.description),a.push(...c(f,t,e)),a.push(...l(f)),d(o,f,e),r(f)&&(a.push([e,{examples:p(f)}]),f.properties&&(o.properties=(t===`throw`?i:n.mergeDeepRight)(o.properties,f.properties),!e&&f.required&&s.push(...f.required)),u(f,o,s,e));return s.length&&(o.required=[...new Set(s)]),o},p=r=>Object.entries(r.properties||{}).reduce((r,[i,a])=>{let{examples:o=[]}=t(a)?a:{};return e(r,o.map(n.objOf(i)),([e,t])=>({...e,...t}))},[]);export{f as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./routing-walker-Uax31V_v.js";import{createRequire as t}from"node:module";let n;const r=(r,i=`default`)=>{try{let e=(n??=t(import.meta.url))(r);return i==="default"?e.default===void 0?e:e.default:e[i]}catch{throw new e(r)}};export{r as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{globalRegistry as e,z as t}from"zod";import*as n from"ramda";import{isPromise as r}from"node:util/types";import i,{isHttpError as a}from"http-errors";import o from"express";const s={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},c=[`get`,`post`,`put`,`delete`,`patch`,`query`],l=[...c,`head`],u=e=>c.includes(e),d=t.object({}),f=/:([A-Za-z0-9_]+)/g,ee=e=>e.match(f)?.map(e=>e.slice(1))||[],te=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(s.upload);return`files`in e&&t},ne={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},p=[`body`,`query`,`params`],m=e=>e.method.toLowerCase(),h=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:u(e)?e:void 0;return(n?t[n]||ne[n]:void 0)||p},g=(e,t={})=>{let n=m(e);return h(n,t).filter(t=>t!==`files`||te(e)).reduce((t,n)=>Object.assign(t,e[n]),{})},_=e=>e instanceof Error?e:e instanceof t.ZodError?new t.ZodRealError(e.issues):Error(String(e)),v=e=>e instanceof t.ZodError?e.issues.map(({path:e,message:n})=>`${e.length?`${t.core.toDotPath(e)}: `:``}${n}`).join(`; `):e.message,y=(e,t)=>C(e)&&`_zod`in e&&(!t||n.path([`_zod`,`def`,`type`],e)===t),b=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),x=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),S=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(x).join(``)},re=n.tryCatch((e,n)=>typeof t.parse(e,n),n.always(void 0)),C=e=>typeof e==`object`&&!!e,w=n.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),ie=(e,t)=>!!t&&e!==`head`,T=`x-brand`,E=t=>{let{[T]:n}=e.get(t)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},D=t=>{let{examples:n}=e.get(t)||{};return Array.isArray(n)?n:[]},O=Symbol(`Buffer`),k=()=>t.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[T]:O}),A=Symbol(`DateIn`),ae=({examples:e,...n}={})=>t.union([t.iso.date(),t.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(t.date()).meta({...n,[T]:A}),j=Symbol(`DateOut`),M=(e={})=>t.date().transform(e=>e.toISOString()).pipe(t.iso.datetime()).meta({...e,[T]:j});var N=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},oe=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},P=class extends Error{name=`IOSchemaError`},se=class extends P{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},F=class extends P{cause;name=`OutputValidationError`;constructor(e){let n=new t.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(v(n),{cause:e}),this.cause=e}},I=class extends P{cause;name=`InputValidationError`;constructor(e){super(v(e),{cause:e}),this.cause=e}},L=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(v(e),{cause:e}),this.cause=e,this.handled=t}},ce=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const R=Symbol(`Form`),le=e=>(e instanceof t.ZodObject?e:t.object(e)).meta({[T]:R}),z=Symbol(`Upload`),B=e=>C(e)&&`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,V=()=>t.custom(e=>B(e)&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).meta({[T]:z}),H=Symbol(`Raw`),U=t.object({raw:k()}),W=e=>U.extend(e).meta({[T]:H});function ue(e){return e?W(e):U.meta({[T]:H})}const G=(e,{io:r,condition:i})=>n.tryCatch(()=>void t.toJSONSchema(e,{io:r,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new se(e)}}),e=>e.cause)(),de=(e,{io:r})=>{let i=[t.toJSONSchema(e,{io:r,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(n.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...n.values(t))}n.is(Array,t)&&i.push(...n.values(t))}return!1},fe=e=>G(e,{condition:e=>{let t=E(e);return typeof t==`symbol`&&[z,H,R].includes(t)},io:`input`}),pe=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],me=(e,t)=>G(e,{io:t,condition:e=>{let n=E(e),{type:r}=e._zod.def;return!!(pe.includes(r)||n===O||t===`input`&&(r===`date`||n===j)||t===`output`&&(n===A||n===H||n===z))}});var he=class{},K=class extends he{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...n}){try{let t=await(this.#e||d).parseAsync(e);return this.#n({...n,input:t})}catch(e){throw e instanceof t.ZodError?new I(e):e}}},q=class extends K{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:i,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(i,a))},u=e(i,a,l);return r(u)&&u.catch(l),o}})}};const ge=(e,{variant:n,args:r,...i})=>{if(typeof e==`function`&&(e=e(...r)),e instanceof t.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new L(Error(`At least one ${n} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},_e=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),ve=e=>a(e)?e:i(e instanceof I?400:500,v(e),{cause:e.cause||e}),ye=e=>w()&&!e.expose?i(e.statusCode).message:e.message,be=e=>Object.entries(e._zod.def.shape).reduce((e,[t,r])=>b(e,D(r).map(n.objOf(t)),([e,t])=>({...e,...t})),[]);var J=class{nest(e){return{...e,"":this}}},xe=class r extends J{#e;#t;#n=n.once(()=>{if(D(this.#e.outputSchema).length||!y(this.#e.outputSchema,`object`))return;let t=be(this.#e.outputSchema);if(!t.length)return;let n=this.#e.outputSchema.meta();e.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:t})});constructor(e){super(),this.#e=e}#r(e){return new r({...this.#e,...e})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get summary(){return this.#e.summary}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=fe(this.#e.inputSchema);if(e){let t=E(e);if(t===z)return`upload`;if(t===H)return`raw`;if(t===R)return`form`}return`json`})()}getResponses(e){return e===`positive`&&this.#n(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new F(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof q))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...n}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new I(e):e}return this.#e.handler({...n,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=m(e),a={},o,s=g(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:_(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const Y={positive:200,negative:400},Se=Object.keys(Y);var X=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,o.static(...this.#e))}};const Ce=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},we=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&u(t)?[n,t]:[e]},Te=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Z=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&u(t)&&r instanceof J?[`/`,t]:we(t);return[[n||``].concat(Te(i)||[]).join(`/`),r,a]}),Q=(e,t)=>{throw new N(`Route with explicit method can only be assigned with Endpoint`,e,t)},Ee=(e,t,n)=>{if(!(!n||n.includes(e)))throw new N(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new N(`Route has a duplicate`,e,t);n.add(r)},De=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Z(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof J)if(c)$(c,o,a),Ee(c,o,s.methods),n(c,o,s);else{let{methods:e=[`get`]}=s;for(let t of e)$(t,o,a),n(t,o,s)}else c&&Q(c,o),s instanceof X?r&&s.apply(o,r):i.splice(e+1,0,...Z(t,s,o))}};export{k as A,ee as B,F as C,j as D,M as E,d as F,S as G,C as H,_ as I,x as J,f as K,g as L,E as M,D as N,ae as O,b as P,h as R,ce as S,N as T,w as U,re as V,y as W,u as X,l as Y,s as Z,z as _,Se as a,oe as b,ye as c,q as d,K as f,ue as g,H as h,Y as i,O as j,A as k,_e as l,de as m,Ce as n,xe as o,me as p,ie as q,X as r,ve as s,De as t,ge as u,V as v,L as w,I as x,le as y,v as z};
|
|
1
|
+
import{globalRegistry as e,z as t}from"zod";import*as n from"ramda";import{isPromise as r}from"node:util/types";import i,{isHttpError as a}from"http-errors";import o from"express";const s={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},c=[`get`,`post`,`put`,`delete`,`patch`,`query`],l=[...c,`head`],u=e=>c.includes(e),d=t.object({}),f=/:([A-Za-z0-9_]+)/g,ee=e=>e.match(f)?.map(e=>e.slice(1))||[],te=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(s.upload);return`files`in e&&t},ne={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},p=[`body`,`query`,`params`],m=e=>e.method.toLowerCase(),h=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:u(e)?e:void 0;return(n?t[n]||ne[n]:void 0)||p},g=(e,t={})=>{let n=m(e);return h(n,t).filter(t=>t!==`files`||te(e)).reduce((t,n)=>Object.assign(t,e[n]),{})},_=e=>e instanceof Error?e:e instanceof t.ZodError?new t.ZodRealError(e.issues):Error(String(e)),v=e=>e instanceof t.ZodError?e.issues.map(({path:e,message:n})=>`${e.length?`${t.core.toDotPath(e)}: `:``}${n}`).join(`; `):e.message,y=(e,t)=>C(e)&&`_zod`in e&&(!t||n.path([`_zod`,`def`,`type`],e)===t),b=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),x=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),S=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(x).join(``)},re=n.tryCatch((e,n)=>typeof t.parse(e,n),n.always(void 0)),C=e=>typeof e==`object`&&!!e,w=n.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),ie=(e,t)=>!!t&&e!==`head`,T=`x-brand`,E=t=>{let{[T]:n}=e.get(t)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},D=t=>{let{examples:n}=e.get(t)||{};return Array.isArray(n)?n:[]},O=Symbol(`Buffer`),k=()=>t.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[T]:O}),A=Symbol(`DateIn`),ae=({examples:e,...n}={})=>t.union([t.iso.date(),t.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(t.date()).meta({...n,[T]:A}),j=Symbol(`DateOut`),M=(e={})=>t.date().transform(e=>e.toISOString()).pipe(t.iso.datetime()).meta({...e,[T]:j});var N=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},oe=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},P=class extends Error{name=`IOSchemaError`},se=class extends P{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},F=class extends P{cause;name=`OutputValidationError`;constructor(e){let n=new t.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(v(n),{cause:e}),this.cause=e}},I=class extends P{cause;name=`InputValidationError`;constructor(e){super(v(e),{cause:e}),this.cause=e}},L=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(v(e),{cause:e}),this.cause=e,this.handled=t}},ce=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const R=Symbol(`Form`),le=e=>(e instanceof t.ZodObject?e:t.object(e)).meta({[T]:R}),z=Symbol(`Upload`),B=e=>C(e)&&`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,V=()=>t.custom(e=>B(e)&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).meta({[T]:z}),H=Symbol(`Raw`),U=t.object({raw:k()}),W=e=>U.extend(e).meta({[T]:H});function ue(e){return e?W(e):U.meta({[T]:H})}const G=(e,{io:r,condition:i})=>n.tryCatch(()=>void t.toJSONSchema(e,{io:r,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new se(e)}}),e=>e.cause)(),de=(e,{io:r})=>{let i=[t.toJSONSchema(e,{io:r,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(n.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...n.values(t))}n.is(Array,t)&&i.push(...n.values(t))}return!1},fe=e=>G(e,{condition:e=>{let t=E(e);return typeof t==`symbol`&&[z,H,R].includes(t)},io:`input`}),pe=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],me=(e,t)=>G(e,{io:t,condition:e=>{let n=E(e),{type:r}=e._zod.def;return!!(pe.includes(r)||n===O||t===`input`&&(r===`date`||n===j)||t===`output`&&(n===A||n===H||n===z))}});var he=class{},K=class extends he{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...n}){try{let t=await(this.#e||d).parseAsync(e);return this.#n({...n,input:t})}catch(e){throw e instanceof t.ZodError?new I(e):e}}},q=class extends K{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:i,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(i,a))},u=e(i,a,l);return r(u)&&u.catch(l),o}})}};const ge=(e,{variant:n,args:r,...i})=>{if(typeof e==`function`&&(e=e(...r)),e instanceof t.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new L(Error(`At least one ${n} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},_e=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),ve=e=>a(e)?e:i(e instanceof I?400:500,v(e),{cause:e.cause||e}),ye=e=>w()&&!e.expose?i(e.statusCode).message:e.message,be=e=>Object.entries(e._zod.def.shape).reduce((e,[t,r])=>b(e,D(r).map(n.objOf(t)),([e,t])=>({...e,...t})),[]);var J=class{nest(e){return{...e,"":this}}},xe=class r extends J{#e;#t;#n=n.once(()=>{if(D(this.#e.outputSchema).length||!y(this.#e.outputSchema,`object`))return;let t=be(this.#e.outputSchema);if(!t.length)return;let n=this.#e.outputSchema.meta();e.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:t})});constructor(e){super(),this.#e=e}#r(e){return new r({...this.#e,...e})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get summary(){return this.#e.summary}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=fe(this.#e.inputSchema);if(e){let t=E(e);if(t===z)return`upload`;if(t===H)return`raw`;if(t===R)return`form`}return`json`})()}getResponses(e){return e===`positive`&&this.#n(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new F(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof q))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...n}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new I(e):e}return this.#e.handler({...n,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=m(e),a={},o,s=g(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:_(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const Y={positive:200,negative:400},Se=Object.keys(Y);function Ce(e){return e instanceof t.ZodType?{schema:e}:e}var X=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,o.static(...this.#e))}};const we=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},Z=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&u(t)?[n,t]:[e]},Te=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Q=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&u(t)&&r instanceof J?[`/`,t]:Z(t);return[[n||``].concat(Te(i)||[]).join(`/`),r,a]}),Ee=(e,t)=>{throw new N(`Route with explicit method can only be assigned with Endpoint`,e,t)},De=(e,t,n)=>{if(!(!n||n.includes(e)))throw new N(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new N(`Route has a duplicate`,e,t);n.add(r)},Oe=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Q(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof J)if(c)$(c,o,a),De(c,o,s.methods),n(c,o,s);else{let{methods:e=[`get`]}=s;for(let t of e)$(t,o,a),n(t,o,s)}else c&&Ee(c,o),s instanceof X?r&&s.apply(o,r):i.splice(e+1,0,...Q(t,s,o))}};export{A,v as B,ce as C,M as D,N as E,b as F,y as G,re as H,d as I,ie as J,S as K,_ as L,O as M,E as N,j as O,D as P,s as Q,g as R,I as S,L as T,C as U,ee as V,w as W,l as X,x as Y,u as Z,ue as _,Y as a,le as b,ve as c,ge as d,q as f,H as g,de as h,Ce as i,k as j,ae as k,ye as l,me as m,we as n,Se as o,K as p,f as q,X as r,xe as s,Oe as t,_e as u,z as v,F as w,oe as x,V as y,h as z};
|
|
@@ -31,6 +31,10 @@ interface ApiResponse<S extends z.ZodType> {
|
|
|
31
31
|
* */
|
|
32
32
|
mimeType?: string | [string, ...string[]] | null;
|
|
33
33
|
}
|
|
34
|
+
/** @desc Creates an ApiResponse from a schema. */
|
|
35
|
+
declare function createApiResponse<S extends z.ZodType>(schema: S): ApiResponse<S>;
|
|
36
|
+
/** @desc Convenience method for asserting ApiResponse. */
|
|
37
|
+
declare function createApiResponse<S extends z.ZodType>(response: ApiResponse<S>): ApiResponse<S>;
|
|
34
38
|
declare const severity: {
|
|
35
39
|
debug: number;
|
|
36
40
|
info: number;
|
|
@@ -699,44 +703,37 @@ interface Routing {
|
|
|
699
703
|
[K: string]: Routing | AbstractEndpoint | ServeStatic;
|
|
700
704
|
}
|
|
701
705
|
export {
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
FinalInputSchema as
|
|
711
|
-
|
|
712
|
-
arrayResultHandler as O,
|
|
713
|
-
ClientMethod as P,
|
|
714
|
-
LoggerOverrides as R,
|
|
715
|
-
AppConfig as S,
|
|
716
|
-
createConfig as T,
|
|
717
|
-
EmptySchema as _,
|
|
706
|
+
AbstractLogger as A,
|
|
707
|
+
ensureHttpError as C,
|
|
708
|
+
ClientMethod as D,
|
|
709
|
+
IOSchema as E,
|
|
710
|
+
ResponseVariant as M,
|
|
711
|
+
createApiResponse as N,
|
|
712
|
+
Method as O,
|
|
713
|
+
defaultResultHandler as S,
|
|
714
|
+
FinalInputSchema as T,
|
|
715
|
+
ServerConfig as _,
|
|
718
716
|
Handler as a,
|
|
719
|
-
|
|
717
|
+
ResultHandler as b,
|
|
720
718
|
Middleware as c,
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
719
|
+
FlatObject as d,
|
|
720
|
+
Tag as f,
|
|
721
|
+
CommonConfig as g,
|
|
722
|
+
AppConfig as h,
|
|
725
723
|
Endpoint as i,
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
724
|
+
LoggerOverrides as j,
|
|
725
|
+
BuiltinLogger as k,
|
|
726
|
+
EmptyObject as l,
|
|
727
|
+
getMessageFromError as m,
|
|
730
728
|
ServeStatic as n,
|
|
731
729
|
AbstractMiddleware as o,
|
|
732
|
-
|
|
730
|
+
TagOverrides as p,
|
|
733
731
|
AbstractEndpoint as r,
|
|
734
732
|
ExpressMiddleware as s,
|
|
735
733
|
Routing as t,
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
ApiResponse as z,
|
|
734
|
+
EmptySchema as u,
|
|
735
|
+
createConfig as v,
|
|
736
|
+
Extension as w,
|
|
737
|
+
arrayResultHandler as x,
|
|
738
|
+
AbstractResultHandler as y,
|
|
742
739
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "29.0.0-beta.
|
|
3
|
+
"version": "29.0.0-beta.5",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"node": "^22.19.0 || ^24.11.0 || ^26.0.0"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"ansis": "^4.
|
|
48
|
+
"ansis": "^4.3.1",
|
|
49
49
|
"node-mocks-http": "^1.18.0",
|
|
50
50
|
"openapi3-ts": "^4.6.0",
|
|
51
51
|
"ramda": "^0.32.0"
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"@types/compression": "^1.7.5",
|
|
55
55
|
"@types/cookie-parser": "^1.4.10",
|
|
56
|
-
"@types/express": "^5.0.
|
|
56
|
+
"@types/express": "^5.0.6",
|
|
57
57
|
"@types/express-fileupload": "^1.5.0",
|
|
58
58
|
"@types/http-errors": "^2.0.2",
|
|
59
59
|
"compression": "^1.8.0",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"http-errors": "^2.0.1",
|
|
65
65
|
"typescript": "^5.1.3 || ^6.0.2",
|
|
66
66
|
"zod": "^4.3.4",
|
|
67
|
-
"@express-zod-api/zod-plugin": "^6.0.0
|
|
67
|
+
"@express-zod-api/zod-plugin": "^6.0.0"
|
|
68
68
|
},
|
|
69
69
|
"peerDependenciesMeta": {
|
|
70
70
|
"@express-zod-api/zod-plugin": {
|
|
@@ -125,7 +125,7 @@
|
|
|
125
125
|
"typescript": "^6.0.2",
|
|
126
126
|
"undici": "^8.2.0",
|
|
127
127
|
"zod": "^4.4.3",
|
|
128
|
-
"@express-zod-api/zod-plugin": "^6.0.0
|
|
128
|
+
"@express-zod-api/zod-plugin": "^6.0.0"
|
|
129
129
|
},
|
|
130
130
|
"keywords": [
|
|
131
131
|
"nodejs",
|