@davars/graphql-codegen-zod 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 davars
4
+ Copyright (c) 2022 codehex (original graphql-codegen-typescript-validation-schema)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # @davars/graphql-codegen-zod
2
+
3
+ [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) plugin that generates [Zod v4](https://zod.dev) validation schemas from GraphQL types, with support for custom transforms.
4
+
5
+ Derived from [graphql-codegen-typescript-validation-schema](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema) by Code-Hex (MIT licensed). Stripped to Zod v4 only, with added transform support for custom type constructors.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add -D @davars/graphql-codegen-zod
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```yaml
16
+ # codegen.yml
17
+ generates:
18
+ path/to/schemas.ts:
19
+ plugins:
20
+ - @davars/graphql-codegen-zod
21
+ config:
22
+ schema: zodv4
23
+ withObjectType: true
24
+ importFrom: ./graphql-operations
25
+ scalarSchemas:
26
+ UUID: z.string().uuid()
27
+ DateTime: z.coerce.date()
28
+ ```
29
+
30
+ ## Transforms
31
+
32
+ Transforms let you convert plain parsed objects into custom class instances using Zod's `.transform()`.
33
+
34
+ ### 1. Define a transform function alongside your model
35
+
36
+ ```typescript
37
+ // models/DateRange.ts
38
+ export class DateRange {
39
+ constructor(readonly start: Date, readonly end: Date) {}
40
+ }
41
+
42
+ export function transformDateRange(raw: { start?: Date | null; end?: Date | null }): DateRange | null {
43
+ if (raw.start == null || raw.end == null) return null
44
+ return new DateRange(raw.start, raw.end)
45
+ }
46
+ ```
47
+
48
+ ### 2. Create a transforms config
49
+
50
+ ```typescript
51
+ // transforms.config.ts
52
+ import type { TransformConfig } from '@davars/graphql-codegen-zod/config'
53
+ import { transformDateRange } from './models/DateRange'
54
+
55
+ const config: TransformConfig = {
56
+ DateRange: transformDateRange,
57
+ }
58
+ export default config
59
+ ```
60
+
61
+ ### 3. Reference in codegen.yml
62
+
63
+ ```yaml
64
+ config:
65
+ transforms: ./path/to/transforms.config.ts
66
+ ```
67
+
68
+ The generated schema will include:
69
+ ```typescript
70
+ import { transformDateRange } from './models/DateRange'
71
+
72
+ export function DateRangeSchema() {
73
+ return z.object({
74
+ __typename: z.literal('DateRange').optional(),
75
+ start: z.coerce.date().nullish(),
76
+ end: z.coerce.date().nullish(),
77
+ }).transform(transformDateRange)
78
+ }
79
+ ```
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,363 @@
1
+ import type { TypeScriptPluginConfig } from '@graphql-codegen/typescript';
2
+ import type { NamingConventionMap } from '@graphql-codegen/visitor-plugin-common';
3
+ export type ValidationSchema = 'yup' | 'zod' | 'zodv4' | 'myzod' | 'valibot';
4
+ export type ValidationSchemaExportType = 'function' | 'const';
5
+ export interface DirectiveConfig {
6
+ [directive: string]: {
7
+ [argument: string]: string | string[] | DirectiveObjectArguments;
8
+ };
9
+ }
10
+ export interface DirectiveObjectArguments {
11
+ [matched: string]: string | string[];
12
+ }
13
+ interface ScalarSchemas {
14
+ [name: string]: string;
15
+ }
16
+ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
17
+ /**
18
+ * @description Specifies a custom import path for the zod package. This is useful when you want to use a specific
19
+ * version or subpath of zod, such as the v3 compatibility layer in zod v4 ('zod/v3').
20
+ * Only applies when schema is set to 'zod'.
21
+ * @default 'zod'
22
+ *
23
+ * @exampleMarkdown
24
+ * ```yml
25
+ * generates:
26
+ * path/to/schemas.ts:
27
+ * plugins:
28
+ * - graphql-codegen-validation-schema
29
+ * config:
30
+ * schema: zod
31
+ * # Use zod v3 compatibility layer when using zod v4
32
+ * zodImportPath: zod/v3
33
+ * ```
34
+ */
35
+ zodImportPath?: string;
36
+ /**
37
+ * @description specify generate schema
38
+ * @default yup
39
+ *
40
+ * @exampleMarkdown
41
+ * ```yml
42
+ * generates:
43
+ * path/to/file.ts:
44
+ * plugins:
45
+ * - typescript
46
+ * - graphql-codegen-validation-schema
47
+ * config:
48
+ * schema: yup
49
+ * ```
50
+ */
51
+ schema?: ValidationSchema;
52
+ /**
53
+ * @description import types from generated typescript type path
54
+ * if not given, omit import statement.
55
+ *
56
+ * @exampleMarkdown
57
+ * ```yml
58
+ * generates:
59
+ * path/to/types.ts:
60
+ * plugins:
61
+ * - typescript
62
+ * path/to/schemas.ts:
63
+ * plugins:
64
+ * - graphql-codegen-validation-schema
65
+ * config:
66
+ * schema: yup
67
+ * importFrom: ./path/to/types
68
+ * ```
69
+ */
70
+ importFrom?: string;
71
+ /**
72
+ * @description If defined, will use named imports from the specified module (defined in `importFrom`)
73
+ * rather than individual imports for each type.
74
+ *
75
+ * @exampleMarkdown
76
+ * ```yml
77
+ * generates:
78
+ * path/to/types.ts:
79
+ * plugins:
80
+ * - typescript
81
+ * path/to/schemas.ts:
82
+ * plugins:
83
+ * - graphql-codegen-validation-schema
84
+ * config:
85
+ * schema: yup
86
+ * importFrom: ./path/to/types
87
+ * schemaNamespacedImportName: types
88
+ * ```
89
+ */
90
+ schemaNamespacedImportName?: string;
91
+ /**
92
+ * @description Will use `import type {}` rather than `import {}` when importing generated typescript types.
93
+ * This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option
94
+ * Should used in conjunction with `importFrom` option.
95
+ * @default false
96
+ *
97
+ * @exampleMarkdown
98
+ * ```yml
99
+ * generates:
100
+ * path/to/types.ts:
101
+ * plugins:
102
+ * - typescript
103
+ * path/to/schemas.ts:
104
+ * plugins:
105
+ * - graphql-codegen-validation-schema
106
+ * config:
107
+ * schema: yup
108
+ * importFrom: ./path/to/types
109
+ * useTypeImports: true
110
+ * ```
111
+ */
112
+ useTypeImports?: boolean;
113
+ /**
114
+ * @description Prefixes all import types from generated typescript type.
115
+ * @default ""
116
+ *
117
+ * @exampleMarkdown
118
+ * ```yml
119
+ * generates:
120
+ * path/to/types.ts:
121
+ * plugins:
122
+ * - typescript
123
+ * path/to/schemas.ts:
124
+ * plugins:
125
+ * - graphql-codegen-validation-schema
126
+ * config:
127
+ * typesPrefix: I
128
+ * importFrom: ./path/to/types
129
+ * ```
130
+ */
131
+ typesPrefix?: string;
132
+ /**
133
+ * @description Suffixes all import types from generated typescript type.
134
+ * @default ""
135
+ *
136
+ * @exampleMarkdown
137
+ * ```yml
138
+ * generates:
139
+ * path/to/types.ts:
140
+ * plugins:
141
+ * - typescript
142
+ * path/to/schemas.ts:
143
+ * plugins:
144
+ * - graphql-codegen-validation-schema
145
+ * config:
146
+ * typesSuffix: I
147
+ * importFrom: ./path/to/types
148
+ * ```
149
+ */
150
+ typesSuffix?: string;
151
+ /**
152
+ * @description Generates validation schema for enum as TypeScript `type`
153
+ * @default false
154
+ *
155
+ * @exampleMarkdown
156
+ * ```yml
157
+ * generates:
158
+ * path/to/file.ts:
159
+ * plugins:
160
+ * - graphql-codegen-validation-schema
161
+ * config:
162
+ * enumsAsTypes: true
163
+ * ```
164
+ *
165
+ * ```yml
166
+ * generates:
167
+ * path/to/file.ts:
168
+ * plugins:
169
+ * - typescript
170
+ * - graphql-codegen-validation-schema
171
+ * config:
172
+ * enumsAsTypes: true
173
+ * ```
174
+ */
175
+ enumsAsTypes?: boolean;
176
+ /**
177
+ * @description Generates validation string schema as do not allow empty characters by default.
178
+ * @default false
179
+ *
180
+ * @exampleMarkdown
181
+ * ```yml
182
+ * generates:
183
+ * path/to/file.ts:
184
+ * plugins:
185
+ * - graphql-codegen-validation-schema
186
+ * config:
187
+ * notAllowEmptyString: true
188
+ * ```
189
+ */
190
+ notAllowEmptyString?: boolean;
191
+ /**
192
+ * @description Extends or overrides validation schema for the built-in scalars and custom GraphQL scalars.
193
+ *
194
+ * @exampleMarkdown
195
+ * ```yml
196
+ * config:
197
+ * schema: yup
198
+ * scalarSchemas:
199
+ * Date: yup.date()
200
+ * Email: yup.string().email()
201
+ * ```
202
+ *
203
+ * @exampleMarkdown
204
+ * ```yml
205
+ * config:
206
+ * schema: zod
207
+ * scalarSchemas:
208
+ * Date: z.date()
209
+ * Email: z.string().email()
210
+ * ```
211
+ */
212
+ scalarSchemas?: ScalarSchemas;
213
+ /**
214
+ * @description Fallback scalar type for undefined scalar types in the schema not found in `scalarSchemas`.
215
+ *
216
+ * @exampleMarkdown
217
+ * ```yml
218
+ * config:
219
+ * schema: yup
220
+ * defaultScalarSchema: yup.unknown()
221
+ * ```
222
+ *
223
+ * @exampleMarkdown
224
+ * ```yml
225
+ * config:
226
+ * schema: zod
227
+ * defaultScalarSchema: z.unknown()
228
+ * ```
229
+ */
230
+ defaultScalarTypeSchema?: string;
231
+ /**
232
+ * @description Generates validation schema with GraphQL type objects.
233
+ * but excludes "Query", "Mutation", "Subscription" objects.
234
+ *
235
+ * @exampleMarkdown
236
+ * ```yml
237
+ * generates:
238
+ * path/to/types.ts:
239
+ * plugins:
240
+ * - typescript
241
+ * path/to/schemas.ts:
242
+ * plugins:
243
+ * - graphql-codegen-validation-schema
244
+ * config:
245
+ * schema: yup
246
+ * withObjectType: true
247
+ * ```
248
+ */
249
+ withObjectType?: boolean;
250
+ /**
251
+ * @description Specify validation schema export type.
252
+ * @default function
253
+ *
254
+ * @exampleMarkdown
255
+ * ```yml
256
+ * generates:
257
+ * path/to/file.ts:
258
+ * plugins:
259
+ * - typescript
260
+ * - graphql-codegen-validation-schema
261
+ * config:
262
+ * validationSchemaExportType: const
263
+ * ```
264
+ */
265
+ validationSchemaExportType?: ValidationSchemaExportType;
266
+ /**
267
+ * @description Uses the full path of the enum type as the default value instead of the stringified value.
268
+ * @default false
269
+ *
270
+ * @exampleMarkdown
271
+ * ```yml
272
+ * generates:
273
+ * path/to/file.ts:
274
+ * plugins:
275
+ * - typescript
276
+ * - graphql-codegen-validation-schema
277
+ * config:
278
+ * useEnumTypeAsDefaultValue: true
279
+ * ```
280
+ */
281
+ useEnumTypeAsDefaultValue?: boolean;
282
+ /**
283
+ * @description Uses the full path of the enum type as the default value instead of the stringified value.
284
+ * @default { enumValues: "change-case-all#pascalCase" }
285
+ * @link https://the-guild.dev/graphql/codegen/docs/config-reference/naming-convention
286
+ *
287
+ * Note: This option has not been tested with `namingConvention.transformUnderscore` and `namingConvention.typeNames` options,
288
+ * and may not work as expected.
289
+ *
290
+ * @exampleMarkdown
291
+ * ```yml
292
+ * generates:
293
+ * path/to/file.ts:
294
+ * plugins:
295
+ * - typescript
296
+ * - graphql-codegen-validation-schema
297
+ * config:
298
+ * namingConvention:
299
+ * enumValues: change-case-all#pascalCase
300
+ * ```
301
+ */
302
+ namingConvention?: NamingConventionMap;
303
+ /**
304
+ * @description Generates validation schema with more API based on directive schema.
305
+ * @exampleMarkdown
306
+ * ```yml
307
+ * generates:
308
+ * path/to/file.ts:
309
+ * plugins:
310
+ * - graphql-codegen-validation-schema
311
+ * config:
312
+ * schema: yup
313
+ * directives:
314
+ * required:
315
+ * msg: required
316
+ * # This is example using constraint directive.
317
+ * # see: https://github.com/confuser/graphql-constraint-directive
318
+ * constraint:
319
+ * minLength: min # same as ['min', '$1']
320
+ * maxLength: max
321
+ * startsWith: ["matches", "/^$1/"]
322
+ * endsWith: ["matches", "/$1$/"]
323
+ * contains: ["matches", "/$1/"]
324
+ * notContains: ["matches", "/^((?!$1).)*$/"]
325
+ * pattern: ["matches", "/$1/"]
326
+ * format:
327
+ * # For example, `@constraint(format: "uri")`. this case $1 will be "uri".
328
+ * # Therefore the generator generates yup schema `.url()` followed by `uri: 'url'`
329
+ * # If $1 does not match anywhere, the generator will ignore.
330
+ * uri: url
331
+ * email: email
332
+ * uuid: uuid
333
+ * # yup does not have `ipv4` API. If you want to add this,
334
+ * # you need to add the logic using `yup.addMethod`.
335
+ * # see: https://github.com/jquense/yup#addmethodschematype-schema-name-string-method--schema-void
336
+ * ipv4: ipv4
337
+ * min: ["min", "$1 - 1"]
338
+ * max: ["max", "$1 + 1"]
339
+ * exclusiveMin: min
340
+ * exclusiveMax: max
341
+ * ```
342
+ */
343
+ directives?: DirectiveConfig;
344
+ /**
345
+ * @description Path to a TypeScript config file that exports transform definitions.
346
+ * The config maps GraphQL type names to imported transform functions.
347
+ * When a transform is configured for a type, the generated schema will append
348
+ * `.transform(fn)` to produce custom class instances instead of plain objects.
349
+ *
350
+ * @exampleMarkdown
351
+ * ```yml
352
+ * generates:
353
+ * path/to/schemas.ts:
354
+ * plugins:
355
+ * - graphql-codegen-validation-schema
356
+ * config:
357
+ * schema: zod
358
+ * transforms: ./path/to/transforms.config.ts
359
+ * ```
360
+ */
361
+ transforms?: string;
362
+ }
363
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { ConstArgumentNode, ConstDirectiveNode, ConstValueNode } from 'graphql';
2
+ import type { DirectiveConfig, DirectiveObjectArguments } from './config.js';
3
+ export interface FormattedDirectiveConfig {
4
+ [directive: string]: FormattedDirectiveArguments;
5
+ }
6
+ export interface FormattedDirectiveArguments {
7
+ [argument: string]: string[] | FormattedDirectiveObjectArguments | undefined;
8
+ }
9
+ export interface FormattedDirectiveObjectArguments {
10
+ [matched: string]: string[] | undefined;
11
+ }
12
+ export declare function formatDirectiveConfig(config: DirectiveConfig): FormattedDirectiveConfig;
13
+ export declare function formatDirectiveObjectArguments(args: DirectiveObjectArguments): FormattedDirectiveObjectArguments;
14
+ export declare function buildApi(config: FormattedDirectiveConfig, directives: ReadonlyArray<ConstDirectiveNode>): string;
15
+ export declare function buildApiForValibot(config: FormattedDirectiveConfig, directives: ReadonlyArray<ConstDirectiveNode>): string[];
16
+ declare function buildApiFromDirectiveArguments(config: FormattedDirectiveArguments, args: ReadonlyArray<ConstArgumentNode>): string;
17
+ declare function buildApiFromDirectiveObjectArguments(config: FormattedDirectiveObjectArguments, argValue: ConstValueNode): string;
18
+ declare function applyArgToApiSchemaTemplate(template: string, apiArgs: any[]): string;
19
+ export declare const exportedForTesting: {
20
+ applyArgToApiSchemaTemplate: typeof applyArgToApiSchemaTemplate;
21
+ buildApiFromDirectiveObjectArguments: typeof buildApiFromDirectiveObjectArguments;
22
+ buildApiFromDirectiveArguments: typeof buildApiFromDirectiveArguments;
23
+ };
24
+ export {};