@bram-dc/fastify-type-provider-zod 5.0.2 → 5.0.3

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.
Files changed (43) hide show
  1. package/README.md +53 -46
  2. package/dist/cjs/core.cjs +137 -0
  3. package/dist/cjs/core.cjs.map +1 -0
  4. package/dist/cjs/core.d.cts +68 -0
  5. package/dist/cjs/errors.cjs +57 -0
  6. package/dist/cjs/errors.cjs.map +1 -0
  7. package/dist/cjs/errors.d.cts +30 -0
  8. package/dist/cjs/index.cjs +16 -0
  9. package/dist/cjs/index.cjs.map +1 -0
  10. package/dist/cjs/index.d.cts +2 -0
  11. package/dist/cjs/json-to-oas.cjs +85 -0
  12. package/dist/cjs/json-to-oas.cjs.map +1 -0
  13. package/dist/cjs/json-to-oas.d.cts +9 -0
  14. package/dist/cjs/zod-to-json.cjs +98 -0
  15. package/dist/cjs/zod-to-json.cjs.map +1 -0
  16. package/dist/cjs/zod-to-json.d.cts +8 -0
  17. package/dist/esm/core.d.ts +68 -0
  18. package/dist/esm/core.js +137 -0
  19. package/dist/esm/core.js.map +1 -0
  20. package/dist/esm/errors.d.ts +30 -0
  21. package/dist/esm/errors.js +57 -0
  22. package/dist/esm/errors.js.map +1 -0
  23. package/dist/esm/index.d.ts +2 -0
  24. package/dist/esm/index.js +16 -0
  25. package/dist/esm/index.js.map +1 -0
  26. package/dist/esm/json-to-oas.d.ts +9 -0
  27. package/dist/esm/json-to-oas.js +85 -0
  28. package/dist/esm/json-to-oas.js.map +1 -0
  29. package/dist/esm/zod-to-json.d.ts +8 -0
  30. package/dist/esm/zod-to-json.js +98 -0
  31. package/dist/esm/zod-to-json.js.map +1 -0
  32. package/package.json +73 -58
  33. package/src/core.ts +244 -0
  34. package/src/errors.ts +99 -0
  35. package/src/index.ts +21 -0
  36. package/src/json-to-oas.ts +109 -0
  37. package/src/zod-to-json.ts +150 -0
  38. package/dist/index.d.ts +0 -2
  39. package/dist/index.js +0 -16
  40. package/dist/src/core.d.ts +0 -59
  41. package/dist/src/core.js +0 -121
  42. package/dist/src/errors.d.ts +0 -35
  43. package/dist/src/errors.js +0 -43
