express-zod-api 9.2.1 → 10.0.0-beta2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +62 -0
- package/README.md +28 -20
- package/SECURITY.md +14 -13
- package/dist/esm/index.js +58 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/index.d.ts +776 -21
- package/dist/index.js +55 -69
- package/dist/index.js.map +1 -1
- package/package.json +31 -25
- package/dist/api-response.d.ts +0 -16
- package/dist/api-response.js +0 -3
- package/dist/api-response.js.map +0 -1
- package/dist/client-helpers.d.ts +0 -23
- package/dist/client-helpers.js +0 -71
- package/dist/client-helpers.js.map +0 -1
- package/dist/client.d.ts +0 -15
- package/dist/client.js +0 -120
- package/dist/client.js.map +0 -1
- package/dist/common-helpers.d.ts +0 -46
- package/dist/common-helpers.js +0 -207
- package/dist/common-helpers.js.map +0 -1
- package/dist/config-type.d.ts +0 -59
- package/dist/config-type.js +0 -11
- package/dist/config-type.js.map +0 -1
- package/dist/date-in-schema.d.ts +0 -11
- package/dist/date-in-schema.js +0 -46
- package/dist/date-in-schema.js.map +0 -1
- package/dist/date-out-schema.d.ts +0 -10
- package/dist/date-out-schema.js +0 -31
- package/dist/date-out-schema.js.map +0 -1
- package/dist/depends-on-method.d.ts +0 -10
- package/dist/depends-on-method.js +0 -32
- package/dist/depends-on-method.js.map +0 -1
- package/dist/endpoint.d.ts +0 -98
- package/dist/endpoint.js +0 -261
- package/dist/endpoint.js.map +0 -1
- package/dist/endpoints-factory.d.ts +0 -161
- package/dist/endpoints-factory.js +0 -68
- package/dist/endpoints-factory.js.map +0 -1
- package/dist/errors.d.ts +0 -35
- package/dist/errors.js +0 -64
- package/dist/errors.js.map +0 -1
- package/dist/extend-zod.d.ts +0 -22
- package/dist/extend-zod.js +0 -33
- package/dist/extend-zod.js.map +0 -1
- package/dist/file-schema.d.ts +0 -23
- package/dist/file-schema.js +0 -55
- package/dist/file-schema.js.map +0 -1
- package/dist/io-schema.d.ts +0 -16
- package/dist/io-schema.js +0 -21
- package/dist/io-schema.js.map +0 -1
- package/dist/logger.d.ts +0 -3
- package/dist/logger.js +0 -54
- package/dist/logger.js.map +0 -1
- package/dist/logical-container.d.ts +0 -16
- package/dist/logical-container.js +0 -85
- package/dist/logical-container.js.map +0 -1
- package/dist/metadata.d.ts +0 -27
- package/dist/metadata.js +0 -58
- package/dist/metadata.js.map +0 -1
- package/dist/method.d.ts +0 -8
- package/dist/method.js +0 -5
- package/dist/method.js.map +0 -1
- package/dist/middleware.d.ts +0 -32
- package/dist/middleware.js +0 -16
- package/dist/middleware.js.map +0 -1
- package/dist/mime.d.ts +0 -2
- package/dist/mime.js +0 -10
- package/dist/mime.js.map +0 -1
- package/dist/mock.d.ts +0 -38
- package/dist/mock.js +0 -66
- package/dist/mock.js.map +0 -1
- package/dist/open-api-helpers.d.ts +0 -83
- package/dist/open-api-helpers.js +0 -621
- package/dist/open-api-helpers.js.map +0 -1
- package/dist/open-api.d.ts +0 -25
- package/dist/open-api.js +0 -98
- package/dist/open-api.js.map +0 -1
- package/dist/result-handler.d.ts +0 -151
- package/dist/result-handler.js +0 -71
- package/dist/result-handler.js.map +0 -1
- package/dist/routing-walker.d.ts +0 -12
- package/dist/routing-walker.js +0 -55
- package/dist/routing-walker.js.map +0 -1
- package/dist/routing.d.ts +0 -15
- package/dist/routing.js +0 -25
- package/dist/routing.js.map +0 -1
- package/dist/schema-walker.d.ts +0 -23
- package/dist/schema-walker.js +0 -26
- package/dist/schema-walker.js.map +0 -1
- package/dist/security.d.ts +0 -72
- package/dist/security.js +0 -3
- package/dist/security.js.map +0 -1
- package/dist/serve-static.d.ts +0 -9
- package/dist/serve-static.js +0 -17
- package/dist/serve-static.js.map +0 -1
- package/dist/server.d.ts +0 -20
- package/dist/server.js +0 -131
- package/dist/server.js.map +0 -1
- package/dist/startup-logo.d.ts +0 -1
- package/dist/startup-logo.js +0 -27
- package/dist/startup-logo.js.map +0 -1
- package/dist/upload-schema.d.ts +0 -11
- package/dist/upload-schema.js +0 -42
- package/dist/upload-schema.js.map +0 -1
- package/dist/zts-helpers.d.ts +0 -37
- package/dist/zts-helpers.js +0 -60
- package/dist/zts-helpers.js.map +0 -1
- package/dist/zts.d.ts +0 -31
- package/dist/zts.js +0 -147
- package/dist/zts.js.map +0 -1
- package/dist-esm/api-response.js +0 -2
- package/dist-esm/api-response.js.map +0 -1
- package/dist-esm/client-helpers.js +0 -48
- package/dist-esm/client-helpers.js.map +0 -1
- package/dist-esm/client.js +0 -113
- package/dist-esm/client.js.map +0 -1
- package/dist-esm/common-helpers.js +0 -188
- package/dist-esm/common-helpers.js.map +0 -1
- package/dist-esm/config-type.js +0 -7
- package/dist-esm/config-type.js.map +0 -1
- package/dist-esm/date-in-schema.js +0 -42
- package/dist-esm/date-in-schema.js.map +0 -1
- package/dist-esm/date-out-schema.js +0 -27
- package/dist-esm/date-out-schema.js.map +0 -1
- package/dist-esm/depends-on-method.js +0 -28
- package/dist-esm/depends-on-method.js.map +0 -1
- package/dist-esm/endpoint.js +0 -256
- package/dist-esm/endpoint.js.map +0 -1
- package/dist-esm/endpoints-factory.js +0 -64
- package/dist-esm/endpoints-factory.js.map +0 -1
- package/dist-esm/errors.js +0 -54
- package/dist-esm/errors.js.map +0 -1
- package/dist-esm/extend-zod.js +0 -16
- package/dist-esm/extend-zod.js.map +0 -1
- package/dist-esm/file-schema.js +0 -51
- package/dist-esm/file-schema.js.map +0 -1
- package/dist-esm/index.js +0 -19
- package/dist-esm/index.js.map +0 -1
- package/dist-esm/io-schema.js +0 -17
- package/dist-esm/io-schema.js.map +0 -1
- package/dist-esm/logger.js +0 -47
- package/dist-esm/logger.js.map +0 -1
- package/dist-esm/logical-container.js +0 -78
- package/dist-esm/logical-container.js.map +0 -1
- package/dist-esm/metadata.js +0 -51
- package/dist-esm/metadata.js.map +0 -1
- package/dist-esm/method.js +0 -2
- package/dist-esm/method.js.map +0 -1
- package/dist-esm/middleware.js +0 -12
- package/dist-esm/middleware.js.map +0 -1
- package/dist-esm/mime.js +0 -4
- package/dist-esm/mime.js.map +0 -1
- package/dist-esm/mock.js +0 -57
- package/dist-esm/mock.js.map +0 -1
- package/dist-esm/open-api-helpers.js +0 -575
- package/dist-esm/open-api-helpers.js.map +0 -1
- package/dist-esm/open-api.js +0 -94
- package/dist-esm/open-api.js.map +0 -1
- package/dist-esm/package.json +0 -1
- package/dist-esm/result-handler.js +0 -66
- package/dist-esm/result-handler.js.map +0 -1
- package/dist-esm/routing-walker.js +0 -51
- package/dist-esm/routing-walker.js.map +0 -1
- package/dist-esm/routing.js +0 -21
- package/dist-esm/routing.js.map +0 -1
- package/dist-esm/schema-walker.js +0 -22
- package/dist-esm/schema-walker.js.map +0 -1
- package/dist-esm/security.js +0 -2
- package/dist-esm/security.js.map +0 -1
- package/dist-esm/serve-static.js +0 -10
- package/dist-esm/serve-static.js.map +0 -1
- package/dist-esm/server.js +0 -98
- package/dist-esm/server.js.map +0 -1
- package/dist-esm/startup-logo.js +0 -23
- package/dist-esm/startup-logo.js.map +0 -1
- package/dist-esm/upload-schema.js +0 -38
- package/dist-esm/upload-schema.js.map +0 -1
- package/dist-esm/zts-helpers.js +0 -50
- package/dist-esm/zts-helpers.js.map +0 -1
- package/dist-esm/zts.js +0 -140
- package/dist-esm/zts.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6CAA2D;AAAlD,2GAAA,YAAY,OAAA;AACrB,uCAA8C;AAArC,4GAAA,gBAAgB,OAAA;AAEzB,yDAAgF;AAAvE,qHAAA,gBAAgB,OAAA;AAAE,4HAAA,uBAAuB,OAAA;AAElD,mDAI0B;AAFxB,qHAAA,mBAAmB,OAAA;AACnB,wHAAA,sBAAsB,OAAA;AAExB,mCAAwC;AAA/B,sGAAA,YAAY,OAAA;AACrB,2CAAgD;AAAvC,8GAAA,gBAAgB,OAAA;AACzB,mDAA6E;AAApE,qHAAA,mBAAmB,OAAA;AAAE,sHAAA,oBAAoB,OAAA;AAClD,yDAAsD;AAA7C,oHAAA,eAAe,OAAA;AACxB,+CAA6C;AAApC,2GAAA,WAAW,OAAA;AAEpB,mCAAuD;AAA9C,sGAAA,YAAY,OAAA;AAAE,uGAAA,aAAa,OAAA;AACpC,uCAAqC;AAA5B,mGAAA,OAAO,OAAA;AAChB,mCAMkB;AALhB,sGAAA,YAAY,OAAA;AACZ,8GAAA,oBAAoB,OAAA;AACpB,sGAAA,YAAY,OAAA;AACZ,+GAAA,qBAAqB,OAAA;AACrB,8GAAA,oBAAoB,OAAA;AAEtB,uCAAsC;AAA7B,oGAAA,QAAQ,OAAA;AACjB,+BAAsC;AAA7B,oGAAA,YAAY,OAAA;AACrB,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AAEf,gDAAkC;AAGR,cAAC;AAF3B,8DAA0C;AAEjC,0BAFF,qBAAe,CAEE"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config-type.ts","../src/endpoint.ts","../src/common-helpers.ts","../src/metadata.ts","../src/mime.ts","../src/upload-schema.ts","../src/errors.ts","../src/logical-container.ts","../src/result-handler.ts","../src/method.ts","../src/endpoints-factory.ts","../src/io-schema.ts","../src/middleware.ts","../src/logger.ts","../src/depends-on-method.ts","../src/serve-static.ts","../src/routing-walker.ts","../src/startup-logo.ts","../src/routing.ts","../src/server.ts","../src/open-api.ts","../src/open-api-helpers.ts","../src/date-in-schema.ts","../src/schema-walker.ts","../src/mock.ts","../src/client.ts","../src/client-helpers.ts","../src/zts.ts","../src/zts-helpers.ts","../src/date-out-schema.ts","../src/file-schema.ts","../src/ez-namespace.ts"],"sourcesContent":["export { createConfig, LoggerConfig } from \"./config-type\";\nexport { AbstractEndpoint } from \"./endpoint\";\nexport { Method } from \"./method\";\nexport { EndpointsFactory, defaultEndpointsFactory } from \"./endpoints-factory\";\nexport { IOSchema } from \"./io-schema\";\nexport {\n FlatObject,\n getMessageFromError,\n getStatusCodeFromError,\n} from \"./common-helpers\";\nexport { createLogger } from \"./logger\";\nexport { createMiddleware } from \"./middleware\";\nexport { createResultHandler, defaultResultHandler } from \"./result-handler\";\nexport { DependsOnMethod } from \"./depends-on-method\";\nexport { ServeStatic } from \"./serve-static\";\nexport { Routing } from \"./routing\";\nexport { createServer, attachRouting } from \"./server\";\nexport { OpenAPI } from \"./open-api\";\nexport {\n OpenAPIError,\n DependsOnMethodError,\n RoutingError,\n OutputValidationError,\n InputValidationError,\n} from \"./errors\";\nexport { withMeta } from \"./metadata\";\nexport { testEndpoint } from \"./mock\";\nexport { Client } from \"./client\";\nexport { ez } from \"./ez-namespace\";\n\nimport createHttpError from \"http-errors\";\nexport { createHttpError };\n","import compression from \"compression\";\nimport { NextHandleFunction } from \"connect\";\nimport { Express, Request } from \"express\";\nimport fileUpload from \"express-fileupload\";\nimport { ServerOptions } from \"https\";\nimport { Logger } from \"winston\";\nimport { AbstractEndpoint } from \"./endpoint\";\nimport { Method } from \"./method\";\nimport { ResultHandlerDefinition } from \"./result-handler\";\n\nexport const loggerLevels = {\n silent: true,\n warn: true,\n debug: true,\n};\n\nexport interface LoggerConfig {\n level: keyof typeof loggerLevels;\n color: boolean;\n}\n\ntype UploadOptions = Pick<\n fileUpload.Options,\n | \"createParentPath\"\n | \"uriDecodeFileNames\"\n | \"safeFileNames\"\n | \"preserveExtension\"\n | \"useTempFiles\"\n | \"tempFileDir\"\n | \"debug\"\n | \"uploadTimeout\"\n>;\n\ntype CompressionOptions = Pick<\n compression.CompressionOptions,\n \"threshold\" | \"level\" | \"strategy\" | \"chunkSize\" | \"memLevel\"\n>;\n\nexport interface ServerConfig {\n server: {\n // server configuration\n listen: number | string; // port or socket\n jsonParser?: NextHandleFunction; // custom JSON parser, default: express.json()\n upload?: boolean | UploadOptions; // enable or configure uploads handling\n compression?: boolean | CompressionOptions; // enable or configure response compression\n };\n https?: {\n // enables HTTPS server as well\n options: ServerOptions; // at least \"cert\" and \"key\" options required\n listen: number | string; // port or socket\n };\n}\n\nexport interface AppConfig {\n app: Express; // or your custom express app\n}\n\nexport type InputSource = keyof Pick<\n Request,\n \"query\" | \"body\" | \"files\" | \"params\"\n>;\nexport type InputSources = Record<Method, InputSource[]>;\n\ntype Headers = Record<string, string>;\ntype HeadersProvider = (params: {\n defaultHeaders: Headers; // the default headers to be overridden\n request: Request;\n endpoint: AbstractEndpoint;\n logger: Logger;\n}) => Headers | Promise<Headers>;\n\nexport type TagsConfig<TAG extends string> = Record<\n TAG,\n string | { description: string; url?: string }\n>;\n\nexport interface CommonConfig<TAG extends string = string> {\n // enable cross-origin resource sharing\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\n // you can override the default CORS headers by setting up a provider function here\n cors: boolean | HeadersProvider;\n // custom ResultHandlerDefinition for common errors,\n // default: defaultResultHandler()\n errorHandler?: ResultHandlerDefinition<any, any>;\n // logger configuration or your custom winston logger\n logger: LoggerConfig | Logger;\n // you can disable the startup logo, default: true\n startupLogo?: boolean;\n // what request properties are combined into input for endpoints and middlewares\n // the order matters: priority from lowest to highest\n // default: { get: [query, params], post: [body, params, files],\n // put: [body, params], patch: [body, params], delete: [query, params] }\n inputSources?: Partial<InputSources>;\n // optional endpoints tagging configuration, example: { users: \"Everything about the users\" }\n tags?: TagsConfig<TAG>;\n}\n\nexport const createConfig = <\n TAG extends string,\n T extends (ServerConfig | AppConfig) & CommonConfig<TAG>\n>(\n config: T\n): T => config;\n","import { Request, Response } from \"express\";\nimport { Logger } from \"winston\";\nimport { z } from \"zod\";\nimport { ApiResponse } from \"./api-response\";\nimport { CommonConfig } from \"./config-type\";\nimport {\n IOSchemaError,\n InputValidationError,\n OutputValidationError,\n ResultHandlerError,\n} from \"./errors\";\nimport {\n FlatObject,\n getActualMethod,\n getInput,\n hasTopLevelTransformingEffect,\n hasUpload,\n makeErrorFromAnything,\n} from \"./common-helpers\";\nimport { IOSchema } from \"./io-schema\";\nimport { LogicalContainer, combineContainers } from \"./logical-container\";\nimport { AuxMethod, Method, MethodsDefinition } from \"./method\";\nimport { AnyMiddlewareDef } from \"./middleware\";\nimport { mimeJson, mimeMultipart } from \"./mime\";\nimport {\n ResultHandlerDefinition,\n defaultStatusCodes,\n lastResortHandler,\n} from \"./result-handler\";\nimport { Security } from \"./security\";\n\nconst getMimeTypesFromApiResponse = <S extends z.ZodTypeAny>(\n subject: S | ApiResponse<S>,\n fallback = [mimeJson]\n) => {\n if (subject instanceof z.ZodType) {\n return fallback;\n }\n const { mimeTypes, mimeType } = subject;\n return mimeType ? [mimeType] : mimeTypes || fallback;\n};\n\nexport type Handler<IN, OUT, OPT> = (params: {\n input: IN;\n options: OPT;\n logger: Logger;\n}) => Promise<OUT>;\n\ntype DescriptionVariant = \"short\" | \"long\";\ntype IOVariant = \"input\" | \"output\";\ntype ResponseVariant = \"positive\" | \"negative\";\ntype MimeVariant = Extract<IOVariant, \"input\"> | ResponseVariant;\n\nexport abstract class AbstractEndpoint {\n public abstract execute(params: {\n request: Request;\n response: Response;\n logger: Logger;\n config: CommonConfig;\n }): Promise<void>;\n public abstract getDescription(\n variant: DescriptionVariant\n ): string | undefined;\n public abstract getMethods(): Method[];\n public abstract getSchema(variant: IOVariant): IOSchema;\n public abstract getSchema(variant: ResponseVariant): z.ZodTypeAny;\n public abstract getMimeTypes(variant: MimeVariant): string[];\n public abstract getStatusCode(variant: ResponseVariant): number;\n public abstract getSecurity(): LogicalContainer<Security>;\n public abstract getScopes(): string[];\n public abstract getTags(): string[];\n public abstract _setSiblingMethods(methods: Method[]): void;\n}\n\ntype EndpointProps<\n IN extends IOSchema,\n OUT extends IOSchema,\n OPT extends FlatObject,\n M extends Method,\n POS extends z.ZodTypeAny,\n NEG extends z.ZodTypeAny,\n SCO extends string,\n TAG extends string\n> = {\n middlewares: AnyMiddlewareDef[];\n inputSchema: IN;\n outputSchema: OUT;\n handler: Handler<z.output<IN>, z.input<OUT>, OPT>;\n resultHandler: ResultHandlerDefinition<POS, NEG>;\n description?: string;\n shortDescription?: string;\n} & ({ scopes?: SCO[] } | { scope?: SCO }) &\n ({ tags?: TAG[] } | { tag?: TAG }) &\n MethodsDefinition<M>;\n\nexport class Endpoint<\n IN extends IOSchema,\n OUT extends IOSchema,\n OPT extends FlatObject,\n M extends Method,\n POS extends z.ZodTypeAny,\n NEG extends z.ZodTypeAny,\n SCO extends string,\n TAG extends string\n> extends AbstractEndpoint {\n protected readonly descriptions: Record<\n DescriptionVariant,\n string | undefined\n >;\n protected readonly methods: M[] = [];\n protected siblingMethods: Method[] = [];\n protected readonly middlewares: AnyMiddlewareDef[] = [];\n protected readonly mimeTypes: Record<MimeVariant, string[]>;\n protected readonly statusCodes: Record<ResponseVariant, number>;\n protected readonly handler: Handler<z.output<IN>, z.input<OUT>, OPT>;\n protected readonly resultHandler: ResultHandlerDefinition<POS, NEG>;\n protected readonly schemas: {\n input: IN;\n output: OUT;\n positive: POS;\n negative: NEG;\n };\n protected readonly scopes: SCO[] = [];\n protected readonly tags: TAG[] = [];\n\n constructor({\n middlewares,\n inputSchema,\n outputSchema,\n handler,\n resultHandler,\n description,\n shortDescription,\n ...rest\n }: EndpointProps<IN, OUT, OPT, M, POS, NEG, SCO, TAG>) {\n super();\n [\n { name: \"input schema\", schema: inputSchema },\n { name: \"output schema\", schema: outputSchema },\n ].forEach(({ name, schema }) => {\n if (hasTopLevelTransformingEffect(schema)) {\n throw new IOSchemaError(\n `Using transformations on the top level of endpoint ${name} is not allowed.`\n );\n }\n });\n this.middlewares = middlewares;\n const apiResponse = {\n positive: resultHandler.getPositiveResponse(outputSchema),\n negative: resultHandler.getNegativeResponse(),\n };\n this.mimeTypes = {\n input: hasUpload(inputSchema) ? [mimeMultipart] : [mimeJson],\n positive: getMimeTypesFromApiResponse(apiResponse.positive),\n negative: getMimeTypesFromApiResponse(apiResponse.negative),\n };\n this.schemas = {\n input: inputSchema,\n output: outputSchema,\n positive:\n apiResponse.positive instanceof z.ZodType\n ? apiResponse.positive\n : apiResponse.positive.schema,\n negative:\n apiResponse.negative instanceof z.ZodType\n ? apiResponse.negative\n : apiResponse.negative.schema,\n };\n this.statusCodes = {\n positive:\n apiResponse.positive instanceof z.ZodType\n ? defaultStatusCodes.positive\n : apiResponse.positive.statusCode || defaultStatusCodes.positive,\n negative:\n apiResponse.negative instanceof z.ZodType\n ? defaultStatusCodes.negative\n : apiResponse.negative.statusCode || defaultStatusCodes.negative,\n };\n this.handler = handler;\n this.resultHandler = resultHandler;\n this.descriptions = { long: description, short: shortDescription };\n if (\"scopes\" in rest && rest.scopes) {\n this.scopes.push(...rest.scopes);\n }\n if (\"scope\" in rest && rest.scope) {\n this.scopes.push(rest.scope);\n }\n if (\"tags\" in rest && rest.tags) {\n this.tags.push(...rest.tags);\n }\n if (\"tag\" in rest && rest.tag) {\n this.tags.push(rest.tag);\n }\n if (\"methods\" in rest) {\n this.methods = rest.methods;\n } else {\n this.methods = [rest.method];\n }\n }\n\n /**\n * @desc Sets the other methods supported by the same path. Used by Routing in DependsOnMethod case, for options.\n * @deprecated This method is for internal needs of the library, please avoid using it.\n * */\n public override _setSiblingMethods(methods: Method[]): void {\n this.siblingMethods = methods;\n }\n\n public override getDescription(variant: DescriptionVariant) {\n return this.descriptions[variant];\n }\n\n public override getMethods(): M[] {\n return this.methods;\n }\n\n public override getSchema(variant: \"input\"): IN;\n public override getSchema(variant: \"output\"): OUT;\n public override getSchema(variant: \"positive\"): POS;\n public override getSchema(variant: \"negative\"): NEG;\n public override getSchema(variant: IOVariant | ResponseVariant) {\n return this.schemas[variant];\n }\n\n public override getMimeTypes(variant: MimeVariant) {\n return this.mimeTypes[variant];\n }\n\n public override getStatusCode(variant: ResponseVariant) {\n return this.statusCodes[variant];\n }\n\n public override getSecurity() {\n return this.middlewares.reduce<LogicalContainer<Security>>(\n (acc, middleware) =>\n middleware.security ? combineContainers(acc, middleware.security) : acc,\n { and: [] }\n );\n }\n\n public override getScopes(): SCO[] {\n return this.scopes;\n }\n\n public override getTags(): TAG[] {\n return this.tags;\n }\n\n #getDefaultCorsHeaders(): Record<string, string> {\n const accessMethods = (this.methods as Array<Method | AuxMethod>)\n .concat(this.siblingMethods)\n .concat(\"options\")\n .join(\", \")\n .toUpperCase();\n return {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": accessMethods,\n \"Access-Control-Allow-Headers\": \"content-type\",\n };\n }\n\n async #parseOutput(output: any) {\n try {\n return await this.schemas.output.parseAsync(output);\n } catch (e) {\n if (e instanceof z.ZodError) {\n throw new OutputValidationError(e);\n }\n throw e;\n }\n }\n\n async #runMiddlewares({\n method,\n input,\n request,\n response,\n logger,\n }: {\n method: Method | AuxMethod;\n input: Readonly<any>; // Issue #673: input is immutable, since this.inputSchema is combined with ones of middlewares\n request: Request;\n response: Response;\n logger: Logger;\n }) {\n const options: any = {};\n let isStreamClosed = false;\n for (const def of this.middlewares) {\n if (method === \"options\" && def.type === \"proprietary\") {\n continue;\n }\n let finalInput: any;\n try {\n finalInput = await def.input.parseAsync(input);\n } catch (e) {\n if (e instanceof z.ZodError) {\n throw new InputValidationError(e);\n }\n throw e;\n }\n Object.assign(\n options,\n await def.middleware({\n input: finalInput,\n options,\n request,\n response,\n logger,\n })\n );\n isStreamClosed = \"writableEnded\" in response && response.writableEnded;\n if (isStreamClosed) {\n logger.warn(\n `The middleware ${def.middleware.name} has closed the stream. Accumulated options:`,\n options\n );\n break;\n }\n }\n return { options, isStreamClosed };\n }\n\n async #parseAndRunHandler({\n input,\n options,\n logger,\n }: {\n input: Readonly<any>;\n options: any;\n logger: Logger;\n }) {\n let finalInput: z.output<IN>; // final input types transformations for handler\n try {\n finalInput = (await this.schemas.input.parseAsync(input)) as z.output<IN>;\n } catch (e) {\n if (e instanceof z.ZodError) {\n throw new InputValidationError(e);\n }\n throw e;\n }\n return this.handler({\n input: finalInput,\n options,\n logger,\n });\n }\n\n async #handleResult({\n error,\n request,\n response,\n logger,\n input,\n output,\n }: {\n error: Error | null;\n request: Request;\n response: Response;\n logger: Logger;\n input: any;\n output: any;\n }) {\n try {\n await this.resultHandler.handler({\n error,\n output,\n request,\n response,\n logger,\n input,\n });\n } catch (e) {\n lastResortHandler({\n logger,\n response,\n error: new ResultHandlerError(makeErrorFromAnything(e).message, error),\n });\n }\n }\n\n public override async execute({\n request,\n response,\n logger,\n config,\n }: {\n request: Request;\n response: Response;\n logger: Logger;\n config: CommonConfig;\n }) {\n const method = getActualMethod(request);\n let output: any;\n let error: Error | null = null;\n if (config.cors) {\n let headers = this.#getDefaultCorsHeaders();\n if (typeof config.cors === \"function\") {\n headers = await config.cors({\n request,\n logger,\n endpoint: this,\n defaultHeaders: headers,\n });\n }\n for (const key in headers) {\n response.set(key, headers[key]);\n }\n }\n const input = getInput(request, config.inputSources);\n try {\n const { options, isStreamClosed } = await this.#runMiddlewares({\n method,\n input,\n request,\n response,\n logger,\n });\n if (isStreamClosed) {\n return;\n }\n if (method === \"options\") {\n response.status(200).end();\n return;\n }\n output = await this.#parseOutput(\n await this.#parseAndRunHandler({ input, options, logger })\n );\n } catch (e) {\n error = makeErrorFromAnything(e);\n }\n await this.#handleResult({\n input,\n output,\n request,\n response,\n error,\n logger,\n });\n }\n}\n","import { Request } from \"express\";\nimport { HttpError } from \"http-errors\";\nimport { z } from \"zod\";\nimport {\n CommonConfig,\n InputSource,\n InputSources,\n LoggerConfig,\n loggerLevels,\n} from \"./config-type\";\nimport { InputValidationError, OutputValidationError } from \"./errors\";\nimport { IOSchema } from \"./io-schema\";\nimport { getMeta } from \"./metadata\";\nimport { AuxMethod, Method } from \"./method\";\nimport { mimeMultipart } from \"./mime\";\nimport { ZodUpload } from \"./upload-schema\";\n\nexport type FlatObject = Record<string, any>;\n\n/** @see https://expressjs.com/en/guide/routing.html */\nexport const routePathParamsRegex = /:([A-Za-z0-9_]+)/g;\n\nfunction areFilesAvailable(request: Request) {\n const contentType = request.header(\"content-type\") || \"\";\n const isMultipart =\n contentType.slice(0, mimeMultipart.length).toLowerCase() === mimeMultipart;\n return \"files\" in request && isMultipart;\n}\n\nexport const defaultInputSources: InputSources = {\n get: [\"query\", \"params\"],\n post: [\"body\", \"params\", \"files\"],\n put: [\"body\", \"params\"],\n patch: [\"body\", \"params\"],\n delete: [\"query\", \"params\"],\n};\nconst fallbackInputSource: InputSource[] = [\"body\", \"query\", \"params\"];\n\nexport const getActualMethod = (request: Request) =>\n request.method.toLowerCase() as Method | AuxMethod;\n\nexport function getInput(\n request: Request,\n inputAssignment: CommonConfig[\"inputSources\"]\n): any {\n const method = getActualMethod(request);\n if (method === \"options\") {\n return {};\n }\n let props = fallbackInputSource;\n if (method in defaultInputSources) {\n props = defaultInputSources[method];\n }\n if (inputAssignment && method in inputAssignment) {\n props = inputAssignment[method] || props;\n }\n return props\n .filter((prop) => (prop === \"files\" ? areFilesAvailable(request) : true))\n .reduce(\n (carry, prop) => ({\n ...carry,\n ...request[prop],\n }),\n {}\n );\n}\n\nexport function isLoggerConfig(logger: any): logger is LoggerConfig {\n return (\n typeof logger === \"object\" &&\n \"level\" in logger &&\n \"color\" in logger &&\n Object.keys(loggerLevels).includes(logger.level) &&\n typeof logger.color === \"boolean\"\n );\n}\n\nexport function isValidDate(date: Date): boolean {\n return !isNaN(date.getTime());\n}\n\nexport function makeErrorFromAnything<T extends Error>(subject: T): T;\nexport function makeErrorFromAnything(subject: any): Error;\nexport function makeErrorFromAnything<T>(subject: T): Error {\n return subject instanceof Error\n ? subject\n : new Error(\n typeof subject === \"symbol\" ? subject.toString() : `${subject}`\n );\n}\n\nexport function getMessageFromError(error: Error): string {\n if (error instanceof z.ZodError) {\n return error.issues\n .map(({ path, message }) =>\n (path.length ? [path.join(\"/\")] : []).concat(message).join(\": \")\n )\n .join(\"; \");\n }\n if (error instanceof OutputValidationError) {\n const hasFirstField = error.originalError.issues[0]?.path.length > 0;\n return `output${hasFirstField ? \"/\" : \": \"}${error.message}`;\n }\n return error.message;\n}\n\nexport function getStatusCodeFromError(error: Error): number {\n if (error instanceof HttpError) {\n return error.statusCode;\n }\n if (error instanceof InputValidationError) {\n return 400;\n }\n return 500;\n}\n\ntype Examples<T extends z.ZodTypeAny> = Readonly<z.input<T>[] | z.output<T>[]>;\nexport const getExamples = <T extends z.ZodTypeAny>(\n schema: T,\n parseToOutput: boolean\n): Examples<T> => {\n const examples = getMeta(schema, \"examples\");\n if (examples === undefined) {\n return [];\n }\n return examples.reduce((carry, example) => {\n const parsedExample = schema.safeParse(example);\n return carry.concat(\n parsedExample.success\n ? parseToOutput\n ? parsedExample.data\n : example\n : []\n );\n }, [] as z.output<typeof schema>[]);\n};\n\nexport const combinations = <T extends any>(\n a: T[],\n b: T[]\n): { type: \"single\"; value: T[] } | { type: \"tuple\"; value: [T, T][] } => {\n if (a.length === 0) {\n return { type: \"single\", value: b };\n }\n if (b.length === 0) {\n return { type: \"single\", value: a };\n }\n const result: [T, T][] = [];\n for (const itemA of a) {\n for (const itemB of b) {\n result.push([itemA, itemB]);\n }\n }\n return { type: \"tuple\", value: result };\n};\n\nexport function getRoutePathParams(path: string): string[] {\n const match = path.match(routePathParamsRegex);\n if (!match) {\n return [];\n }\n return match.map((param) => param.slice(1));\n}\n\nconst reduceBool = (arr: boolean[]) =>\n arr.reduce((carry, bool) => carry || bool, false);\n\nexport function hasTopLevelTransformingEffect(schema: IOSchema): boolean {\n if (schema instanceof z.ZodEffects) {\n if (schema._def.effect.type !== \"refinement\") {\n return true;\n }\n }\n if (schema instanceof z.ZodUnion) {\n return reduceBool(schema.options.map(hasTopLevelTransformingEffect));\n }\n if (schema instanceof z.ZodIntersection) {\n return reduceBool(\n [schema._def.left, schema._def.right].map(hasTopLevelTransformingEffect)\n );\n }\n return false; // ZodObject left\n}\n\nexport function hasUpload(schema: z.ZodTypeAny): boolean {\n if (schema instanceof ZodUpload) {\n return true;\n }\n if (schema instanceof z.ZodObject) {\n return reduceBool(Object.values<z.ZodTypeAny>(schema.shape).map(hasUpload));\n }\n if (schema instanceof z.ZodUnion) {\n return reduceBool(schema.options.map(hasUpload));\n }\n if (schema instanceof z.ZodIntersection) {\n return reduceBool([schema._def.left, schema._def.right].map(hasUpload));\n }\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return hasUpload(schema.unwrap());\n }\n if (schema instanceof z.ZodEffects || schema instanceof z.ZodTransformer) {\n return hasUpload(schema._def.schema);\n }\n if (schema instanceof z.ZodRecord) {\n return hasUpload(schema._def.valueType);\n }\n if (schema instanceof z.ZodArray) {\n return hasUpload(schema._def.type);\n }\n if (schema instanceof z.ZodDefault) {\n return hasUpload(schema._def.innerType);\n }\n return false;\n}\n\n/**\n * @desc isNullable() and isOptional() validate the schema's input\n * @desc They always return true in case of coercion, which should be taken into account when depicting response\n */\nexport const hasCoercion = (schema: z.ZodTypeAny): boolean =>\n \"coerce\" in schema._def && typeof schema._def.coerce === \"boolean\"\n ? schema._def.coerce\n : false;\n\nexport const makeCleanId = (path: string, method: string, suffix?: string) => {\n return [method]\n .concat(path.split(\"/\"))\n .concat(suffix || [])\n .flatMap((entry) => entry.split(/[^A-Z0-9]/gi))\n .map(\n (entry) => entry.slice(0, 1).toUpperCase() + entry.slice(1).toLowerCase()\n )\n .join(\"\");\n};\n\nexport const tryToTransform = ({\n effect,\n sample,\n}: {\n effect: z.Effect<any> & { type: \"transform\" };\n sample: any;\n}) => {\n try {\n return typeof effect.transform(sample, {\n addIssue: () => {},\n path: [],\n });\n } catch (e) {\n return undefined;\n }\n};\n\n// obtaining the private helper type from Zod\nexport type ErrMessage = Exclude<\n Parameters<typeof z.ZodString.prototype.email>[0],\n undefined\n>;\n\n// the copy of the private Zod errorUtil.errToObj\nexport const errToObj = (message: ErrMessage | undefined) =>\n typeof message === \"string\" ? { message } : message || {};\n","import { combinations } from \"./common-helpers\";\nimport { z } from \"zod\";\nimport { clone, mergeDeepRight } from \"ramda\";\n\nexport const metaProp = \"expressZodApiMeta\";\ntype MetaProp = typeof metaProp;\n\nexport type MetaDef<T extends z.ZodTypeAny> = {\n [K in MetaProp]: {\n examples: z.input<T>[];\n };\n};\ntype MetaKey = keyof MetaDef<any>[MetaProp];\ntype MetaValue<T extends z.ZodTypeAny, K extends MetaKey> = Readonly<\n MetaDef<T>[MetaProp][K]\n>;\n\ntype ExampleSetter<T extends z.ZodTypeAny> = (\n example: z.input<T>\n) => WithMeta<T>;\n\n/**\n * @desc fixes the incompatibility of the ZodObject.keyof() method introduced in v3.17.9\n * @todo remove it if/when it will be compatible\n */\ntype MetaFixForStrippedObject<T> = T extends z.ZodObject<any>\n ? T & { keyof: z.ZodObject<any>[\"keyof\"] }\n : T;\n\ntype WithMeta<T extends z.ZodTypeAny> = MetaFixForStrippedObject<T> & {\n _def: T[\"_def\"] & MetaDef<T>;\n example: ExampleSetter<T>;\n};\n\n/** @desc it's the same approach as in zod's .describe() */\nconst cloneSchemaForMeta = <T extends z.ZodTypeAny>(schema: T): WithMeta<T> => {\n const This = (schema as any).constructor;\n const def = clone(schema._def) as MetaDef<T>;\n def[metaProp] = def[metaProp] || { examples: [] };\n return new This(def) as WithMeta<T>;\n};\n\nexport const withMeta = <T extends z.ZodTypeAny>(schema: T): WithMeta<T> => {\n const copy = cloneSchemaForMeta(schema);\n Object.defineProperties(copy, {\n example: {\n get: (): ExampleSetter<T> => (value) => {\n const localCopy = withMeta<T>(copy);\n localCopy._def[metaProp].examples.push(value);\n return localCopy;\n },\n },\n });\n return copy;\n};\n\nexport const hasMeta = <T extends z.ZodTypeAny>(\n schema: T\n): schema is WithMeta<T> => {\n if (!(metaProp in schema._def)) {\n return false;\n }\n return (\n typeof schema._def[metaProp] === \"object\" && schema._def[metaProp] !== null\n );\n};\n\nexport function getMeta<T extends z.ZodTypeAny, K extends MetaKey>(\n schema: T,\n meta: K\n): MetaValue<T, K> | undefined {\n if (!hasMeta(schema)) {\n return undefined;\n }\n const def = schema._def as MetaDef<T>;\n return meta in def[metaProp] ? def[metaProp][meta] : undefined;\n}\n\nexport const copyMeta = <A extends z.ZodTypeAny, B extends z.ZodTypeAny>(\n src: A,\n dest: B\n): B | WithMeta<B> => {\n if (!hasMeta(src)) {\n return dest;\n }\n const result = withMeta(dest);\n const examplesCombinations = combinations<B>(\n result._def[metaProp].examples,\n src._def[metaProp].examples\n );\n result._def[metaProp].examples = []; // if added more meta, restore mergeDeepRight\n if (examplesCombinations.type === \"single\") {\n result._def[metaProp].examples = examplesCombinations.value;\n } else {\n for (const [destExample, srcExample] of examplesCombinations.value) {\n result._def[metaProp].examples.push(\n mergeDeepRight({ ...destExample }, { ...srcExample })\n );\n }\n }\n return result;\n};\n","import mime from \"mime\";\n\nexport const mimeJson = mime.getType(\"json\") || \"application/json\";\nexport const mimeMultipart = \"multipart/form-data\";\n","import { UploadedFile } from \"express-fileupload\";\nimport {\n INVALID,\n OK,\n ParseInput,\n ParseReturnType,\n ZodIssueCode,\n ZodParsedType,\n ZodType,\n ZodTypeDef,\n addIssueToContext,\n} from \"zod\";\n\nconst zodUploadKind = \"ZodUpload\";\n\nexport interface ZodUploadDef extends ZodTypeDef {\n typeName: typeof zodUploadKind;\n}\n\nconst isUploadedFile = (data: any): data is UploadedFile =>\n typeof data === \"object\" &&\n data !== null &&\n \"name\" in data &&\n \"encoding\" in data &&\n \"mimetype\" in data &&\n \"data\" in data &&\n \"tempFilePath\" in data &&\n \"truncated\" in data &&\n \"size\" in data &&\n \"md5\" in data &&\n \"mv\" in data &&\n typeof data.name === \"string\" &&\n typeof data.mimetype === \"string\" &&\n typeof data.data === \"object\" &&\n typeof data.tempFilePath === \"string\" &&\n typeof data.truncated === \"boolean\" &&\n typeof data.size === \"number\" &&\n typeof data.md5 === \"string\" &&\n typeof data.mv === \"function\";\n\nexport class ZodUpload extends ZodType<UploadedFile, ZodUploadDef> {\n _parse(input: ParseInput): ParseReturnType<UploadedFile> {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object || !isUploadedFile(ctx.data)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.custom,\n message: `Expected file upload, received ${ctx.parsedType}`,\n });\n return INVALID;\n }\n\n return OK(ctx.data);\n }\n\n static create = () =>\n new ZodUpload({\n typeName: zodUploadKind,\n });\n}\n","import { ZodError } from \"zod\";\nimport { getMessageFromError } from \"./common-helpers\";\n\n/** @desc An error related to the wrong Routing declaration */\nexport class RoutingError extends Error {\n public override name = \"RoutingError\";\n}\n\n/** @desc An error related to the issues of using DependsOnMethod class */\nexport class DependsOnMethodError extends RoutingError {\n public override name = \"DependsOnMethodError\";\n}\n\n/** @desc An error related to the generating of the documentation */\nexport class OpenAPIError extends Error {\n public override name = \"OpenAPIError\";\n}\n\n/** @desc An error related to the input and output schemas declaration */\nexport class IOSchemaError extends Error {\n public override name = \"IOSchemaError\";\n}\n\n/** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */\nexport class OutputValidationError extends IOSchemaError {\n public override name = \"OutputValidationError\";\n public readonly originalError: ZodError;\n\n constructor(originalError: ZodError) {\n super(getMessageFromError(originalError));\n this.originalError = originalError;\n }\n}\n\n/** @desc An error of validating the input sources against the Middleware or Endpoint input schema */\nexport class InputValidationError extends IOSchemaError {\n public override name = \"InputValidationError\";\n public readonly originalError: ZodError;\n\n constructor(originalError: ZodError) {\n super(getMessageFromError(originalError));\n this.originalError = originalError;\n }\n}\n\n/** @desc An error related to the execution of ResultHandler */\nexport class ResultHandlerError extends Error {\n public override name = \"ResultHandlerError\";\n public readonly originalError: Error | undefined;\n\n constructor(message: string, originalError?: Error | null) {\n super(message);\n this.originalError = originalError || undefined;\n }\n}\n","import { combinations } from \"./common-helpers\";\n\ntype LogicalOr<T> = { or: T[] };\ntype LogicalAnd<T> = { and: T[] };\n\nexport type LogicalContainer<T> =\n | LogicalOr<T | LogicalAnd<T>>\n | LogicalAnd<T | LogicalOr<T>>\n | T;\n\nconst isObject = <\n T extends LogicalContainer<any> | LogicalAnd<any> | LogicalOr<any>\n>(\n subject: T\n): subject is Exclude<T & {}, null> =>\n typeof subject === \"object\" && subject !== null;\n\n/** @desc combines several LogicalAnds into a one */\nexport const flattenAnds = <T>(\n subject: (T | LogicalAnd<T>)[]\n): LogicalAnd<T> => ({\n and: subject.reduce<T[]>(\n (agg, item) =>\n agg.concat(isObject(item) && \"and\" in item ? item.and : item),\n []\n ),\n});\n\n/** @desc creates a LogicalContainer out of another one */\nexport const mapLogicalContainer = <T, S>(\n container: LogicalContainer<T>,\n fn: (subject: T) => S\n): LogicalContainer<S> => {\n if (isObject(container)) {\n if (\"and\" in container) {\n return {\n and: container.and.map((entry) =>\n isObject(entry) && \"or\" in entry\n ? { or: entry.or.map(fn) }\n : fn(entry)\n ),\n };\n }\n if (\"or\" in container) {\n return {\n or: container.or.map((entry) =>\n isObject(entry) && \"and\" in entry\n ? { and: entry.and.map(fn) }\n : fn(entry)\n ),\n };\n }\n }\n return fn(container);\n};\n\n/** @desc converts LogicalAnd into LogicalOr */\nexport const andToOr = <T>(\n subject: LogicalAnd<T | LogicalOr<T>>\n): LogicalOr<T | LogicalAnd<T>> => {\n return subject.and.reduce<LogicalOr<T | LogicalAnd<T>>>(\n (acc, item) => {\n const combs = combinations(\n acc.or,\n isObject(item) && \"or\" in item ? item.or : [item]\n );\n if (combs.type === \"single\") {\n acc.or.push(...combs.value);\n } else {\n acc.or = combs.value.map(flattenAnds);\n }\n return acc;\n },\n {\n or: [],\n }\n );\n};\n\n/** @desc reducer, combines two LogicalContainers */\nexport const combineContainers = <T>(\n a: LogicalContainer<T>,\n b: LogicalContainer<T>\n): LogicalContainer<T> => {\n if (isObject(a)) {\n if (\"and\" in a) {\n if (isObject(b)) {\n if (\"and\" in b) {\n return flattenAnds([a, b]);\n }\n if (\"or\" in b) {\n return combineContainers(andToOr(a), b);\n }\n }\n return flattenAnds([a, b]);\n }\n if (\"or\" in a) {\n if (isObject(b)) {\n if (\"and\" in b) {\n return combineContainers(b, a);\n }\n if (\"or\" in b) {\n const combs = combinations(a.or, b.or);\n return {\n or:\n combs.type === \"single\"\n ? combs.value\n : combs.value.map(flattenAnds),\n };\n }\n }\n return combineContainers(a, { and: [b] });\n }\n }\n\n if (isObject(b) && (\"and\" in b || \"or\" in b)) {\n return combineContainers(b, a);\n }\n\n return { and: [a as T, b as T] };\n};\n","import { Request, Response } from \"express\";\nimport { Logger } from \"winston\";\nimport { z } from \"zod\";\nimport { ApiResponse } from \"./api-response\";\nimport { ResultHandlerError } from \"./errors\";\nimport { getMessageFromError, getStatusCodeFromError } from \"./common-helpers\";\nimport { IOSchema } from \"./io-schema\";\nimport { getMeta, withMeta } from \"./metadata\";\n\ninterface LastResortHandlerParams {\n error: ResultHandlerError;\n logger: Logger;\n response: Response;\n}\n\ninterface ResultHandlerParams<RES> {\n error: Error | null;\n input: any;\n output: any;\n request: Request;\n response: Response<RES>;\n logger: Logger;\n}\n\ntype ResultHandler<RES> = (\n params: ResultHandlerParams<RES>\n) => void | Promise<void>;\n\nexport interface ResultHandlerDefinition<\n POS extends z.ZodTypeAny,\n NEG extends z.ZodTypeAny\n> {\n getPositiveResponse: (output: IOSchema) => POS | ApiResponse<POS>;\n getNegativeResponse: () => NEG | ApiResponse<NEG>;\n handler: ResultHandler<z.output<POS> | z.output<NEG>>;\n}\n\nexport const defaultStatusCodes = {\n positive: 200,\n negative: 400,\n};\n\nexport const createResultHandler = <\n POS extends z.ZodTypeAny,\n NEG extends z.ZodTypeAny\n>(\n definition: ResultHandlerDefinition<POS, NEG>\n) => definition;\n\nexport const defaultResultHandler = createResultHandler({\n getPositiveResponse: (output: IOSchema) => {\n const examples = getMeta(output, \"examples\") || [];\n const responseSchema = withMeta(\n z.object({\n status: z.literal(\"success\"),\n data: output,\n })\n );\n return examples.reduce<typeof responseSchema>(\n (acc, example) =>\n acc.example({\n status: \"success\",\n data: example,\n }),\n responseSchema\n );\n },\n getNegativeResponse: () =>\n withMeta(\n z.object({\n status: z.literal(\"error\"),\n error: z.object({\n message: z.string(),\n }),\n })\n ).example({\n status: \"error\",\n error: {\n message: getMessageFromError(new Error(\"Sample error message\")),\n },\n }),\n handler: ({ error, input, output, request, response, logger }) => {\n if (!error) {\n response.status(defaultStatusCodes.positive).json({\n status: \"success\" as const,\n data: output,\n });\n return;\n }\n const statusCode = getStatusCodeFromError(error);\n if (statusCode === 500) {\n logger.error(`Internal server error\\n${error.stack}\\n`, {\n url: request.url,\n payload: input,\n });\n }\n response.status(statusCode).json({\n status: \"error\" as const,\n error: { message: getMessageFromError(error) },\n });\n },\n});\n\nexport const lastResortHandler = ({\n error,\n logger,\n response,\n}: LastResortHandlerParams) => {\n logger.error(`Result handler failure: ${error.message}.`);\n response\n .status(500)\n .end(\n `An error occurred while serving the result: ${error.message}.` +\n (error.originalError\n ? `\\nOriginal error: ${error.originalError.message}.`\n : \"\")\n );\n};\n","export type Method = \"get\" | \"post\" | \"put\" | \"delete\" | \"patch\";\nexport const methods: Method[] = [\"get\", \"post\", \"put\", \"delete\", \"patch\"];\nexport type AuxMethod = \"options\";\n\nexport type MethodsDefinition<M extends Method> =\n | {\n methods: M[];\n }\n | {\n method: M;\n };\n","import { Request, Response } from \"express\";\nimport { z } from \"zod\";\nimport { FlatObject } from \"./common-helpers\";\nimport { CommonConfig } from \"./config-type\";\nimport { Endpoint, Handler } from \"./endpoint\";\nimport {\n IOSchema,\n ProbableIntersection,\n getFinalEndpointInputSchema,\n} from \"./io-schema\";\nimport { Method, MethodsDefinition } from \"./method\";\nimport {\n AnyMiddlewareDef,\n ExpressMiddleware,\n ExpressMiddlewareFeatures,\n MiddlewareDefinition,\n createMiddleware,\n} from \"./middleware\";\nimport {\n ResultHandlerDefinition,\n defaultResultHandler,\n} from \"./result-handler\";\n\ntype BuildProps<\n IN extends IOSchema,\n OUT extends IOSchema,\n MIN extends IOSchema<\"strip\"> | null,\n OPT extends FlatObject,\n M extends Method,\n SCO extends string,\n TAG extends string\n> = {\n input: IN;\n output: OUT;\n handler: Handler<z.output<ProbableIntersection<MIN, IN>>, z.input<OUT>, OPT>;\n description?: string;\n shortDescription?: string;\n} & ({ scopes?: SCO[] } | { scope?: SCO }) &\n ({ tags?: TAG[] } | { tag?: TAG }) &\n MethodsDefinition<M>;\n\nexport class EndpointsFactory<\n POS extends z.ZodTypeAny,\n NEG extends z.ZodTypeAny,\n IN extends IOSchema<\"strip\"> | null = null,\n OUT extends FlatObject = {},\n SCO extends string = string,\n TAG extends string = string\n> {\n protected resultHandler: ResultHandlerDefinition<POS, NEG>;\n protected middlewares: AnyMiddlewareDef[] = [];\n\n constructor(resultHandler: ResultHandlerDefinition<POS, NEG>);\n /** @desc Consider using the \"config\" prop with the \"tags\" option to enforce constraints on tagging the endpoints */\n constructor(params: {\n resultHandler: ResultHandlerDefinition<POS, NEG>;\n config?: CommonConfig<TAG>;\n });\n constructor(\n subject:\n | ResultHandlerDefinition<POS, NEG>\n | {\n resultHandler: ResultHandlerDefinition<POS, NEG>;\n config?: CommonConfig<TAG>;\n }\n ) {\n this.resultHandler =\n \"resultHandler\" in subject ? subject.resultHandler : subject;\n }\n\n static #create<\n CPOS extends z.ZodTypeAny,\n CNEG extends z.ZodTypeAny,\n CIN extends IOSchema<\"strip\"> | null,\n COUT extends FlatObject,\n CSCO extends string,\n CTAG extends string\n >(\n middlewares: AnyMiddlewareDef[],\n resultHandler: ResultHandlerDefinition<CPOS, CNEG>\n ) {\n const factory = new EndpointsFactory<CPOS, CNEG, CIN, COUT, CSCO, CTAG>(\n resultHandler\n );\n factory.middlewares = middlewares;\n return factory;\n }\n\n public addMiddleware<\n AIN extends IOSchema<\"strip\">,\n AOUT extends FlatObject,\n ASCO extends string\n >(subject: MiddlewareDefinition<AIN, OUT, AOUT, ASCO>) {\n return EndpointsFactory.#create<\n POS,\n NEG,\n ProbableIntersection<IN, AIN>,\n OUT & AOUT,\n SCO & ASCO,\n TAG\n >(this.middlewares.concat(subject), this.resultHandler);\n }\n\n public use = this.addExpressMiddleware;\n\n public addExpressMiddleware<\n R extends Request,\n S extends Response,\n AOUT extends FlatObject = {}\n >(\n middleware: ExpressMiddleware<R, S>,\n features?: ExpressMiddlewareFeatures<R, S, AOUT>\n ) {\n const transformer = features?.transformer || ((err: Error) => err);\n const provider = features?.provider || (() => ({} as AOUT));\n const definition: AnyMiddlewareDef = {\n type: \"express\",\n input: z.object({}),\n middleware: async ({ request, response }) =>\n new Promise<AOUT>((resolve, reject) => {\n const next = (err?: any) => {\n if (err && err instanceof Error) {\n return reject(transformer(err));\n }\n resolve(provider(request as R, response as S));\n };\n middleware(request as R, response as S, next);\n }),\n };\n return EndpointsFactory.#create<POS, NEG, IN, OUT & AOUT, SCO, TAG>(\n this.middlewares.concat(definition),\n this.resultHandler\n );\n }\n\n public addOptions<AOUT extends FlatObject>(options: AOUT) {\n return EndpointsFactory.#create<POS, NEG, IN, OUT & AOUT, SCO, TAG>(\n this.middlewares.concat(\n createMiddleware({\n input: z.object({}),\n middleware: async () => options,\n })\n ),\n this.resultHandler\n );\n }\n\n public build<BIN extends IOSchema, BOUT extends IOSchema, M extends Method>({\n input,\n handler,\n output: outputSchema,\n ...rest\n }: BuildProps<BIN, BOUT, IN, OUT, M, SCO, TAG>): Endpoint<\n ProbableIntersection<IN, BIN>,\n BOUT,\n OUT,\n M,\n POS,\n NEG,\n SCO,\n TAG\n > {\n const { middlewares, resultHandler } = this;\n return new Endpoint({\n handler,\n middlewares,\n outputSchema,\n resultHandler,\n inputSchema: getFinalEndpointInputSchema<IN, BIN>(middlewares, input),\n ...rest,\n });\n }\n}\n\nexport const defaultEndpointsFactory = new EndpointsFactory(\n defaultResultHandler\n);\n","import { z } from \"zod\";\nimport { copyMeta } from \"./metadata\";\nimport { AnyMiddlewareDef } from \"./middleware\";\n\n// the copy of the private Zod utility type of ZodObject\ntype UnknownKeysParam = \"passthrough\" | \"strict\" | \"strip\";\n\ntype Refined<T extends z.ZodTypeAny> = T extends z.ZodType<infer O>\n ? z.ZodEffects<T | Refined<T>, O, O>\n : never;\n\n/**\n * @desc The type allowed on the top level of Middlewares and Endpoints\n * @param U — only \"strip\" is allowed for Middlewares due to intersection issue (Zod) #600\n * */\nexport type IOSchema<U extends UnknownKeysParam = any> =\n | z.ZodObject<any, U>\n | z.ZodUnion<[IOSchema<U>, ...IOSchema<U>[]]>\n | z.ZodIntersection<IOSchema<U>, IOSchema<U>>\n | z.ZodDiscriminatedUnion<string, z.ZodObject<any, U>[]>\n | Refined<z.ZodObject<any, U>>;\n\nexport type ProbableIntersection<\n A extends IOSchema<\"strip\"> | null,\n B extends IOSchema\n> = A extends null\n ? B\n : A extends IOSchema<\"strip\">\n ? z.ZodIntersection<A, B>\n : never;\n\n/**\n * @description intersects input schemas of middlewares and the endpoint\n * @since 07.03.2022 former combineEndpointAndMiddlewareInputSchemas()\n * @since 05.03.2023 is immutable to metadata\n * @see copyMeta\n */\nexport const getFinalEndpointInputSchema = <\n MIN extends IOSchema<\"strip\"> | null,\n IN extends IOSchema\n>(\n middlewares: AnyMiddlewareDef[],\n input: IN\n): ProbableIntersection<MIN, IN> => {\n const allSchemas = middlewares\n .map(({ input: schema }) => schema)\n .concat(input);\n\n const finalSchema = allSchemas.reduce((acc, schema) =>\n acc.and(schema)\n ) as ProbableIntersection<MIN, IN>;\n\n return allSchemas.reduce((acc, schema) => copyMeta(schema, acc), finalSchema);\n};\n","import { Request, Response } from \"express\";\nimport { HttpError } from \"http-errors\";\nimport { Logger } from \"winston\";\nimport { z } from \"zod\";\nimport { FlatObject, hasTopLevelTransformingEffect } from \"./common-helpers\";\nimport { IOSchemaError } from \"./errors\";\nimport { IOSchema } from \"./io-schema\";\nimport { LogicalContainer } from \"./logical-container\";\nimport { Security } from \"./security\";\n\ninterface MiddlewareParams<IN, OPT> {\n input: IN;\n options: OPT;\n request: Request;\n response: Response;\n logger: Logger;\n}\n\ntype Middleware<IN, OPT, OUT> = (\n params: MiddlewareParams<IN, OPT>\n) => Promise<OUT>;\n\ninterface MiddlewareCreationProps<\n IN extends IOSchema<\"strip\">,\n OPT,\n OUT extends FlatObject,\n SCO extends string\n> {\n input: IN;\n security?: LogicalContainer<Security<keyof z.input<IN> & string, SCO>>;\n middleware: Middleware<z.output<IN>, OPT, OUT>;\n}\n\nexport interface MiddlewareDefinition<\n IN extends IOSchema<\"strip\">,\n OPT,\n OUT extends FlatObject,\n SCO extends string\n> extends MiddlewareCreationProps<IN, OPT, OUT, SCO> {\n type: \"proprietary\" | \"express\";\n}\n\nexport type AnyMiddlewareDef = MiddlewareDefinition<any, any, any, any>;\n\nexport const createMiddleware = <\n IN extends IOSchema<\"strip\">,\n OPT,\n OUT extends FlatObject,\n SCO extends string\n>(\n props: MiddlewareCreationProps<IN, OPT, OUT, SCO>\n): MiddlewareDefinition<IN, OPT, OUT, SCO> => {\n if (hasTopLevelTransformingEffect(props.input)) {\n throw new IOSchemaError(\n \"Using transformations on the top level of middleware input schema is not allowed.\"\n );\n }\n return {\n ...props,\n type: \"proprietary\",\n };\n};\n\nexport type ExpressMiddleware<R extends Request, S extends Response> = (\n request: R,\n response: S,\n next: (error?: any) => void\n) => void | Promise<void>;\n\nexport interface ExpressMiddlewareFeatures<\n R extends Request,\n S extends Response,\n OUT extends FlatObject\n> {\n provider?: (request: R, response: S) => OUT | Promise<OUT>;\n transformer?: (err: Error) => HttpError | Error;\n}\n","import { inspect } from \"util\";\nimport type { Format } from \"logform\";\nimport { LEVEL, MESSAGE, SPLAT } from \"triple-beam\";\nimport winston from \"winston\";\nimport type Transport from \"winston-transport\";\nimport { LoggerConfig } from \"./config-type\";\n\nconst { combine, colorize, timestamp: useTimestamp, printf } = winston.format;\n\nexport function createLogger(loggerConfig: LoggerConfig): winston.Logger {\n const prettyPrint = (meta: any) => {\n const {\n [LEVEL]: noLevel,\n [MESSAGE]: noMessage,\n [SPLAT]: noSplat,\n ...rest\n } = meta;\n return inspect(rest, false, 1, loggerConfig.color);\n };\n\n const getOutputFormat = (isPretty?: boolean) =>\n printf(({ timestamp, message, level, durationMs, ...meta }) => {\n if (typeof message === \"object\") {\n meta = { ...meta, ...(message as object) };\n message = \"[No message]\";\n }\n return (\n `${timestamp} ${level}: ${message}` +\n (durationMs === undefined ? \"\" : ` duration: ${durationMs}ms`) +\n (Object.keys(meta).length === 0\n ? \"\"\n : \" \" + (isPretty ? prettyPrint(meta) : JSON.stringify(meta)))\n );\n });\n\n const formats: Format[] = [useTimestamp()];\n\n const consoleOutputOptions: Transport.TransportStreamOptions = {\n handleExceptions: true,\n };\n\n if (loggerConfig.color) {\n formats.push(colorize());\n }\n\n switch (loggerConfig.level) {\n case \"debug\":\n consoleOutputOptions.level = \"debug\";\n formats.push(getOutputFormat(true));\n break;\n case \"silent\":\n case \"warn\":\n default:\n consoleOutputOptions.level = \"warn\";\n formats.push(getOutputFormat());\n }\n\n consoleOutputOptions.format = combine(...formats);\n\n return winston.createLogger({\n silent: loggerConfig.level === \"silent\",\n levels: winston.config.npm.levels,\n transports: [new winston.transports.Console(consoleOutputOptions)],\n exitOnError: false,\n });\n}\n","import { Endpoint } from \"./endpoint\";\nimport { DependsOnMethodError } from \"./errors\";\nimport { Method } from \"./method\";\n\nexport class DependsOnMethod {\n constructor(\n public readonly methods: {\n [K in Method]?:\n | Endpoint<any, any, any, K, any, any, any, any>\n | Endpoint<any, any, any, Method, any, any, any, any>;\n }\n ) {\n (Object.keys(methods) as (keyof typeof methods)[]).forEach((key) => {\n if (key in methods) {\n const endpointMethods = methods[key]?.getMethods() || [];\n if (!endpointMethods.includes(key)) {\n throw new DependsOnMethodError(\n `The endpoint assigned to the '${key}' parameter must have at least this method in its specification.\\n` +\n \"This error should prevent mistakes during the development process.\\n\" +\n \"Example:\\n\\n\" +\n `new ${this.constructor.name}({\\n` +\n ` ${key}: endpointsFactory.build({\\n` +\n ` methods: ['${key}', ` +\n ((methods[key]?.getMethods() || [])\n .map((m) => `'${m}'`)\n .join(\", \") || \"...\") +\n \"]\\n\" +\n ` // or method: '${key}'\\n` +\n \" ...\\n\" +\n \" })\\n\" +\n \"});\\n\"\n );\n }\n }\n });\n }\n}\n","import express from \"express\";\n\ntype OriginalStatic = typeof express.static;\nexport type StaticHandler = ReturnType<OriginalStatic>;\n\nexport class ServeStatic {\n public params: Parameters<OriginalStatic>;\n\n constructor(...params: Parameters<OriginalStatic>) {\n this.params = params;\n }\n\n public apply(\n path: string,\n cb: (path: string, handler: StaticHandler) => void\n ): void {\n return cb(path, express.static(...this.params));\n }\n}\n","import { DependsOnMethod } from \"./depends-on-method\";\nimport { AbstractEndpoint } from \"./endpoint\";\nimport { RoutingError } from \"./errors\";\nimport { AuxMethod, Method } from \"./method\";\nimport { Routing } from \"./routing\";\nimport { ServeStatic, StaticHandler } from \"./serve-static\";\n\nexport interface RoutingWalkerParams {\n routing: Routing;\n onEndpoint: (\n endpoint: AbstractEndpoint,\n path: string,\n method: Method | AuxMethod\n ) => void;\n onStatic?: (path: string, handler: StaticHandler) => void;\n parentPath?: string;\n hasCors?: boolean;\n}\n\nexport const walkRouting = ({\n routing,\n onEndpoint,\n onStatic,\n parentPath,\n hasCors,\n}: RoutingWalkerParams) => {\n Object.entries(routing).forEach(([segment, element]) => {\n segment = segment.trim();\n if (segment.match(/\\//)) {\n throw new RoutingError(\n \"Routing elements should not contain '/' character.\\n\" +\n `The error caused by ${\n parentPath\n ? `'${parentPath}' route that has a '${segment}'`\n : `'${segment}'`\n } entry.`\n );\n }\n const path = `${parentPath || \"\"}${segment ? `/${segment}` : \"\"}`;\n if (element instanceof AbstractEndpoint) {\n const methods: (Method | AuxMethod)[] = element.getMethods().slice();\n if (hasCors) {\n methods.push(\"options\");\n }\n methods.forEach((method) => {\n onEndpoint(element, path, method);\n });\n } else if (element instanceof ServeStatic) {\n if (onStatic) {\n element.apply(path, onStatic);\n }\n } else if (element instanceof DependsOnMethod) {\n Object.entries<AbstractEndpoint>(element.methods).forEach(\n ([method, endpoint]) => {\n onEndpoint(endpoint, path, method as Method);\n }\n );\n if (hasCors && Object.keys(element.methods).length > 0) {\n const [firstMethod, ...siblingMethods] = Object.keys(\n element.methods\n ) as Method[];\n const firstEndpoint = element.methods[firstMethod]!;\n firstEndpoint._setSiblingMethods(siblingMethods);\n onEndpoint(firstEndpoint, path, \"options\");\n }\n } else {\n walkRouting({\n onEndpoint,\n onStatic,\n hasCors,\n routing: element,\n parentPath: path,\n });\n }\n });\n};\n","// ANSI font attribution\n// Colossal.flf (Jonathon - jon@mq.edu.au), 8 June 1994\n\nexport const getStartupLogo = () => {\n return `\n\u001b[94m\u001b[39m\n\u001b[94m\u001b[39m\n\u001b[94m8888888888 8888888888P 888 d8888 8888888b. 8888888 \u001b[39m\n\u001b[94m888 d88P 888 d88888 888 Y88b 888\u001b[39m\u001b[95m\u001b[39m\n\u001b[95m888 d88P 888 d88P888 888 888 888\u001b[39m\n\u001b[95m8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b d88P .d88b. .d88888 d88P 888 888 d88P 888\u001b[39m\u001b[97m\u001b[39m\n\u001b[97m888 \\`Y8bd8P' 888 \"88b 888P\" d8P Y8b 88K 88K d88P d88\"\"88b d88\" 888 d88P 888 8888888P\" 888 \u001b[39m\n\u001b[97m888 X88K 888 888 888 88888888 \"Y8888b. \"Y8888b. d88P 888 888 888 888 d88P 888 888 888\u001b[39m\u001b[95m\u001b[39m\n\u001b[95m888 .d8\"\"8b. 888 d88P 888 Y8b. X88 X88 d88P Y88..88P Y88b 888 d8888888888 888 888 \u001b[39m\n\u001b[95m8888888888 888 888 88888P\" 888 \"Y8888 88888P' 88888P' d8888888888 \"Y88P\" \"Y88888 d88P 888 888 8888888\u001b[39m\u001b[94m\u001b[39m\n\u001b[94m 888\u001b[39m\n\u001b[94m 888\u001b[3m Proudly supports transgender community.\u001b[23m\u001b[39m\n\u001b[94m\u001b[3mfor Gisberta \u001b[23m 888\u001b[3m Start your API server with I/O schema validation and custom middlewares in minutes.\u001b[23m\u001b[39m\u001b[90m\u001b[39m\n\u001b[90m\u001b[3m Thank you for choosing Express Zod API for your project.\u001b[23m\u001b[39m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0m\n\u001b[0m\u001b[0m\n`.trim();\n};\n","import { Express } from \"express\";\nimport { Logger } from \"winston\";\nimport { CommonConfig } from \"./config-type\";\nimport { DependsOnMethod } from \"./depends-on-method\";\nimport { AbstractEndpoint } from \"./endpoint\";\nimport { walkRouting } from \"./routing-walker\";\nimport { ServeStatic } from \"./serve-static\";\nimport { getStartupLogo } from \"./startup-logo\";\n\nexport interface Routing {\n [SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;\n}\n\nexport const initRouting = ({\n app,\n logger,\n config,\n routing,\n}: {\n app: Express;\n logger: Logger;\n config: CommonConfig;\n routing: Routing;\n}) => {\n if (config.startupLogo !== false) {\n console.log(getStartupLogo());\n }\n walkRouting({\n routing,\n hasCors: !!config.cors,\n onEndpoint: (endpoint, path, method) => {\n app[method](path, async (request, response) => {\n logger.info(`${request.method}: ${path}`);\n await endpoint.execute({ request, response, logger, config });\n });\n },\n onStatic: (path, handler) => {\n app.use(path, handler);\n },\n });\n};\n","import express, { ErrorRequestHandler, RequestHandler, json } from \"express\";\nimport compression from \"compression\";\nimport fileUpload from \"express-fileupload\";\nimport https from \"https\";\nimport { Logger } from \"winston\";\nimport { AppConfig, CommonConfig, ServerConfig } from \"./config-type\";\nimport { ResultHandlerError } from \"./errors\";\nimport { isLoggerConfig, makeErrorFromAnything } from \"./common-helpers\";\nimport { createLogger } from \"./logger\";\nimport { defaultResultHandler, lastResortHandler } from \"./result-handler\";\nimport { Routing, initRouting } from \"./routing\";\nimport createHttpError from \"http-errors\";\n\ntype AnyResultHandler = NonNullable<CommonConfig[\"errorHandler\"]>;\n\nexport const createParserFailureHandler =\n (errorHandler: AnyResultHandler, logger: Logger): ErrorRequestHandler =>\n (error, request, response, next) => {\n if (!error) {\n return next();\n }\n errorHandler.handler({\n error,\n request,\n response,\n logger,\n input: request.body,\n output: null,\n });\n };\n\nexport const createNotFoundHandler =\n (errorHandler: AnyResultHandler, logger: Logger): RequestHandler =>\n (request, response) => {\n const error = createHttpError(\n 404,\n `Can not ${request.method} ${request.path}`\n );\n try {\n errorHandler.handler({\n request,\n response,\n logger,\n error,\n input: null,\n output: null,\n });\n } catch (e) {\n lastResortHandler({\n response,\n logger,\n error: new ResultHandlerError(makeErrorFromAnything(e).message, error),\n });\n }\n };\n\nexport function attachRouting(\n config: AppConfig & CommonConfig,\n routing: Routing\n) {\n const logger = isLoggerConfig(config.logger)\n ? createLogger(config.logger)\n : config.logger;\n initRouting({ app: config.app, routing, logger, config });\n const errorHandler = config.errorHandler || defaultResultHandler;\n const notFoundHandler = createNotFoundHandler(errorHandler, logger);\n return { notFoundHandler, logger };\n}\n\nexport function createServer(\n config: ServerConfig & CommonConfig,\n routing: Routing\n) {\n const logger = isLoggerConfig(config.logger)\n ? createLogger(config.logger)\n : config.logger;\n const app = express();\n app.disable(\"x-powered-by\");\n const errorHandler = config.errorHandler || defaultResultHandler;\n const compressor = config.server.compression\n ? compression({\n ...(typeof config.server.compression === \"object\"\n ? config.server.compression\n : {}),\n })\n : undefined;\n const jsonParser = config.server.jsonParser || json();\n const multipartParser = config.server.upload\n ? fileUpload({\n ...(typeof config.server.upload === \"object\"\n ? config.server.upload\n : {}),\n abortOnLimit: false,\n parseNested: true,\n })\n : undefined;\n\n const middlewares = ([] as RequestHandler[])\n .concat(compressor || [])\n .concat(jsonParser)\n .concat(multipartParser || []);\n app.use(middlewares);\n app.use(createParserFailureHandler(errorHandler, logger));\n initRouting({ app, routing, logger, config });\n app.use(createNotFoundHandler(errorHandler, logger));\n\n const httpServer = app.listen(config.server.listen, () => {\n logger.info(`Listening ${config.server.listen}`);\n });\n\n let httpsServer: https.Server | undefined;\n if (config.https) {\n httpsServer = https\n .createServer(config.https.options, app)\n .listen(config.https.listen, () => {\n logger.info(`Listening ${config.https!.listen}`);\n });\n }\n\n return { app, httpServer, httpsServer, logger };\n}\n","import {\n OpenApiBuilder,\n OperationObject,\n SecuritySchemeObject,\n SecuritySchemeType,\n} from \"openapi3-ts\";\nimport { defaultInputSources, makeCleanId } from \"./common-helpers\";\nimport { CommonConfig } from \"./config-type\";\nimport { mapLogicalContainer } from \"./logical-container\";\nimport { Method } from \"./method\";\nimport {\n depictRequest,\n depictRequestParams,\n depictResponse,\n depictSecurity,\n depictSecurityRefs,\n depictTags,\n ensureShortDescription,\n reformatParamsInPath,\n} from \"./open-api-helpers\";\nimport { Routing } from \"./routing\";\nimport { RoutingWalkerParams, walkRouting } from \"./routing-walker\";\n\ninterface GeneratorParams {\n title: string;\n version: string;\n serverUrl: string;\n routing: Routing;\n config: CommonConfig;\n /** @default Successful response */\n successfulResponseDescription?: string;\n /** @default Error response */\n errorResponseDescription?: string;\n /** @default true */\n hasSummaryFromDescription?: boolean;\n}\n\nexport class OpenAPI extends OpenApiBuilder {\n protected lastSecuritySchemaIds: Partial<Record<SecuritySchemeType, number>> =\n {};\n protected lastOperationIdSuffixes: Record<string, number> = {};\n\n protected ensureUniqOperationId(path: string, method: Method) {\n const operationId = makeCleanId(path, method);\n if (operationId in this.lastOperationIdSuffixes) {\n this.lastOperationIdSuffixes[operationId]++;\n return `${operationId}${this.lastOperationIdSuffixes[operationId]}`;\n }\n this.lastOperationIdSuffixes[operationId] = 1;\n return operationId;\n }\n\n protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject) {\n for (const name in this.rootDoc.components?.securitySchemes || {}) {\n if (\n JSON.stringify(subject) ===\n JSON.stringify(this.rootDoc.components?.securitySchemes?.[name])\n ) {\n return name;\n }\n }\n this.lastSecuritySchemaIds[subject.type] =\n (this.lastSecuritySchemaIds?.[subject.type] || 0) + 1;\n return `${subject.type.toUpperCase()}_${\n this.lastSecuritySchemaIds[subject.type]\n }`;\n }\n\n public constructor({\n routing,\n config,\n title,\n version,\n serverUrl,\n successfulResponseDescription = \"Successful response\",\n errorResponseDescription = \"Error response\",\n hasSummaryFromDescription = true,\n }: GeneratorParams) {\n super();\n this.addInfo({ title, version }).addServer({ url: serverUrl });\n const onEndpoint: RoutingWalkerParams[\"onEndpoint\"] = (\n endpoint,\n path,\n _method\n ) => {\n const method = _method as Method;\n const commonParams = { path, method, endpoint };\n const [shortDesc, longDesc] = ([\"short\", \"long\"] as const).map(\n endpoint.getDescription.bind(endpoint)\n );\n const inputSources =\n config.inputSources?.[method] || defaultInputSources[method];\n const depictedParams = depictRequestParams({\n ...commonParams,\n inputSources,\n });\n const operation: OperationObject = {\n operationId: this.ensureUniqOperationId(path, method),\n responses: {\n [endpoint.getStatusCode(\"positive\")]: depictResponse({\n ...commonParams,\n description: successfulResponseDescription,\n isPositive: true,\n }),\n [endpoint.getStatusCode(\"negative\")]: depictResponse({\n ...commonParams,\n description: errorResponseDescription,\n isPositive: false,\n }),\n },\n };\n if (longDesc) {\n operation.description = longDesc;\n if (hasSummaryFromDescription && shortDesc === undefined) {\n operation.summary = ensureShortDescription(longDesc);\n }\n }\n if (shortDesc) {\n operation.summary = ensureShortDescription(shortDesc);\n }\n if (endpoint.getTags().length > 0) {\n operation.tags = endpoint.getTags();\n }\n if (depictedParams.length > 0) {\n operation.parameters = depictedParams;\n }\n if (inputSources.includes(\"body\")) {\n operation.requestBody = depictRequest(commonParams);\n }\n const securityRefs = depictSecurityRefs(\n mapLogicalContainer(\n depictSecurity(endpoint.getSecurity()),\n (securitySchema) => {\n const name = this.ensureUniqSecuritySchemaName(securitySchema);\n const scopes = [\"oauth2\", \"openIdConnect\"].includes(\n securitySchema.type\n )\n ? endpoint.getScopes()\n : [];\n this.addSecurityScheme(name, securitySchema);\n return { name, scopes };\n }\n )\n );\n if (securityRefs.length > 0) {\n operation.security = securityRefs;\n }\n const swaggerCompatiblePath = reformatParamsInPath(path);\n this.addPath(swaggerCompatiblePath, {\n [method]: operation,\n });\n };\n walkRouting({ routing, onEndpoint });\n this.rootDoc.tags = config.tags ? depictTags(config.tags) : [];\n }\n}\n","import {\n ContentObject,\n ExampleObject,\n ExamplesObject,\n MediaTypeObject,\n OAuthFlowsObject,\n ParameterObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n SchemaObjectType,\n SecurityRequirementObject,\n SecuritySchemeObject,\n TagObject,\n} from \"openapi3-ts\";\nimport { omit } from \"ramda\";\nimport { z } from \"zod\";\nimport {\n getExamples,\n getRoutePathParams,\n hasCoercion,\n hasTopLevelTransformingEffect,\n routePathParamsRegex,\n tryToTransform,\n} from \"./common-helpers\";\nimport { InputSource, TagsConfig } from \"./config-type\";\nimport { ZodDateIn, isoDateRegex } from \"./date-in-schema\";\nimport { ZodDateOut } from \"./date-out-schema\";\nimport { AbstractEndpoint } from \"./endpoint\";\nimport { OpenAPIError } from \"./errors\";\nimport { ZodFile } from \"./file-schema\";\nimport { IOSchema } from \"./io-schema\";\nimport {\n LogicalContainer,\n andToOr,\n mapLogicalContainer,\n} from \"./logical-container\";\nimport { copyMeta } from \"./metadata\";\nimport { Method } from \"./method\";\nimport {\n HandlingRules,\n HandlingVariant,\n SchemaHandler,\n walkSchema,\n} from \"./schema-walker\";\nimport { Security } from \"./security\";\nimport { ZodUpload } from \"./upload-schema\";\n\ntype MediaExamples = Pick<MediaTypeObject, \"examples\">;\n\nexport interface OpenAPIContext {\n isResponse: boolean;\n}\n\ntype Depicter<\n T extends z.ZodTypeAny,\n Variant extends HandlingVariant = \"regular\"\n> = SchemaHandler<T, SchemaObject, OpenAPIContext, Variant>;\n\ninterface ReqResDepictHelperCommonProps {\n method: Method;\n path: string;\n endpoint: AbstractEndpoint;\n}\n\nconst shortDescriptionLimit = 50;\nconst isoDateDocumentationUrl =\n \"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString\";\n\nconst samples: Record<\n Exclude<NonNullable<SchemaObjectType>, Array<any>>,\n any\n> = {\n integer: 0,\n number: 0,\n string: \"\",\n boolean: false,\n object: {},\n null: null,\n array: [],\n};\n\n/* eslint-disable @typescript-eslint/no-use-before-define */\n\nexport const reformatParamsInPath = (path: string) =>\n path.replace(routePathParamsRegex, (param) => `{${param.slice(1)}}`);\n\nexport const depictDefault: Depicter<z.ZodDefault<z.ZodTypeAny>> = ({\n schema: {\n _def: { innerType, defaultValue },\n },\n next,\n}) => ({\n ...next({ schema: innerType }),\n default: defaultValue(),\n});\n\nexport const depictCatch: Depicter<z.ZodCatch<z.ZodTypeAny>> = ({\n schema: {\n _def: { innerType },\n },\n next,\n}) => next({ schema: innerType });\n\nexport const depictAny: Depicter<z.ZodAny> = () => ({\n format: \"any\",\n});\n\nexport const depictUpload: Depicter<ZodUpload> = ({ isResponse }) => {\n if (isResponse) {\n throw new OpenAPIError(\"Please use z.upload() only for input.\");\n }\n return {\n type: \"string\",\n format: \"binary\",\n };\n};\n\nexport const depictFile: Depicter<ZodFile> = ({\n schema: { isBinary, isBase64 },\n isResponse,\n}) => {\n if (!isResponse) {\n throw new OpenAPIError(\"Please use z.file() only within ResultHandler.\");\n }\n return {\n type: \"string\",\n format: isBinary ? \"binary\" : isBase64 ? \"byte\" : \"file\",\n };\n};\n\nexport const depictUnion: Depicter<\n z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]>\n> = ({ schema: { options }, next }) => ({\n oneOf: options.map((option) => next({ schema: option })),\n});\n\nexport const depictDiscriminatedUnion: Depicter<\n z.ZodDiscriminatedUnion<string, z.ZodObject<any>[]>\n> = ({ schema: { options, discriminator }, next }) => {\n return {\n discriminator: { propertyName: discriminator },\n oneOf: Array.from(options.values()).map((option) =>\n next({ schema: option })\n ),\n };\n};\n\nexport const depictIntersection: Depicter<\n z.ZodIntersection<z.ZodTypeAny, z.ZodTypeAny>\n> = ({\n schema: {\n _def: { left, right },\n },\n next,\n}) => ({\n allOf: [left, right].map((entry) => next({ schema: entry })),\n});\n\nexport const depictOptional: Depicter<z.ZodOptional<any>> = ({\n schema,\n next,\n}) => next({ schema: schema.unwrap() });\n\nexport const depictNullable: Depicter<z.ZodNullable<any>> = ({\n schema,\n next,\n}) => ({\n nullable: true,\n ...next({ schema: schema.unwrap() }),\n});\n\nexport const depictEnum: Depicter<z.ZodEnum<any> | z.ZodNativeEnum<any>> = ({\n schema,\n}) => ({\n type: typeof Object.values(schema.enum)[0] as \"string\" | \"number\",\n enum: Object.values(schema.enum),\n});\n\nexport const depictLiteral: Depicter<z.ZodLiteral<any>> = ({\n schema: { value },\n}) => ({\n type: typeof value as \"string\" | \"number\" | \"boolean\",\n enum: [value],\n});\n\nexport const depictObject: Depicter<z.AnyZodObject> = ({\n schema,\n isResponse,\n next,\n}) => {\n const required = Object.keys(schema.shape).filter((key) => {\n const prop = schema.shape[key];\n const isOptional =\n isResponse && hasCoercion(prop)\n ? prop instanceof z.ZodOptional\n : prop.isOptional();\n return !isOptional;\n });\n return {\n type: \"object\",\n properties: depictObjectProperties({ schema, isResponse, next }),\n ...(required.length ? { required } : {}),\n };\n};\n\n/**\n * @see https://swagger.io/docs/specification/data-models/data-types/\n * @todo use type:\"null\" for OpenAPI 3.1\n * */\nexport const depictNull: Depicter<z.ZodNull> = () => ({\n type: \"string\",\n nullable: true,\n format: \"null\",\n});\n\nexport const depictDateIn: Depicter<ZodDateIn> = ({ isResponse }) => {\n if (isResponse) {\n throw new OpenAPIError(\"Please use z.dateOut() for output.\");\n }\n return {\n description: \"YYYY-MM-DDTHH:mm:ss.sssZ\",\n type: \"string\",\n format: \"date-time\",\n pattern: isoDateRegex.source,\n externalDocs: {\n url: isoDateDocumentationUrl,\n },\n };\n};\n\nexport const depictDateOut: Depicter<ZodDateOut> = ({ isResponse }) => {\n if (!isResponse) {\n throw new OpenAPIError(\"Please use z.dateIn() for input.\");\n }\n return {\n description: \"YYYY-MM-DDTHH:mm:ss.sssZ\",\n type: \"string\",\n format: \"date-time\",\n externalDocs: {\n url: isoDateDocumentationUrl,\n },\n };\n};\n\n/** @throws OpenAPIError */\nexport const depictDate: Depicter<z.ZodDate> = ({ isResponse }) => {\n throw new OpenAPIError(\n `Using z.date() within ${\n isResponse ? \"output\" : \"input\"\n } schema is forbidden. Please use z.date${\n isResponse ? \"Out\" : \"In\"\n }() instead. Check out the documentation for details.`\n );\n};\n\nexport const depictBoolean: Depicter<z.ZodBoolean> = () => ({\n type: \"boolean\",\n});\n\nexport const depictBigInt: Depicter<z.ZodBigInt> = () => ({\n type: \"integer\",\n format: \"bigint\",\n});\n\nexport const depictRecord: Depicter<z.ZodRecord<z.ZodTypeAny>> = ({\n schema: { keySchema, valueSchema },\n isResponse,\n next,\n}) => {\n if (keySchema instanceof z.ZodEnum || keySchema instanceof z.ZodNativeEnum) {\n const keys = Object.values(keySchema.enum) as string[];\n const shape = keys.reduce(\n (carry, key) => ({\n ...carry,\n [key]: valueSchema,\n }),\n {} as z.ZodRawShape\n );\n return {\n type: \"object\",\n properties: depictObjectProperties({\n schema: z.object(shape),\n isResponse,\n next,\n }),\n ...(keys.length ? { required: keys } : {}),\n };\n }\n if (keySchema instanceof z.ZodLiteral) {\n return {\n type: \"object\",\n properties: depictObjectProperties({\n schema: z.object({\n [keySchema.value]: valueSchema,\n }),\n isResponse,\n next,\n }),\n required: [keySchema.value],\n };\n }\n if (keySchema instanceof z.ZodUnion) {\n const areOptionsLiteral = keySchema.options.reduce(\n (carry: boolean, option: z.ZodTypeAny) =>\n carry && option instanceof z.ZodLiteral,\n true\n );\n if (areOptionsLiteral) {\n const shape = keySchema.options.reduce(\n (carry: z.ZodRawShape, option: z.ZodLiteral<any>) => ({\n ...carry,\n [option.value]: valueSchema,\n }),\n {} as z.ZodRawShape\n );\n return {\n type: \"object\",\n properties: depictObjectProperties({\n schema: z.object(shape),\n isResponse,\n next,\n }),\n required: keySchema.options.map(\n (option: z.ZodLiteral<any>) => option.value\n ),\n };\n }\n }\n return {\n type: \"object\",\n additionalProperties: next({ schema: valueSchema }),\n };\n};\n\nexport const depictArray: Depicter<z.ZodArray<z.ZodTypeAny>> = ({\n schema: { _def: def, element },\n next,\n}) => ({\n type: \"array\",\n items: next({ schema: element }),\n ...(def.minLength !== null && { minItems: def.minLength.value }),\n ...(def.maxLength !== null && { maxItems: def.maxLength.value }),\n});\n\n/** @todo improve it when OpenAPI 3.1.0 will be released */\nexport const depictTuple: Depicter<z.ZodTuple> = ({\n schema: { items },\n next,\n}) => {\n const types = items.map((item) => next({ schema: item }));\n return {\n type: \"array\",\n minItems: types.length,\n maxItems: types.length,\n items: {\n oneOf: types,\n format: \"tuple\",\n ...(types.length > 0 && {\n description: types\n .map((item, index) => `${index}: ${item.type}`)\n .join(\", \"),\n }),\n },\n };\n};\n\nexport const depictString: Depicter<z.ZodString> = ({\n schema: {\n isEmail,\n isURL,\n minLength,\n maxLength,\n isUUID,\n isCUID,\n isCUID2,\n isULID,\n isIP,\n isEmoji,\n isDatetime,\n _def: { checks },\n },\n}) => {\n const regexCheck = checks.find(\n (check): check is z.ZodStringCheck & { kind: \"regex\" } =>\n check.kind === \"regex\"\n );\n const datetimeCheck = checks.find(\n (check): check is z.ZodStringCheck & { kind: \"datetime\" } =>\n check.kind === \"datetime\"\n );\n const regex = regexCheck\n ? regexCheck.regex\n : datetimeCheck\n ? datetimeCheck.offset\n ? new RegExp(\n `^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(\\\\.\\\\d+)?(([+-]\\\\d{2}:\\\\d{2})|Z)$`\n )\n : new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(\\\\.\\\\d+)?Z$`)\n : undefined;\n return {\n type: \"string\" as const,\n ...(isDatetime && { format: \"date-time\" }),\n ...(isEmail && { format: \"email\" }),\n ...(isURL && { format: \"url\" }),\n ...(isUUID && { format: \"uuid\" }),\n ...(isCUID && { format: \"cuid\" }),\n ...(isCUID2 && { format: \"cuid2\" }),\n ...(isULID && { format: \"ulid\" }),\n ...(isIP && { format: \"ip\" }),\n ...(isEmoji && { format: \"emoji\" }),\n ...(minLength !== null && { minLength }),\n ...(maxLength !== null && { maxLength }),\n ...(regex && { pattern: `/${regex.source}/${regex.flags}` }),\n };\n};\n\n/** @todo support exclusive min/max as numbers in case of OpenAPI v3.1.x */\nexport const depictNumber: Depicter<z.ZodNumber> = ({ schema }) => {\n const minCheck = schema._def.checks.find(({ kind }) => kind === \"min\") as\n | Extract<z.ZodNumberCheck, { kind: \"min\" }>\n | undefined;\n const isMinInclusive = minCheck ? minCheck.inclusive : true;\n const maxCheck = schema._def.checks.find(({ kind }) => kind === \"max\") as\n | Extract<z.ZodNumberCheck, { kind: \"max\" }>\n | undefined;\n const isMaxInclusive = maxCheck ? maxCheck.inclusive : true;\n return {\n type: schema.isInt ? (\"integer\" as const) : (\"number\" as const),\n format: schema.isInt ? (\"int64\" as const) : (\"double\" as const),\n minimum:\n schema.minValue === null\n ? schema.isInt\n ? Number.MIN_SAFE_INTEGER\n : Number.MIN_VALUE\n : schema.minValue,\n exclusiveMinimum: !isMinInclusive,\n maximum:\n schema.maxValue === null\n ? schema.isInt\n ? Number.MAX_SAFE_INTEGER\n : Number.MAX_VALUE\n : schema.maxValue,\n exclusiveMaximum: !isMaxInclusive,\n };\n};\n\nexport const depictObjectProperties = ({\n schema: { shape },\n next,\n}: Parameters<Depicter<z.AnyZodObject>>[0]) => {\n return Object.keys(shape).reduce(\n (carry, key) => ({\n ...carry,\n [key]: next({ schema: shape[key] }),\n }),\n {} as Record<string, SchemaObject>\n );\n};\n\nconst makeSample = (depicted: SchemaObject) => {\n const type = (\n Array.isArray(depicted.type) ? depicted.type[0] : depicted.type\n ) as keyof typeof samples;\n return samples?.[type];\n};\n\nexport const depictEffect: Depicter<z.ZodEffects<z.ZodTypeAny>> = ({\n schema,\n isResponse,\n next,\n}) => {\n const input = next({ schema: schema.innerType() });\n const { effect } = schema._def;\n if (isResponse && effect.type === \"transform\") {\n const outputType = tryToTransform({ effect, sample: makeSample(input) });\n if (outputType && [\"number\", \"string\", \"boolean\"].includes(outputType)) {\n return { type: outputType as \"number\" | \"string\" | \"boolean\" };\n } else {\n return next({ schema: z.any() });\n }\n }\n if (!isResponse && effect.type === \"preprocess\") {\n const { type: inputType, ...rest } = input;\n return {\n ...rest,\n format: `${rest.format || inputType} (preprocessed)`,\n };\n }\n return input;\n};\n\nexport const depictPipeline: Depicter<z.ZodPipeline<any, any>> = ({\n schema,\n isResponse,\n next,\n}) => next({ schema: schema._def[isResponse ? \"out\" : \"in\"] });\n\nexport const depictBranded: Depicter<z.ZodBranded<z.ZodTypeAny, any>> = ({\n schema,\n next,\n}) => next({ schema: schema.unwrap() });\n\nexport const depictExamples = (\n schema: z.ZodTypeAny,\n isResponse: boolean,\n omitProps: string[] = []\n): MediaExamples => {\n const examples = getExamples(schema, isResponse);\n if (examples.length === 0) {\n return {};\n }\n return {\n examples: examples.reduce<ExamplesObject>(\n (carry, example, index) => ({\n ...carry,\n [`example${index + 1}`]: <ExampleObject>{\n value: omit(omitProps, example),\n },\n }),\n {}\n ),\n };\n};\n\nexport const depictParamExamples = (\n schema: z.ZodTypeAny,\n isResponse: boolean,\n param: string\n): MediaExamples => {\n const examples = getExamples(schema, isResponse);\n if (examples.length === 0) {\n return {};\n }\n return {\n examples: examples.reduce<ExamplesObject>(\n (carry, example, index) =>\n param in example\n ? {\n ...carry,\n [`example${index + 1}`]: <ExampleObject>{\n value: example[param],\n },\n }\n : carry,\n {}\n ),\n };\n};\n\nexport function extractObjectSchema(subject: IOSchema) {\n if (subject instanceof z.ZodObject) {\n return subject;\n }\n let objectSchema: z.AnyZodObject;\n if (\n subject instanceof z.ZodUnion ||\n subject instanceof z.ZodDiscriminatedUnion\n ) {\n objectSchema = Array.from(subject.options.values())\n .map((option) => extractObjectSchema(option))\n .reduce((acc, option) => acc.merge(option.partial()), z.object({}));\n } else if (subject instanceof z.ZodEffects) {\n if (hasTopLevelTransformingEffect(subject)) {\n throw new OpenAPIError(\n \"Using transformations on the top level of input schema is not allowed.\"\n );\n }\n objectSchema = extractObjectSchema(subject._def.schema); // object refinement\n } else {\n // intersection\n objectSchema = extractObjectSchema(subject._def.left).merge(\n extractObjectSchema(subject._def.right)\n );\n }\n return copyMeta(subject, objectSchema);\n}\n\nexport const depictRequestParams = ({\n path,\n method,\n endpoint,\n inputSources,\n}: ReqResDepictHelperCommonProps & {\n inputSources: InputSource[];\n}): ParameterObject[] => {\n const schema = endpoint.getSchema(\"input\");\n const shape = extractObjectSchema(schema).shape;\n const pathParams = getRoutePathParams(path);\n const isQueryEnabled = inputSources.includes(\"query\");\n const isParamsEnabled = inputSources.includes(\"params\");\n const isPathParam = (name: string) =>\n isParamsEnabled && pathParams.includes(name);\n return Object.keys(shape)\n .filter((name) => isQueryEnabled || isPathParam(name))\n .map((name) => ({\n name,\n in: isPathParam(name) ? \"path\" : \"query\",\n required: !shape[name].isOptional(),\n schema: {\n description: `${method.toUpperCase()} ${path} parameter`,\n ...walkSchema({\n schema: shape[name],\n isResponse: false,\n rules: depicters,\n onEach,\n onMissing,\n }),\n },\n ...depictParamExamples(schema, false, name),\n }));\n};\n\nexport const depicters: HandlingRules<SchemaObject, OpenAPIContext> = {\n ZodString: depictString,\n ZodNumber: depictNumber,\n ZodBigInt: depictBigInt,\n ZodBoolean: depictBoolean,\n ZodDateIn: depictDateIn,\n ZodDateOut: depictDateOut,\n ZodNull: depictNull,\n ZodArray: depictArray,\n ZodTuple: depictTuple,\n ZodRecord: depictRecord,\n ZodObject: depictObject,\n ZodLiteral: depictLiteral,\n ZodIntersection: depictIntersection,\n ZodUnion: depictUnion,\n ZodFile: depictFile,\n ZodUpload: depictUpload,\n ZodAny: depictAny,\n ZodDefault: depictDefault,\n ZodEnum: depictEnum,\n ZodNativeEnum: depictEnum,\n ZodEffects: depictEffect,\n ZodOptional: depictOptional,\n ZodNullable: depictNullable,\n ZodDiscriminatedUnion: depictDiscriminatedUnion,\n ZodBranded: depictBranded,\n ZodDate: depictDate,\n ZodCatch: depictCatch,\n ZodPipeline: depictPipeline,\n};\n\nexport const onEach: Depicter<z.ZodTypeAny, \"last\"> = ({\n schema,\n isResponse,\n}) => {\n const { description } = schema;\n const examples = getExamples(schema, isResponse);\n return {\n ...(description && { description }),\n ...(schema.isNullable() &&\n !(isResponse && hasCoercion(schema)) && { nullable: true }),\n ...(examples.length > 0 && { example: examples[0] }),\n };\n};\n\nexport const onMissing = (schema: z.ZodTypeAny) => {\n throw new OpenAPIError(`Zod type ${schema.constructor.name} is unsupported`);\n};\n\nexport const excludeParamsFromDepiction = (\n depicted: SchemaObject,\n pathParams: string[]\n): SchemaObject => {\n const properties = depicted.properties\n ? omit(pathParams, depicted.properties)\n : undefined;\n const example = depicted.example\n ? omit(pathParams, depicted.example)\n : undefined;\n const required = depicted.required\n ? depicted.required.filter((name) => !pathParams.includes(name))\n : undefined;\n const allOf = depicted.allOf\n ? (depicted.allOf as SchemaObject[]).map((entry) =>\n excludeParamsFromDepiction(entry, pathParams)\n )\n : undefined;\n const oneOf = depicted.oneOf\n ? (depicted.oneOf as SchemaObject[]).map((entry) =>\n excludeParamsFromDepiction(entry, pathParams)\n )\n : undefined;\n\n return omit(\n Object.entries({ properties, required, example, allOf, oneOf })\n .filter(([{}, value]) => value === undefined)\n .map(([key]) => key),\n {\n ...depicted,\n properties,\n required,\n example,\n allOf,\n oneOf,\n }\n );\n};\n\nexport const excludeExampleFromDepiction = (\n depicted: SchemaObject\n): SchemaObject => omit([\"example\"], depicted);\n\nexport const depictResponse = ({\n method,\n path,\n description,\n endpoint,\n isPositive,\n}: ReqResDepictHelperCommonProps & {\n description: string;\n isPositive: boolean;\n}): ResponseObject => {\n const schema = isPositive\n ? endpoint.getSchema(\"positive\")\n : endpoint.getSchema(\"negative\");\n const mimeTypes = isPositive\n ? endpoint.getMimeTypes(\"positive\")\n : endpoint.getMimeTypes(\"negative\");\n const depictedSchema = excludeExampleFromDepiction(\n walkSchema({\n schema,\n isResponse: true,\n rules: depicters,\n onEach,\n onMissing,\n })\n );\n const examples = depictExamples(schema, true);\n\n return {\n description: `${method.toUpperCase()} ${path} ${description}`,\n content: mimeTypes.reduce(\n (carry, mimeType) => ({\n ...carry,\n [mimeType]: {\n schema: depictedSchema,\n ...examples,\n },\n }),\n {} as ContentObject\n ),\n };\n};\n\ntype SecurityHelper<K extends Security[\"type\"]> = (\n security: Security & { type: K }\n) => SecuritySchemeObject;\n\nconst depictBasicSecurity: SecurityHelper<\"basic\"> = () => ({\n type: \"http\",\n scheme: \"basic\",\n});\nconst depictBearerSecurity: SecurityHelper<\"bearer\"> = ({\n format: bearerFormat,\n}) => ({\n type: \"http\",\n scheme: \"bearer\",\n ...(bearerFormat && { bearerFormat }),\n});\n// @todo add description on actual input placement\nconst depictInputSecurity: SecurityHelper<\"input\"> = ({ name }) => ({\n type: \"apiKey\",\n in: \"query\", // body is not supported yet, https://swagger.io/docs/specification/authentication/api-keys/\n name,\n});\nconst depictHeaderSecurity: SecurityHelper<\"header\"> = ({ name }) => ({\n type: \"apiKey\",\n in: \"header\",\n name,\n});\nconst depictCookieSecurity: SecurityHelper<\"cookie\"> = ({ name }) => ({\n type: \"apiKey\",\n in: \"cookie\",\n name,\n});\nconst depictOpenIdSecurity: SecurityHelper<\"openid\"> = ({\n url: openIdConnectUrl,\n}) => ({\n type: \"openIdConnect\",\n openIdConnectUrl,\n});\nconst depictOAuth2Security: SecurityHelper<\"oauth2\"> = ({ flows = {} }) => ({\n type: \"oauth2\",\n flows: (\n Object.keys(flows) as (keyof typeof flows)[]\n ).reduce<OAuthFlowsObject>((acc, key) => {\n const flow = flows[key];\n if (!flow) {\n return acc;\n }\n const { scopes = {}, ...rest } = flow;\n return { ...acc, [key]: { ...rest, scopes } };\n }, {}),\n});\n\nexport const depictSecurity = (\n container: LogicalContainer<Security>\n): LogicalContainer<SecuritySchemeObject> => {\n const methods: { [K in Security[\"type\"]]: SecurityHelper<K> } = {\n basic: depictBasicSecurity,\n bearer: depictBearerSecurity,\n input: depictInputSecurity,\n header: depictHeaderSecurity,\n cookie: depictCookieSecurity,\n openid: depictOpenIdSecurity,\n oauth2: depictOAuth2Security,\n };\n return mapLogicalContainer(container, (security) =>\n (methods[security.type] as SecurityHelper<typeof security.type>)(security)\n );\n};\n\nexport const depictSecurityRefs = (\n container: LogicalContainer<{ name: string; scopes: string[] }>\n): SecurityRequirementObject[] => {\n if (typeof container === \"object\") {\n if (\"or\" in container) {\n return container.or.map((entry) =>\n (\"and\" in entry\n ? entry.and\n : [entry]\n ).reduce<SecurityRequirementObject>(\n (agg, { name, scopes }) => ({\n ...agg,\n [name]: scopes,\n }),\n {}\n )\n );\n }\n if (\"and\" in container) {\n return depictSecurityRefs(andToOr(container));\n }\n }\n return depictSecurityRefs({ or: [container] });\n};\n\nexport const depictRequest = ({\n method,\n path,\n endpoint,\n}: ReqResDepictHelperCommonProps): RequestBodyObject => {\n const pathParams = getRoutePathParams(path);\n const bodyDepiction = excludeExampleFromDepiction(\n excludeParamsFromDepiction(\n walkSchema({\n schema: endpoint.getSchema(\"input\"),\n isResponse: false,\n rules: depicters,\n onEach,\n onMissing,\n }),\n pathParams\n )\n );\n const bodyExamples = depictExamples(\n endpoint.getSchema(\"input\"),\n false,\n pathParams\n );\n\n return {\n content: endpoint.getMimeTypes(\"input\").reduce(\n (carry, mimeType) => ({\n ...carry,\n [mimeType]: {\n schema: {\n description: `${method.toUpperCase()} ${path} request body`,\n ...bodyDepiction,\n },\n ...bodyExamples,\n },\n }),\n {} as ContentObject\n ),\n };\n};\n\nexport const depictTags = <TAG extends string>(\n tags: TagsConfig<TAG>\n): TagObject[] =>\n (Object.keys(tags) as TAG[]).map((tag) => {\n const def = tags[tag];\n return {\n name: tag,\n description: typeof def === \"string\" ? def : def.description,\n ...(typeof def === \"object\" &&\n def.url && { externalDocs: { url: def.url } }),\n };\n });\n\nexport const ensureShortDescription = (description: string) => {\n if (description.length <= shortDescriptionLimit) {\n return description;\n }\n return description.slice(0, shortDescriptionLimit - 1) + \"…\";\n};\n","import {\n INVALID,\n ParseInput,\n ParseReturnType,\n ZodIssueCode,\n ZodParsedType,\n ZodType,\n ZodTypeDef,\n addIssueToContext,\n} from \"zod\";\nimport { isValidDate } from \"./common-helpers\";\n\n// simple regex for ISO date, supports the following formats:\n// 2021-01-01T00:00:00.000Z\n// 2021-01-01T00:00:00.0Z\n// 2021-01-01T00:00:00Z\n// 2021-01-01T00:00:00\n// 2021-01-01\nexport const isoDateRegex =\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$/;\n\nconst zodDateInKind = \"ZodDateIn\";\n\nexport interface ZodDateInDef extends ZodTypeDef {\n typeName: typeof zodDateInKind;\n}\n\nexport class ZodDateIn extends ZodType<Date, ZodDateInDef, string> {\n _parse(input: ParseInput): ParseReturnType<Date> {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.string) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n\n if (!isoDateRegex.test(ctx.data as string)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"regex\",\n });\n status.dirty();\n }\n\n const date = new Date(ctx.data);\n\n if (!isValidDate(date)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n\n return { status: status.value, value: date };\n }\n\n static create = () =>\n new ZodDateIn({\n typeName: zodDateInKind,\n });\n}\n","import { z } from \"zod\";\nimport { ProprietaryKinds } from \"./ez-namespace\";\n\nexport type HandlingVariant = \"last\" | \"regular\";\ntype VariantDependingProps<\n Variant extends HandlingVariant,\n U\n> = Variant extends \"regular\"\n ? {\n next: SchemaHandler<z.ZodTypeAny, U, {}, \"last\">;\n }\n : {};\n\ntype SchemaHandlingProps<\n T extends z.ZodTypeAny,\n U,\n Context extends object,\n Variant extends HandlingVariant\n> = {\n schema: T;\n} & Context &\n VariantDependingProps<Variant, U>;\n\nexport type SchemaHandler<\n T extends z.ZodTypeAny,\n U,\n Context extends object = {},\n Variant extends HandlingVariant = \"regular\"\n> = (params: SchemaHandlingProps<T, U, Context, Variant>) => U;\n\nexport type HandlingRules<U, Context extends object = {}> = Partial<\n Record<\n z.ZodFirstPartyTypeKind | ProprietaryKinds,\n SchemaHandler<any, U, Context>\n >\n>;\n\nexport const walkSchema = <U, Context extends object = {}>({\n schema,\n onEach,\n rules,\n onMissing,\n ...context\n}: SchemaHandlingProps<z.ZodTypeAny, U, Context, \"last\"> & {\n onEach?: SchemaHandler<z.ZodTypeAny, U, Context, \"last\">;\n rules: HandlingRules<U, Context>;\n onMissing: (schema: z.ZodTypeAny) => U;\n}): U => {\n const overrides = onEach && onEach({ schema, ...(context as Context) });\n const handler =\n \"typeName\" in schema._def\n ? rules[schema._def.typeName as keyof typeof rules]\n : undefined;\n const next: SchemaHandler<z.ZodTypeAny, U, {}, \"last\"> = (params) =>\n walkSchema({\n ...params,\n ...(context as Context),\n onEach,\n rules: rules,\n onMissing,\n });\n const result = handler\n ? handler({\n schema,\n ...(context as Context),\n next,\n })\n : onMissing(schema);\n return overrides ? { ...result, ...overrides } : result;\n};\n","import { Request, Response } from \"express\";\nimport http from \"http\";\nimport { Logger } from \"winston\";\nimport { CommonConfig } from \"./config-type\";\nimport { AbstractEndpoint } from \"./endpoint\";\nimport { mimeJson } from \"./mime\";\n\ninterface TestEndpointProps<REQ, RES, LOG> {\n endpoint: AbstractEndpoint;\n requestProps?: REQ;\n responseProps?: RES;\n configProps?: Partial<CommonConfig>;\n loggerProps?: LOG;\n /** @deprecated for testing purposes only */\n __noJest?: boolean;\n}\n\nexport const makeRequestMock = <REQ>(requestProps?: REQ) =>\n <\n { method: string } & Record<\"header\", jest.Mock> &\n (REQ extends undefined ? {} : REQ)\n >{\n method: \"GET\",\n header: jest.fn(() => mimeJson),\n ...requestProps,\n };\n\nexport const makeResponseMock = <RES>(responseProps?: RES) => {\n const responseMock = <\n {\n writableEnded: boolean;\n statusCode: number;\n statusMessage: string;\n } & Record<\"set\" | \"status\" | \"json\" | \"end\", jest.Mock> &\n (RES extends undefined ? {} : RES)\n >{\n writableEnded: false,\n statusCode: 200,\n statusMessage: http.STATUS_CODES[200],\n set: jest.fn(() => responseMock),\n status: jest.fn((code: number) => {\n responseMock.statusCode = code;\n responseMock.statusMessage = http.STATUS_CODES[code]!;\n return responseMock;\n }),\n json: jest.fn(() => responseMock),\n end: jest.fn(() => {\n responseMock.writableEnded = true;\n return responseMock;\n }),\n ...responseProps,\n };\n return responseMock;\n};\n\n/**\n * @description You need to install Jest and probably @types/jest to use this method\n */\nexport const testEndpoint = async <\n REQ extends Partial<Record<keyof Request, any>> | undefined = undefined,\n RES extends Partial<Record<keyof Response, any>> | undefined = undefined,\n LOG extends Partial<Record<keyof Logger, any>> | undefined = undefined\n>({\n endpoint,\n requestProps,\n responseProps,\n configProps,\n loggerProps,\n __noJest,\n}: TestEndpointProps<REQ, RES, LOG>) => {\n if (!jest || __noJest) {\n throw new Error(\"You need to install Jest in order to use testEndpoint().\");\n }\n const requestMock = makeRequestMock(requestProps);\n const responseMock = makeResponseMock(responseProps);\n const loggerMock = <\n Record<\"info\" | \"warn\" | \"error\" | \"debug\", jest.Mock> &\n (LOG extends undefined ? {} : LOG)\n >{\n info: jest.fn(),\n warn: jest.fn(),\n error: jest.fn(),\n debug: jest.fn(),\n ...loggerProps,\n };\n const configMock = {\n cors: false,\n logger: loggerMock,\n ...configProps,\n };\n await endpoint.execute({\n request: requestMock as unknown as Request,\n response: responseMock as unknown as Response,\n config: configMock as CommonConfig,\n logger: loggerMock as unknown as Logger,\n });\n return { requestMock, responseMock, loggerMock };\n};\n","import ts from \"typescript\";\nimport {\n exportModifier,\n f,\n makeAnyPromise,\n makeConst,\n makeEmptyInitializingConstructor,\n makeImplementationCallFn,\n makeIndexedPromise,\n makeObjectKeysReducer,\n makeParam,\n makeParams,\n makePublicClass,\n makePublicExtendedInterface,\n makePublicLiteralType,\n makePublicReadonlyProp,\n makePublicType,\n makeQuotedProp,\n makeRecord,\n makeTemplate,\n makeTypeParams,\n parametricIndexNode,\n protectedReadonlyModifier,\n} from \"./client-helpers\";\nimport { makeCleanId } from \"./common-helpers\";\nimport { methods } from \"./method\";\nimport { mimeJson } from \"./mime\";\nimport { Routing } from \"./routing\";\nimport { walkRouting } from \"./routing-walker\";\nimport { zodToTs } from \"./zts\";\nimport { createTypeAlias, printNode } from \"./zts-helpers\";\n\ninterface Registry {\n [METHOD_PATH: string]: Record<\"in\" | \"out\", string> & { isJson: boolean };\n}\n\nexport class Client {\n protected agg: ts.Node[] = [];\n protected registry: Registry = {};\n protected paths: string[] = [];\n\n constructor(routing: Routing) {\n walkRouting({\n routing,\n onEndpoint: (endpoint, path, method) => {\n const inputId = makeCleanId(path, method, \"input\");\n const responseId = makeCleanId(path, method, \"response\");\n const input = zodToTs({\n schema: endpoint.getSchema(\"input\"),\n isResponse: false,\n });\n const response = zodToTs({\n isResponse: true,\n schema: endpoint\n .getSchema(\"positive\")\n .or(endpoint.getSchema(\"negative\")),\n });\n const inputAlias = createTypeAlias(input, inputId);\n const responseAlias = createTypeAlias(response, responseId);\n this.agg.push(inputAlias);\n this.agg.push(responseAlias);\n if (method !== \"options\") {\n this.paths.push(path);\n this.registry[`${method} ${path}`] = {\n in: inputId,\n out: responseId,\n isJson: endpoint.getMimeTypes(\"positive\").includes(mimeJson),\n };\n }\n },\n });\n\n const pathNode = makePublicLiteralType(\"Path\", this.paths);\n const methodNode = makePublicLiteralType(\"Method\", methods);\n\n const methodPathNode = makePublicType(\n \"MethodPath\",\n makeTemplate([methodNode.name, pathNode.name])\n );\n\n const extenderClause = [\n f.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [\n makeRecord(methodPathNode.name, ts.SyntaxKind.AnyKeyword),\n ]),\n ];\n\n const inputNode = makePublicExtendedInterface(\n \"Input\",\n extenderClause,\n Object.keys(this.registry).map((methodPath) =>\n makeQuotedProp(methodPath, this.registry[methodPath].in)\n )\n );\n\n const responseNode = makePublicExtendedInterface(\n \"Response\",\n extenderClause,\n Object.keys(this.registry).map((methodPath) =>\n makeQuotedProp(methodPath, this.registry[methodPath].out)\n )\n );\n\n const jsonEndpointsNode = f.createVariableStatement(\n exportModifier,\n makeConst(\n \"jsonEndpoints\",\n f.createObjectLiteralExpression(\n Object.keys(this.registry)\n .filter((methodPath) => this.registry[methodPath].isJson)\n .map((methodPath) =>\n f.createPropertyAssignment(`\"${methodPath}\"`, f.createTrue())\n )\n )\n )\n );\n\n const providerNode = makePublicType(\n \"Provider\",\n f.createFunctionTypeNode(\n makeTypeParams({ M: methodNode.name, P: pathNode.name }),\n makeParams({\n method: f.createTypeReferenceNode(\"M\"),\n path: f.createTypeReferenceNode(\"P\"),\n params: f.createIndexedAccessTypeNode(\n f.createTypeReferenceNode(inputNode.name),\n parametricIndexNode\n ),\n }),\n makeIndexedPromise(responseNode.name, parametricIndexNode)\n )\n );\n\n const implementationNode = makePublicType(\n \"Implementation\",\n f.createFunctionTypeNode(\n undefined,\n makeParams({\n method: f.createTypeReferenceNode(methodNode.name),\n path: f.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),\n params: makeRecord(\n ts.SyntaxKind.StringKeyword,\n ts.SyntaxKind.AnyKeyword\n ),\n }),\n makeAnyPromise()\n )\n );\n\n const keyParamExpression = f.createTemplateExpression(\n f.createTemplateHead(\":\"),\n [\n f.createTemplateSpan(\n f.createIdentifier(\"key\"),\n f.createTemplateTail(\"\")\n ),\n ]\n );\n\n const clientNode = makePublicClass(\n \"ExpressZodAPIClient\",\n makeEmptyInitializingConstructor([\n makeParam(\n \"implementation\",\n f.createTypeReferenceNode(implementationNode.name),\n protectedReadonlyModifier\n ),\n ]),\n [\n makePublicReadonlyProp(\n \"provide\",\n f.createTypeReferenceNode(providerNode.name),\n makeImplementationCallFn(\n [\"method\", \"path\", \"params\"],\n [\n f.createIdentifier(\"method\"),\n makeObjectKeysReducer(\n \"params\",\n f.createCallExpression(\n f.createPropertyAccessExpression(\n f.createIdentifier(\"acc\"),\n \"replace\"\n ),\n undefined,\n [\n keyParamExpression,\n f.createElementAccessExpression(\n f.createIdentifier(\"params\"),\n f.createIdentifier(\"key\")\n ),\n ]\n ),\n f.createIdentifier(\"path\")\n ),\n makeObjectKeysReducer(\n \"params\",\n f.createConditionalExpression(\n f.createBinaryExpression(\n f.createCallExpression(\n f.createPropertyAccessExpression(\n f.createIdentifier(\"path\"),\n \"indexOf\"\n ),\n undefined,\n [keyParamExpression]\n ),\n ts.SyntaxKind.GreaterThanEqualsToken,\n f.createNumericLiteral(0)\n ),\n undefined,\n f.createIdentifier(\"acc\"),\n undefined,\n f.createObjectLiteralExpression([\n f.createSpreadAssignment(f.createIdentifier(\"acc\")),\n f.createPropertyAssignment(\n \"[key]\", // @todo is there a better way to do it?\n f.createElementAccessExpression(\n f.createIdentifier(\"params\"),\n f.createIdentifier(\"key\")\n )\n ),\n ])\n ),\n f.createObjectLiteralExpression()\n ),\n ]\n )\n ),\n ]\n );\n\n ts.addSyntheticLeadingComment(\n clientNode,\n ts.SyntaxKind.MultiLineCommentTrivia,\n \"\\n\" +\n \"export const exampleImplementation: Implementation = async (\\n\" +\n \" method,\\n\" +\n \" path,\\n\" +\n \" params\\n\" +\n \") => {\\n\" +\n \" const searchParams =\\n\" +\n ' method === \"get\" ? `?${new URLSearchParams(params)}` : \"\";\\n' +\n \" const response = await fetch(`https://example.com${path}${searchParams}`, {\\n\" +\n \" method: method.toUpperCase(),\\n\" +\n \" headers:\\n\" +\n ' method === \"get\" ? undefined : { \"Content-Type\": \"application/json\" },\\n' +\n ' body: method === \"get\" ? undefined : JSON.stringify(params),\\n' +\n \" });\\n\" +\n \" if (`${method} ${path}` in jsonEndpoints) {\\n\" +\n \" return response.json();\\n\" +\n \" }\\n\" +\n \" return response.text();\\n\" +\n \"};\\n\" +\n \"\\n\" +\n \"const client = new ExpressZodAPIClient(exampleImplementation);\\n\" +\n 'client.provide(\"get\", \"/v1/user/retrieve\", { id: \"10\" });\\n',\n true\n );\n\n this.agg.push(\n pathNode,\n methodNode,\n methodPathNode,\n inputNode,\n responseNode,\n jsonEndpointsNode,\n providerNode,\n implementationNode,\n clientNode\n );\n }\n\n public print(printerOptions?: ts.PrinterOptions) {\n return this.agg.map((node) => printNode(node, printerOptions)).join(\"\\n\\n\");\n }\n}\n","import ts from \"typescript\";\n\nexport const f = ts.factory;\n\nexport const exportModifier = [f.createModifier(ts.SyntaxKind.ExportKeyword)];\n\nexport const publicReadonlyModifier = [\n f.createModifier(ts.SyntaxKind.PublicKeyword),\n f.createModifier(ts.SyntaxKind.ReadonlyKeyword),\n];\n\nexport const protectedReadonlyModifier = [\n f.createModifier(ts.SyntaxKind.ProtectedKeyword),\n f.createModifier(ts.SyntaxKind.ReadonlyKeyword),\n];\n\nconst emptyPrefix = f.createTemplateHead(\"\");\n\nconst emptyEnding = f.createTemplateTail(\"\");\n\nconst spacingSuffix = f.createTemplateMiddle(\" \");\n\nexport const makeTemplate = (names: (ts.Identifier | string)[]) =>\n f.createTemplateLiteralType(\n emptyPrefix,\n names.map((name, index) =>\n f.createTemplateLiteralTypeSpan(\n f.createTypeReferenceNode(name),\n index === names.length - 1 ? emptyEnding : spacingSuffix\n )\n )\n );\n\nexport const parametricIndexNode = makeTemplate([\"M\", \"P\"]);\n\nexport const makeParam = (\n name: string,\n type?: ts.TypeNode,\n mod?: ts.Modifier[]\n) => f.createParameterDeclaration(mod, undefined, name, undefined, type);\n\nexport const makeParams = (\n params: Record<string, ts.TypeNode | undefined>,\n mod?: ts.Modifier[]\n) =>\n Object.keys(params).reduce(\n (acc, name) => acc.concat(makeParam(name, params[name], mod)),\n [] as ts.ParameterDeclaration[]\n );\n\nexport const makeRecord = (\n key: ts.Identifier | ts.KeywordTypeSyntaxKind,\n value: ts.KeywordTypeSyntaxKind\n) =>\n f.createExpressionWithTypeArguments(f.createIdentifier(\"Record\"), [\n typeof key === \"number\"\n ? f.createKeywordTypeNode(key)\n : f.createTypeReferenceNode(key),\n f.createKeywordTypeNode(value),\n ]);\n\nexport const makeEmptyInitializingConstructor = (\n params: ts.ParameterDeclaration[]\n) => f.createConstructorDeclaration(undefined, params, f.createBlock([]));\n\nexport const makeQuotedProp = (name: string, ref: string) =>\n f.createPropertySignature(\n undefined,\n `\"${name}\"`,\n undefined,\n f.createTypeReferenceNode(ref)\n );\n\nexport const makeConst = (name: string, value: ts.Expression) =>\n f.createVariableDeclarationList(\n [f.createVariableDeclaration(name, undefined, undefined, value)],\n ts.NodeFlags.Const\n );\n\nexport const makePublicLiteralType = (name: string, literals: string[]) =>\n f.createTypeAliasDeclaration(\n exportModifier,\n name,\n undefined,\n f.createUnionTypeNode(\n literals.map((option) =>\n f.createLiteralTypeNode(f.createStringLiteral(option))\n )\n )\n );\n\nexport const makePublicType = (name: string, value: ts.TypeNode) =>\n f.createTypeAliasDeclaration(exportModifier, name, undefined, value);\n\nexport const makePublicReadonlyProp = (\n name: string,\n type: ts.TypeNode,\n exp: ts.Expression\n) =>\n f.createPropertyDeclaration(\n publicReadonlyModifier,\n name,\n undefined,\n type,\n exp\n );\n\nexport const makePublicClass = (\n name: string,\n constructor: ts.ConstructorDeclaration,\n props: ts.PropertyDeclaration[] = []\n) =>\n f.createClassDeclaration(exportModifier, name, undefined, undefined, [\n constructor,\n ...props,\n ]);\n\nexport const makeIndexedPromise = (type: ts.Identifier, index: ts.TypeNode) =>\n f.createTypeReferenceNode(\"Promise\", [\n f.createIndexedAccessTypeNode(f.createTypeReferenceNode(type), index),\n ]);\n\nexport const makeAnyPromise = () =>\n f.createTypeReferenceNode(\"Promise\", [\n f.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),\n ]);\n\nexport const makePublicExtendedInterface = (\n name: string,\n extender: ts.HeritageClause[],\n props: ts.PropertySignature[]\n) =>\n f.createInterfaceDeclaration(\n exportModifier,\n name,\n undefined,\n extender,\n props\n );\n\nexport const makeTypeParams = (params: Record<string, ts.Identifier>) =>\n Object.keys(params).reduce(\n (acc, name) =>\n acc.concat(\n f.createTypeParameterDeclaration(\n [],\n name,\n f.createTypeReferenceNode(params[name])\n )\n ),\n [] as ts.TypeParameterDeclaration[]\n );\n\nexport const makeImplementationCallFn = (\n params: string[],\n args: ts.Expression[]\n) =>\n f.createArrowFunction(\n undefined,\n undefined,\n params.map((key) => makeParam(key)),\n undefined,\n undefined,\n f.createCallExpression(\n f.createPropertyAccessExpression(f.createThis(), \"implementation\"),\n undefined,\n args\n )\n );\n\nexport const makeObjectKeysReducer = (\n obj: string,\n exp: ts.Expression,\n initial: ts.Expression\n) =>\n f.createCallExpression(\n f.createPropertyAccessExpression(\n f.createCallExpression(\n f.createPropertyAccessExpression(f.createIdentifier(\"Object\"), \"keys\"),\n undefined,\n [f.createIdentifier(obj)]\n ),\n \"reduce\"\n ),\n undefined,\n [\n f.createArrowFunction(\n undefined,\n undefined,\n makeParams({ acc: undefined, key: undefined }),\n undefined,\n undefined,\n exp\n ),\n initial,\n ]\n );\n","/**\n * This file is based on https://github.com/sachinraja/zod-to-ts\n *\n * MIT License\n *\n * Copyright (c) 2021 Sachin Raja\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport ts from \"typescript\";\nimport { z } from \"zod\";\nimport { hasCoercion, tryToTransform } from \"./common-helpers\";\nimport { HandlingRules, walkSchema } from \"./schema-walker\";\nimport {\n LiteralType,\n Producer,\n ZTSContext,\n addJsDocComment,\n makePropertyIdentifier,\n} from \"./zts-helpers\";\n\nconst { factory: f } = ts;\n\nconst samples: Partial<Record<ts.KeywordTypeSyntaxKind, any>> = {\n [ts.SyntaxKind.AnyKeyword]: \"\",\n [ts.SyntaxKind.BigIntKeyword]: BigInt(0),\n [ts.SyntaxKind.BooleanKeyword]: false,\n [ts.SyntaxKind.NumberKeyword]: 0,\n [ts.SyntaxKind.ObjectKeyword]: {},\n [ts.SyntaxKind.StringKeyword]: \"\",\n [ts.SyntaxKind.UndefinedKeyword]: undefined,\n};\n\nconst onLiteral: Producer<z.ZodLiteral<LiteralType>> = ({\n schema: { value },\n}) =>\n f.createLiteralTypeNode(\n typeof value === \"number\"\n ? f.createNumericLiteral(value)\n : typeof value === \"boolean\"\n ? value\n ? f.createTrue()\n : f.createFalse()\n : f.createStringLiteral(value)\n );\n\nconst onObject: Producer<z.ZodObject<z.ZodRawShape>> = ({\n schema: { shape },\n isResponse,\n next,\n}) => {\n const members = Object.entries(shape).map<ts.TypeElement>(([key, value]) => {\n const isOptional =\n isResponse && hasCoercion(value)\n ? value instanceof z.ZodOptional\n : value.isOptional();\n const propertySignature = f.createPropertySignature(\n undefined,\n makePropertyIdentifier(key),\n isOptional ? f.createToken(ts.SyntaxKind.QuestionToken) : undefined,\n next({ schema: value })\n );\n if (value.description) {\n addJsDocComment(propertySignature, value.description);\n }\n return propertySignature;\n });\n return f.createTypeLiteralNode(members);\n};\n\nconst onArray: Producer<z.ZodArray<z.ZodTypeAny>> = ({\n schema: { element },\n next,\n}) => f.createArrayTypeNode(next({ schema: element }));\n\nconst onEnum: Producer<z.ZodEnum<[string, ...string[]]>> = ({\n schema: { options },\n}) =>\n f.createUnionTypeNode(\n options.map((option) =>\n f.createLiteralTypeNode(f.createStringLiteral(option))\n )\n );\n\nconst onSomeUnion: Producer<\n | z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]>\n | z.ZodDiscriminatedUnion<string, z.ZodObject<z.ZodRawShape>[]>\n> = ({ schema: { options }, next }) =>\n f.createUnionTypeNode(options.map((option) => next({ schema: option })));\n\nconst makeSample = (produced: ts.TypeNode) =>\n samples?.[produced.kind as keyof typeof samples];\n\nconst onEffects: Producer<z.ZodEffects<z.ZodTypeAny>> = ({\n schema,\n next,\n isResponse,\n}) => {\n const input = next({ schema: schema.innerType() });\n const effect = schema._def.effect;\n if (isResponse && effect.type === \"transform\") {\n const outputType = tryToTransform({ effect, sample: makeSample(input) });\n const resolutions: Partial<\n Record<NonNullable<typeof outputType>, ts.KeywordTypeSyntaxKind>\n > = {\n number: ts.SyntaxKind.NumberKeyword,\n bigint: ts.SyntaxKind.BigIntKeyword,\n boolean: ts.SyntaxKind.BooleanKeyword,\n string: ts.SyntaxKind.StringKeyword,\n undefined: ts.SyntaxKind.UndefinedKeyword,\n object: ts.SyntaxKind.ObjectKeyword,\n };\n return f.createKeywordTypeNode(\n (outputType && resolutions[outputType]) || ts.SyntaxKind.AnyKeyword\n );\n }\n return input;\n};\n\nconst onNativeEnum: Producer<z.ZodNativeEnum<z.EnumLike>> = ({ schema }) =>\n f.createUnionTypeNode(\n Object.values(schema.enum).map((value) =>\n f.createLiteralTypeNode(\n typeof value === \"number\"\n ? f.createNumericLiteral(value)\n : f.createStringLiteral(value)\n )\n )\n );\n\nconst onOptional: Producer<z.ZodOptional<z.ZodTypeAny>> = ({ next, schema }) =>\n f.createUnionTypeNode([\n next({ schema: schema.unwrap() }),\n f.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),\n ]);\n\nconst onNullable: Producer<z.ZodNullable<z.ZodTypeAny>> = ({ next, schema }) =>\n f.createUnionTypeNode([\n next({ schema: schema.unwrap() }),\n f.createLiteralTypeNode(f.createNull()),\n ]);\n\nconst onTuple: Producer<z.ZodTuple> = ({ next, schema: { items } }) =>\n f.createTupleTypeNode(items.map((option) => next({ schema: option })));\n\nconst onRecord: Producer<z.ZodRecord> = ({\n next,\n schema: { keySchema, valueSchema },\n}) =>\n f.createExpressionWithTypeArguments(f.createIdentifier(\"Record\"), [\n next({ schema: keySchema }),\n next({ schema: valueSchema }),\n ]);\n\nconst onIntersection: Producer<\n z.ZodIntersection<z.ZodTypeAny, z.ZodTypeAny>\n> = ({ next, schema }) =>\n f.createIntersectionTypeNode(\n [schema._def.left, schema._def.right].map((entry) =>\n next({ schema: entry })\n )\n );\n\nconst onDefault: Producer<z.ZodDefault<z.ZodTypeAny>> = ({ next, schema }) =>\n next({ schema: schema._def.innerType });\n\nconst onPrimitive =\n (syntaxKind: ts.KeywordTypeSyntaxKind): Producer<z.ZodTypeAny> =>\n () =>\n f.createKeywordTypeNode(syntaxKind);\n\nconst onBranded: Producer<z.ZodBranded<z.ZodTypeAny, any>> = ({\n next,\n schema,\n}) => next({ schema: schema.unwrap() });\n\nconst onCatch: Producer<z.ZodCatch<z.ZodTypeAny>> = ({ next, schema }) =>\n next({ schema: schema._def.innerType });\n\nconst onPipeline: Producer<z.ZodPipeline<z.ZodTypeAny, z.ZodTypeAny>> = ({\n schema,\n next,\n isResponse,\n}) => next({ schema: schema._def[isResponse ? \"out\" : \"in\"] });\n\nconst onNull: Producer<z.ZodNull> = () =>\n f.createLiteralTypeNode(f.createNull());\n\nconst producers: HandlingRules<ts.TypeNode, ZTSContext> = {\n ZodString: onPrimitive(ts.SyntaxKind.StringKeyword),\n ZodNumber: onPrimitive(ts.SyntaxKind.NumberKeyword),\n ZodBigInt: onPrimitive(ts.SyntaxKind.BigIntKeyword),\n ZodBoolean: onPrimitive(ts.SyntaxKind.BooleanKeyword),\n ZodDateIn: onPrimitive(ts.SyntaxKind.StringKeyword),\n ZodDateOut: onPrimitive(ts.SyntaxKind.StringKeyword),\n ZodNull: onNull,\n ZodArray: onArray,\n ZodTuple: onTuple,\n ZodRecord: onRecord,\n ZodObject: onObject,\n ZodLiteral: onLiteral,\n ZodIntersection: onIntersection,\n ZodUnion: onSomeUnion,\n ZodFile: onPrimitive(ts.SyntaxKind.StringKeyword),\n // ZodUpload:\n ZodAny: onPrimitive(ts.SyntaxKind.AnyKeyword),\n ZodDefault: onDefault,\n ZodEnum: onEnum,\n ZodNativeEnum: onNativeEnum,\n ZodEffects: onEffects,\n ZodOptional: onOptional,\n ZodNullable: onNullable,\n ZodDiscriminatedUnion: onSomeUnion,\n ZodBranded: onBranded,\n ZodCatch: onCatch,\n ZodPipeline: onPipeline,\n};\n\nexport const zodToTs = ({\n schema,\n ...context\n}: {\n schema: z.ZodTypeAny;\n} & ZTSContext) =>\n walkSchema<ts.TypeNode, ZTSContext>({\n schema,\n rules: producers,\n onMissing: () => f.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),\n ...context,\n });\n","/**\n * This file is based on https://github.com/sachinraja/zod-to-ts\n *\n * MIT License\n *\n * Copyright (c) 2021 Sachin Raja\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport ts from \"typescript\";\nimport { z } from \"zod\";\nimport { SchemaHandler } from \"./schema-walker\";\n\nconst { factory: f } = ts;\n\nexport type LiteralType = string | number | boolean;\n\nexport type ZTSContext = { isResponse?: boolean };\n\nexport type Producer<T extends z.ZodTypeAny> = SchemaHandler<\n T,\n ts.TypeNode,\n ZTSContext\n>;\n\nexport const addJsDocComment = (node: ts.Node, text: string) => {\n ts.addSyntheticLeadingComment(\n node,\n ts.SyntaxKind.MultiLineCommentTrivia,\n `* ${text} `,\n true\n );\n};\n\nexport const createTypeAlias = (\n node: ts.TypeNode,\n identifier: string,\n comment?: string\n) => {\n const typeAlias = f.createTypeAliasDeclaration(\n undefined,\n f.createIdentifier(identifier),\n undefined,\n node\n );\n if (comment) {\n addJsDocComment(typeAlias, comment);\n }\n return typeAlias;\n};\n\nexport const printNode = (\n node: ts.Node,\n printerOptions?: ts.PrinterOptions\n) => {\n const sourceFile = ts.createSourceFile(\n \"print.ts\",\n \"\",\n ts.ScriptTarget.Latest,\n false,\n ts.ScriptKind.TS\n );\n const printer = ts.createPrinter(printerOptions);\n return printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);\n};\n\nconst safePropRegex = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nexport const makePropertyIdentifier = (name: string) => {\n if (safePropRegex.test(name)) {\n return f.createIdentifier(name);\n }\n return f.createStringLiteral(name);\n};\n","import {\n INVALID,\n ParseInput,\n ParseReturnType,\n ZodIssueCode,\n ZodParsedType,\n ZodType,\n ZodTypeDef,\n addIssueToContext,\n} from \"zod\";\nimport { isValidDate } from \"./common-helpers\";\n\nconst zodDateOutKind = \"ZodDateOut\";\n\nexport interface ZodDateOutDef extends ZodTypeDef {\n typeName: typeof zodDateOutKind;\n}\n\nexport class ZodDateOut extends ZodType<string, ZodDateOutDef, Date> {\n _parse(input: ParseInput): ParseReturnType<string> {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.date) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n\n if (!isValidDate(ctx.data)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n\n return { status: status.value, value: (ctx.data as Date).toISOString() };\n }\n\n static create = () =>\n new ZodDateOut({\n typeName: zodDateOutKind,\n });\n}\n","import {\n INVALID,\n ParseInput,\n ParseReturnType,\n ZodIssueCode,\n ZodParsedType,\n ZodType,\n ZodTypeDef,\n addIssueToContext,\n} from \"zod\";\nimport { ErrMessage, errToObj } from \"./common-helpers\";\n\nconst zodFileKind = \"ZodFile\";\n\ndeclare type ZodFileCheck =\n | {\n kind: \"binary\";\n message?: string;\n }\n | {\n kind: \"base64\";\n message?: string;\n };\n\nexport interface ZodFileDef extends ZodTypeDef {\n checks: ZodFileCheck[];\n typeName: typeof zodFileKind;\n}\n\nconst base64Regex =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n\nexport class ZodFile extends ZodType<string, ZodFileDef> {\n _parse(input: ParseInput): ParseReturnType<string> {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.string) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n\n for (const check of this._def.checks) {\n if (check.kind === \"base64\") {\n if (!base64Regex.test(ctx.data)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.custom,\n message: check.message,\n });\n status.dirty();\n }\n }\n }\n\n return { status: status.value, value: ctx.data };\n }\n\n binary = (message?: ErrMessage) =>\n new ZodFile({\n ...this._def,\n checks: [...this._def.checks, { kind: \"binary\", ...errToObj(message) }],\n });\n\n base64 = (message?: ErrMessage) =>\n new ZodFile({\n ...this._def,\n checks: [...this._def.checks, { kind: \"base64\", ...errToObj(message) }],\n });\n\n get isBinary() {\n return !!this._def.checks.find((check) => check.kind === \"binary\");\n }\n\n get isBase64() {\n return !!this._def.checks.find((check) => check.kind === \"base64\");\n }\n\n static create = () =>\n new ZodFile({\n checks: [],\n typeName: zodFileKind,\n });\n}\n","import { ZodDateIn, ZodDateInDef } from \"./date-in-schema\";\nimport { ZodDateOut, ZodDateOutDef } from \"./date-out-schema\";\nimport { ZodFile, ZodFileDef } from \"./file-schema\";\nimport { ZodUpload, ZodUploadDef } from \"./upload-schema\";\n\nexport namespace ez {\n export const file = ZodFile.create;\n export const upload = ZodUpload.create;\n export const dateIn = ZodDateIn.create;\n export const dateOut = ZodDateOut.create;\n}\n\nexport type ProprietaryKinds =\n | ZodFileDef[\"typeName\"]\n | ZodUploadDef[\"typeName\"]\n | ZodDateInDef[\"typeName\"]\n | ZodDateOutDef[\"typeName\"];\n"],"mappings":"w0BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,EAAA,WAAAC,GAAA,oBAAAC,GAAA,yBAAAC,GAAA,qBAAAC,GAAA,yBAAAC,EAAA,YAAAC,GAAA,iBAAAC,EAAA,0BAAAC,EAAA,iBAAAC,EAAA,gBAAAC,GAAA,kBAAAC,GAAA,iBAAAC,GAAA,uBAAAC,QAAA,iBAAAC,GAAA,qBAAAC,GAAA,wBAAAC,GAAA,iBAAAC,GAAA,4BAAAC,GAAA,yBAAAC,EAAA,OAAAC,GAAA,wBAAAC,EAAA,2BAAAC,GAAA,iBAAAC,GAAA,aAAAC,IAAA,eAAAC,GAAA3B,ICUO,IAAM4B,GAAe,CAC1B,OAAQ,GACR,KAAM,GACN,MAAO,EACT,EAmFaC,GAIXC,GACMA,ECpGR,IAAAC,EAAkB,eCDlB,IAAAC,GAA0B,uBAC1BC,EAAkB,eCAlB,IAAAC,GAAsC,iBAEzBC,EAAW,oBA+BlBC,GAA8CC,GAA2B,CAC7E,IAAMC,EAAQD,EAAe,YACvBE,KAAM,UAAMF,EAAO,IAAI,EAC7B,OAAAE,EAAIJ,CAAQ,EAAII,EAAIJ,CAAQ,GAAK,CAAE,SAAU,CAAC,CAAE,EACzC,IA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,GAAY,KAAKM,EAAI,IAAI,OAC5B,qBAAkBA,EAAK,CACrB,KAAM,eAAa,OACnB,QAASC,EAAM,OACjB,CAAC,EACDF,EAAO,MAAM,IAKnB,MAAO,CAAE,OAAQA,EAAO,MAAO,MAAOC,EAAI,IAAK,CACjD,CAcA,IAAI,UAAW,CACb,MAAO,CAAC,CAAC,KAAK,KAAK,OAAO,KAAMC,GAAUA,EAAM,OAAS,QAAQ,CACnE,CAEA,IAAI,UAAW,CACb,MAAO,CAAC,CAAC,KAAK,KAAK,OAAO,KAAMA,GAAUA,EAAM,OAAS,QAAQ,CACnE,CAOF,EApDaC,GAANP,GAAMO,GA+CJ,OAAS,IACd,IAAIP,GAAQ,CACV,OAAQ,CAAC,EACT,SAAUF,EACZ,CAAC,EC9EE,IAAUU,QACFA,EAAA,KAAOC,GAAQ,OACfD,EAAA,OAASE,EAAU,OACnBF,EAAA,OAASG,GAAU,OACnBH,EAAA,QAAUI,GAAW,SAJnBJ,QAAA,KhCyBjB,IAAAK,GAA4B","names":["src_exports","__export","AbstractEndpoint","Client","DependsOnMethod","DependsOnMethodError","EndpointsFactory","InputValidationError","OpenAPI","OpenAPIError","OutputValidationError","RoutingError","ServeStatic","attachRouting","createConfig","createHttpError","createLogger","createMiddleware","createResultHandler","createServer","defaultEndpointsFactory","defaultResultHandler","ez","getMessageFromError","getStatusCodeFromError","testEndpoint","withMeta","__toCommonJS","loggerLevels","createConfig","config","import_zod","import_http_errors","import_zod","import_ramda","metaProp","cloneSchemaForMeta","schema","This","def","withMeta","copy","value","localCopy","hasMeta","getMeta","meta","copyMeta","src","dest","result","examplesCombinations","combinations","destExample","srcExample","import_mime","mimeJson","mime","mimeMultipart","import_zod","zodUploadKind","isUploadedFile","data","_ZodUpload","input","ctx","ZodUpload","routePathParamsRegex","areFilesAvailable","request","isMultipart","mimeMultipart","defaultInputSources","fallbackInputSource","getActualMethod","getInput","inputAssignment","method","props","prop","carry","isLoggerConfig","logger","loggerLevels","isValidDate","date","makeErrorFromAnything","subject","getMessageFromError","error","path","message","OutputValidationError","getStatusCodeFromError","InputValidationError","getExamples","schema","parseToOutput","examples","getMeta","example","parsedExample","combinations","a","b","result","itemA","itemB","getRoutePathParams","match","param","reduceBool","arr","bool","hasTopLevelTransformingEffect","hasUpload","ZodUpload","hasCoercion","makeCleanId","suffix","entry","tryToTransform","effect","sample","errToObj","RoutingError","DependsOnMethodError","OpenAPIError","IOSchemaError","OutputValidationError","originalError","getMessageFromError","InputValidationError","ResultHandlerError","message","isObject","subject","flattenAnds","agg","item","mapLogicalContainer","container","fn","entry","andToOr","acc","combs","combinations","combineContainers","a","b","import_zod","defaultStatusCodes","createResultHandler","definition","defaultResultHandler","output","examples","getMeta","responseSchema","withMeta","acc","example","getMessageFromError","error","input","request","response","logger","statusCode","getStatusCodeFromError","lastResortHandler","getMimeTypesFromApiResponse","subject","fallback","mimeJson","mimeTypes","mimeType","AbstractEndpoint","_getDefaultCorsHeaders","getDefaultCorsHeaders_fn","_parseOutput","parseOutput_fn","_runMiddlewares","runMiddlewares_fn","_parseAndRunHandler","parseAndRunHandler_fn","_handleResult","handleResult_fn","Endpoint","middlewares","inputSchema","outputSchema","handler","resultHandler","description","shortDescription","rest","__privateAdd","name","schema","hasTopLevelTransformingEffect","IOSchemaError","apiResponse","hasUpload","mimeMultipart","defaultStatusCodes","methods","variant","acc","middleware","combineContainers","request","response","logger","config","method","getActualMethod","output","error","headers","__privateMethod","key","input","getInput","options","isStreamClosed","e","makeErrorFromAnything","OutputValidationError","def","finalInput","InputValidationError","lastResortHandler","ResultHandlerError","methods","import_zod","getFinalEndpointInputSchema","middlewares","input","allSchemas","schema","finalSchema","acc","copyMeta","createMiddleware","props","hasTopLevelTransformingEffect","IOSchemaError","_create","create_fn","_EndpointsFactory","subject","_a","__privateMethod","middleware","features","transformer","err","provider","definition","request","response","resolve","reject","options","createMiddleware","input","handler","outputSchema","rest","middlewares","resultHandler","Endpoint","getFinalEndpointInputSchema","EndpointsFactory","factory","__privateAdd","defaultEndpointsFactory","defaultResultHandler","import_util","import_triple_beam","import_winston","combine","colorize","useTimestamp","printf","winston","createLogger","loggerConfig","prettyPrint","meta","noLevel","noMessage","noSplat","rest","getOutputFormat","isPretty","timestamp","message","level","durationMs","formats","consoleOutputOptions","DependsOnMethod","methods","key","DependsOnMethodError","m","import_express","ServeStatic","params","path","cb","express","walkRouting","routing","onEndpoint","onStatic","parentPath","hasCors","segment","element","RoutingError","path","AbstractEndpoint","methods","method","ServeStatic","DependsOnMethod","endpoint","firstMethod","siblingMethods","firstEndpoint","getStartupLogo","initRouting","app","logger","config","routing","getStartupLogo","walkRouting","endpoint","path","method","request","response","handler","import_express","import_compression","import_express_fileupload","import_https","import_http_errors","createParserFailureHandler","errorHandler","logger","error","request","response","next","createNotFoundHandler","createHttpError","e","lastResortHandler","ResultHandlerError","makeErrorFromAnything","attachRouting","config","routing","isLoggerConfig","createLogger","initRouting","defaultResultHandler","createServer","app","express","compressor","compression","jsonParser","multipartParser","fileUpload","middlewares","httpServer","httpsServer","https","import_openapi3_ts","import_ramda","import_zod","import_zod","isoDateRegex","zodDateInKind","_ZodDateIn","input","status","ctx","date","isValidDate","ZodDateIn","walkSchema","schema","onEach","rules","onMissing","context","overrides","handler","result","params","shortDescriptionLimit","isoDateDocumentationUrl","samples","reformatParamsInPath","path","routePathParamsRegex","param","depictDefault","innerType","defaultValue","next","depictCatch","depictAny","depictUpload","isResponse","OpenAPIError","depictFile","isBinary","isBase64","depictUnion","options","option","depictDiscriminatedUnion","discriminator","depictIntersection","left","right","entry","depictOptional","schema","depictNullable","depictEnum","depictLiteral","value","depictObject","required","key","prop","hasCoercion","depictObjectProperties","depictNull","depictDateIn","isoDateRegex","depictDateOut","depictDate","depictBoolean","depictBigInt","depictRecord","keySchema","valueSchema","keys","shape","carry","depictArray","def","element","depictTuple","items","types","item","index","depictString","isEmail","isURL","minLength","maxLength","isUUID","isCUID","isCUID2","isULID","isIP","isEmoji","isDatetime","checks","regexCheck","check","datetimeCheck","regex","depictNumber","minCheck","kind","isMinInclusive","maxCheck","isMaxInclusive","makeSample","depicted","type","depictEffect","input","effect","outputType","tryToTransform","inputType","rest","depictPipeline","depictBranded","depictExamples","omitProps","examples","getExamples","example","depictParamExamples","extractObjectSchema","subject","objectSchema","acc","hasTopLevelTransformingEffect","copyMeta","depictRequestParams","method","endpoint","inputSources","pathParams","getRoutePathParams","isQueryEnabled","isParamsEnabled","isPathParam","name","walkSchema","depicters","onEach","onMissing","description","excludeParamsFromDepiction","properties","allOf","oneOf","excludeExampleFromDepiction","depictResponse","isPositive","mimeTypes","depictedSchema","mimeType","depictBasicSecurity","depictBearerSecurity","bearerFormat","depictInputSecurity","depictHeaderSecurity","depictCookieSecurity","depictOpenIdSecurity","openIdConnectUrl","depictOAuth2Security","flows","flow","scopes","depictSecurity","container","methods","mapLogicalContainer","security","depictSecurityRefs","agg","andToOr","depictRequest","bodyDepiction","bodyExamples","depictTags","tags","tag","ensureShortDescription","OpenAPI","routing","config","title","version","serverUrl","successfulResponseDescription","errorResponseDescription","hasSummaryFromDescription","walkRouting","endpoint","path","_method","method","commonParams","shortDesc","longDesc","inputSources","defaultInputSources","depictedParams","depictRequestParams","operation","depictResponse","ensureShortDescription","depictRequest","securityRefs","depictSecurityRefs","mapLogicalContainer","depictSecurity","securitySchema","name","scopes","swaggerCompatiblePath","reformatParamsInPath","depictTags","operationId","makeCleanId","subject","import_http","makeRequestMock","requestProps","mimeJson","makeResponseMock","responseProps","responseMock","http","code","testEndpoint","endpoint","configProps","loggerProps","__noJest","requestMock","loggerMock","configMock","import_typescript","import_typescript","f","ts","exportModifier","publicReadonlyModifier","protectedReadonlyModifier","emptyPrefix","emptyEnding","spacingSuffix","makeTemplate","names","name","index","parametricIndexNode","makeParam","type","mod","makeParams","params","acc","makeRecord","key","value","makeEmptyInitializingConstructor","makeQuotedProp","ref","makeConst","makePublicLiteralType","literals","option","makePublicType","makePublicReadonlyProp","exp","makePublicClass","constructor","props","makeIndexedPromise","makeAnyPromise","makePublicExtendedInterface","extender","makeTypeParams","makeImplementationCallFn","args","makeObjectKeysReducer","obj","initial","import_typescript","import_zod","import_typescript","f","ts","addJsDocComment","node","text","createTypeAlias","identifier","comment","typeAlias","printNode","printerOptions","sourceFile","safePropRegex","makePropertyIdentifier","name","f","ts","samples","onLiteral","value","onObject","shape","isResponse","next","members","key","isOptional","hasCoercion","propertySignature","makePropertyIdentifier","addJsDocComment","onArray","element","onEnum","options","option","onSomeUnion","makeSample","produced","onEffects","schema","input","effect","outputType","tryToTransform","resolutions","onNativeEnum","onOptional","onNullable","onTuple","items","onRecord","keySchema","valueSchema","onIntersection","entry","onDefault","onPrimitive","syntaxKind","onBranded","onCatch","onPipeline","onNull","producers","zodToTs","context","walkSchema","Client","routing","walkRouting","endpoint","path","method","inputId","makeCleanId","responseId","input","zodToTs","response","inputAlias","createTypeAlias","responseAlias","mimeJson","pathNode","makePublicLiteralType","methodNode","methods","methodPathNode","makePublicType","makeTemplate","extenderClause","f","ts","makeRecord","inputNode","makePublicExtendedInterface","methodPath","makeQuotedProp","responseNode","jsonEndpointsNode","exportModifier","makeConst","providerNode","makeTypeParams","makeParams","parametricIndexNode","makeIndexedPromise","implementationNode","makeAnyPromise","keyParamExpression","clientNode","makePublicClass","makeEmptyInitializingConstructor","makeParam","protectedReadonlyModifier","makePublicReadonlyProp","makeImplementationCallFn","makeObjectKeysReducer","printerOptions","node","printNode","import_zod","zodDateOutKind","_ZodDateOut","input","status","ctx","isValidDate","ZodDateOut","import_zod","zodFileKind","base64Regex","_ZodFile","message","errToObj","input","status","ctx","check","ZodFile","ez","ZodFile","ZodUpload","ZodDateIn","ZodDateOut","import_http_errors"]}
|