Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/zod/src/v4/core/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1903,6 +1903,8 @@ export const $ZodObjectJIT: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$
// requires cast because technically $ZodObject doesn't extend
$ZodObject.init(inst, def);

const visitedNodes = new Set();

const superParse = inst._zod.parse;
const _normalized = util.cached(() => normalizeDef(def));

Expand Down Expand Up @@ -1979,6 +1981,15 @@ export const $ZodObjectJIT: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$
return payload;
}

if (visitedNodes.has(input)) {
return {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this is the right thing to return or it should be return payload instead.

value: input,
issues: [],
};
}

visitedNodes.add(input);

if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
// always synchronous
if (!fastpass) fastpass = generateFastpass(def.shape);
Expand All @@ -1990,6 +2001,8 @@ export const $ZodObjectJIT: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$

return superParse(payload, ctx);
};

visitedNodes.clear();
}
);

Expand Down
40 changes: 40 additions & 0 deletions packages/zod/src/v4/core/tests/circular-object.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { test, expect } from "vitest";
import * as z from "zod/v4";

test("validates circular objects", () => {
const userSchema = z.object({
id: z.number(),
get posts() {
return z.array(postSchema);
},
});

const postSchema = z.object({
title: z.string(),
get author() {
return userSchema;
},
});

const user = {
id: 1,
posts: [
{
title: "First",
get author() {
return user;
},
},
],
};

expect(userSchema.parse(user)).toEqual({
id: 1,
posts: [
{
title: "First",
author: user,
},
],
});
});
Loading