@@ -0,0 +1,109 @@
1
+ import type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'
2
+ import type { JSONSchema } from 'zod/v4/core'
3
+
4
+ type OASVersion = '3.0' | '3.1'
5
+
6
+ export const getOASVersion = (documentObject: {
7
+ openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>
8
+ }): OASVersion => {
9
+ const openapiVersion = documentObject.openapiObject.openapi || '3.0.3'
10
+
11
+ if (openapiVersion.startsWith('3.1')) {
12
+ return '3.1'
13
+ }
14
+
15
+ if (openapiVersion.startsWith('3.0')) {
16
+ return '3.0'
17
+ }
18
+
19
+ throw new Error('Unsupported OpenAPI document object')
20
+ }
21
+
22
+ export const jsonSchemaToOAS_3_0 = (jsonSchema: JSONSchema.BaseSchema): OpenAPIV3.SchemaObject => {
23
+ const clone: any = { ...jsonSchema }
24
+
25
+ if (clone.type === 'null') {
26
+ clone.nullable = true
27
+ delete clone.type
28
+ clone.enum = [null]
29
+ }
30
+
31
+ if (Array.isArray(clone.prefixItems)) {
32
+ const tuple = clone.prefixItems as JSONSchema.BaseSchema[]
33
+
34
+ clone.minItems ??= tuple.length
35
+ clone.maxItems ??= tuple.length
36
+
37
+ clone.items = {
38
+ oneOf: tuple.map(jsonSchemaToOAS_3_0),
39
+ }
40
+
41
+ delete clone.prefixItems
42
+ }
43
+
44
+ if ('const' in clone && clone.const !== undefined) {
45
+ clone.enum = [clone.const]
46
+ delete clone.const
47
+ }
48
+
49
+ if (typeof clone.exclusiveMinimum === 'number') {
50
+ clone.minimum = clone.exclusiveMinimum
51
+ clone.exclusiveMinimum = true
52
+ }
53
+ if (typeof clone.exclusiveMaximum === 'number') {
54
+ clone.maximum = clone.exclusiveMaximum
55
+ clone.exclusiveMaximum = true
56
+ }
57
+
58
+ for (const key of [
59
+ '$schema',
60
+ '$id',
61
+ 'unevaluatedProperties',
62
+ 'dependentSchemas',
63
+ 'patternProperties',
64
+ 'propertyNames',
65
+ 'contentEncoding',
66
+ 'contentMediaType',
67
+ ]) {
68
+ delete clone[key]
69
+ }
70
+
71
+ const recursive = (v: any): any =>
72
+ Array.isArray(v) ? v.map(jsonSchemaToOAS_3_0) : jsonSchemaToOAS_3_0(v)
73
+
74
+ if (clone.properties) {
75
+ for (const [k, v] of Object.entries(clone.properties)) {
76
+ clone.properties![k] = jsonSchemaToOAS_3_0(v as any)
77
+ }
78
+ }
79
+
80
+ if (clone.items && !Array.isArray(clone.items)) {
81
+ clone.items = recursive(clone.items)
82
+ }
83
+
84
+ for (const key of ['allOf', 'anyOf', 'oneOf', 'not', 'then', 'else', 'if', 'contains']) {
85
+ if (clone[key]) {
86
+ clone[key] = recursive(clone[key])
87
+ }
88
+ }
89
+
90
+ return clone as OpenAPIV3.SchemaObject
91
+ }
92
+
93
+ const jsonSchemaToOAS_3_1 = (jsonSchema: JSONSchema.BaseSchema): OpenAPIV3_1.SchemaObject => {
94
+ return jsonSchema as OpenAPIV3_1.SchemaObject
95
+ }
96
+
97
+ export const jsonSchemaToOAS = (
98
+ jsonSchema: JSONSchema.BaseSchema,
99
+ oasVersion: OASVersion,
100
+ ): OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject => {
101
+ switch (oasVersion) {
102
+ case '3.0':
103
+ return jsonSchemaToOAS_3_0(jsonSchema)
104
+ case '3.1':
105
+ return jsonSchemaToOAS_3_1(jsonSchema)
106
+ default:
107
+ throw new Error(`Unsupported OpenAPI version: ${oasVersion}`)
108
+ }
109
+ }
@@ -0,0 +1,150 @@
1
+ import type { $ZodDate, $ZodUndefined, $ZodUnion, JSONSchema } from 'zod/v4/core'
2
+ import { $ZodRegistry, $ZodType, toJSONSchema } from 'zod/v4/core'
3
+
4
+ const getSchemaId = (id: string, io: 'input' | 'output') => {
5
+ return io === 'input' ? `${id}Input` : id
6
+ }
7
+
8
+ const getReferenceUri = (id: string, io: 'input' | 'output') => {
9
+ return `#/components/schemas/${getSchemaId(id, io)}`
10
+ }
11
+
12
+ function isZodDate(entity: unknown): entity is $ZodDate {
13
+ return entity instanceof $ZodType && entity._zod.def.type === 'date'
14
+ }
15
+
16
+ function isZodUnion(entity: unknown): entity is $ZodUnion {
17
+ return entity instanceof $ZodType && entity._zod.def.type === 'union'
18
+ }
19
+
20
+ function isZodUndefined(entity: unknown): entity is $ZodUndefined {
21
+ return entity instanceof $ZodType && entity._zod.def.type === 'undefined'
22
+ }
23
+
24
+ const getOverride = (
25
+ ctx: {
26
+ zodSchema: $ZodType
27
+ jsonSchema: JSONSchema.BaseSchema
28
+ },
29
+ io: 'input' | 'output',
30
+ ) => {
31
+ if (isZodUnion(ctx.zodSchema)) {
32
+ // Filter unrepresentable types in unions
33
+ // TODO: Should be fixed upstream and not merged in this plugin.
34
+ // Remove when passed: https://github.com/colinhacks/zod/pull/5013
35
+ ctx.jsonSchema.anyOf = ctx.jsonSchema.anyOf?.filter((schema) => Object.keys(schema).length > 0)
36
+ }
37
+
38
+ if (isZodDate(ctx.zodSchema)) {
39
+ // Allow dates to be represented as strings in output schemas
40
+ if (io === 'output') {
41
+ ctx.jsonSchema.type = 'string'
42
+ ctx.jsonSchema.format = 'date-time'
43
+ }
44
+ }
45
+
46
+ if (isZodUndefined(ctx.zodSchema)) {
47
+ // Allow undefined to be represented as null in output schemas
48
+ if (io === 'output') {
49
+ ctx.jsonSchema.type = 'null'
50
+ }
51
+ }
52
+ }
53
+
54
+ export const zodSchemaToJson: (
55
+ zodSchema: $ZodType,
56
+ registry: $ZodRegistry<{ id?: string }>,
57
+ io: 'input' | 'output',
58
+ ) => JSONSchema.BaseSchema = (zodSchema, registry, io) => {
59
+ const schemaRegistryEntry = registry.get(zodSchema)
60
+
61
+ /**
62
+ * Checks whether the provided schema is registered in the given registry.
63
+ * If it is present and has an `id`, it can be referenced as component.
64
+ *
65
+ * @see https://github.com/turkerdev/fastify-type-provider-zod/issues/173
66
+ */
67
+ if (schemaRegistryEntry?.id) {
68
+ return {
69
+ $ref: getReferenceUri(schemaRegistryEntry.id, io),
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Unfortunately, at the time of writing, there is no way to generate a schema with `$ref`
75
+ * using `toJSONSchema` and a zod schema.
76
+ *
77
+ * As a workaround, we create a zod registry containing only the specific schema we want to convert.
78
+ *
79
+ * @see https://github.com/colinhacks/zod/issues/4281
80
+ */
81
+ const tempID = 'GEN'
82
+ const tempRegistry = new $ZodRegistry<{ id?: string }>()
83
+ tempRegistry.add(zodSchema, { id: tempID })
84
+
85
+ const {
86
+ schemas: { [tempID]: result },
87
+ } = toJSONSchema(tempRegistry, {
88
+ target: 'draft-2020-12',
89
+ metadata: registry,
90
+ io,
91
+ unrepresentable: 'any',
92
+ cycles: 'ref',
93
+ reused: 'inline',
94
+
95
+ /**
96
+ * The uri option only allows customizing the base path of the `$ref`, and it automatically appends a path to it.
97
+ * As a workaround, we set a placeholder that looks something like this:
98
+ *
99
+ * | marker | always added by zod | meta.id |
100
+ * |__SCHEMA__PLACEHOLDER__| #/$defs/ | User |
101
+ *
102
+ * @example `__SCHEMA__PLACEHOLDER__#/$defs/User"`
103
+ * @example `__SCHEMA__PLACEHOLDER__#/$defs/Group"`
104
+ *
105
+ * @see jsonSchemaReplaceRef
106
+ * @see https://github.com/colinhacks/zod/issues/4750
107
+ */
108
+ uri: () => `__SCHEMA__PLACEHOLDER__`,
109
+ override: (ctx) => getOverride(ctx, io),
110
+ })
111
+
112
+ const jsonSchema = { ...result }
113
+ delete jsonSchema.id
114
+
115
+ /**
116
+ * Replace the previous generated placeholders with the final `$ref` value
117
+ */
118
+ const jsonSchemaReplaceRef = JSON.stringify(jsonSchema).replaceAll(
119
+ /"__SCHEMA__PLACEHOLDER__#\/\$defs\/(.+?)"/g,
120
+ (_, id) => `"${getReferenceUri(id, io)}"`,
121
+ )
122
+
123
+ return JSON.parse(jsonSchemaReplaceRef) as typeof result
124
+ }
125
+
126
+ export const zodRegistryToJson: (
127
+ registry: $ZodRegistry<{ id?: string }>,
128
+ io: 'input' | 'output',
129
+ ) => Record<string, JSONSchema.BaseSchema> = (registry, io) => {
130
+ const result = toJSONSchema(registry, {
131
+ target: 'draft-2020-12',
132
+ io,
133
+ unrepresentable: 'any',
134
+ cycles: 'ref',
135
+ reused: 'inline',
136
+ uri: (id) => getReferenceUri(id, io),
137
+ override: (ctx) => getOverride(ctx, io),
138
+ }).schemas
139
+
140
+ const jsonSchemas: Record<string, JSONSchema.BaseSchema> = {}
141
+ for (const id in result) {
142
+ const jsonSchema = { ...result[id] }
143
+
144
+ delete jsonSchema.id
145
+
146
+ jsonSchemas[getSchemaId(id, io)] = jsonSchema
147
+ }
148
+
149
+ return jsonSchemas
150
+ }
package/dist/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export { type ZodTypeProvider, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, type ZodSerializerCompilerOptions, jsonSchemaTransform, createJsonSchemaTransform, jsonSchemaTransformObject, createJsonSchemaTransformObject, serializerCompiler, validatorCompiler, createSerializerCompiler, } from './src/core';
2
- export { type ZodFastifySchemaValidationError, ResponseSerializationError, InvalidSchemaError, hasZodFastifySchemaValidationErrors, isResponseSerializationError, } from './src/errors';
package/dist/index.js DELETED
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isResponseSerializationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = exports.createSerializerCompiler = exports.validatorCompiler = exports.serializerCompiler = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransform = exports.jsonSchemaTransform = void 0;
4
- var core_1 = require("./src/core");
5
- Object.defineProperty(exports, "jsonSchemaTransform", { enumerable: true, get: function () { return core_1.jsonSchemaTransform; } });
6
- Object.defineProperty(exports, "createJsonSchemaTransform", { enumerable: true, get: function () { return core_1.createJsonSchemaTransform; } });
7
- Object.defineProperty(exports, "jsonSchemaTransformObject", { enumerable: true, get: function () { return core_1.jsonSchemaTransformObject; } });
8
- Object.defineProperty(exports, "createJsonSchemaTransformObject", { enumerable: true, get: function () { return core_1.createJsonSchemaTransformObject; } });
9
- Object.defineProperty(exports, "serializerCompiler", { enumerable: true, get: function () { return core_1.serializerCompiler; } });
10
- Object.defineProperty(exports, "validatorCompiler", { enumerable: true, get: function () { return core_1.validatorCompiler; } });
11
- Object.defineProperty(exports, "createSerializerCompiler", { enumerable: true, get: function () { return core_1.createSerializerCompiler; } });
12
- var errors_1 = require("./src/errors");
13
- Object.defineProperty(exports, "ResponseSerializationError", { enumerable: true, get: function () { return errors_1.ResponseSerializationError; } });
14
- Object.defineProperty(exports, "InvalidSchemaError", { enumerable: true, get: function () { return errors_1.InvalidSchemaError; } });
15
- Object.defineProperty(exports, "hasZodFastifySchemaValidationErrors", { enumerable: true, get: function () { return errors_1.hasZodFastifySchemaValidationErrors; } });
16
- Object.defineProperty(exports, "isResponseSerializationError", { enumerable: true, get: function () { return errors_1.isResponseSerializationError; } });
@@ -1,59 +0,0 @@
1
- import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger';
2
- import type { FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifySchema, FastifySchemaCompiler, FastifyTypeProvider, RawServerBase, RawServerDefault } from 'fastify';
3
- import type { FastifySerializerCompiler } from 'fastify/types/schema';
4
- import { z } from 'zod';
5
- export interface ZodTypeProvider extends FastifyTypeProvider {
6
- validator: this['schema'] extends z.ZodTypeAny ? z.output<this['schema']> : unknown;
7
- serializer: this['schema'] extends z.ZodTypeAny ? z.input<this['schema']> : unknown;
8
- }
9
- interface Schema extends FastifySchema {
10
- hide?: boolean;
11
- }
12
- type CreateJsonSchemaTransformOptions = {
13
- skipList?: readonly string[];
14
- schemaRegistry?: z.core.$ZodJSONSchemaRegistry;
15
- };
16
- export declare const createJsonSchemaTransform: ({ skipList, schemaRegistry, }: CreateJsonSchemaTransformOptions) => SwaggerTransform<Schema>;
17
- export declare const jsonSchemaTransform: SwaggerTransform<Schema>;
18
- type CreateJsonSchemaTransformObjectOptions = {
19
- schemaRegistry?: z.core.$ZodJSONSchemaRegistry;
20
- };
21
- export declare const createJsonSchemaTransformObject: ({ schemaRegistry, }: CreateJsonSchemaTransformObjectOptions) => SwaggerTransformObject;
22
- export declare const jsonSchemaTransformObject: SwaggerTransformObject;
23
- export declare const validatorCompiler: FastifySchemaCompiler<z.ZodTypeAny>;
24
- type ReplacerFunction = (this: any, key: string, value: any) => any;
25
- export type ZodSerializerCompilerOptions = {
26
- replacer?: ReplacerFunction;
27
- };
28
- export declare const createSerializerCompiler: (options?: ZodSerializerCompilerOptions) => FastifySerializerCompiler<z.ZodTypeAny | {
29
- properties: z.ZodTypeAny;
30
- }>;
31
- export declare const serializerCompiler: FastifySerializerCompiler<z.ZodType<unknown, unknown> | {
32
- properties: z.ZodTypeAny;
33
- }>;
34
- /**
35
- * FastifyPluginCallbackZod with Zod automatic type inference
36
- *
37
- * @example
38
- * ```typescript
39
- * import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
40
- *
41
- * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
42
- * done()
43
- * }
44
- * ```
45
- */
46
- export type FastifyPluginCallbackZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
47
- /**
48
- * FastifyPluginAsyncZod with Zod automatic type inference
49
- *
50
- * @example
51
- * ```typescript
52
- * import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
53
- *
54
- * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
55
- * }
56
- * ```
57
- */
58
- export type FastifyPluginAsyncZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
59
- export {};
package/dist/src/core.js DELETED
@@ -1,121 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.serializerCompiler = exports.createSerializerCompiler = exports.validatorCompiler = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransform = exports.createJsonSchemaTransform = void 0;
4
- const zod_1 = require("zod");
5
- const errors_1 = require("./errors");
6
- const defaultSkipList = [
7
- '/documentation/',
8
- '/documentation/initOAuth',
9
- '/documentation/json',
10
- '/documentation/uiConfig',
11
- '/documentation/yaml',
12
- '/documentation/*',
13
- '/documentation/static/*',
14
- ];
15
- const createJsonSchemaTransform = ({ skipList = defaultSkipList, schemaRegistry = zod_1.z.globalRegistry, }) => {
16
- return ({ schema, url }) => {
17
- if (!schema) {
18
- return {
19
- schema,
20
- url,
21
- };
22
- }
23
- const { response, headers, querystring, body, params, hide, ...rest } = schema;
24
- const transformed = {};
25
- if (skipList.includes(url) || hide) {
26
- transformed.hide = true;
27
- return { schema: transformed, url };
28
- }
29
- const zodSchemas = { headers, querystring, body, params };
30
- for (const prop in zodSchemas) {
31
- const zodSchema = zodSchemas[prop];
32
- if (zodSchema) {
33
- transformed[prop] = zod_1.z.toJSONSchema(zodSchema, {
34
- external: {
35
- registry: schemaRegistry,
36
- uri: (id) => `#/components/schemas/${id}`,
37
- defs: {},
38
- },
39
- });
40
- }
41
- }
42
- if (response) {
43
- transformed.response = {};
44
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
- for (const prop in response) {
46
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
- const zodSchema = resolveSchema(response[prop]);
48
- const transformedResponse = zod_1.z.toJSONSchema(zodSchema, {
49
- external: {
50
- registry: schemaRegistry,
51
- uri: (id) => `#/components/schemas/${id}`,
52
- defs: {},
53
- },
54
- });
55
- transformed.response[prop] = transformedResponse;
56
- }
57
- }
58
- for (const prop in rest) {
59
- const meta = rest[prop];
60
- if (meta) {
61
- transformed[prop] = meta;
62
- }
63
- }
64
- return { schema: transformed, url };
65
- };
66
- };
67
- exports.createJsonSchemaTransform = createJsonSchemaTransform;
68
- exports.jsonSchemaTransform = (0, exports.createJsonSchemaTransform)({});
69
- const createJsonSchemaTransformObject = ({ schemaRegistry = zod_1.z.globalRegistry, }) => (input) => {
70
- if ('swaggerObject' in input) {
71
- console.warn('This package currently does not support component references for Swagger 2.0');
72
- return input.swaggerObject;
73
- }
74
- const { schemas } = zod_1.z.toJSONSchema(schemaRegistry, {
75
- uri: (id) => `#/components/schemas/${id}`,
76
- external: {
77
- registry: schemaRegistry,
78
- uri: (id) => `#/components/schemas/${id}`,
79
- defs: {},
80
- },
81
- });
82
- return {
83
- ...input.openapiObject,
84
- components: {
85
- ...input.openapiObject.components,
86
- schemas: {
87
- ...input.openapiObject.components?.schemas,
88
- ...schemas,
89
- },
90
- },
91
- };
92
- };
93
- exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
94
- exports.jsonSchemaTransformObject = (0, exports.createJsonSchemaTransformObject)({});
95
- const validatorCompiler = ({ schema }) => (data) => {
96
- const result = schema.safeParse(data);
97
- if (result.error) {
98
- return { error: (0, errors_1.createValidationError)(result.error) };
99
- }
100
- return { value: result.data };
101
- };
102
- exports.validatorCompiler = validatorCompiler;
103
- function resolveSchema(maybeSchema) {
104
- if ('safeParse' in maybeSchema) {
105
- return maybeSchema;
106
- }
107
- if ('properties' in maybeSchema) {
108
- return maybeSchema.properties;
109
- }
110
- throw new errors_1.InvalidSchemaError(JSON.stringify(maybeSchema));
111
- }
112
- const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, url }) => (data) => {
113
- const schema = resolveSchema(maybeSchema);
114
- const result = schema.safeParse(data);
115
- if (result.error) {
116
- throw new errors_1.ResponseSerializationError(method, url, { cause: result.error });
117
- }
118
- return JSON.stringify(result.data, options?.replacer);
119
- };
120
- exports.createSerializerCompiler = createSerializerCompiler;
121
- exports.serializerCompiler = (0, exports.createSerializerCompiler)({});
@@ -1,35 +0,0 @@
1
- import type { FastifyError } from 'fastify';
2
- import type { z } from 'zod';
3
- declare const ResponseSerializationError_base: import("@fastify/error").FastifyErrorConstructor<{
4
- code: string;
5
- }, [{
6
- cause: z.core.$ZodError;
7
- }]>;
8
- export declare class ResponseSerializationError extends ResponseSerializationError_base {
9
- method: string;
10
- url: string;
11
- cause: z.core.$ZodError;
12
- constructor(method: string, url: string, options: {
13
- cause: z.core.$ZodError;
14
- });
15
- }
16
- export declare function isResponseSerializationError(value: unknown): value is ResponseSerializationError;
17
- export declare const InvalidSchemaError: import("@fastify/error").FastifyErrorConstructor<{
18
- code: string;
19
- }, [string]>;
20
- declare const ZodFastifySchemaValidationErrorSymbol: unique symbol;
21
- export type ZodFastifySchemaValidationError = {
22
- [ZodFastifySchemaValidationErrorSymbol]: true;
23
- keyword: string;
24
- instancePath: string;
25
- schemaPath: string;
26
- params: {
27
- issue: z.core.$ZodIssue;
28
- };
29
- message: string;
30
- };
31
- export declare const hasZodFastifySchemaValidationErrors: (error: unknown) => error is Omit<FastifyError, "validation"> & {
32
- validation: ZodFastifySchemaValidationError[];
33
- };
34
- export declare const createValidationError: (error: z.core.$ZodError) => ZodFastifySchemaValidationError[];
35
- export {};
@@ -1,43 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createValidationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = void 0;
7
- exports.isResponseSerializationError = isResponseSerializationError;
8
- const error_1 = __importDefault(require("@fastify/error"));
9
- class ResponseSerializationError extends (0, error_1.default)('FST_ERR_RESPONSE_SERIALIZATION', "Response doesn't match the schema", 500) {
10
- constructor(method, url, options) {
11
- super({ cause: options.cause });
12
- this.method = method;
13
- this.url = url;
14
- }
15
- }
16
- exports.ResponseSerializationError = ResponseSerializationError;
17
- function isResponseSerializationError(value) {
18
- return 'method' in value;
19
- }
20
- exports.InvalidSchemaError = (0, error_1.default)('FST_ERR_INVALID_SCHEMA', 'Invalid schema passed: %s', 500);
21
- const ZodFastifySchemaValidationErrorSymbol = Symbol.for('ZodFastifySchemaValidationError');
22
- const isZodFastifySchemaValidationError = (error) => typeof error === 'object' &&
23
- error !== null &&
24
- ZodFastifySchemaValidationErrorSymbol in error &&
25
- error[ZodFastifySchemaValidationErrorSymbol] === true;
26
- const hasZodFastifySchemaValidationErrors = (error) => typeof error === 'object' &&
27
- error !== null &&
28
- 'validation' in error &&
29
- Array.isArray(error.validation) &&
30
- error.validation.length > 0 &&
31
- isZodFastifySchemaValidationError(error.validation[0]);
32
- exports.hasZodFastifySchemaValidationErrors = hasZodFastifySchemaValidationErrors;
33
- const createValidationError = (error) => error.issues.map((issue) => ({
34
- [ZodFastifySchemaValidationErrorSymbol]: true,
35
- keyword: issue.code ?? 'custom',
36
- instancePath: `/${issue.path.join('/')}`,
37
- schemaPath: `#/${issue.path.join('/')}/${issue.code}`,
38
- params: {
39
- issue,
40
- },
41
- message: issue.message,
42
- }));
43
- exports.createValidationError = createValidationError;