@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
package/README.md CHANGED
@@ -4,22 +4,29 @@
4
4
  [![NPM Downloads](https://img.shields.io/npm/dm/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)
5
5
  [![Build Status](https://github.com//turkerdev/fastify-type-provider-zod/workflows/CI/badge.svg)](https://github.com//turkerdev/fastify-type-provider-zod/actions)
6
6
 
7
+ ## Zod compatibility
8
+
9
+ | fastify-type-provider-zod | zod |
10
+ |---------------------------|------|
11
+ | <=4.x | v3 |
12
+ | >=5.x | v4 |
13
+
7
14
  ## How to use?
8
15
 
9
- ```js
10
- import Fastify from "fastify";
11
- import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";
12
- import z from "zod";
16
+ ```ts
17
+ import type { ZodTypeProvider } from 'fastify-type-provider-zod';
18
+ import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
19
+ import { z } from 'zod/v4';
13
20
 
14
- const app = Fastify()
21
+ const app = Fastify();
15
22
 
16
23
  // Add schema validator and serializer
17
24
  app.setValidatorCompiler(validatorCompiler);
18
25
  app.setSerializerCompiler(serializerCompiler);
19
26
 
20
27
  app.withTypeProvider<ZodTypeProvider>().route({
21
- method: "GET",
22
- url: "/",
28
+ method: 'GET',
29
+ url: '/',
23
30
  // Define your schema
24
31
  schema: {
25
32
  querystring: z.object({
@@ -45,10 +52,9 @@ type ZodSerializerCompilerOptions = {
45
52
  };
46
53
  ```
47
54
 
48
- ```js
55
+ ```ts
49
56
  import Fastify from 'fastify';
50
57
  import { createSerializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
51
- import z from 'zod';
52
58
 
53
59
  const app = Fastify();
54
60
 
@@ -77,14 +83,13 @@ app.listen({ port: 4949 });
77
83
  import fastify from 'fastify';
78
84
  import fastifySwagger from '@fastify/swagger';
79
85
  import fastifySwaggerUI from '@fastify/swagger-ui';
80
- import { z } from 'zod';
81
-
86
+ import { z } from 'zod/v4';
87
+ import type { ZodTypeProvider } from 'fastify-type-provider-zod';
82
88
  import {
83
89
  jsonSchemaTransform,
84
90
  createJsonSchemaTransform,
85
91
  serializerCompiler,
86
92
  validatorCompiler,
87
- ZodTypeProvider,
88
93
  } from 'fastify-type-provider-zod';
89
94
 
90
95
  const app = fastify();
@@ -147,48 +152,50 @@ run();
147
152
  You can add custom handling of request and response validation errors to your fastify error handler like this:
148
153
 
149
154
  ```ts
150
- import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod'
155
+ import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod';
151
156
 
152
157
  fastifyApp.setErrorHandler((err, req, reply) => {
153
- if (hasZodFastifySchemaValidationErrors(err)) {
154
- return reply.code(400).send({
155
- error: 'Response Validation Error',
156
- message: "Request doesn't match the schema",
157
- statusCode: 400,
158
- details: {
159
- issues: err.validation,
160
- method: req.method,
161
- url: req.url,
162
- },
163
- })
164
- }
165
-
166
- if (isResponseSerializationError(err)) {
167
- return reply.code(500).send({
168
- error: 'Internal Server Error',
169
- message: "Response doesn't match the schema",
170
- statusCode: 500,
171
- details: {
172
- issues: err.cause.issues,
173
- method: err.method,
174
- url: err.url,
175
- },
176
- })
177
- }
178
-
179
- // the rest of the error handler
180
- })
158
+ if (hasZodFastifySchemaValidationErrors(err)) {
159
+ return reply.code(400).send({
160
+ error: 'Response Validation Error',
161
+ message: "Request doesn't match the schema",
162
+ statusCode: 400,
163
+ details: {
164
+ issues: err.validation,
165
+ method: req.method,
166
+ url: req.url,
167
+ },
168
+ });
169
+ }
170
+
171
+ if (isResponseSerializationError(err)) {
172
+ return reply.code(500).send({
173
+ error: 'Internal Server Error',
174
+ message: "Response doesn't match the schema",
175
+ statusCode: 500,
176
+ details: {
177
+ issues: err.cause.issues,
178
+ method: err.method,
179
+ url: err.url,
180
+ },
181
+ });
182
+ }
183
+
184
+ // the rest of the error handler
185
+ });
181
186
  ```
182
187
 
183
188
  ## How to create refs to the schemas?
184
189
 
185
- When provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas to the global zod registry and give it an `id` and fastifySwagger will create a OpenAPI document in which the schemas are referenced. The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.
190
+ When provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas with the global Zod registry and assign them an `id`. `fastifySwagger` will then create an OpenAPI document that references the schemas.
191
+
192
+ The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.
186
193
 
187
194
  ```ts
188
195
  import fastifySwagger from '@fastify/swagger';
189
196
  import fastifySwaggerUI from '@fastify/swagger-ui';
190
197
  import fastify from 'fastify';
191
- import { z } from 'zod';
198
+ import { z } from 'zod/v4';
192
199
  import type { ZodTypeProvider } from 'fastify-type-provider-zod';
193
200
  import {
194
201
  jsonSchemaTransformObject,
@@ -202,7 +209,7 @@ const USER_SCHEMA = z.object({
202
209
  name: z.string().describe('The name of the user'),
203
210
  });
204
211
 
205
- z.globalRegistry.add(USER_SCHEMA, { id: 'User' })
212
+ z.globalRegistry.add(USER_SCHEMA, { id: 'User' });
206
213
 
207
214
  const app = fastify();
208
215
  app.setValidatorCompiler(validatorCompiler);
@@ -256,8 +263,8 @@ run();
256
263
  ## How to create a plugin?
257
264
 
258
265
  ```ts
259
- import { z } from 'zod';
260
- import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
266
+ import { z } from 'zod/v4';
267
+ import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
261
268
 
262
269
  const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
263
270
  fastify.route({
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("zod/v4/core");
4
+ const errors = require("./errors.cjs");
5
+ const jsonToOas = require("./json-to-oas.cjs");
6
+ const zodToJson = require("./zod-to-json.cjs");
7
+ const defaultSkipList = [
8
+ "/documentation/",
9
+ "/documentation/initOAuth",
10
+ "/documentation/json",
11
+ "/documentation/uiConfig",
12
+ "/documentation/yaml",
13
+ "/documentation/*",
14
+ "/documentation/static/*"
15
+ ];
16
+ const createJsonSchemaTransform = ({
17
+ skipList = defaultSkipList,
18
+ schemaRegistry = core.globalRegistry
19
+ }) => {
20
+ return (input) => {
21
+ if ("swaggerObject" in input) {
22
+ throw new Error("OpenAPI 2.0 is not supported");
23
+ }
24
+ const { schema, url } = input;
25
+ if (!schema) {
26
+ return {
27
+ schema,
28
+ url
29
+ };
30
+ }
31
+ const { response, headers, querystring, body, params, hide, ...rest } = schema;
32
+ const transformed = {};
33
+ if (skipList.includes(url) || hide) {
34
+ transformed.hide = true;
35
+ return { schema: transformed, url };
36
+ }
37
+ const zodSchemas = { headers, querystring, body, params };
38
+ const oasVersion = jsonToOas.getOASVersion(input);
39
+ for (const prop in zodSchemas) {
40
+ const zodSchema = zodSchemas[prop];
41
+ if (zodSchema) {
42
+ const jsonSchema = zodToJson.zodSchemaToJson(zodSchema, schemaRegistry, "input");
43
+ const oasSchema = jsonToOas.jsonSchemaToOAS(jsonSchema, oasVersion);
44
+ transformed[prop] = oasSchema;
45
+ }
46
+ }
47
+ if (response) {
48
+ transformed.response = {};
49
+ for (const prop in response) {
50
+ const zodSchema = resolveSchema(response[prop]);
51
+ const jsonSchema = zodToJson.zodSchemaToJson(zodSchema, schemaRegistry, "output");
52
+ if (jsonSchema.type === "null") {
53
+ transformed.response[prop] = jsonSchema;
54
+ continue;
55
+ }
56
+ const oasSchema = jsonToOas.jsonSchemaToOAS(jsonSchema, oasVersion);
57
+ transformed.response[prop] = oasSchema;
58
+ }
59
+ }
60
+ for (const prop in rest) {
61
+ const meta = rest[prop];
62
+ if (meta) {
63
+ transformed[prop] = meta;
64
+ }
65
+ }
66
+ return { schema: transformed, url };
67
+ };
68
+ };
69
+ const jsonSchemaTransform = createJsonSchemaTransform({});
70
+ const createJsonSchemaTransformObject = ({
71
+ schemaRegistry = core.globalRegistry
72
+ }) => (input) => {
73
+ if ("swaggerObject" in input) {
74
+ throw new Error("OpenAPI 2.0 is not supported");
75
+ }
76
+ const oasVersion = jsonToOas.getOASVersion(input);
77
+ const inputSchemas = zodToJson.zodRegistryToJson(schemaRegistry, "input");
78
+ const outputSchemas = zodToJson.zodRegistryToJson(schemaRegistry, "output");
79
+ for (const key in outputSchemas) {
80
+ if (inputSchemas[key]) {
81
+ throw new Error(
82
+ `Collision detected for schema "${key}". The is already an input schema with the same name.`
83
+ );
84
+ }
85
+ }
86
+ const jsonSchemas = {
87
+ ...inputSchemas,
88
+ ...outputSchemas
89
+ };
90
+ const oasSchemas = Object.fromEntries(
91
+ Object.entries(jsonSchemas).map(([key, value]) => [key, jsonToOas.jsonSchemaToOAS(value, oasVersion)])
92
+ );
93
+ return {
94
+ ...input.openapiObject,
95
+ components: {
96
+ ...input.openapiObject.components,
97
+ schemas: {
98
+ ...input.openapiObject.components?.schemas,
99
+ ...oasSchemas
100
+ }
101
+ }
102
+ };
103
+ };
104
+ const jsonSchemaTransformObject = createJsonSchemaTransformObject({});
105
+ const validatorCompiler = ({ schema }) => (data) => {
106
+ const result = core.safeParse(schema, data);
107
+ if (result.error) {
108
+ return { error: errors.createValidationError(result.error) };
109
+ }
110
+ return { value: result.data };
111
+ };
112
+ function resolveSchema(maybeSchema) {
113
+ if (maybeSchema instanceof core.$ZodType) {
114
+ return maybeSchema;
115
+ }
116
+ if ("properties" in maybeSchema && maybeSchema.properties instanceof core.$ZodType) {
117
+ return maybeSchema.properties;
118
+ }
119
+ throw new errors.InvalidSchemaError(JSON.stringify(maybeSchema));
120
+ }
121
+ const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, url }) => (data) => {
122
+ const schema = resolveSchema(maybeSchema);
123
+ const result = core.safeParse(schema, data);
124
+ if (result.error) {
125
+ throw new errors.ResponseSerializationError(method, url, { cause: result.error });
126
+ }
127
+ return JSON.stringify(result.data, options?.replacer);
128
+ };
129
+ const serializerCompiler = createSerializerCompiler({});
130
+ exports.createJsonSchemaTransform = createJsonSchemaTransform;
131
+ exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
132
+ exports.createSerializerCompiler = createSerializerCompiler;
133
+ exports.jsonSchemaTransform = jsonSchemaTransform;
134
+ exports.jsonSchemaTransformObject = jsonSchemaTransformObject;
135
+ exports.serializerCompiler = serializerCompiler;
136
+ exports.validatorCompiler = validatorCompiler;
137
+ //# sourceMappingURL=core.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.cjs","sources":["../../src/core.ts"],"sourcesContent":["import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger'\nimport type {\n FastifyPluginAsync,\n FastifyPluginCallback,\n FastifyPluginOptions,\n FastifySchema,\n FastifySchemaCompiler,\n FastifyTypeProvider,\n RawServerBase,\n RawServerDefault,\n} from 'fastify'\nimport type { FastifySerializerCompiler } from 'fastify/types/schema'\nimport type { $ZodRegistry, input, output } from 'zod/v4/core'\nimport { $ZodType, globalRegistry, safeParse } from 'zod/v4/core'\nimport { createValidationError, InvalidSchemaError, ResponseSerializationError } from './errors'\nimport { getOASVersion, jsonSchemaToOAS } from './json-to-oas'\nimport { zodRegistryToJson, zodSchemaToJson } from './zod-to-json'\n\ntype FreeformRecord = Record<string, any>\n\nconst defaultSkipList = [\n '/documentation/',\n '/documentation/initOAuth',\n '/documentation/json',\n '/documentation/uiConfig',\n '/documentation/yaml',\n '/documentation/*',\n '/documentation/static/*',\n]\n\nexport interface ZodTypeProvider extends FastifyTypeProvider {\n validator: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n serializer: this['schema'] extends $ZodType ? input<this['schema']> : unknown\n}\n\ninterface Schema extends FastifySchema {\n hide?: boolean\n}\n\ntype CreateJsonSchemaTransformOptions = {\n skipList?: readonly string[]\n schemaRegistry?: $ZodRegistry<{ id?: string | undefined }>\n}\n\nexport const createJsonSchemaTransform = ({\n skipList = defaultSkipList,\n schemaRegistry = globalRegistry,\n}: CreateJsonSchemaTransformOptions): SwaggerTransform<Schema> => {\n return (input) => {\n if ('swaggerObject' in input) {\n throw new Error('OpenAPI 2.0 is not supported')\n }\n\n const { schema, url } = input\n\n if (!schema) {\n return {\n schema,\n url,\n }\n }\n\n const { response, headers, querystring, body, params, hide, ...rest } = schema\n\n const transformed: FreeformRecord = {}\n\n if (skipList.includes(url) || hide) {\n transformed.hide = true\n return { schema: transformed, url }\n }\n\n const zodSchemas: FreeformRecord = { headers, querystring, body, params }\n\n const oasVersion = getOASVersion(input)\n\n for (const prop in zodSchemas) {\n const zodSchema = zodSchemas[prop]\n if (zodSchema) {\n const jsonSchema = zodSchemaToJson(zodSchema, schemaRegistry, 'input')\n const oasSchema = jsonSchemaToOAS(jsonSchema, oasVersion)\n\n transformed[prop] = oasSchema\n }\n }\n\n if (response) {\n transformed.response = {}\n\n for (const prop in response as any) {\n const zodSchema = resolveSchema((response as any)[prop])\n const jsonSchema = zodSchemaToJson(zodSchema, schemaRegistry, 'output')\n\n // Check is the JSON schema is null then return as it is since fastify-swagger will handle it\n if (jsonSchema.type === 'null') {\n transformed.response[prop] = jsonSchema\n continue\n }\n\n const oasSchema = jsonSchemaToOAS(jsonSchema, oasVersion)\n\n transformed.response[prop] = oasSchema\n }\n }\n\n for (const prop in rest) {\n const meta = rest[prop as keyof typeof rest]\n if (meta) {\n transformed[prop] = meta\n }\n }\n\n return { schema: transformed, url }\n }\n}\n\nexport const jsonSchemaTransform: SwaggerTransform<Schema> = createJsonSchemaTransform({})\n\ntype CreateJsonSchemaTransformObjectOptions = {\n schemaRegistry?: $ZodRegistry<{ id?: string | undefined }>\n}\n\nexport const createJsonSchemaTransformObject =\n ({\n schemaRegistry = globalRegistry,\n }: CreateJsonSchemaTransformObjectOptions): SwaggerTransformObject =>\n (input) => {\n if ('swaggerObject' in input) {\n throw new Error('OpenAPI 2.0 is not supported')\n }\n\n const oasVersion = getOASVersion(input)\n\n const inputSchemas = zodRegistryToJson(schemaRegistry, 'input')\n const outputSchemas = zodRegistryToJson(schemaRegistry, 'output')\n\n for (const key in outputSchemas) {\n if (inputSchemas[key]) {\n throw new Error(\n `Collision detected for schema \"${key}\". The is already an input schema with the same name.`,\n )\n }\n }\n\n const jsonSchemas = {\n ...inputSchemas,\n ...outputSchemas,\n }\n\n const oasSchemas = Object.fromEntries(\n Object.entries(jsonSchemas).map(([key, value]) => [key, jsonSchemaToOAS(value, oasVersion)]),\n )\n\n return {\n ...input.openapiObject,\n components: {\n ...input.openapiObject.components,\n schemas: {\n ...input.openapiObject.components?.schemas,\n ...oasSchemas,\n },\n },\n } as ReturnType<SwaggerTransformObject>\n }\n\nexport const jsonSchemaTransformObject: SwaggerTransformObject = createJsonSchemaTransformObject({})\n\nexport const validatorCompiler: FastifySchemaCompiler<$ZodType> =\n ({ schema }) =>\n (data) => {\n const result = safeParse(schema, data)\n if (result.error) {\n return { error: createValidationError(result.error) as unknown as Error }\n }\n\n return { value: result.data }\n }\n\nfunction resolveSchema(maybeSchema: $ZodType | { properties: $ZodType }): $ZodType {\n if (maybeSchema instanceof $ZodType) {\n return maybeSchema\n }\n if ('properties' in maybeSchema && maybeSchema.properties instanceof $ZodType) {\n return maybeSchema.properties\n }\n throw new InvalidSchemaError(JSON.stringify(maybeSchema))\n}\n\ntype ReplacerFunction = (this: any, key: string, value: any) => any\n\nexport type ZodSerializerCompilerOptions = {\n replacer?: ReplacerFunction\n}\n\nexport const createSerializerCompiler =\n (\n options?: ZodSerializerCompilerOptions,\n ): FastifySerializerCompiler<$ZodType | { properties: $ZodType }> =>\n ({ schema: maybeSchema, method, url }) =>\n (data) => {\n const schema = resolveSchema(maybeSchema)\n\n const result = safeParse(schema, data)\n if (result.error) {\n throw new ResponseSerializationError(method, url, { cause: result.error })\n }\n\n return JSON.stringify(result.data, options?.replacer)\n }\n\nexport const serializerCompiler: ReturnType<typeof createSerializerCompiler> =\n createSerializerCompiler({})\n\n/**\n * FastifyPluginCallbackZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginCallbackZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {\n * done()\n * }\n * ```\n */\nexport type FastifyPluginCallbackZod<\n Options extends FastifyPluginOptions = Record<never, never>,\n Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginCallback<Options, Server, ZodTypeProvider>\n\n/**\n * FastifyPluginAsyncZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginAsyncZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {\n * }\n * ```\n */\nexport type FastifyPluginAsyncZod<\n Options extends FastifyPluginOptions = Record<never, never>,\n Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginAsync<Options, Server, ZodTypeProvider>\n"],"names":["globalRegistry","getOASVersion","zodSchemaToJson","jsonSchemaToOAS","zodRegistryToJson","safeParse","createValidationError","$ZodType","InvalidSchemaError","ResponseSerializationError"],"mappings":";;;;;;AAoBA,MAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAgBO,MAAM,4BAA4B,CAAC;AAAA,EACxC,WAAW;AAAA,EACX,iBAAiBA,KAAAA;AACnB,MAAkE;AAChE,SAAO,CAAC,UAAU;AAChB,QAAI,mBAAmB,OAAO;AAC5B,YAAM,IAAI,MAAM,8BAA8B;AAAA,IAChD;AAEA,UAAM,EAAE,QAAQ,IAAA,IAAQ;AAExB,QAAI,CAAC,QAAQ;AACX,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,UAAM,EAAE,UAAU,SAAS,aAAa,MAAM,QAAQ,MAAM,GAAG,KAAA,IAAS;AAExE,UAAM,cAA8B,CAAA;AAEpC,QAAI,SAAS,SAAS,GAAG,KAAK,MAAM;AAClC,kBAAY,OAAO;AACnB,aAAO,EAAE,QAAQ,aAAa,IAAA;A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B,QAAQ,KAAK,EAAE,OAAO,OAAO,OAAO;AAAA,EAC3E;AAEA,SAAO,KAAK,UAAU,OAAO,MAAM,SAAS,QAAQ;AACtD;AAEK,MAAM,qBACX,yBAAyB,CAAA,CAAE;;;;;;;;"}
@@ -0,0 +1,68 @@
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 type { $ZodRegistry, input, output } from "zod/v4/core";
5
+ import { $ZodType } from "zod/v4/core";
6
+ export interface ZodTypeProvider extends FastifyTypeProvider {
7
+ validator: this["schema"] extends $ZodType ? output<this["schema"]> : unknown;
8
+ serializer: this["schema"] extends $ZodType ? input<this["schema"]> : unknown;
9
+ }
10
+ interface Schema extends FastifySchema {
11
+ hide?: boolean;
12
+ }
13
+ type CreateJsonSchemaTransformOptions = {
14
+ skipList?: readonly string[];
15
+ schemaRegistry?: $ZodRegistry<{
16
+ id?: string | undefined;
17
+ }>;
18
+ };
19
+ export declare const createJsonSchemaTransform: ({ skipList, schemaRegistry }: CreateJsonSchemaTransformOptions) => SwaggerTransform<Schema>;
20
+ export declare const jsonSchemaTransform: SwaggerTransform<Schema>;
21
+ type CreateJsonSchemaTransformObjectOptions = {
22
+ schemaRegistry?: $ZodRegistry<{
23
+ id?: string | undefined;
24
+ }>;
25
+ };
26
+ export declare const createJsonSchemaTransformObject: ({ schemaRegistry }: CreateJsonSchemaTransformObjectOptions) => SwaggerTransformObject;
27
+ export declare const jsonSchemaTransformObject: SwaggerTransformObject;
28
+ export declare const validatorCompiler: FastifySchemaCompiler<$ZodType>;
29
+ type ReplacerFunction = (this: any, key: string, value: any) => any;
30
+ export type ZodSerializerCompilerOptions = {
31
+ replacer?: ReplacerFunction;
32
+ };
33
+ export declare const createSerializerCompiler: (options?: ZodSerializerCompilerOptions) => FastifySerializerCompiler<$ZodType | {
34
+ properties: $ZodType;
35
+ }>;
36
+ export declare const serializerCompiler: ReturnType<typeof createSerializerCompiler>;
37
+ /**
38
+ * FastifyPluginCallbackZod with Zod automatic type inference
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
43
+ *
44
+ * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
45
+ * done()
46
+ * }
47
+ * ```
48
+ */
49
+ export type FastifyPluginCallbackZod<
50
+ Options extends FastifyPluginOptions = Record<never, never>,
51
+ Server extends RawServerBase = RawServerDefault
52
+ > = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
53
+ /**
54
+ * FastifyPluginAsyncZod with Zod automatic type inference
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
59
+ *
60
+ * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
61
+ * }
62
+ * ```
63
+ */
64
+ export type FastifyPluginAsyncZod<
65
+ Options extends FastifyPluginOptions = Record<never, never>,
66
+ Server extends RawServerBase = RawServerDefault
67
+ > = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
68
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const createError = require("@fastify/error");
4
+ const InvalidSchemaError = createError("FST_ERR_INVALID_SCHEMA", "Invalid schema passed: %s", 500);
5
+ const ZodFastifySchemaValidationErrorSymbol = Symbol.for("ZodFastifySchemaValidationError");
6
+ const ResponseSerializationBase = createError(
7
+ "FST_ERR_RESPONSE_SERIALIZATION",
8
+ "Response doesn't match the schema",
9
+ 500
10
+ );
11
+ class ResponseSerializationError extends ResponseSerializationBase {
12
+ constructor(method, url, options) {
13
+ super({ cause: options.cause });
14
+ this.method = method;
15
+ this.url = url;
16
+ this.cause = options.cause;
17
+ }
18
+ cause;
19
+ }
20
+ function isResponseSerializationError(value) {
21
+ return "method" in value;
22
+ }
23
+ function isZodFastifySchemaValidationError(error) {
24
+ return typeof error === "object" && error !== null && error[ZodFastifySchemaValidationErrorSymbol] === true;
25
+ }
26
+ function hasZodFastifySchemaValidationErrors(error) {
27
+ return typeof error === "object" && error !== null && "validation" in error && Array.isArray(error.validation) && error.validation.length > 0 && isZodFastifySchemaValidationError(error.validation[0]);
28
+ }
29
+ function omit(obj, keys) {
30
+ const result = {};
31
+ for (const key of Object.keys(obj)) {
32
+ if (!keys.includes(key)) {
33
+ result[key] = obj[key];
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+ function createValidationError(error) {
39
+ return error.issues.map((issue) => {
40
+ return {
41
+ [ZodFastifySchemaValidationErrorSymbol]: true,
42
+ keyword: issue.code,
43
+ instancePath: `/${issue.path.join("/")}`,
44
+ schemaPath: `#/${issue.path.join("/")}/${issue.code}`,
45
+ message: issue.message,
46
+ params: {
47
+ ...omit(issue, ["path", "code", "message"])
48
+ }
49
+ };
50
+ });
51
+ }
52
+ exports.InvalidSchemaError = InvalidSchemaError;
53
+ exports.ResponseSerializationError = ResponseSerializationError;
54
+ exports.createValidationError = createValidationError;
55
+ exports.hasZodFastifySchemaValidationErrors = hasZodFastifySchemaValidationErrors;
56
+ exports.isResponseSerializationError = isResponseSerializationError;
57
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","sources":["../../src/errors.ts"],"sourcesContent":["import createError, { type FastifyErrorConstructor } from '@fastify/error'\nimport type { FastifyError } from 'fastify'\nimport type { FastifySchemaValidationError } from 'fastify/types/schema'\nimport type { $ZodError } from 'zod/v4/core'\n\nexport const InvalidSchemaError: FastifyErrorConstructor<\n {\n code: string\n },\n [string]\n> = createError<[string]>('FST_ERR_INVALID_SCHEMA', 'Invalid schema passed: %s', 500)\n\nconst ZodFastifySchemaValidationErrorSymbol: symbol = Symbol.for('ZodFastifySchemaValidationError')\n\nexport type ZodFastifySchemaValidationError = FastifySchemaValidationError & {\n [ZodFastifySchemaValidationErrorSymbol]: true\n}\n\nconst ResponseSerializationBase: FastifyErrorConstructor<\n {\n code: string\n },\n [\n {\n cause: $ZodError\n },\n ]\n> = createError<[{ cause: $ZodError }]>(\n 'FST_ERR_RESPONSE_SERIALIZATION',\n \"Response doesn't match the schema\",\n 500,\n)\n\nexport class ResponseSerializationError extends ResponseSerializationBase {\n cause!: $ZodError\n\n constructor(\n public method: string,\n public url: string,\n options: { cause: $ZodError },\n ) {\n super({ cause: options.cause })\n\n this.cause = options.cause\n }\n}\n\nexport function isResponseSerializationError(value: unknown): value is ResponseSerializationError {\n return 'method' in (value as ResponseSerializationError)\n}\n\nfunction isZodFastifySchemaValidationError(\n error: unknown,\n): error is ZodFastifySchemaValidationError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as ZodFastifySchemaValidationError)[ZodFastifySchemaValidationErrorSymbol] === true\n )\n}\n\nexport function hasZodFastifySchemaValidationErrors(\n error: unknown,\n): error is Omit<FastifyError, 'validation'> & { validation: ZodFastifySchemaValidationError[] } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'validation' in error &&\n Array.isArray(error.validation) &&\n error.validation.length > 0 &&\n isZodFastifySchemaValidationError(error.validation[0])\n )\n}\n\nfunction omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K> {\n const result = {} as Omit<T, K>\n for (const key of Object.keys(obj) as Array<keyof T>) {\n if (!keys.includes(key as K)) {\n // @ts-expect-error\n result[key] = obj[key]\n }\n }\n return result\n}\n\nexport function createValidationError(error: $ZodError): ZodFastifySchemaValidationError[] {\n return error.issues.map((issue) => {\n return {\n [ZodFastifySchemaValidationErrorSymbol]: true,\n keyword: issue.code,\n instancePath: `/${issue.path.join('/')}`,\n schemaPath: `#/${issue.path.join('/')}/${issue.code}`,\n message: issue.message,\n params: {\n ...omit(issue, ['path', 'code', 'message']),\n },\n }\n })\n}\n"],"names":[],"mappings":";;;AAKO,MAA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SAAS,CAAC;AAAA,MAAA;AAAA,IAC5C;AAAA,EAEJ,CAAC;AACH;;;;;;"}
@@ -0,0 +1,30 @@
1
+ import { type FastifyErrorConstructor } from "@fastify/error";
2
+ import type { FastifyError } from "fastify";
3
+ import type { FastifySchemaValidationError } from "fastify/types/schema";
4
+ import type { $ZodError } from "zod/v4/core";
5
+ export declare const InvalidSchemaError: FastifyErrorConstructor<{
6
+ code: string;
7
+ }, [string]>;
8
+ declare const ZodFastifySchemaValidationErrorSymbol: symbol;
9
+ export type ZodFastifySchemaValidationError = FastifySchemaValidationError & {
10
+ [ZodFastifySchemaValidationErrorSymbol]: true;
11
+ };
12
+ declare const ResponseSerializationBase: FastifyErrorConstructor<{
13
+ code: string;
14
+ }, [{
15
+ cause: $ZodError;
16
+ }]>;
17
+ export declare class ResponseSerializationError extends ResponseSerializationBase {
18
+ method: string;
19
+ url: string;
20
+ cause: $ZodError;
21
+ constructor(method: string, url: string, options: {
22
+ cause: $ZodError;
23
+ });
24
+ }
25
+ export declare function isResponseSerializationError(value: unknown): value is ResponseSerializationError;
26
+ export declare function hasZodFastifySchemaValidationErrors(error: unknown): error is Omit<FastifyError, "validation"> & {
27
+ validation: ZodFastifySchemaValidationError[];
28
+ };
29
+ export declare function createValidationError(error: $ZodError): ZodFastifySchemaValidationError[];
30
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("./core.cjs");
4
+ const errors = require("./errors.cjs");
5
+ exports.createJsonSchemaTransform = core.createJsonSchemaTransform;
6
+ exports.createJsonSchemaTransformObject = core.createJsonSchemaTransformObject;
7
+ exports.createSerializerCompiler = core.createSerializerCompiler;
8
+ exports.jsonSchemaTransform = core.jsonSchemaTransform;
9
+ exports.jsonSchemaTransformObject = core.jsonSchemaTransformObject;
10
+ exports.serializerCompiler = core.serializerCompiler;
11
+ exports.validatorCompiler = core.validatorCompiler;
12
+ exports.InvalidSchemaError = errors.InvalidSchemaError;
13
+ exports.ResponseSerializationError = errors.ResponseSerializationError;
14
+ exports.hasZodFastifySchemaValidationErrors = errors.hasZodFastifySchemaValidationErrors;
15
+ exports.isResponseSerializationError = errors.isResponseSerializationError;
16
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
@@ -0,0 +1,2 @@
1
+ export { createJsonSchemaTransform, createJsonSchemaTransformObject, createSerializerCompiler, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, jsonSchemaTransform, jsonSchemaTransformObject, serializerCompiler, validatorCompiler, type ZodSerializerCompilerOptions, type ZodTypeProvider } from "../cjs/core.cjs";
2
+ export { hasZodFastifySchemaValidationErrors, InvalidSchemaError, isResponseSerializationError, ResponseSerializationError, type ZodFastifySchemaValidationError } from "../cjs/errors.cjs";
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const getOASVersion = (documentObject) => {
4
+ const openapiVersion = documentObject.openapiObject.openapi || "3.0.3";
5
+ if (openapiVersion.startsWith("3.1")) {
6
+ return "3.1";
7
+ }
8
+ if (openapiVersion.startsWith("3.0")) {
9
+ return "3.0";
10
+ }
11
+ throw new Error("Unsupported OpenAPI document object");
12
+ };
13
+ const jsonSchemaToOAS_3_0 = (jsonSchema) => {
14
+ const clone = { ...jsonSchema };
15
+ if (clone.type === "null") {
16
+ clone.nullable = true;
17
+ delete clone.type;
18
+ clone.enum = [null];
19
+ }
20
+ if (Array.isArray(clone.prefixItems)) {
21
+ const tuple = clone.prefixItems;
22
+ clone.minItems ??= tuple.length;
23
+ clone.maxItems ??= tuple.length;
24
+ clone.items = {
25
+ oneOf: tuple.map(jsonSchemaToOAS_3_0)
26
+ };
27
+ delete clone.prefixItems;
28
+ }
29
+ if ("const" in clone && clone.const !== void 0) {
30
+ clone.enum = [clone.const];
31
+ delete clone.const;
32
+ }
33
+ if (typeof clone.exclusiveMinimum === "number") {
34
+ clone.minimum = clone.exclusiveMinimum;
35
+ clone.exclusiveMinimum = true;
36
+ }
37
+ if (typeof clone.exclusiveMaximum === "number") {
38
+ clone.maximum = clone.exclusiveMaximum;
39
+ clone.exclusiveMaximum = true;
40
+ }
41
+ for (const key of [
42
+ "$schema",
43
+ "$id",
44
+ "unevaluatedProperties",
45
+ "dependentSchemas",
46
+ "patternProperties",
47
+ "propertyNames",
48
+ "contentEncoding",
49
+ "contentMediaType"
50
+ ]) {
51
+ delete clone[key];
52
+ }
53
+ const recursive = (v) => Array.isArray(v) ? v.map(jsonSchemaToOAS_3_0) : jsonSchemaToOAS_3_0(v);
54
+ if (clone.properties) {
55
+ for (const [k, v] of Object.entries(clone.properties)) {
56
+ clone.properties[k] = jsonSchemaToOAS_3_0(v);
57
+ }
58
+ }
59
+ if (clone.items && !Array.isArray(clone.items)) {
60
+ clone.items = recursive(clone.items);
61
+ }
62
+ for (const key of ["allOf", "anyOf", "oneOf", "not", "then", "else", "if", "contains"]) {
63
+ if (clone[key]) {
64
+ clone[key] = recursive(clone[key]);
65
+ }
66
+ }
67
+ return clone;
68
+ };
69
+ const jsonSchemaToOAS_3_1 = (jsonSchema) => {
70
+ return jsonSchema;
71
+ };
72
+ const jsonSchemaToOAS = (jsonSchema, oasVersion) => {
73
+ switch (oasVersion) {
74
+ case "3.0":
75
+ return jsonSchemaToOAS_3_0(jsonSchema);
76
+ case "3.1":
77
+ return jsonSchemaToOAS_3_1(jsonSchema);
78
+ default:
79
+ throw new Error(`Unsupported OpenAPI version: ${oasVersion}`);
80
+ }
81
+ };
82
+ exports.getOASVersion = getOASVersion;
83
+ exports.jsonSchemaToOAS = jsonSchemaToOAS;
84
+ exports.jsonSchemaToOAS_3_0 = jsonSchemaToOAS_3_0;
85
+ //# sourceMappingURL=json-to-oas.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-to-oas.cjs","sources":["../../src/json-to-oas.ts"],"sourcesContent":["import type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\nimport type { JSONSchema } from 'zod/v4/core'\n\ntype OASVersion = '3.0' | '3.1'\n\nexport const getOASVersion = (documentObject: {\n openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>\n}): OASVersion => {\n const openapiVersion = documentObject.openapiObject.openapi || '3.0.3'\n\n if (openapiVersion.startsWith('3.1')) {\n return '3.1'\n }\n\n if (openapiVersion.startsWith('3.0')) {\n return '3.0'\n }\n\n throw new Error('Unsupported OpenAPI document object')\n}\n\nexport const jsonSchemaToOAS_3_0 = (jsonSchema: JSONSchema.BaseSchema): OpenAPIV3.SchemaObject => {\n const clone: any = { ...jsonSchema }\n\n if (clone.type === 'null') {\n clone.nullable = true\n delete clone.type\n clone.enum = [null]\n }\n\n if (Array.isArray(clone.prefixItems)) {\n const tuple = clone.prefixItems as JSONSchema.BaseSchema[]\n\n clone.minItems ??= tuple.length\n clone.maxItems ??= tuple.length\n\n clone.items = {\n oneOf: tuple.map(jsonSchemaToOAS_3_0),\n }\n\n delete clone.prefixItems\n }\n\n if ('const' in clone && clone.const !== undefined) {\n clone.enum = [clone.const]\n delete clone.const\n }\n\n if (typeof clone.exclusiveMinimum === 'number') {\n clone.minimum = clone.exclusiveMinimum\n clone.exclusiveMinimum = true\n }\n if (typeof clone.exclusiveMaximum === 'number') {\n clone.maximum = clone.exclusiveMaximum\n clone.exclusiveMaximum = true\n }\n\n for (const key of [\n '$schema',\n '$id',\n 'unevaluatedProperties',\n 'dependentSchemas',\n 'patternProperties',\n 'propertyNames',\n 'contentEncoding',\n 'contentMediaType',\n ]) {\n delete clone[key]\n }\n\n const recursive = (v: any): any =>\n Array.isArray(v) ? v.map(jsonSchemaToOAS_3_0) : jsonSchemaToOAS_3_0(v)\n\n if (clone.properties) {\n for (const [k, v] of Object.entries(clone.properties)) {\n clone.properties![k] = jsonSchemaToOAS_3_0(v as any)\n }\n }\n\n if (clone.items && !Array.isArray(clone.items)) {\n clone.items = recursive(clone.items)\n }\n\n for (const key of ['allOf', 'anyOf', 'oneOf', 'not', 'then', 'else', 'if', 'contains']) {\n if (clone[key]) {\n clone[key] = recursive(clone[key])\n }\n }\n\n return clone as OpenAPIV3.SchemaObject\n}\n\nconst jsonSchemaToOAS_3_1 = (jsonSchema: JSONSchema.BaseSchema): OpenAPIV3_1.SchemaObject => {\n return jsonSchema as OpenAPIV3_1.SchemaObject\n}\n\nexport const jsonSchemaToOAS = (\n jsonSchema: JSONSchema.BaseSchema,\n oasVersion: OASVersion,\n): OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject => {\n switch (oasVersion) {\n case '3.0':\n return jsonSchemaToOAS_3_0(jsonSchema)\n case '3.1':\n return jsonSchemaToOAS_3_1(jsonSchema)\n default:\n throw new Error(`Unsupported OpenAPI version: ${oasVersion}`)\n }\n}\n"],"names":[],"mappings":";;AAKO,MAAM,gBAAgB,CAAC,mBAEZ;AAChB,QAAM,iBAAiB,eAAe,cAAc,WAAW;AAE/D,MAAI,eAAe,WAAW,KAAK,GAAG;AACpC,WAAO;AAAA,EACT;AAEA,MAAI,eAAe,WAAW,KAAK,GAAG;AACpC,WAAO;AAAA,EACT;AAEA,QAAM,IAAI,MAAM,qCAAqC;AACvD;AAEO,MAAM,sBAAsB,CAAC,eAA8D;AAChG,QAAM,QAAa,EAAE,GAAG,WAAA;AAExB,MAAI,MAAM,SAAS,QAAQ;AACzB,UAAM,WAAW;AACjB,WAAO,MAAM;AACb,UAAM,OAAO,CAAC,IAAI;AAAA,EACpB;AAEA,MAAI,MAAM,QAAQ,MAAM,WAAW,GAAG;AACpC,UAAM,QAAQ,MAAM;AAEpB,UAAM,aAAa,MAAM;AACzB,UAAM,aAAa,MAAM;AAEzB,UAAM,QAAQ;AAAA,MACZ,OAAO,MAAM,IAAI,mBAAmB;AAAA,IAAA;AAGtC,WAAO,MAAM;AAAA,EACf;AAEA,MAAI,WAAW,SAAS,MAAM,UAAU,QAA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AE;AAAA,EAAA;AAElE;;;;"}
@@ -0,0 +1,9 @@
1
+ import type { OpenAPIV3, OpenAPIV3_1 } from "openapi-types";
2
+ import type { JSONSchema } from "zod/v4/core";
3
+ type OASVersion = "3.0" | "3.1";
4
+ export declare const getOASVersion: (documentObject: {
5
+ openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
6
+ }) => OASVersion;
7
+ export declare const jsonSchemaToOAS_3_0: (jsonSchema: JSONSchema.BaseSchema) => OpenAPIV3.SchemaObject;
8
+ export declare const jsonSchemaToOAS: (jsonSchema: JSONSchema.BaseSchema, oasVersion: OASVersion) => OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject;
9
+ export {};