StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
854 stars 67 forks source link

Incorrect $ref for self-referencing types #99

Closed LaserUnicorns closed 8 months ago

LaserUnicorns commented 9 months ago

Given a self-referencing type:

const Test = z.lazy(() =>
  z.object({
    id: z.string(),
    test: z.optional(Test),
  }),
)

When using zodToJsonSchema, the produced JSON schema is as follows:

{
  "type": "object",
  "properties": {
    "id": {
      "type": "string"
    },
    "test": {
      "$ref": "#/" // <- this one
    }
  },
  "required": [
    "id"
  ],
  "additionalProperties": false,
  "$schema": "http://json-schema.org/draft-07/schema#"
}

The issue arises with the "$ref" property under "test," which currently contains #/. According to RFC6901, this points to an empty string property:

{
  "": "this"
}

To adhere to the RFC, the $ref property should simply contain #, pointing to the entire document.

StefanTerdell commented 8 months ago

Fair. Fix published in 3.22.3