1 import { z, ZodError } from "@medusajs/deps/zod"
2 import { isObject, MedusaError } from "@medusajs/utils"
3
4 /**
5 * Zod v4 does not export public issue types, so we use internal types from z.core.
6 * These are prefixed with $ to indicate they are internal.
7 * While internal, they are stable for type-checking purposes.
8 * Runtime behavior relies on the `code` property and duck-typing, not these types.
9 *
10 * IMPORTANT: All runtime code uses duck-typing guards to gracefully handle
11 * potential changes in Zod's internal structure across versions.
12 */
13 type ZodIssue = z.core.$ZodIssue
14 type ZodIssueInvalidValue = z.core.$ZodIssueInvalidValue
15
16 /**
17 * Duck-typed issue types for runtime guards.
18 * These match the expected shape without relying on Zod's internal types.
19 */
20 type InvalidTypeIssue = {
21 code: "invalid_type"
22 expected: string
23 path: PropertyKey[]
24 }
25
26 type InvalidUnionIssue = {
27 code: "invalid_union"
28 errors: unknown[]
29 path: PropertyKey[]
30 message: string
31 }
32
33 /**
34 * Runtime guard for invalid_type issues.
35 * Uses duck-typing to avoid relying on internal Zod types at runtime.
36 */
37 function isInvalidTypeIssue(issue: unknown): issue is InvalidTypeIssue {
38 return (
39 isObject(issue) &&
40 "code" in issue &&
41 issue.code === "invalid_type" &&
42 "expected" in issue &&
43 "path" in issue &&
44 Array.isArray(issue.path)
45 )
46 }
47
48 /**
49 * Runtime guard for invalid_union issues.
50 * Uses duck-typing to avoid relying on internal Zod types at runtime.
51 */
52 function isInvalidUnionIssue(issue: unknown): issue is InvalidUnionIssue {
53 return (
54 isObject(issue) &&
55 "code" in issue &&
56 issue.code === "invalid_union" &&
57 "errors" in issue &&
58 Array.isArray(issue.errors)
59 )
60 }
61
62 /**
63 * Runtime guard for invalid_value issues (enums, literals).
64 * Uses duck-typing to avoid relying on internal Zod types at runtime.
65 */
66 function isInvalidValueIssue(issue: unknown): issue is {
67 code: "invalid_value"
68 values?: unknown[]
69 path: PropertyKey[]
70 message: string
71 } {
72 return (
73 isObject(issue) &&
74 "code" in issue &&
75 issue.code === "invalid_value" &&
76 "path" in issue &&
77 Array.isArray(issue.path)
78 )
79 }
80
81 function getReceivedValue(issue: ZodIssueInvalidValue, body: unknown): unknown {
82 if ("input" in issue) {
83 return issue.input
84 } else if ("received" in issue) {
85 return issue.received
86 } else {
87 return getValueFromBody(issue, body)
88 }
89 }
90
91 const formatPath = (issue: { path: PropertyKey[] }) => {
92 return issue.path.join(", ")
93 }
94
95 /**
96 * Gets the actual value from body using issue path.
97 * Used to distinguish between missing fields and wrong type values.
98 * Safely traverses the body object using the issue path.
99 */
100 function getValueFromBody(
101 issue: { path: PropertyKey[] },
102 body: unknown
103 ): unknown {
104 if (!isObject(body)) {
105 return undefined
106 }
107 return issue.path.reduce<unknown>((acc, curr: PropertyKey) => {
108 if (!isObject(acc)) {
109 return undefined
110 }
111 return (acc as Record<PropertyKey, unknown>)[curr]
112 }, body)
113 }
114
115 const formatInvalidType = (issues: ZodIssue[], body?: unknown) => {
116 const validIssues: InvalidTypeIssue[] = []
117 for (const issue of issues) {
118 if (isInvalidTypeIssue(issue)) {
119 validIssues.push(issue)
120 }
121 }
122
123 const expected = validIssues
124 .map((i) => {
125 // In Zod v4, check if value exists in body to distinguish wrong type vs missing
126 const receivedValue =
127 body !== undefined ? getValueFromBody(i, body) : undefined
128 if (receivedValue !== undefined) {
129 return i.expected
130 }
131 return
132 })
133 .filter(Boolean)
134
135 if (!expected.length) {
136 return
137 }
138
139 const firstIssue = validIssues[0]
140 if (!firstIssue) {
141 return
142 }
143
144 const received =
145 body !== undefined ? getValueFromBody(firstIssue, body) : "unknown"
146
147 return `Expected type: '${expected.join(", ")}' for field '${formatPath(
148 firstIssue
149 )}', got: '${received}'`
150 }
151
152 const formatRequiredField = (issues: ZodIssue[], body?: unknown) => {
153 // Find the first issue that indicates a required field (value is undefined in body)
154 const requiredIssue = issues
155 .filter((i) => i != null)
156 .find((i) => {
157 if (isInvalidTypeIssue(i)) {
158 // In Zod v4, check if value is undefined in body to detect missing fields
159 const valueInBody =
160 body !== undefined ? getValueFromBody(i, body) : undefined
161 return valueInBody === undefined
162 }
163 // Also check invalid_value issues - if value is undefined in body
164 if (isInvalidValueIssue(i)) {
165 const valueInBody =
166 body !== undefined ? getValueFromBody(i, body) : undefined
167 return valueInBody === undefined
168 }
169 return false
170 })
171
172 if (!requiredIssue) {
173 return
174 }
175
176 return `Field '${formatPath(requiredIssue)}' is required`
177 }
178
179 const formatUnionError = (
180 issue: unknown,
181 body?: unknown
182 ): string | undefined => {
183 // Use runtime guard to validate the issue structure
184 if (!isInvalidUnionIssue(issue)) {
185 return isObject(issue) && "message" in issue
186 ? String(issue.message)
187 : undefined
188 }
189
190 const parentPath = issue.path ?? []
191 const issues = issue.errors
192 .flatMap((e: unknown) => {
193 // In Zod v4, errors is an array of arrays (each inner array contains issues for a union variant)
194 if (Array.isArray(e)) {
195 return e
196 }
197 // Fallback for object with issues property (for compatibility)
198 if (isObject(e) && "issues" in e) {
199 return (e as { issues: unknown[] }).issues
200 }
201 return []
202 })
203 .filter((i): i is ZodIssue => isObject(i) && "path" in i)
204 .map((i) => ({
205 ...i,
206 path: [...parentPath, ...i.path],
207 }))
208
209 if (!issues.length) {
210 return issue.message
211 }
212
213 return (
214 formatInvalidType(issues, body) ||
215 formatRequiredField(issues, body) ||
216 issue.message
217 )
218 }
219
220 const formatError = (err: ZodError, body: unknown) => {
221 const issueMessages = err.issues.slice(0, 3).map((issue) => {
222 switch (issue.code) {
223 case "invalid_type":
224 return (
225 formatInvalidType([issue], body) ||
226 formatRequiredField([issue], body) ||
227 issue.message
228 )
229 case "invalid_value": {
230 const invalidValueIssue = issue as ZodIssueInvalidValue
231 const receivedValue = getReceivedValue(issue, body)
232
233 const hasReceivedValue = receivedValue !== undefined
234
235 if (invalidValueIssue.values) {
236 if (!hasReceivedValue) {
237 return `Field '${formatPath(issue)}' is required`
238 }
239
240 return `Expected: '${invalidValueIssue.values.join(
241 ", "
242 )}' for field '${formatPath(issue)}', but got: '${receivedValue}'`
243 }
244
245 if (!hasReceivedValue) {
246 return `Field '${formatPath(issue)}' is required`
247 }
248 return issue.message
249 }
250 case "invalid_union":
251 return formatUnionError(issue, body)
252 case "unrecognized_keys":
253 return `Unrecognized fields: '${issue.keys.join(", ")}'`
254 case "too_small":
255 return `Value for field '${formatPath(
256 issue
257 )}' too small, expected at least: '${issue.minimum}'`
258 case "too_big":
259 return `Value for field '${formatPath(
260 issue
261 )}' too big, expected at most: '${issue.maximum}'`
262 case "not_multiple_of":
263 return `Value for field '${formatPath(issue)}' not multiple of: '${
264 issue.divisor
265 }'`
266 case "invalid_format":
267 case "invalid_key":
268 case "invalid_element":
269 case "custom":
270 default:
271 return issue.message
272 }
273 })
274
275 return issueMessages.join("; ")
276 }
277
278 function isZodError(err: unknown): err is ZodError {
279 return (
280 err instanceof ZodError ||
281 (isObject(err) && "issues" in err && Array.isArray(err.issues))
282 )
283 }
284
285 export async function zodValidator<T>(
286 zodSchema: z.ZodObject<any, any> | z.ZodType<any, any, any>,
287 body: T
288 ): Promise<z.output<z.ZodObject<any, any> | z.ZodType<any, any, any>>> {
289 let strictSchema = zodSchema
290 if ("strict" in zodSchema) {
291 strictSchema = zodSchema.strict()
292 }
293
294 try {
295 return await strictSchema.parseAsync(body)
296 } catch (err) {
297 if (isZodError(err)) {
298 throw new MedusaError(
299 MedusaError.Types.INVALID_DATA,
300 `Invalid request: ${formatError(err, body)}`
301 )
302 }
303
304 throw err
305 }
306 }