-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzod.ts
212 lines (184 loc) · 5.36 KB
/
zod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright Oxide Computer Company
*/
import { type IO } from "../io";
import { makeSchemaGenerator, refToSchemaName } from "./base";
import { type OpenAPIV3 } from "openapi-types";
import { snakeToCamel } from "../util";
export const schemaToZod = makeSchemaGenerator({
ref(schema, { w0 }) {
if ("$ref" in schema) {
w0(refToSchemaName(schema.$ref));
}
},
boolean(schema, { w0 }) {
w0(`SafeBoolean`);
if ("default" in schema) {
w0(`.default(${schema.default})`);
}
},
enum(schema, io) {
if (schema.type === "string") {
io.w0(`z.enum(${JSON.stringify(schema.enum)})`);
} else if (schema.type === "integer") {
schemaToZodInt(schema, io);
} else {
throw new Error(`Unsupported enum type ${schema.type}`);
}
},
string(schema, { w0 }) {
w0(`z.string()`);
if ("default" in schema) {
w0(`.default(${JSON.stringify(schema.default)})`);
}
if (schema.format === "uuid") {
w0(".uuid()");
}
if (schema.format === "ip") {
w0(".ip()");
} else if (schema.format === "ipv4") {
w0(".ip({ version: 'v4' })");
} else if (schema.format === "ipv6") {
w0(".ip({ version: 'v6' })");
}
if ("minLength" in schema) {
w0(`.min(${schema.minLength})`);
}
if ("maxLength" in schema) {
w0(`.max(${schema.maxLength})`);
}
if ("pattern" in schema) {
w0(`.regex(${new RegExp(schema.pattern!).toString()})`);
}
},
date(_, { w0 }) {
w0("z.coerce.date()");
},
number(_, { w0 }) {
w0("z.number()");
},
integer: schemaToZodInt,
array(schema, io) {
const { w0 } = io;
schemaToZod(schema.items, io);
w0(".array()");
if ("default" in schema) {
w0(`.default(${JSON.stringify(schema.default)})`);
}
if (schema.uniqueItems) {
w0(`.refine(...uniqueItems)`);
}
},
object(schema, io) {
const { w0, w } = io;
// record type, which only tells us the type of the values
if (!schema.properties || Object.keys(schema.properties).length === 0) {
w0("z.record(z.string().min(1),");
if (typeof schema.additionalProperties === "object") {
schemaToZod(schema.additionalProperties, io);
} else {
w0("z.unknown()");
}
w0(")");
return;
}
w0("z.object({");
for (const [name, subSchema] of Object.entries(schema.properties || {})) {
w0(`${JSON.stringify(snakeToCamel(name))}: `);
schemaToZod(subSchema, io);
if (!schema.required?.includes(name)) {
w0(`.optional()`);
}
w(",");
}
w0("})");
},
oneOf(schema, io) {
if (!schema.oneOf) return;
const { w } = io;
if (schema.oneOf.length === 1) {
schemaToZod(schema.oneOf[0], io);
return;
}
/**
* When dropshot serializes an enum sometimes it breaks it down into a `oneOf` with
* single element enums such that each individual enum can contain its own description. For zod
* this translates into a union of single element enums which is unnecessarily complex. We just
* flatten it down to a single enum here.
*
* @see https://github.com/oxidecomputer/oxide.ts/issues/178 for more details
*/
if (schema.oneOf.every((s) => s && "enum" in s && s.enum?.length === 1)) {
const enums = schema.oneOf.map(
(s) => (s as OpenAPIV3.SchemaObject).enum![0]
);
w(`z.enum([${enums.map((e) => JSON.stringify(e)).join(", ")}])`);
return;
}
w("z.union([");
for (const s of schema.oneOf) {
schemaToZod(s, io);
w(",");
}
w("])");
},
allOf(schema, io) {
if (!schema.allOf) return;
const { w, w0 } = io;
if (schema.allOf.length === 0) {
throw new Error(
`Unexpected "allOf" should have at least one schema: ${schema}`
);
}
if (schema.allOf.length === 1) {
schemaToZod(schema.allOf[0], io);
} else {
w("z.intersection([");
for (const s of schema.allOf) {
schemaToZod(s, io);
w(",");
}
w("])");
}
if ("default" in schema) {
w0(`.default(${JSON.stringify(schema.default)})`);
}
},
empty({ w0 }) {
w0("z.record(z.unknown())");
},
default(schema) {
throw Error(`UNHANDLED SCHEMA: ${JSON.stringify(schema, null, 2)}`);
},
});
function schemaToZodInt(schema: OpenAPIV3.SchemaObject, { w0 }: IO) {
if ("enum" in schema) {
/** See comment in {@link setupZod} */
w0(`IntEnum(${JSON.stringify(schema.enum)} as const)`);
} else {
w0(`z.number()`);
}
if (schema.default) {
w0(`.default(${schema.default})`);
}
const [, unsigned, size] = schema.format?.match(/(u?)int(\d+)/) || [];
if ("minimum" in schema) {
w0(`.min(${schema.minimum})`);
} else if (unsigned) {
w0(`.min(0)`);
} else if (size && parseInt(size) < 64) {
w0(`.min(-${Math.pow(2, parseInt(size) - 1) - 1})`);
}
if ("maximum" in schema) {
w0(`.max(${schema.maximum})`);
} else if (size && unsigned && parseInt(size) < 64) {
w0(`.max(${Math.pow(2, parseInt(size)) - 1})`);
} else if (size && parseInt(size) < 64) {
// It's signed so remove the most significant bit
w0(`.max(${Math.pow(2, parseInt(size) - 1) - 1})`);
}
}