@devries-cameron20 / composio Mirror · read-only / commits / f119f0571
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 08:30 UTC

feat(json-schema-to-zod): add a zod v4 builder at `/v4` (#4919)

## Summary Adds a `@composio/json-schema-to-zod/v4` entry that builds classic Zod v4 schemas with the same `jsonSchemaToZod` and `jsonSchemaToZodShape` API as the root entry, which keeps building Zod v3 schemas. Callers switch by changing only the import path. The parsers are now written once against a small backend interface, with one backend per Zod major. The JSON Schema semantics (dispatch order, root preservation through the whole-schema guard, permissive widening, linear pattern compilation) stay shared, so the two builders cannot drift. This PR also fixes a root behavior bug: issues raised inside a nested object carried the parent path twice. Stacked on https://github.com/ComposioHQ/composio/pull/4910. GitHub retargets it to `next` when that merges. Moving core and the providers to `/v4` is the follow-up in https://github.com/ComposioHQ/composio/issues/4911. Designated PR reviewer: [@jkomyno](mailto:alberto@composio.dev). ## Reviewer notes Read the commits in order: the v3 output fingerprint is pinned first (`75838b23`), then the standalone nested-path fix, then the backend refactors, then the `/v4` feature and publishing. The `*.snap` files are generated — verify them by rerunning `pnpm --filter @composio/json-schema-to-zod test`, not by reading the diff; they render collapsed as generated files. ## Changes - **Root fix, nested issue paths.** Issues from `patternProperties`, `additionalProperties`, unrecognized keys, and `oneOf` under a property used to report `['x', 'x', 'key']`; they now report `['x', 'key']`. A regression test pins the paths for both builders. - **Backend split.** `ZodBackend<S>` with `zod-v3` and `zod-v4` implementations; parsers no longer import Zod, enforced by an oxlint `no-restricted-imports` override. The v3 output is unchanged, proven by a fingerprint snapshot taken before the refactor. - **`/v4` builder.** Kind-preserving throughout: guarded roots stay `ZodObject`, `patternProperties` rewrites use a check instead of a `ZodPipe`, and defaults use `prefault` so nested defaults still parse. `uri`, `uuid`, and `integer` keep v3 and Ajv acceptance (no URL normalization, no RFC variant-bit check, no safe-integer bound). - **zod floor for `/v4`.** `/v4` throws at load time below zod `4.1.13`, the first release whose `zod/v4` shares its metadata registry through `globalThis`. Below that, descriptions and annotations vanish when the building and serializing copies differ. The package peer range stays `>=3.25.76 <5` for the root. The floor protects the building copy only; a consumer whose serializing copy is older still loses metadata, as the README states. - **Annotation forwarding (v4 only).** `format`, `contentEncoding`, `contentMediaType`, and `type: "integer"` go into `.meta()`, so `z.toJSONSchema()` and frameworks built on it render them. Descriptions keep the v3 composition. `withoutAnnotations: true` turns forwarding off. Nothing else is forwarded: `title` and `examples` already fold into the description, and a meta `default` would contradict LangChain's `io: "output"` requiredness. - **Publishing.** `exports["./v4"]`, a second tsdown entry, attw on both entrypoints. `dist/index.mjs` and the shared chunk import only `zod/v3`. ## Type of change - [x] Bug fix - [x] New feature - [x] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? The parameterized suites (`json-to-zod`, the Ajv-oracle semantic regressions, the property-based semantics, and the pattern suites) run against both builders. Two aliased Vitest projects add coverage on other zod installs: one on zod 4.1.13, the `/v4` floor, running everything; one on zod 3.25.76, running the v3 builder plus a test that `/v4` refuses to load. | Command | Result | |---|---| | `pnpm --filter @composio/json-schema-to-zod test` | 39 files, 2251 tests passed | | `pnpm --filter @composio/json-schema-to-zod typecheck` | passed | | `pnpm --filter @composio/json-schema-to-zod build` | passed, attw and publint clean | | `pnpm --filter @composio/core --filter @composio/json-schema-to-effect-schema test` | core 1843 passed, 2 expected fail; effect-schema 156 passed | | Vercel, LangChain, LlamaIndex, Claude Agent SDK, OpenAI provider tests | passed | | `pnpm --filter @composio/cli test` | passed; one analytics concurrency case is load-sensitive and passes alone | | `pnpm --filter @e2e-tests/node-json-schema-to-zod-v4 test:e2e` | 39 passed | | `pnpm --filter @e2e-tests/node-json-schema-to-zod-v3 test:e2e` | 36 passed | | `pnpm lint:packages` | passed, pre-existing warnings only | | `pnpm validate:changesets` | passed | `knip` lists the `zod-3-25` and `zod-floor` dev aliases as unused because only `vitest.config.ts` resolves them; its other entries for this package predate the PR. ## Checklist - [ ] I have read the Code of Conduct and this PR adheres to it - [ ] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the [third-party links policy](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md#third-party-links-in-docs) - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [x] I added a changeset if this change affects published packages ## Additional context Zod's native `z.fromJSONSchema` (4.3 and later) was considered and does not fit. It throws on `not`, `if`/`then`/`else`, and `dependentRequired`, compiles `pattern` with the host `RegExp`, and maps `integer`, `uuid`, and `uri` to the stricter or mutating checks this converter avoids.

Alberto Schiabel committed Oct 16, 2026 at 14:11 UTC f119f0571ca27fce8b014a1b287e3b71458755c1
69 files changed +11345 -756
.changeset/json-schema-to-zod-v4.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/json-schema-to-zod': minor
3 +---
4 +
5 +Add a `@composio/json-schema-to-zod/v4` entry that builds classic Zod v4 schemas with the same `jsonSchemaToZod` and `jsonSchemaToZodShape` functions as the root entry, which keeps building Zod v3 schemas. The v4 builder forwards `format`, `contentEncoding`, `contentMediaType`, and `type: "integer"` into the schema's metadata so `z.toJSONSchema()` and the frameworks built on it render them again; `withoutAnnotations: true` turns that off. `/v4` requires zod `>= 4.1.13`, the first release whose `zod/v4` shares its metadata registry across copies, and throws at load time below it.
6 +
7 +The root builder now reports an issue inside a nested object once, at its own path. Issues raised by `patternProperties`, `additionalProperties`, unrecognized keys, and `oneOf` under a property previously carried that property's name twice (`['x', 'x', 'key']`).
.gitattributes
+4
@@ -14,6 +14,10 @@ pnpm-lock.yaml linguist-generated=true
14 uv.lock linguist-generated=true
15 **/bun.lock linguist-generated=true
16
17 +# Vitest snapshots (written by the test runner; verify by rerunning the suite,
18 +# not by reading the diff)
19 +**/__snapshots__/*.snap linguist-generated=true
20 +
21 # Managed-block conformance fixtures are byte-exact inputs/outputs shared by
22 # the sh harness and the TS reconciler test; never normalize their line endings.
23 test/managed-block-fixtures/** -text
.oxlintrc.json
+36
@@ -457,6 +457,42 @@
457 ]
458 }
459 },
460 + {
461 + // The JSON Schema semantics of the Zod converter are written once over
462 + // an opaque schema type. Only the backends, the public type aliases, and
463 + // the two entry modules speak Zod.
464 + "files": [
465 + "ts/packages/json-schema-to-zod/src/parsers/**/*.ts",
466 + "ts/packages/json-schema-to-zod/src/utils/**/*.ts",
467 + "ts/packages/json-schema-to-zod/src/convert.ts",
468 + "ts/packages/json-schema-to-zod/src/context.ts",
469 + "ts/packages/json-schema-to-zod/src/annotations.ts",
470 + "ts/packages/json-schema-to-zod/src/whole-schema-validation.ts"
471 + ],
472 + "rules": {
473 + "no-restricted-imports": [
474 + "error",
475 + {
476 + "paths": [
477 + { "name": "crypto", "message": "Use Web Crypto API instead." },
478 + { "name": "node:crypto", "message": "Use Web Crypto API instead." },
479 + { "name": "buffer", "message": "Use Uint8Array instead." },
480 + { "name": "node:buffer", "message": "Use Uint8Array instead." },
481 + {
482 + "name": "zod",
483 + "message": "Shared converter code calls the backend on the parse context; only src/backend/** may import Zod."
484 + }
485 + ],
486 + "patterns": [
487 + {
488 + "group": ["zod/*"],
489 + "message": "Shared converter code calls the backend on the parse context; only src/backend/** may import Zod."
490 + }
491 + ]
492 + }
493 + ]
494 + }
495 + },
496 {
497 // Examples are console-driven references. Keep type-safety rules
498 // (no-explicit-any, unused-vars) but drop console noise. The Buffer/crypto
pnpm-lock.yaml
+23 -3
@@ -1456,6 +1456,12 @@ importers:
1456 specifier: ^2.8.6
1457 version: 2.8.6
1458 devDependencies:
1459 + '@ai-sdk/provider-utils':
1460 + specifier: ^5.0.58
1461 + version: 5.0.58(zod@4.5.4)
1462 + '@langchain/core':
1463 + specifier: ^1.2.17
1464 + version: 1.2.17(@opentelemetry/api@1.9.1)(openai@7.32.0(@aws-sdk/credential-provider-node@3.972.84)(@smithy/signature-v4@5.7.4)(undici@6.29.0)(ws@8.22.0)(zod@4.5.4))(ws@8.22.0)
1465 '@types/json-schema':
1466 specifier: ^7.0.15
1467 version: 7.0.15
@@ -1480,6 +1486,15 @@ importers:
1486 zod:
1487 specifier: ^4.5.4
1488 version: 4.5.4
1489 + zod-3-25:
1490 + specifier: npm:zod@3.25.76
1491 + version: zod@3.25.76
1492 + zod-floor:
1493 + specifier: npm:zod@4.1.13
1494 + version: zod@4.1.13
1495 + zod-to-json-schema:
1496 + specifier: 'catalog:'
1497 + version: 3.25.2(zod@4.5.4)
1498
1499 ts/packages/providers/anthropic:
1500 devDependencies:
@@ -6856,6 +6871,9 @@ packages:
6871 zod@3.25.76:
6872 resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
6873
6874 + zod@4.1.13:
6875 + resolution: {integrity: sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==}
6876 +
6877 zod@4.4.3:
6878 resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
6879
@@ -7003,7 +7021,7 @@ snapshots:
7021 '@standard-schema/spec': 1.1.0
7022 '@workflow/serde': 4.1.0
7023 eventsource-parser: 3.1.1
7006 - undici: 7.29.1
7024 + undici: 7.30.0
7025 zod: 3.25.76
7026
7027 '@ai-sdk/provider-utils@5.0.47(zod@4.5.4)':
@@ -7012,7 +7030,7 @@ snapshots:
7030 '@standard-schema/spec': 1.1.0
7031 '@workflow/serde': 4.1.0
7032 eventsource-parser: 3.1.1
7015 - undici: 7.29.1
7033 + undici: 7.30.0
7034 zod: 4.5.4
7035
7036 '@ai-sdk/provider-utils@5.0.58(zod@4.5.4)':
@@ -7021,7 +7039,7 @@ snapshots:
7039 '@standard-schema/spec': 1.1.0
7040 '@workflow/serde': 4.1.0
7041 eventsource-parser: 3.1.1
7024 - undici: 7.29.1
7042 + undici: 7.30.0
7043 zod: 4.5.4
7044
7045 '@ai-sdk/provider@1.1.3':
@@ -12299,6 +12317,8 @@ snapshots:
12317
12318 zod@3.25.76: {}
12319
12320 + zod@4.1.13: {}
12321 +
12322 zod@4.4.3: {}
12323
12324 zod@4.5.4: {}
ts/e2e-tests/runtimes/node/json-schema-to-zod-v3/README.md
+2 -2
@@ -1,10 +1,10 @@
1 # json-schema-to-zod + Zod v3 Compatibility Test
2
3 -Verifies that `@composio/json-schema-to-zod` works correctly with `zod@3.25.76`.
3 +Verifies that `@composio/json-schema-to-zod` works correctly for a consumer that depends on `zod@3.25.76` and `zod-to-json-schema`.
4
5 ## Why This Exists
6
7 -The `@composio/json-schema-to-zod` package must support both Zod v3 and v4. This suite ensures:
7 +The `@composio/json-schema-to-zod` package must support both Zod v3 and v4. The workspace link resolves the converter's own zod copy from the package, so this suite exercises the root entry's Zod v3 output against a consumer on the oldest supported release; coverage of the converter running on `zod@3.25.76` itself lives in the package's `zod-3.25` Vitest project. This suite ensures:
8
9 - JSON Schema to Zod conversion works with Zod v3
10 - All schema types (string, object, array, anyOf) convert correctly
ts/e2e-tests/runtimes/node/json-schema-to-zod-v4/README.md
+2
@@ -24,6 +24,7 @@ The `@composio/json-schema-to-zod` package must support both Zod v3 and v4. This
24 | additionalProperties | Strict, passthrough, and typed catchall modes |
25 | Complex nested arrays | Arrays of objects with nested arrays |
26 | Union with constraints | anyOf with minLength, minimum, and required fields |
27 +| `/v4` entry | Builds a Zod v4 schema and checks the zod floor it needs |
28
29 ## Test Setup
30
@@ -31,6 +32,7 @@ This test runs **directly in Bun** (no Docker fixtures). The test file imports `
32
33 ```typescript
34 import { jsonSchemaToZod, type JsonSchema } from '@composio/json-schema-to-zod';
35 +import { jsonSchemaToZod as jsonSchemaToZodV4 } from '@composio/json-schema-to-zod/v4';
36 ```
37
38 Tests use `bun:test` assertions to verify schema conversion and parsing behavior.
ts/e2e-tests/runtimes/node/json-schema-to-zod-v4/e2e.test.ts
+27
@@ -6,6 +6,7 @@
6 */
7
8 import { jsonSchemaToZod, type JsonSchema } from '@composio/json-schema-to-zod';
9 +import { jsonSchemaToZod as jsonSchemaToZodV4 } from '@composio/json-schema-to-zod/v4';
10 import { e2e } from '@e2e-tests/utils';
11 import { describe, it, expect } from 'bun:test';
12
@@ -111,6 +112,32 @@ e2e(import.meta.url, {
112 });
113 });
114
115 + describe('/v4 entry', () => {
116 + it('builds a zod v4 schema on a copy that meets the floor', () => {
117 + const schema: JsonSchema = {
118 + type: 'object',
119 + properties: {
120 + name: { type: 'string', description: 'Name' },
121 + count: { type: 'integer' },
122 + },
123 + required: ['name'],
124 + };
125 + const zodSchema = jsonSchemaToZodV4(schema);
126 + const { version } = (
127 + zodSchema as unknown as {
128 + _zod: { version: { major: number; minor: number; patch: number } };
129 + }
130 + )._zod;
131 +
132 + expect(version.major).toBe(4);
133 + expect(version.minor > 1 || (version.minor === 1 && version.patch >= 13)).toBe(true);
134 + expect(zodSchema.parse({ name: 'Ada', count: 2 })).toEqual({ name: 'Ada', count: 2 });
135 + expect(() => zodSchema.parse({ count: 2 })).toThrow();
136 + expect(() => zodSchema.parse({ name: 'Ada', count: 2.5 })).toThrow();
137 + expect(zodSchema.description).toBeUndefined();
138 + });
139 + });
140 +
141 describe('Parsing behavior', () => {
142 it('converts basic schemas and verifies parsing behavior', () => {
143 const schema: JsonSchema = {
ts/packages/json-schema-to-zod/README.md
+31 -3
@@ -11,7 +11,7 @@ npm install @composio/json-schema-to-zod
11 ### Simple example
12
13 ```typescript
14 -import { jsonSchemaToZod } from 'json-schema-to-zod';
14 +import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
15
16 const jsonSchema = {
17 type: 'object',
@@ -22,12 +22,40 @@ const jsonSchema = {
22 },
23 };
24
25 -const zodSchema = jsonSchemaToZod(myObject);
25 +const zodSchema = jsonSchemaToZod(jsonSchema);
26 ```
27
28 +The root entry builds Zod v3 schemas (`zod/v3`), which every supported zod release ships.
29 +
30 +### Object-level keywords and `jsonSchemaToZodShape`
31 +
32 +`jsonSchemaToZodShape` converts each entry of `properties` on its own, so assertions that apply to the object as a whole have no place in the shape and are not enforced: `minProperties`, `maxProperties`, `propertyNames`, `uniqueItems`, or a `required` key with no declared property. Keywords on a property (`{ uniqueItems: true, type: 'array' }` as a property schema) are still enforced. When the object-level assertions must hold, use `jsonSchemaToZod`, or check them yourself on the `z.object(shape)` you build.
33 +
34 +### Zod v4 schemas
35 +
36 +The `/v4` entry builds classic Zod v4 schemas (`zod/v4`) with the same function names, so a caller switches by changing the import path:
37 +
38 +```typescript
39 +import { jsonSchemaToZod, jsonSchemaToZodShape } from '@composio/json-schema-to-zod/v4';
40 +
41 +const zodSchema = jsonSchemaToZod(jsonSchema);
42 +const shape = jsonSchemaToZodShape(jsonSchema);
43 +```
44 +
45 +Both builders accept and reject the same values. Beyond that, the v4 builder forwards the JSON Schema annotations a serializer cannot derive from the schema's checks, so `z.toJSONSchema()` and the frameworks built on it see them again:
46 +
47 +- `format`, verbatim, including values such as `binary`, `int64`, and `time`;
48 +- `contentEncoding` and `contentMediaType`, verbatim;
49 +- `type: "integer"`, since the integer check is a refinement that accepts every integral number, as the root builder and JSON Schema do;
50 +- the description, title, and examples text the root builder also writes.
51 +
52 +Pass `{ withoutAnnotations: true }` to leave the annotations out; `{ withoutDescribes: true }` leaves out the description, as it does for the root entry.
53 +
54 +`/v4` requires zod `>= 4.1.13`: importing it under an older release throws at load time. 4.1.13 is the first release whose `zod/v4` shares its metadata registry across copies through `globalThis`. That check covers only the zod copy that builds the schema. If the code that serializes the schema loads its own copy of zod below 4.1.13 (a framework that depends on zod directly rather than as a peer), that copy reads a separate registry and the descriptions and annotations are lost. Keep every zod copy in the process at 4.1.13 or later.
55 +
56 ### Overriding a parser
57
30 -You can pass a function to the `overrideParser` option, which represents a function that receives the current schema node and the reference object, and should return a zod object when it wants to replace a default output. If the default output should be used for the node just return undefined.
58 +You can pass a function to the `parserOverride` option, which represents a function that receives the current schema node and the reference object, and should return a zod object when it wants to replace a default output. If the default output should be used for the node just return undefined.
59
60 ## Acknowledgements
61
ts/packages/json-schema-to-zod/package.json
+10 -1
@@ -25,6 +25,10 @@
25 ".": {
26 "types": "./dist/index.d.mts",
27 "default": "./dist/index.mjs"
28 + },
29 + "./v4": {
30 + "types": "./dist/v4.d.mts",
31 + "default": "./dist/v4.mjs"
32 }
33 },
34 "files": [
@@ -46,6 +50,8 @@
50 ],
51 "license": "ISC",
52 "devDependencies": {
53 + "@ai-sdk/provider-utils": "^5.0.58",
54 + "@langchain/core": "^1.2.17",
55 "@types/json-schema": "^7.0.15",
56 "@types/node": "^26.6.4",
57 "ajv": "^8.20.0",
@@ -53,7 +59,10 @@
59 "tsdown": "catalog:",
60 "typescript": "catalog:",
61 "vitest": "catalog:",
56 - "zod": "^4.5.4"
62 + "zod": "^4.5.4",
63 + "zod-3-25": "npm:zod@3.25.76",
64 + "zod-floor": "npm:zod@4.1.13",
65 + "zod-to-json-schema": "catalog:"
66 },
67 "peerDependencies": {
68 "zod": ">=3.25.76 <5"
ts/packages/json-schema-to-zod/src/annotations.ts new
+80
@@ -0,0 +1,80 @@
1 +import { ASSERTED_STRING_FORMATS, type StringFormat } from './backend/types';
2 +import type { JsonSchemaObject, Serializable } from './types';
3 +import { its } from './utils/its';
4 +
5 +const ASSERTED_FORMAT_SET: ReadonlySet<StringFormat> = new Set<StringFormat>(
6 + ASSERTED_STRING_FORMATS
7 +);
8 +
9 +export const isAssertedStringFormat = (format: unknown): format is StringFormat =>
10 + typeof format === 'string' && ASSERTED_FORMAT_SET.has(format as StringFormat);
11 +
12 +/**
13 + * The description text a node carries: its `description`, else its `title`,
14 + * followed by the `example` or `examples` it declares. `undefined` when there
15 + * is nothing to say.
16 + */
17 +export const describeText = (jsonSchema: JsonSchemaObject): string | undefined => {
18 + let description = '';
19 +
20 + if (jsonSchema.description) {
21 + description = jsonSchema.description;
22 + } else if (jsonSchema.title) {
23 + description = jsonSchema.title;
24 + }
25 +
26 + if (jsonSchema.example !== undefined) {
27 + const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
28 + description = description ? `${description}\n${exampleText}` : exampleText;
29 + } else if (jsonSchema.examples !== undefined && Array.isArray(jsonSchema.examples)) {
30 + const examples = jsonSchema.examples;
31 + if (examples.length > 0) {
32 + const exampleText =
33 + examples.length === 1
34 + ? `Example: ${JSON.stringify(examples[0])}`
35 + : `Examples:\n${examples.map((ex: unknown) => ` ${JSON.stringify(ex)}`).join('\n')}`;
36 + description = description ? `${description}\n${exampleText}` : exampleText;
37 + }
38 + }
39 +
40 + return description || undefined;
41 +};
42 +
43 +/** Whether the number parser applies its integer check to this node. */
44 +const isIntegerNumber = (jsonSchema: JsonSchemaObject): boolean =>
45 + its.a.primitive(jsonSchema, 'integer') ||
46 + (its.a.primitive(jsonSchema, 'number') &&
47 + (jsonSchema.format === 'int64' || jsonSchema.multipleOf === 1));
48 +
49 +/**
50 + * The JSON Schema annotations a node carries beyond what its checks imply:
51 + * `format`, `contentEncoding`, and `contentMediaType` verbatim, and
52 + * `type: "integer"` wherever the integer check applies, since that check is
53 + * a refinement a serializer cannot see. Everything else the serializer
54 + * derives from the checks themselves, or is deliberately left out.
55 + */
56 +export const collectAnnotations = (
57 + jsonSchema: JsonSchemaObject
58 +): Readonly<Record<string, Serializable>> | undefined => {
59 + // Draft 7 ignores the keywords next to `$ref`, so none of them describe the value.
60 + if ('$ref' in jsonSchema) {
61 + return undefined;
62 + }
63 +
64 + const annotations: Record<string, Serializable> = {};
65 +
66 + if (typeof jsonSchema.format === 'string') {
67 + annotations.format = jsonSchema.format;
68 + }
69 + if (typeof jsonSchema.contentEncoding === 'string') {
70 + annotations.contentEncoding = jsonSchema.contentEncoding;
71 + }
72 + if (typeof jsonSchema.contentMediaType === 'string') {
73 + annotations.contentMediaType = jsonSchema.contentMediaType;
74 + }
75 + if (isIntegerNumber(jsonSchema)) {
76 + annotations.type = 'integer';
77 + }
78 +
79 + return Object.keys(annotations).length > 0 ? annotations : undefined;
80 +};
ts/packages/json-schema-to-zod/src/backend/shared.ts new
+52
@@ -0,0 +1,52 @@
1 +import type { ObjectPolicy, RunFailure, RunResult, WholeSchemaGuard } from './types';
2 +
3 +/** An object schema the object policies can be applied to. */
4 +type PolicyBase<S> = S & {
5 + strict(): S;
6 + passthrough(): S;
7 + catchall(schema: S): S;
8 +};
9 +
10 +/** Anything with the zod parse surface the shared runner needs. */
11 +type SafeParseLike = {
12 + safeParse(
13 + value: unknown
14 + ):
15 + | { success: true; data: unknown }
16 + | { success: false; error: { issues: ReadonlyArray<unknown> } };
17 +};
18 +
19 +/** Spreads an optional relative issue path into an issue body. */
20 +export const withPath = (path: ReadonlyArray<string | number> | undefined) =>
21 + path === undefined ? {} : { path: [...path] };
22 +
23 +/** Runs `guard` first and falls back to the guard already on the schema. */
24 +export const composeGuards = (
25 + guard: WholeSchemaGuard,
26 + inner: WholeSchemaGuard | undefined
27 +): WholeSchemaGuard => (inner ? value => guard(value) ?? inner(value) : guard);
28 +
29 +/** Runs the schema; the failure carries the backend's own error with its issues. */
30 +export const run = (schema: SafeParseLike, value: unknown): RunResult => {
31 + const result = schema.safeParse(value);
32 + const { success } = result;
33 + return success
34 + ? { success, data: result.data }
35 + : { success, failure: result.error as RunFailure };
36 +};
37 +
38 +/** Applies one of the object policies the parsers use to a built object schema. */
39 +export const applyObjectPolicy = <S>(base: PolicyBase<S>, policy: ObjectPolicy<S>): S => {
40 + switch (policy.kind) {
41 + case 'strict':
42 + return base.strict();
43 + case 'loose':
44 + return base.passthrough();
45 + case 'catchall':
46 + return base.catchall(policy.schema);
47 + }
48 +};
49 +
50 +/** Attaches the rest schema to a tuple when the schema declares one. */
51 +export const buildTuple = <S>(tuple: S & { rest(schema: S): S }, rest: S | undefined): S =>
52 + rest === undefined ? tuple : tuple.rest(rest);
ts/packages/json-schema-to-zod/src/backend/types.ts new
+121
@@ -0,0 +1,121 @@
1 +import type { Serializable } from '../types';
2 +
3 +/** String formats the string parser asserts; every other `format` is an annotation. */
4 +export const ASSERTED_STRING_FORMATS = [
5 + 'email',
6 + 'ip',
7 + 'ipv4',
8 + 'ipv6',
9 + 'uri',
10 + 'uuid',
11 + 'date-time',
12 + 'time',
13 + 'date',
14 + 'duration',
15 +] as const;
16 +
17 +export type StringFormat = (typeof ASSERTED_STRING_FORMATS)[number];
18 +
19 +export type NumberBound = 'gt' | 'gte' | 'lt' | 'lte';
20 +
21 +export type ObjectPolicy<S> =
22 + | { readonly kind: 'strict' }
23 + | { readonly kind: 'loose' }
24 + | { readonly kind: 'catchall'; readonly schema: S };
25 +
26 +/** A failed run: the backend's own error object, which always carries `issues`. */
27 +export type RunFailure = { readonly issues: ReadonlyArray<unknown> };
28 +
29 +export type RunResult =
30 + | { readonly success: true; readonly data: unknown }
31 + | { readonly success: false; readonly failure: RunFailure };
32 +
33 +/** Returns the failure message, or `undefined` when the value satisfies the schema. */
34 +export type WholeSchemaGuard = (value: unknown) => string | undefined;
35 +
36 +/** An issue path relative to the refined schema. */
37 +export type RelativePath = ReadonlyArray<string | number>;
38 +
39 +/**
40 + * Issues reported from inside a refinement. Paths are relative to the refined
41 + * schema; an omitted path means the schema's own location.
42 + */
43 +export interface IssueSink {
44 + custom(
45 + message: string,
46 + options?: { readonly path?: RelativePath; readonly params?: Record<string, unknown> }
47 + ): void;
48 + unrecognizedKeys(
49 + keys: readonly string[],
50 + message: string,
51 + options?: { readonly path?: RelativePath }
52 + ): void;
53 + invalidUnion(
54 + message: string,
55 + failures: readonly RunFailure[],
56 + options?: { readonly path?: RelativePath }
57 + ): void;
58 + /** Re-emits every issue of a failed `run()`, keeping their relative paths. */
59 + forward(failure: RunFailure): void;
60 +}
61 +
62 +export interface Decorations {
63 + readonly description?: string;
64 + /** JSON Schema annotations to carry on the schema; ignored by backends that cannot. */
65 + readonly annotations?: Readonly<Record<string, Serializable>>;
66 +}
67 +
68 +/**
69 + * The Zod vocabulary one builder speaks. The JSON Schema semantics live in
70 + * the shared parsers, which only ever call these operations on the opaque
71 + * schema type `S`.
72 + */
73 +export interface ZodBackend<S> {
74 + /** Whether a `parserOverride` result is a schema of this backend. */
75 + isSchema(value: unknown): value is S;
76 + isNever(schema: S): boolean;
77 +
78 + any(): S;
79 + never(): S;
80 + boolean(): S;
81 + null(): S;
82 + string(): S;
83 + number(): S;
84 + literal(value: string | number | boolean | null): S;
85 + enum(values: readonly [string, ...string[]]): S;
86 + /** A schema accepting whatever `test` admits. It must stay JSON-Schema-serializable. */
87 + predicate(test: (value: unknown) => boolean): S;
88 +
89 + stringFormat(schema: S, format: StringFormat, message?: string): S;
90 + base64(schema: S, message?: string): S;
91 + regex(schema: S, pattern: RegExp, message?: string): S;
92 +
93 + integer(schema: S, message?: string): S;
94 + bound(schema: S, kind: NumberBound, value: number, message?: string): S;
95 +
96 + array(item: S): S;
97 + minItems(schema: S, count: number, message?: string): S;
98 + maxItems(schema: S, count: number, message?: string): S;
99 + tuple(items: readonly S[], rest: S | undefined): S;
100 +
101 + object(shape: Readonly<Record<string, S>>, policy: ObjectPolicy<S>): S;
102 + record(value: S): S;
103 +
104 + union(options: readonly [S, S, ...S[]]): S;
105 + intersection(left: S, right: S): S;
106 +
107 + optional(schema: S): S;
108 + nullable(schema: S): S;
109 + withDefault(schema: S, value: unknown): S;
110 + readonly(schema: S): S;
111 + decorate(schema: S, decorations: Decorations): S;
112 +
113 + refine<T>(schema: S, test: (value: T) => boolean, message?: string): S;
114 + superRefine<T>(schema: S, check: (value: T, issues: IssueSink) => void): S;
115 + /** Replaces the parsed value; the backend keeps the schema's kind where it can. */
116 + rewrite<T>(schema: S, fn: (value: T, issues: IssueSink) => unknown): S;
117 +
118 + run(schema: S, value: unknown): RunResult;
119 + /** Checks the source value before the schema parses it. Composes with an existing guard: own first, then inner. */
120 + attachGuard(schema: S, guard: WholeSchemaGuard): S;
121 +}
ts/packages/json-schema-to-zod/src/backend/zod-v3.ts new
+165
@@ -0,0 +1,165 @@
1 +import * as z from 'zod/v3';
2 +
3 +import type { Decorations, IssueSink, StringFormat, WholeSchemaGuard, ZodBackend } from './types';
4 +import { applyObjectPolicy, buildTuple, composeGuards, run, withPath } from './shared';
5 +
6 +type S = z.ZodTypeAny;
7 +
8 +type GuardedDef = z.ZodTypeDef & { wholeSchemaGuard?: WholeSchemaGuard };
9 +type ZodSchemaClass = {
10 + new (def: z.ZodTypeDef): z.ZodTypeAny;
11 + prototype: z.ZodTypeAny;
12 +};
13 +
14 +const guardedSchemaClasses = new WeakMap<ZodSchemaClass, ZodSchemaClass>();
15 +
16 +/**
17 + * A subclass of the parsed schema's own class that checks the source value
18 + * against the guard before parsing it. Keeping the class, rather than wrapping
19 + * it in a pipeline, keeps the schema's kind: a guarded object is still a
20 + * `ZodObject` with a `shape`, which is what zod-to-json-schema and the MCP SDK
21 + * need to emit a root `type: "object"` for LLM tool parameters. The guard lives
22 + * on `_def`, so copies such as `.describe()` keep it.
23 + */
24 +const guardedSchemaClass = (Base: ZodSchemaClass): ZodSchemaClass => {
25 + const cached = guardedSchemaClasses.get(Base);
26 + if (cached) {
27 + return cached;
28 + }
29 +
30 + const parseAsBase = Base.prototype._parse;
31 + class Guarded extends Base {
32 + override _parse(input: z.ParseInput): z.ParseReturnType<unknown> {
33 + const failure = (this._def as GuardedDef).wholeSchemaGuard?.(input.data);
34 + if (failure === undefined) {
35 + return parseAsBase.call(this, input);
36 + }
37 + z.addIssueToContext(this._getOrReturnCtx(input), {
38 + code: z.ZodIssueCode.custom,
39 + message: failure,
40 + });
41 + return z.DIRTY(input.data);
42 + }
43 + }
44 + guardedSchemaClasses.set(Base, Guarded);
45 + // Guarding an already guarded schema reuses its class and composes guards.
46 + guardedSchemaClasses.set(Guarded, Guarded);
47 + return Guarded;
48 +};
49 +
50 +const attachGuard = (schema: S, guard: WholeSchemaGuard): S => {
51 + // Validate the source value before defaults and other Zod transforms run.
52 + // Otherwise a missing required field can be synthesized and incorrectly
53 + // appear valid to the JSON Schema interpreter.
54 + const wholeSchemaGuard = composeGuards(guard, (schema._def as GuardedDef).wholeSchemaGuard);
55 +
56 + const Guarded = guardedSchemaClass(schema.constructor as ZodSchemaClass);
57 + return new Guarded({ ...schema._def, wholeSchemaGuard } as GuardedDef);
58 +};
59 +
60 +/** Issues raised through the refinement context; Zod prefixes the context path itself. */
61 +const sink = (ctx: z.RefinementCtx): IssueSink => ({
62 + custom(message, options) {
63 + ctx.addIssue({
64 + ...withPath(options?.path),
65 + code: z.ZodIssueCode.custom,
66 + message,
67 + ...(options?.params === undefined ? {} : { params: options.params }),
68 + });
69 + },
70 + unrecognizedKeys(keys, message, options) {
71 + ctx.addIssue({
72 + ...withPath(options?.path),
73 + code: z.ZodIssueCode.unrecognized_keys,
74 + keys: [...keys],
75 + message,
76 + });
77 + },
78 + invalidUnion(message, failures, options) {
79 + ctx.addIssue({
80 + ...withPath(options?.path),
81 + code: z.ZodIssueCode.invalid_union,
82 + unionErrors: failures as z.ZodError[],
83 + message,
84 + });
85 + },
86 + forward(failure) {
87 + for (const issue of failure.issues) {
88 + ctx.addIssue(issue as z.ZodIssue);
89 + }
90 + },
91 +});
92 +
93 +const stringFormat = (schema: S, format: StringFormat, message?: string): S => {
94 + const string = schema as z.ZodString;
95 + switch (format) {
96 + case 'email':
97 + return string.email(message);
98 + case 'ip':
99 + return string.ip(message);
100 + case 'ipv4':
101 + return string.ip({ version: 'v4', message });
102 + case 'ipv6':
103 + return string.ip({ version: 'v6', message });
104 + case 'uri':
105 + return string.url(message);
106 + case 'uuid':
107 + return string.uuid(message);
108 + case 'date-time':
109 + return string.datetime({ offset: true, message });
110 + case 'time':
111 + return string.time(message);
112 + case 'date':
113 + return string.date(message);
114 + case 'duration':
115 + return string.duration(message);
116 + }
117 +};
118 +
119 +/** Zod v3 output: descriptions on `_def`, refinements as `ZodEffects`, the guard as a subclass. */
120 +export const zodV3Backend: ZodBackend<S> = {
121 + isSchema: (value): value is S => value instanceof z.ZodType,
122 + isNever: schema => schema instanceof z.ZodNever,
123 +
124 + any: () => z.any(),
125 + never: () => z.never(),
126 + boolean: () => z.boolean(),
127 + null: () => z.null(),
128 + string: () => z.string(),
129 + number: () => z.number(),
130 + literal: value => z.literal(value),
131 + enum: values => z.enum(values as [string, ...string[]]),
132 + predicate: test => z.custom(test),
133 +
134 + stringFormat,
135 + base64: (schema, message) => (schema as z.ZodString).base64(message),
136 + regex: (schema, pattern, message) => (schema as z.ZodString).regex(pattern, message),
137 +
138 + integer: (schema, message) => (schema as z.ZodNumber).int(message),
139 + bound: (schema, kind, value, message) => (schema as z.ZodNumber)[kind](value, message),
140 +
141 + array: item => z.array(item),
142 + minItems: (schema, count, message) => (schema as z.ZodArray<S>).min(count, message),
143 + maxItems: (schema, count, message) => (schema as z.ZodArray<S>).max(count, message),
144 + tuple: (items, rest) => buildTuple<S>(z.tuple(items as unknown as [S]), rest),
145 +
146 + object: (shape, policy) => applyObjectPolicy<S>(z.object(shape), policy),
147 + record: value => z.record(value),
148 +
149 + union: options => z.union(options as unknown as [S, S]),
150 + intersection: (left, right) => z.intersection(left, right),
151 +
152 + optional: schema => schema.optional(),
153 + nullable: schema => schema.nullable(),
154 + withDefault: (schema, value) => schema.default(value),
155 + readonly: schema => schema.readonly(),
156 + decorate: (schema, decorations: Decorations) =>
157 + decorations.description === undefined ? schema : schema.describe(decorations.description),
158 +
159 + refine: (schema, test, message) => schema.refine(test, { message }),
160 + superRefine: (schema, check) => schema.superRefine((value, ctx) => check(value, sink(ctx))),
161 + rewrite: (schema, fn) => schema.transform((value, ctx) => fn(value, sink(ctx))),
162 +
163 + run,
164 + attachGuard,
165 +};
ts/packages/json-schema-to-zod/src/backend/zod-v4-floor.ts new
+23
@@ -0,0 +1,23 @@
1 +type ZodVersion = {
2 + readonly major: number;
3 + readonly minor: number;
4 + readonly patch: number;
5 +};
6 +
7 +/**
8 + * The first zod release whose `zod/v4` shares its metadata registry through
9 + * `globalThis.__zod_globalRegistry`. Below it, two copies of zod in one
10 + * process keep separate registries, and the descriptions and annotations the
11 + * v4 builder writes are invisible to a serializer loaded from the other copy.
12 + */
13 +export const ZOD_V4_FLOOR: ZodVersion = { major: 4, minor: 1, patch: 13 };
14 +
15 +export const formatZodVersion = (version: ZodVersion): string =>
16 + `${version.major}.${version.minor}.${version.patch}`;
17 +
18 +export const meetsZodV4Floor = (version: ZodVersion): boolean =>
19 + version.major !== ZOD_V4_FLOOR.major
20 + ? version.major > ZOD_V4_FLOOR.major
21 + : version.minor !== ZOD_V4_FLOOR.minor
22 + ? version.minor > ZOD_V4_FLOOR.minor
23 + : version.patch >= ZOD_V4_FLOOR.patch;
ts/packages/json-schema-to-zod/src/backend/zod-v4.ts new
+305
@@ -0,0 +1,305 @@
1 +import * as z from 'zod/v4';
2 +
3 +import type { Decorations, IssueSink, StringFormat, WholeSchemaGuard, ZodBackend } from './types';
4 +import { applyObjectPolicy, buildTuple, composeGuards, run, withPath } from './shared';
5 +
6 +type S = z.ZodType;
7 +
8 +type Payload = { value: unknown; issues: unknown[] };
9 +type RunContext = { readonly direction?: 'forward' | 'backward' };
10 +type RunFn = (payload: Payload, ctx: RunContext) => Payload | Promise<Payload>;
11 +type SchemaDef = Record<string, unknown>;
12 +type InstrumentedDef = SchemaDef & { wholeSchemaGuard?: WholeSchemaGuard };
13 +type SchemaConstructor = { new (def: SchemaDef): S };
14 +type Internals = {
15 + def: InstrumentedDef;
16 + constr: SchemaConstructor;
17 + run: RunFn;
18 +};
19 +
20 +const internals = (schema: S): Internals => (schema as unknown as { _zod: Internals })._zod;
21 +
22 +const isUnmergeable = (error: unknown): error is Error =>
23 + error instanceof Error && error.message.startsWith('Unmergable intersection');
24 +
25 +const instrumentedClasses = new WeakMap<SchemaConstructor, SchemaConstructor>();
26 +const baseClasses = new WeakMap<SchemaConstructor, SchemaConstructor>();
27 +
28 +/**
29 + * A constructor that builds the schema with its own class and then wraps its
30 + * `_zod.run`. Zod's `clone()` calls `new inst._zod.constr(def)`, so pointing
31 + * `constr` at this wrapper keeps the behavior through `.describe()`,
32 + * `.meta()`, `.check()`, and the clones frameworks make. The schema keeps
33 + * its class: a guarded object is still a `ZodObject` with a `shape`.
34 + *
35 + * The wrapper reads its configuration from the definition on every run:
36 + * `wholeSchemaGuard` checks the source value before the base parse, and an
37 + * intersection turns the exception zod throws for values its branches
38 + * cannot merge into an issue, as v3 reports it.
39 + */
40 +const instrumentedClass = (Base: SchemaConstructor): SchemaConstructor => {
41 + const cached = instrumentedClasses.get(Base);
42 + if (cached) {
43 + return cached;
44 + }
45 +
46 + function Instrumented(def: SchemaDef): S {
47 + const inst = new Base(def);
48 + const zod = internals(inst);
49 + zod.constr = Instrumented as unknown as SchemaConstructor;
50 + const runAsBase = zod.run;
51 + zod.run = (payload, ctx) => {
52 + const fail = (message: string): Payload => {
53 + payload.issues.push({ code: 'custom', message, input: payload.value, inst, path: [] });
54 + return payload;
55 + };
56 + const guard = zod.def.wholeSchemaGuard;
57 + if (guard !== undefined && ctx.direction !== 'backward') {
58 + const failure = guard(payload.value);
59 + if (failure !== undefined) {
60 + return fail(failure);
61 + }
62 + }
63 + if (zod.def.type !== 'intersection') {
64 + return runAsBase(payload, ctx);
65 + }
66 + try {
67 + return runAsBase(payload, ctx);
68 + } catch (error) {
69 + if (!isUnmergeable(error)) {
70 + throw error;
71 + }
72 + return fail(error.message);
73 + }
74 + };
75 + return inst;
76 + }
77 +
78 + const constructor = Instrumented as unknown as SchemaConstructor;
79 + instrumentedClasses.set(Base, constructor);
80 + instrumentedClasses.set(constructor, constructor);
81 + baseClasses.set(constructor, Base);
82 + return constructor;
83 +};
84 +
85 +/** `schema` rebuilt through the instrumented constructor with `def`, keeping its registry metadata. */
86 +const rebuild = (schema: S, def: InstrumentedDef): S => {
87 + const zod = internals(schema);
88 + const Base = baseClasses.get(zod.constr) ?? zod.constr;
89 + const rebuilt = new (instrumentedClass(Base))(def);
90 + const meta = z.globalRegistry.get(schema);
91 + if (meta) {
92 + z.globalRegistry.add(rebuilt, meta);
93 + }
94 + return rebuilt;
95 +};
96 +
97 +const attachGuard = (schema: S, guard: WholeSchemaGuard): S => {
98 + const zod = internals(schema);
99 + const wholeSchemaGuard = composeGuards(guard, zod.def.wholeSchemaGuard);
100 + return rebuild(schema, z.core.util.mergeDefs(zod.def, { wholeSchemaGuard }) as InstrumentedDef);
101 +};
102 +
103 +const intersection = (left: S, right: S): S => {
104 + const schema = z.intersection(left, right);
105 + return rebuild(schema, internals(schema).def);
106 +};
107 +
108 +/** Wrappers carry the inner description, as every v3 wrapper does through its `_def`. */
109 +const carryDescription = (inner: S, wrapper: S): S => {
110 + const description = z.globalRegistry.get(inner)?.description;
111 + if (description !== undefined) {
112 + z.globalRegistry.add(wrapper, { description });
113 + }
114 + return wrapper;
115 +};
116 +
117 +type Wrapper = 'optional' | 'nullable' | 'readonly' | 'prefault';
118 +
119 +const rewrap: Record<Wrapper, (inner: S, def: SchemaDef) => S> = {
120 + optional: inner => z.optional(inner),
121 + nullable: inner => z.nullable(inner),
122 + readonly: inner => z.readonly(inner),
123 + prefault: (inner, def) => z.prefault(inner, def.defaultValue),
124 +};
125 +
126 +const isWrapper = (type: unknown): type is Wrapper =>
127 + typeof type === 'string' && Object.hasOwn(rewrap, type);
128 +
129 +/**
130 + * Registers `annotations` on the innermost non-wrapper node, rebuilding the
131 + * wrappers above it since `.meta()` clones. Validation-shaped keys such as
132 + * `type: "integer"` must not sit on a wrapper: a nullable renders as
133 + * `anyOf: [inner, null]`, and a `type` beside that `anyOf` would reject null.
134 + */
135 +const annotateInnermost = (schema: S, annotations: Decorations['annotations'] & object): S => {
136 + const def = internals(schema).def;
137 + if (!isWrapper(def.type)) {
138 + return schema.meta(annotations);
139 + }
140 + const inner = annotateInnermost(def.innerType as S, annotations);
141 + const wrapper = rewrap[def.type](inner, def);
142 + const ownMeta = z.globalRegistry.get(schema);
143 + if (ownMeta) {
144 + z.globalRegistry.add(wrapper, ownMeta);
145 + }
146 + return wrapper;
147 +};
148 +
149 +const decorate = (schema: S, decorations: Decorations): S => {
150 + const { description, annotations } = decorations;
151 + if (annotations === undefined) {
152 + return description === undefined ? schema : schema.describe(description);
153 + }
154 + if (!isWrapper(internals(schema).def.type)) {
155 + return schema.meta(description === undefined ? annotations : { description, ...annotations });
156 + }
157 + const annotated = annotateInnermost(schema, annotations);
158 + if (description !== undefined) {
159 + z.globalRegistry.add(annotated, { ...z.globalRegistry.get(annotated), description });
160 + }
161 + return annotated;
162 +};
163 +
164 +type RawIssue = Record<string, unknown>;
165 +
166 +/** Issues pushed onto a check payload; the enclosing schemas prefix the path. */
167 +const sinkFor = (push: (issue: RawIssue) => void): IssueSink => ({
168 + custom(message, options) {
169 + push({
170 + code: 'custom',
171 + message,
172 + ...withPath(options?.path),
173 + ...(options?.params === undefined ? {} : { params: options.params }),
174 + });
175 + },
176 + unrecognizedKeys(keys, message, options) {
177 + push({ code: 'unrecognized_keys', keys: [...keys], message, ...withPath(options?.path) });
178 + },
179 + invalidUnion(message, failures, options) {
180 + push({
181 + code: 'invalid_union',
182 + errors: failures.map(failure => [...failure.issues]),
183 + message,
184 + ...withPath(options?.path),
185 + });
186 + },
187 + forward(failure) {
188 + for (const issue of failure.issues) {
189 + push({ ...(issue as RawIssue) });
190 + }
191 + },
192 +});
193 +
194 +let ipProbes: readonly S[] | undefined;
195 +let urlProbe: S | undefined;
196 +
197 +const isIp = (value: string): boolean => {
198 + ipProbes ??= [z.ipv4(), z.ipv6()];
199 + return ipProbes.some(probe => probe.safeParse(value).success);
200 +};
201 +
202 +const isUrl = (value: string): boolean => {
203 + urlProbe ??= z.url();
204 + return urlProbe.safeParse(value).success;
205 +};
206 +
207 +const stringFormat = (schema: S, format: StringFormat, message?: string): S => {
208 + const string = schema as z.ZodString;
209 + switch (format) {
210 + case 'email':
211 + return string.email(message);
212 + case 'ip':
213 + // v4 has no combined check, and a refinement keeps the value untouched.
214 + return string.refine(isIp, message);
215 + case 'ipv4':
216 + return string.ipv4(message);
217 + case 'ipv6':
218 + return string.ipv6(message);
219 + case 'uri':
220 + // `.url()` rewrites the value it accepts; a refinement over the same
221 + // check keeps the input as given, as v3 does.
222 + return string.refine(isUrl, message);
223 + case 'uuid':
224 + // v3's uuid pattern is v4's guid: the RFC variant bits are not enforced.
225 + return string.guid(message);
226 + case 'date-time':
227 + return string.datetime({ offset: true, error: message });
228 + case 'time':
229 + return string.time(message);
230 + case 'date':
231 + return string.date(message);
232 + case 'duration':
233 + return string.duration(message);
234 + }
235 +};
236 +
237 +/** Zod v4 output: metadata in the global registry, refinements as checks, the guard as a run wrapper. */
238 +export const zodV4Backend: ZodBackend<S> = {
239 + isSchema: (value): value is S => value instanceof z.ZodType,
240 + isNever: schema => schema instanceof z.ZodNever,
241 +
242 + any: () => z.any(),
243 + never: () => z.never(),
244 + boolean: () => z.boolean(),
245 + null: () => z.null(),
246 + string: () => z.string(),
247 + number: () => z.number(),
248 + literal: value => z.literal(value),
249 + enum: values => z.enum(values as [string, ...string[]]),
250 + // `z.custom()` cannot be rendered as JSON Schema; a refined `any` can.
251 + predicate: test => z.any().refine(test),
252 +
253 + stringFormat,
254 + base64: (schema, message) => (schema as z.ZodString).base64(message),
255 + regex: (schema, pattern, message) => (schema as z.ZodString).regex(pattern, message),
256 +
257 + // Native `.int()` is a safe-integer check that also emits ±2^53-1 bounds;
258 + // JSON Schema integers, v3, and Ajv accept any integral number.
259 + integer: (schema, message) => schema.refine(value => Number.isInteger(value), message),
260 + bound: (schema, kind, value, message) => (schema as z.ZodNumber)[kind](value, message),
261 +
262 + array: item => z.array(item),
263 + minItems: (schema, count, message) => (schema as z.ZodArray<S>).min(count, message),
264 + maxItems: (schema, count, message) => (schema as z.ZodArray<S>).max(count, message),
265 + tuple: (items, rest) => buildTuple<S>(z.tuple(items as unknown as [S]), rest),
266 +
267 + object: (shape, policy) => applyObjectPolicy<S>(z.object(shape), policy),
268 + record: value => z.record(z.string(), value),
269 +
270 + union: options => z.union(options as unknown as [S, S]),
271 + intersection,
272 +
273 + optional: schema => carryDescription(schema, schema.optional()),
274 + nullable: schema => carryDescription(schema, schema.nullable()),
275 + // `.default()` short-circuits past the inner schema; `.prefault()` parses the default through it, as v3 does.
276 + withDefault: (schema, value) => carryDescription(schema, schema.prefault(value)),
277 + readonly: schema => carryDescription(schema, schema.readonly()),
278 + decorate,
279 +
280 + refine: <T>(schema: S, test: (value: T) => boolean, message?: string) =>
281 + schema.refine(value => test(value as T), message),
282 + superRefine: <T>(schema: S, check: (value: T, issues: IssueSink) => void) =>
283 + schema.superRefine((value, ctx) =>
284 + check(
285 + value as T,
286 + sinkFor(issue => ctx.addIssue(issue as unknown as z.core.$ZodRawIssue))
287 + )
288 + ),
289 + // A check that replaces the payload value keeps the schema's kind, where
290 + // `.transform()` would produce a pipe that cannot be rendered as JSON Schema.
291 + rewrite: <T>(schema: S, fn: (value: T, issues: IssueSink) => unknown) =>
292 + schema.check(payload => {
293 + const sink = sinkFor(issue =>
294 + payload.issues.push({
295 + input: payload.value,
296 + continue: true,
297 + ...issue,
298 + } as unknown as z.core.$ZodRawIssue)
299 + );
300 + payload.value = fn(payload.value as T, sink);
301 + }),
302 +
303 + run,
304 + attachGuard,
305 +};
ts/packages/json-schema-to-zod/src/context.ts new
+25
@@ -0,0 +1,25 @@
1 +import type { ZodBackend } from './backend/types';
2 +import type { JsonSchema, JsonSchemaObject } from './types';
3 +
4 +export type ParserOverrideOf<S> = (schema: JsonSchemaObject, refs: RefsOf<S>) => S | undefined;
5 +
6 +export type OptionsOf<S> = {
7 + withoutDefaults?: boolean;
8 + withoutDescribes?: boolean;
9 + parserOverride?: ParserOverrideOf<S>;
10 + depth?: number;
11 +};
12 +
13 +export type RefsOf<S> = OptionsOf<S> & {
14 + path: Array<string | number>;
15 + seen: Map<object | boolean, { n: number; r: S | undefined }>;
16 + /** The document that local `$ref` pointers resolve against. */
17 + root?: JsonSchema;
18 +};
19 +
20 +/** What every parser receives: the references plus the builder that turns JSON Schema into `S`. */
21 +export type ParseContext<S> = RefsOf<S> & {
22 + readonly backend: ZodBackend<S>;
23 + /** Suppresses the JSON Schema annotations a backend would otherwise carry. */
24 + readonly withoutAnnotations?: boolean;
25 +};
ts/packages/json-schema-to-zod/src/convert.ts new
+42
@@ -0,0 +1,42 @@
1 +import type { ZodBackend } from './backend/types';
2 +import type { OptionsOf, ParseContext } from './context';
3 +import { parseObjectShape } from './parsers/parse-object-shape';
4 +import { parseSchema } from './parsers/parse-schema';
5 +import type { JsonSchema, JsonSchemaObject } from './types';
6 +import { createWholeSchemaGuard, requiresWholeSchemaValidation } from './whole-schema-validation';
7 +
8 +type ConverterOptions<S> = OptionsOf<S> & { withoutAnnotations?: boolean };
9 +
10 +/** The two conversion entry points, bound to one backend. */
11 +export const createConverter = <S>(backend: ZodBackend<S>) => {
12 + const contextFor = (root: JsonSchema, options: ConverterOptions<S>): ParseContext<S> => ({
13 + path: [],
14 + seen: new Map(),
15 + root,
16 + ...options,
17 + backend,
18 + });
19 +
20 + const jsonSchemaToZod = (schema: JsonSchema, options: ConverterOptions<S> = {}): S => {
21 + const parsedSchema = parseSchema(schema, contextFor(schema, options));
22 +
23 + return requiresWholeSchemaValidation(schema)
24 + ? backend.attachGuard(parsedSchema, createWholeSchemaGuard(schema))
25 + : parsedSchema;
26 + };
27 +
28 + const jsonSchemaToZodShape = (
29 + schema: JsonSchema,
30 + options: ConverterOptions<S> = {}
31 + ): Record<string, S> => {
32 + if (typeof schema !== 'object' || schema === null) {
33 + return {};
34 + }
35 +
36 + const objectSchema = schema as JsonSchemaObject;
37 +
38 + return parseObjectShape(objectSchema, contextFor(objectSchema, options));
39 + };
40 +
41 + return { jsonSchemaToZod, jsonSchemaToZodShape };
42 +};
ts/packages/json-schema-to-zod/src/json-schema-to-zod.ts
+8 -34
@@ -1,28 +1,15 @@
1 -import { z, type ZodTypeAny } from 'zod/v3';
1 +import type { ZodType, ZodTypeAny } from 'zod/v3';
2
3 -import { parseSchema } from './parsers/parse-schema';
4 -import { parseObjectShape } from './parsers/parse-object-shape';
5 -import type { JsonSchemaToZodOptions, JsonSchema, JsonSchemaObject } from './types';
6 -import {
7 - requiresWholeSchemaValidation,
8 - withWholeSchemaValidation,
9 -} from './whole-schema-validation';
3 +import { zodV3Backend } from './backend/zod-v3';
4 +import { createConverter } from './convert';
5 +import type { JsonSchemaToZodOptions, JsonSchema } from './types';
6 +
7 +const converter = createConverter(zodV3Backend);
8
9 export const jsonSchemaToZod = (
10 schema: JsonSchema,
11 options: JsonSchemaToZodOptions = {}
14 -): z.ZodType => {
15 - const parsedSchema = parseSchema(schema, {
16 - path: [],
17 - seen: new Map(),
18 - root: schema,
19 - ...options,
20 - });
21 -
22 - return requiresWholeSchemaValidation(schema)
23 - ? withWholeSchemaValidation(schema, parsedSchema)
24 - : parsedSchema;
25 -};
12 +): ZodType => converter.jsonSchemaToZod(schema, options);
13
14 /**
15 * A simplified type for Zod raw shapes that avoids deep type instantiation issues.
@@ -45,17 +32,4 @@ export type SimpleZodRawShape = Record<string, ZodTypeAny>;
32 export const jsonSchemaToZodShape = (
33 schema: JsonSchema,
34 options: JsonSchemaToZodOptions = {}
48 -): SimpleZodRawShape => {
49 - if (typeof schema !== 'object' || schema === null) {
50 - return {};
51 - }
52 -
53 - const objectSchema = schema as JsonSchemaObject;
54 -
55 - return parseObjectShape(objectSchema, {
56 - path: [],
57 - seen: new Map(),
58 - root: objectSchema,
59 - ...options,
60 - });
61 -};
35 +): SimpleZodRawShape => converter.jsonSchemaToZodShape(schema, options);
ts/packages/json-schema-to-zod/src/parsers/parse-all-of.ts
+17 -19
@@ -1,7 +1,6 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject, JsonSchema } from '../types';
4 import { half } from '../utils/half';
5 import { its } from '../utils/its';
6
@@ -35,30 +34,30 @@ const isClosedObjectBranch = (
34 branch.patternProperties === undefined &&
35 !('$ref' in branch);
36
38 -const intersect = (branches: JsonSchema[], refs: Refs): z.ZodTypeAny => {
37 +const intersect = <S>(branches: JsonSchema[], ctx: ParseContext<S>): S => {
38 if (branches.length === 1) {
39 const item = branches[0];
40
41 return parseSchema(item, {
43 - ...refs,
44 - path: [...refs.path, 'allOf', (item as never)[originalIndex]],
42 + ...ctx,
43 + path: [...ctx.path, 'allOf', (item as never)[originalIndex]],
44 });
45 }
46
47 const [left, right] = half(branches);
49 - return z.intersection(intersect(left, refs), intersect(right, refs));
48 + return ctx.backend.intersection(intersect(left, ctx), intersect(right, ctx));
49 };
50
52 -export function parseAllOf(
51 +export function parseAllOf<S>(
52 jsonSchema: JsonSchemaObject & { allOf: JsonSchema[] },
54 - refs: Refs
55 -): z.ZodTypeAny {
53 + ctx: ParseContext<S>
54 +): S {
55 if (jsonSchema.allOf.length === 0) {
57 - return z.never();
56 + return ctx.backend.never();
57 }
58
59 if (jsonSchema.allOf.length === 1) {
61 - return intersect(ensureOriginalIndex(jsonSchema.allOf), refs);
60 + return intersect(ensureOriginalIndex(jsonSchema.allOf), ctx);
61 }
62
63 // Sibling object branches must not reject each other's keys: each branch is
@@ -67,7 +66,7 @@ export function parseAllOf(
66 const opened = jsonSchema.allOf.map(branch =>
67 isClosedObjectBranch(branch) ? { ...branch, additionalProperties: true } : branch
68 );
70 - const parsed = intersect(ensureOriginalIndex(opened), refs);
69 + const parsed = intersect(ensureOriginalIndex(opened), ctx);
70
71 if (!jsonSchema.allOf.every(isClosedObjectBranch)) {
72 return parsed;
@@ -77,15 +76,14 @@ export function parseAllOf(
76 jsonSchema.allOf.flatMap(branch => Object.keys((branch as JsonSchemaObject).properties ?? {}))
77 );
78
80 - return parsed.superRefine((value, ctx) => {
79 + return ctx.backend.superRefine<unknown>(parsed, (value, issues) => {
80 if (typeof value !== 'object' || value === null || Array.isArray(value)) return;
81 const unrecognizedKeys = Object.keys(value).filter(key => !declaredKeys.has(key));
82 if (unrecognizedKeys.length > 0) {
84 - ctx.addIssue({
85 - code: z.ZodIssueCode.unrecognized_keys,
86 - keys: unrecognizedKeys,
87 - message: `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`,
88 - });
83 + issues.unrecognizedKeys(
84 + unrecognizedKeys,
85 + `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`
86 + );
87 }
88 });
89 }
ts/packages/json-schema-to-zod/src/parsers/parse-any-of.ts
+12 -10
@@ -1,19 +1,21 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject, JsonSchema } from '../types';
4
6 -export const parseAnyOf = (jsonSchema: JsonSchemaObject & { anyOf: JsonSchema[] }, refs: Refs) => {
5 +export const parseAnyOf = <S>(
6 + jsonSchema: JsonSchemaObject & { anyOf: JsonSchema[] },
7 + ctx: ParseContext<S>
8 +): S => {
9 return jsonSchema.anyOf.length
10 ? jsonSchema.anyOf.length === 1
11 ? parseSchema(jsonSchema.anyOf[0], {
10 - ...refs,
11 - path: [...refs.path, 'anyOf', 0],
12 + ...ctx,
13 + path: [...ctx.path, 'anyOf', 0],
14 })
13 - : z.union(
15 + : ctx.backend.union(
16 jsonSchema.anyOf.map((schema, i) =>
15 - parseSchema(schema, { ...refs, path: [...refs.path, 'anyOf', i] })
16 - ) as [z.ZodTypeAny, z.ZodTypeAny]
17 + parseSchema(schema, { ...ctx, path: [...ctx.path, 'anyOf', i] })
18 + ) as [S, S]
19 )
18 - : z.any();
20 + : ctx.backend.any();
21 };
ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
+36 -30
@@ -1,7 +1,6 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, Refs, JsonSchema } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject, JsonSchema } from '../types';
4 import { extendSchemaWithMessage } from '../utils/extend-schema';
5 import { its } from '../utils/its';
6 import type { JSONSchema7TypeName } from 'json-schema';
@@ -9,7 +8,12 @@ import type { JSONSchema7TypeName } from 'json-schema';
8 type MetadataFields =
9 keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'> | 'examples';
10
12 -export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, refs: Refs) => {
11 +export const parseArray = <S>(
12 + jsonSchema: JsonSchemaObject & { type: 'array' },
13 + ctx: ParseContext<S>
14 +): S => {
15 + const { backend } = ctx;
16 +
17 // Handle anyOf pattern first
18 if (its.an.anyOf(jsonSchema)) {
19 const types = new Set<string>();
@@ -53,68 +57,70 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
57 }
58 });
59
56 - return parseSchema(newSchema, refs);
60 + return parseSchema(newSchema, ctx);
61 }
62
63 // Handle regular array schema
64 if (Array.isArray(jsonSchema.items)) {
65 const parsedItems = jsonSchema.items.map((item, index) =>
62 - parseSchema(item, { ...refs, path: [...refs.path, 'items', index] })
66 + parseSchema(item, { ...ctx, path: [...ctx.path, 'items', index] })
67 );
68 const prefixSchemas = parsedItems.map((_, length) =>
65 - z.tuple(parsedItems.slice(0, length) as unknown as [z.ZodTypeAny])
69 + backend.tuple(parsedItems.slice(0, length), undefined)
70 );
67 - const fullTuple = z.tuple(parsedItems as unknown as [z.ZodTypeAny]);
71
69 - let fullLengthSchema: z.ZodTypeAny;
72 + let fullLengthSchema: S;
73 if (jsonSchema.additionalItems === false) {
71 - fullLengthSchema = fullTuple;
74 + fullLengthSchema = backend.tuple(parsedItems, undefined);
75 } else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) {
73 - fullLengthSchema = fullTuple.rest(
76 + fullLengthSchema = backend.tuple(
77 + parsedItems,
78 parseSchema(jsonSchema.additionalItems, {
75 - ...refs,
76 - path: [...refs.path, 'additionalItems'],
79 + ...ctx,
80 + path: [...ctx.path, 'additionalItems'],
81 })
82 );
83 } else {
80 - fullLengthSchema = fullTuple.rest(z.any());
84 + fullLengthSchema = backend.tuple(parsedItems, backend.any());
85 }
86
87 const variants = [...prefixSchemas, fullLengthSchema];
84 - let tupleSchema: z.ZodTypeAny =
85 - variants.length === 1
86 - ? variants[0]
87 - : z.union(variants as unknown as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);
88 + let tupleSchema: S =
89 + variants.length === 1 ? variants[0] : backend.union(variants as unknown as [S, S, ...S[]]);
90
91 if (typeof jsonSchema.minItems === 'number') {
90 - tupleSchema = tupleSchema.refine(value => value.length >= jsonSchema.minItems!, {
91 - message: `Array must contain at least ${jsonSchema.minItems} element(s)`,
92 - });
92 + tupleSchema = backend.refine<unknown[]>(
93 + tupleSchema,
94 + value => value.length >= jsonSchema.minItems!,
95 + `Array must contain at least ${jsonSchema.minItems} element(s)`
96 + );
97 }
98 if (typeof jsonSchema.maxItems === 'number') {
95 - tupleSchema = tupleSchema.refine(value => value.length <= jsonSchema.maxItems!, {
96 - message: `Array must contain at most ${jsonSchema.maxItems} element(s)`,
97 - });
99 + tupleSchema = backend.refine<unknown[]>(
100 + tupleSchema,
101 + value => value.length <= jsonSchema.maxItems!,
102 + `Array must contain at most ${jsonSchema.maxItems} element(s)`
103 + );
104 }
105
106 return tupleSchema;
107 }
108
109 let zodSchema = !jsonSchema.items
104 - ? z.array(z.any())
105 - : z.array(parseSchema(jsonSchema.items, { ...refs, path: [...refs.path, 'items'] }));
110 + ? backend.array(backend.any())
111 + : backend.array(parseSchema(jsonSchema.items, { ...ctx, path: [...ctx.path, 'items'] }));
112
113 zodSchema = extendSchemaWithMessage(
114 zodSchema,
115 jsonSchema,
116 'minItems',
111 - (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
117 + (zs, minItems, errorMessage) => backend.minItems(zs, minItems, errorMessage)
118 );
119 zodSchema = extendSchemaWithMessage(
120 zodSchema,
121 jsonSchema,
122 'maxItems',
117 - (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
123 + (zs, maxItems, errorMessage) => backend.maxItems(zs, maxItems, errorMessage)
124 );
125
126 // Handle generic 'min' property as alias for 'minItems'
@@ -123,7 +129,7 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
129 zodSchema,
130 { ...jsonSchema, minItems: jsonSchema.min },
131 'minItems',
126 - (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
132 + (zs, minItems, errorMessage) => backend.minItems(zs, minItems, errorMessage)
133 );
134 }
135
@@ -133,7 +139,7 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
139 zodSchema,
140 { ...jsonSchema, maxItems: jsonSchema.max },
141 'maxItems',
136 - (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
142 + (zs, maxItems, errorMessage) => backend.maxItems(zs, maxItems, errorMessage)
143 );
144 }
145
ts/packages/json-schema-to-zod/src/parsers/parse-boolean.ts
+6 -4
@@ -1,7 +1,9 @@
1 -import { z } from 'zod/v3';
2 -
1 +import type { ParseContext } from '../context';
2 import type { JsonSchemaObject } from '../types';
3
5 -export const parseBoolean = (_jsonSchema: JsonSchemaObject & { type: 'boolean' }) => {
6 - return z.boolean();
4 +export const parseBoolean = <S>(
5 + _jsonSchema: JsonSchemaObject & { type: 'boolean' },
6 + ctx: ParseContext<S>
7 +): S => {
8 + return ctx.backend.boolean();
9 };
ts/packages/json-schema-to-zod/src/parsers/parse-const.ts
+9 -4
@@ -1,10 +1,15 @@
1 import { parseLiteralValues } from './parse-literal-values';
2 import { parseSchema } from './parse-schema';
3 -import type { JsonSchemaObject, Refs, Serializable } from '../types';
3 +import type { ParseContext } from '../context';
4 +import type { JsonSchemaObject, Serializable } from '../types';
5
5 -export const parseConst = (jsonSchema: JsonSchemaObject & { const: Serializable }, refs: Refs) => {
6 +export const parseConst = <S>(
7 + jsonSchema: JsonSchemaObject & { const: Serializable },
8 + ctx: ParseContext<S>
9 +): S => {
10 const { const: value, ...baseSchema } = jsonSchema;
7 - return parseSchema(baseSchema, { ...refs, seen: new Map(refs.seen) }, true).and(
8 - parseLiteralValues([value])
11 + return ctx.backend.intersection(
12 + parseSchema(baseSchema, { ...ctx, seen: new Map(ctx.seen) }, true),
13 + parseLiteralValues([value], ctx.backend)
14 );
15 };
ts/packages/json-schema-to-zod/src/parsers/parse-default.ts
+3 -4
@@ -1,7 +1,6 @@
1 -import { z } from 'zod/v3';
2 -
1 +import type { ParseContext } from '../context';
2 import type { JsonSchemaObject } from '../types';
3
5 -export const parseDefault = (_jsonSchema: JsonSchemaObject) => {
6 - return z.any();
4 +export const parseDefault = <S>(_jsonSchema: JsonSchemaObject, ctx: ParseContext<S>): S => {
5 + return ctx.backend.any();
6 };
ts/packages/json-schema-to-zod/src/parsers/parse-enum.ts
+9 -4
@@ -1,10 +1,15 @@
1 import { parseLiteralValues } from './parse-literal-values';
2 import { parseSchema } from './parse-schema';
3 -import type { JsonSchemaObject, Refs, Serializable } from '../types';
3 +import type { ParseContext } from '../context';
4 +import type { JsonSchemaObject, Serializable } from '../types';
5
5 -export const parseEnum = (jsonSchema: JsonSchemaObject & { enum: Serializable[] }, refs: Refs) => {
6 +export const parseEnum = <S>(
7 + jsonSchema: JsonSchemaObject & { enum: Serializable[] },
8 + ctx: ParseContext<S>
9 +): S => {
10 const { enum: values, ...baseSchema } = jsonSchema;
7 - return parseSchema(baseSchema, { ...refs, seen: new Map(refs.seen) }, true).and(
8 - parseLiteralValues(values)
11 + return ctx.backend.intersection(
12 + parseSchema(baseSchema, { ...ctx, seen: new Map(ctx.seen) }, true),
13 + parseLiteralValues(values, ctx.backend)
14 );
15 };
ts/packages/json-schema-to-zod/src/parsers/parse-if-then-else.ts
+16 -14
@@ -1,31 +1,33 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject, JsonSchema } from '../types';
4
6 -export const parseIfThenElse = (
5 +export const parseIfThenElse = <S>(
6 jsonSchema: JsonSchemaObject & {
7 if: JsonSchema;
8 then: JsonSchema;
9 else: JsonSchema;
10 },
12 - refs: Refs
13 -) => {
14 - const $if = parseSchema(jsonSchema.if, { ...refs, path: [...refs.path, 'if'] });
11 + ctx: ParseContext<S>
12 +): S => {
13 + const { backend } = ctx;
14 + const $if = parseSchema(jsonSchema.if, { ...ctx, path: [...ctx.path, 'if'] });
15 const $then = parseSchema(jsonSchema.then, {
16 - ...refs,
17 - path: [...refs.path, 'then'],
16 + ...ctx,
17 + path: [...ctx.path, 'then'],
18 });
19 const $else = parseSchema(jsonSchema.else, {
20 - ...refs,
21 - path: [...refs.path, 'else'],
20 + ...ctx,
21 + path: [...ctx.path, 'else'],
22 });
23
24 - return z.union([$then, $else]).superRefine((value, ctx) => {
25 - const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
24 + return backend.superRefine<unknown>(backend.union([$then, $else]), (value, issues) => {
25 + const result = backend.run($if, value).success
26 + ? backend.run($then, value)
27 + : backend.run($else, value);
28
29 if (!result.success) {
28 - result.error.errors.forEach(error => ctx.addIssue(error));
30 + issues.forward(result.failure);
31 }
32 });
33 };
ts/packages/json-schema-to-zod/src/parsers/parse-literal-values.ts
+13 -12
@@ -1,21 +1,22 @@
1 import { dequal } from 'dequal/lite';
2 -import { z } from 'zod/v3';
2
3 +import type { ZodBackend } from '../backend/types';
4 import type { Serializable } from '../types';
5
6 -export const parseLiteralValues = (values: ReadonlyArray<Serializable>): z.ZodTypeAny => {
7 - if (values.length === 0) return z.never();
6 +export const parseLiteralValues = <S>(
7 + values: ReadonlyArray<Serializable>,
8 + backend: ZodBackend<S>
9 +): S => {
10 + if (values.length === 0) return backend.never();
11
12 if (values.every(value => value === null || typeof value !== 'object')) {
10 - if (values.length === 1) return z.literal(values[0] as z.Primitive);
11 - if (values.every(value => typeof value === 'string')) return z.enum(values as [string]);
12 - return z.union(
13 - values.map(value => z.literal(value as z.Primitive)) as unknown as [
14 - z.ZodTypeAny,
15 - z.ZodTypeAny,
16 - ]
17 - );
13 + const primitives = values as ReadonlyArray<string | number | boolean | null>;
14 + if (primitives.length === 1) return backend.literal(primitives[0]);
15 + if (primitives.every(value => typeof value === 'string')) {
16 + return backend.enum(primitives as [string, ...string[]]);
17 + }
18 + return backend.union(primitives.map(value => backend.literal(value)) as unknown as [S, S]);
19 }
20
20 - return z.custom<Serializable>(value => values.some(candidate => dequal(value, candidate)));
21 + return backend.predicate(value => values.some(candidate => dequal(value, candidate)));
22 };
ts/packages/json-schema-to-zod/src/parsers/parse-multiple-type.ts
+7 -11
@@ -1,16 +1,12 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchema, JsonSchemaObject, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchema, JsonSchemaObject } from '../types';
4
6 -export const parseMultipleType = (
5 +export const parseMultipleType = <S>(
6 jsonSchema: JsonSchemaObject & { type: string[] },
8 - refs: Refs
9 -) => {
10 - return z.union(
11 - jsonSchema.type.map(type => parseSchema({ ...jsonSchema, type } as JsonSchema, refs)) as [
12 - z.ZodTypeAny,
13 - z.ZodTypeAny,
14 - ]
7 + ctx: ParseContext<S>
8 +): S => {
9 + return ctx.backend.union(
10 + jsonSchema.type.map(type => parseSchema({ ...jsonSchema, type } as JsonSchema, ctx)) as [S, S]
11 );
12 };
ts/packages/json-schema-to-zod/src/parsers/parse-not.ts
+16 -9
@@ -1,15 +1,22 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject, JsonSchema } from '../types';
4
6 -export const parseNot = (jsonSchema: JsonSchemaObject & { not: JsonSchema }, refs: Refs) => {
7 - return z.any().refine(
5 +export const parseNot = <S>(
6 + jsonSchema: JsonSchemaObject & { not: JsonSchema },
7 + ctx: ParseContext<S>
8 +): S => {
9 + const { backend } = ctx;
10 + return backend.refine<unknown>(
11 + backend.any(),
12 value =>
9 - !parseSchema(jsonSchema.not, {
10 - ...refs,
11 - path: [...refs.path, 'not'],
12 - }).safeParse(value).success,
13 + !backend.run(
14 + parseSchema(jsonSchema.not, {
15 + ...ctx,
16 + path: [...ctx.path, 'not'],
17 + }),
18 + value
19 + ).success,
20 'Invalid input: Should NOT be valid against schema'
21 );
22 };
ts/packages/json-schema-to-zod/src/parsers/parse-null.ts
+6 -4
@@ -1,7 +1,9 @@
1 -import { z } from 'zod/v3';
2 -
1 +import type { ParseContext } from '../context';
2 import type { JsonSchemaObject } from '../types';
3
5 -export const parseNull = (_jsonSchema: JsonSchemaObject & { type: 'null' }) => {
6 - return z.null();
4 +export const parseNull = <S>(
5 + _jsonSchema: JsonSchemaObject & { type: 'null' },
6 + ctx: ParseContext<S>
7 +): S => {
8 + return ctx.backend.null();
9 };
ts/packages/json-schema-to-zod/src/parsers/parse-nullable.ts
+8 -4
@@ -1,11 +1,15 @@
1 import { parseSchema } from './parse-schema';
2 -import type { JsonSchemaObject, Refs } from '../types';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject } from '../types';
4 import { omit } from '../utils/omit';
5
6 /**
7 * For compatibility with open api 3.0 nullable
8 */
8 -export const parseNullable = (jsonSchema: JsonSchemaObject & { nullable: true }, refs: Refs) => {
9 +export const parseNullable = <S>(
10 + jsonSchema: JsonSchemaObject & { nullable: true },
11 + ctx: ParseContext<S>
12 +): S => {
13 // If the schema has a null default, we need to handle it specially
14 // Remove the default from the base schema to prevent it from being applied to non-null types
15 const hasNullDefault = jsonSchema.default === null;
@@ -13,8 +17,8 @@ export const parseNullable = (jsonSchema: JsonSchemaObject & { nullable: true },
17 ? omit(omit(jsonSchema, 'nullable'), 'default')
18 : omit(jsonSchema, 'nullable');
19
16 - const zodSchema = parseSchema(baseSchema, refs, true).nullable();
20 + const zodSchema = ctx.backend.nullable(parseSchema(baseSchema, ctx, true));
21
22 // Apply the null default at the nullable level if it exists
19 - return hasNullDefault ? zodSchema.default(null) : zodSchema;
23 + return hasNullDefault ? ctx.backend.withDefault(zodSchema, null) : zodSchema;
24 };
ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
+26 -20
@@ -1,5 +1,4 @@
1 -import { z } from 'zod/v3';
2 -
1 +import type { ZodBackend } from '../backend/types';
2 import type { JsonSchemaObject } from '../types';
3 import { extendSchemaWithMessage } from '../utils/extend-schema';
4
@@ -38,36 +37,39 @@ const isJsonMultipleOf = (value: number, multiple: number): boolean => {
37 return scaledDividend % scaledDivisor === 0n;
38 };
39
41 -export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'integer' }) => {
42 - let zodSchema = z.number();
40 +export const parseNumber = <S>(
41 + jsonSchema: JsonSchemaObject & { type: 'number' | 'integer' },
42 + backend: ZodBackend<S>
43 +): S => {
44 + let zodSchema = backend.number();
45
46 let isInteger = false;
47 if (jsonSchema.type === 'integer') {
48 isInteger = true;
49 zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'type', (zs, _, errorMsg) =>
48 - zs.int(errorMsg)
50 + backend.integer(zs, errorMsg)
51 );
52 } else if (jsonSchema.format === 'int64') {
53 isInteger = true;
54 zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, _, errorMsg) =>
53 - zs.int(errorMsg)
55 + backend.integer(zs, errorMsg)
56 );
57 }
58
59 if (typeof jsonSchema.minimum === 'number') {
58 - if ((jsonSchema as unknown as { exclusiveMinimum?: boolean }).exclusiveMinimum === true) {
60 + if (jsonSchema.exclusiveMinimum === true) {
61 zodSchema = extendSchemaWithMessage(
62 zodSchema,
63 jsonSchema,
64 'minimum',
63 - (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg)
65 + (zs, minimum, errorMsg) => backend.bound(zs, 'gt', minimum, errorMsg)
66 );
67 } else {
68 zodSchema = extendSchemaWithMessage(
69 zodSchema,
70 jsonSchema,
71 'minimum',
70 - (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
72 + (zs, minimum, errorMsg) => backend.bound(zs, 'gte', minimum, errorMsg)
73 );
74 }
75 }
@@ -76,24 +78,25 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
78 zodSchema,
79 jsonSchema,
80 'exclusiveMinimum',
79 - (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum as number, errorMsg)
81 + (zs, exclusiveMinimum, errorMsg) =>
82 + backend.bound(zs, 'gt', exclusiveMinimum as number, errorMsg)
83 );
84 }
85
86 if (typeof jsonSchema.maximum === 'number') {
84 - if ((jsonSchema as unknown as { exclusiveMaximum?: boolean }).exclusiveMaximum === true) {
87 + if (jsonSchema.exclusiveMaximum === true) {
88 zodSchema = extendSchemaWithMessage(
89 zodSchema,
90 jsonSchema,
91 'maximum',
89 - (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg)
92 + (zs, maximum, errorMsg) => backend.bound(zs, 'lt', maximum, errorMsg)
93 );
94 } else {
95 zodSchema = extendSchemaWithMessage(
96 zodSchema,
97 jsonSchema,
98 'maximum',
96 - (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
99 + (zs, maximum, errorMsg) => backend.bound(zs, 'lte', maximum, errorMsg)
100 );
101 }
102 }
@@ -102,7 +105,8 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
105 zodSchema,
106 jsonSchema,
107 'exclusiveMaximum',
105 - (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum as number, errorMsg)
108 + (zs, exclusiveMaximum, errorMsg) =>
109 + backend.bound(zs, 'lt', exclusiveMaximum as number, errorMsg)
110 );
111 }
112
@@ -112,7 +116,7 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
116 zodSchema,
117 { ...jsonSchema, minimum: jsonSchema.min },
118 'minimum',
115 - (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
119 + (zs, minimum, errorMsg) => backend.bound(zs, 'gte', minimum, errorMsg)
120 );
121 }
122
@@ -122,7 +126,7 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
126 zodSchema,
127 { ...jsonSchema, maximum: jsonSchema.max },
128 'maximum',
125 - (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
129 + (zs, maximum, errorMsg) => backend.bound(zs, 'lte', maximum, errorMsg)
130 );
131 }
132
@@ -131,11 +135,13 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
135 jsonSchema as JsonSchemaObject & { errorMessage?: Record<string, string> }
136 ).errorMessage?.multipleOf;
137 if (jsonSchema.multipleOf === 1) {
134 - return isInteger ? zodSchema : zodSchema.int(errorMessage);
138 + return isInteger ? zodSchema : backend.integer(zodSchema, errorMessage);
139 }
136 - return zodSchema.refine(value => isJsonMultipleOf(value, jsonSchema.multipleOf!), {
137 - message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}`,
138 - });
140 + return backend.refine<number>(
141 + zodSchema,
142 + value => isJsonMultipleOf(value, jsonSchema.multipleOf!),
143 + errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}`
144 + );
145 }
146
147 return zodSchema;
ts/packages/json-schema-to-zod/src/parsers/parse-object-shape.ts
+32 -56
@@ -1,11 +1,12 @@
1 -import * as z from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, Refs, JsonSchema } from '../types';
2 +import { applyPropertyPresence } from './property-presence';
3 +import type { ParseContext } from '../context';
4 +import type { JsonSchemaObject } from '../types';
5 import {
6 + createWholeSchemaGuard,
7 guardSchemaAt,
8 + requiresPermissiveMaterialization,
9 requiresWholeSchemaValidation,
8 - withWholeSchemaValidation,
10 } from '../whole-schema-validation';
11
12 /**
@@ -13,10 +14,13 @@ import {
14 * This is useful when you need ZodRawShape instead of a complete ZodObject.
15 *
16 * @param objectSchema - The JSON Schema object to parse
16 - * @param refs - Parser references for handling nested schemas
17 + * @param ctx - Parser context for handling nested schemas
18 * @returns A Zod raw shape object
19 */
19 -export function parseObjectShape(objectSchema: JsonSchemaObject, refs: Refs): z.ZodRawShape {
20 +export function parseObjectShape<S>(
21 + objectSchema: JsonSchemaObject,
22 + ctx: ParseContext<S>
23 +): Record<string, S> {
24 if (!objectSchema.properties) {
25 return {};
26 }
@@ -26,66 +30,38 @@ export function parseObjectShape(objectSchema: JsonSchemaObject, refs: Refs): z.
30 return {};
31 }
32
29 - const properties: z.ZodRawShape = {};
33 + const { backend } = ctx;
34 + const properties: Record<string, S> = {};
35
36 for (const key of propertyKeys) {
37 const propJsonSchema = objectSchema.properties[key];
33 - const propRefs = {
34 - ...refs,
35 - root: refs.root ?? objectSchema,
36 - path: [...refs.path, 'properties', key],
38 + const propCtx = {
39 + ...ctx,
40 + root: ctx.root ?? objectSchema,
41 + path: [...ctx.path, 'properties', key],
42 };
43
39 - const parsedProperty = parseSchema(propJsonSchema, propRefs);
40 - const propZodSchema = requiresWholeSchemaValidation(propJsonSchema)
41 - ? withWholeSchemaValidation(guardSchemaAt(propJsonSchema, propRefs), parsedProperty)
42 - : parsedProperty;
44 + const parsedProperty = parseSchema(propJsonSchema, propCtx);
45 + // A permissive property (`$ref`, typeless constraints) already carries the
46 + // identical guard from the permissive branch of `selectParser`; attaching
47 + // again would run two full interpretations of the document per parse. A
48 + // `parserOverride` result skips `selectParser`, so with an override in
49 + // play the property keeps its own guard.
50 + const carriesGuard =
51 + ctx.parserOverride === undefined && requiresPermissiveMaterialization(propJsonSchema);
52 + const propZodSchema =
53 + requiresWholeSchemaValidation(propJsonSchema) && !carriesGuard
54 + ? backend.attachGuard(
55 + parsedProperty,
56 + createWholeSchemaGuard(guardSchemaAt(propJsonSchema, propCtx))
57 + )
58 + : parsedProperty;
59
60 const required = Array.isArray(objectSchema.required)
61 ? objectSchema.required.includes(key)
62 : false;
63
48 - // Handle default values for optional properties
49 - if (
50 - !required &&
51 - propJsonSchema &&
52 - typeof propJsonSchema === 'object' &&
53 - 'default' in propJsonSchema
54 - ) {
55 - // If default is null, make the field nullable with the null default
56 - // But don't make it nullable if it's already an anyOf/oneOf that includes null
57 - if (propJsonSchema.default === null) {
58 - const hasAnyOfWithNull =
59 - propJsonSchema.anyOf &&
60 - Array.isArray(propJsonSchema.anyOf) &&
61 - propJsonSchema.anyOf.some(
62 - (schema: JsonSchema) =>
63 - typeof schema === 'object' && schema !== null && schema.type === 'null'
64 - );
65 - const hasOneOfWithNull =
66 - propJsonSchema.oneOf &&
67 - Array.isArray(propJsonSchema.oneOf) &&
68 - propJsonSchema.oneOf.some(
69 - (schema: JsonSchema) =>
70 - typeof schema === 'object' && schema !== null && schema.type === 'null'
71 - );
72 - const isNullable =
73 - 'nullable' in propJsonSchema &&
74 - (propJsonSchema as JsonSchemaObject & { nullable?: boolean }).nullable === true;
75 -
76 - if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) {
77 - // The schema already handles null through anyOf/oneOf/nullable, just make it optional with default
78 - properties[key] = propZodSchema.optional().default(null);
79 - } else {
80 - // Make the field nullable with the null default
81 - properties[key] = propZodSchema.nullable().optional().default(null);
82 - }
83 - } else {
84 - properties[key] = propZodSchema.optional().default(propJsonSchema.default);
85 - }
86 - } else {
87 - properties[key] = required ? propZodSchema : propZodSchema.optional();
88 - }
64 + properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required);
65 }
66
67 return properties;
ts/packages/json-schema-to-zod/src/parsers/parse-object.ts
+67 -106
@@ -1,10 +1,10 @@
1 -import * as z from 'zod/v3';
2 -
1 import { parseAllOf } from './parse-all-of';
2 import { parseAnyOf } from './parse-any-of';
3 import { parseOneOf } from './parse-one-of';
4 import { parseSchema } from './parse-schema';
7 -import type { JsonSchemaObject, Refs, JsonSchema } from '../types';
5 +import { applyPropertyPresence } from './property-presence';
6 +import type { ParseContext } from '../context';
7 +import type { JsonSchemaObject } from '../types';
8 import { compilePattern } from '../utils/compile-pattern';
9 import { its } from '../utils/its';
10
@@ -19,7 +19,10 @@ import { its } from '../utils/its';
19 * is the defect it was masking, and the OpenAI provider suite is part of this
20 * package's verification precisely so the claim stays checked.
21 */
22 -function parseObjectProperties(objectSchema: JsonSchemaObject & { type?: 'object' }, refs: Refs) {
22 +function parseObjectProperties<S>(
23 + objectSchema: JsonSchemaObject & { type?: 'object' },
24 + ctx: ParseContext<S>
25 +): Record<string, S> | undefined {
26 if (!objectSchema.properties) {
27 return undefined;
28 }
@@ -29,64 +32,25 @@ function parseObjectProperties(objectSchema: JsonSchemaObject & { type?: 'object
32 return undefined;
33 }
34
32 - const properties: Record<string, z.ZodTypeAny> = {};
35 + const { backend } = ctx;
36 + const properties: Record<string, S> = {};
37
38 for (const key of propertyKeys) {
39 const propJsonSchema = objectSchema.properties[key];
40
41 const propZodSchema = parseSchema(propJsonSchema, {
38 - ...refs,
39 - path: [...refs.path, 'properties', key],
42 + ...ctx,
43 + path: [...ctx.path, 'properties', key],
44 });
45
46 const required = Array.isArray(objectSchema.required)
47 ? objectSchema.required.includes(key)
48 : false;
49
46 - // Handle default values for optional properties
47 - if (
48 - !required &&
49 - propJsonSchema &&
50 - typeof propJsonSchema === 'object' &&
51 - 'default' in propJsonSchema
52 - ) {
53 - // If default is null, make the field nullable with the null default
54 - // But don't make it nullable if it's already an anyOf/oneOf that includes null
55 - if (propJsonSchema.default === null) {
56 - const hasAnyOfWithNull =
57 - propJsonSchema.anyOf &&
58 - Array.isArray(propJsonSchema.anyOf) &&
59 - propJsonSchema.anyOf.some(
60 - (schema: JsonSchema) =>
61 - typeof schema === 'object' && schema !== null && schema.type === 'null'
62 - );
63 - const hasOneOfWithNull =
64 - propJsonSchema.oneOf &&
65 - Array.isArray(propJsonSchema.oneOf) &&
66 - propJsonSchema.oneOf.some(
67 - (schema: JsonSchema) =>
68 - typeof schema === 'object' && schema !== null && schema.type === 'null'
69 - );
70 - const isNullable =
71 - 'nullable' in propJsonSchema &&
72 - (propJsonSchema as JsonSchemaObject & { nullable?: boolean }).nullable === true;
73 -
74 - if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) {
75 - // The schema already handles null through anyOf/oneOf/nullable, just make it optional with default
76 - properties[key] = propZodSchema.optional().default(null);
77 - } else {
78 - // Make the field nullable with the null default
79 - properties[key] = propZodSchema.nullable().optional().default(null);
80 - }
81 - } else {
82 - properties[key] = propZodSchema.optional().default(propJsonSchema.default);
83 - }
84 - } else {
85 - properties[key] = required ? propZodSchema : propZodSchema.optional();
86 - }
50 + properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required);
51 }
52
89 - return z.object(properties);
53 + return properties;
54 }
55
56 /**
@@ -97,34 +61,35 @@ function parseObjectProperties(objectSchema: JsonSchemaObject & { type?: 'object
61 * property claims the key. A catch-all union would instead let a key sneak past
62 * its own pattern by satisfying an unrelated one.
63 */
100 -function parseDynamicKeyObject(
64 +function parseDynamicKeyObject<S>(
65 normalizedSchema: JsonSchemaObject & { type?: 'object' },
102 - propertiesSchema: z.ZodObject<Record<string, z.ZodTypeAny>, 'strip', z.ZodTypeAny> | undefined,
103 - additionalProperties: z.ZodTypeAny | undefined,
104 - refs: Refs
105 -): z.ZodTypeAny {
66 + shape: Record<string, S> | undefined,
67 + additionalProperties: S | undefined,
68 + ctx: ParseContext<S>
69 +): S {
70 + const { backend } = ctx;
71 const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(
72 ([pattern, schema]) => ({
108 - regex: compilePattern('patternProperties', pattern, refs),
73 + regex: compilePattern('patternProperties', pattern, ctx),
74 parser: parseSchema(schema, {
110 - ...refs,
111 - path: [...refs.path, 'patternProperties', pattern],
75 + ...ctx,
76 + path: [...ctx.path, 'patternProperties', pattern],
77 }),
78 })
79 );
80
81 const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
82 const rejectsUnmatched =
118 - additionalProperties instanceof z.ZodNever ||
83 + (additionalProperties !== undefined && backend.isNever(additionalProperties)) ||
84 (additionalProperties === undefined && declaredKeys.size > 0);
85 const validatesUnmatched =
86 additionalProperties !== undefined &&
122 - !(additionalProperties instanceof z.ZodNever) &&
87 + !backend.isNever(additionalProperties) &&
88 normalizedSchema.additionalProperties !== true;
89
125 - const base = (propertiesSchema ?? z.object({})).passthrough();
90 + const base = backend.object(shape ?? {}, { kind: 'loose' });
91
127 - return base.transform((value: Record<string, unknown>, ctx) => {
92 + return backend.rewrite<Record<string, unknown>>(base, (value, issues) => {
93 const result: Record<string, unknown> = { ...value };
94 const unrecognizedKeys: string[] = [];
95
@@ -132,13 +97,11 @@ function parseDynamicKeyObject(
97 const matching = patterns.filter(({ regex }) => regex.test(key));
98
99 for (const { parser } of matching) {
135 - const parsed = parser.safeParse(value[key]);
100 + const parsed = backend.run(parser, value[key]);
101 if (!parsed.success) {
137 - ctx.addIssue({
138 - path: [...ctx.path, key],
139 - code: 'custom',
140 - message: `Invalid input: key "${key}" must match its patternProperties schema`,
141 - params: { issues: parsed.error.issues },
102 + issues.custom(`Invalid input: key "${key}" must match its patternProperties schema`, {
103 + path: [key],
104 + params: { issues: parsed.failure.issues },
105 });
106 } else if (!declaredKeys.has(key)) {
107 result[key] = parsed.data;
@@ -152,13 +115,11 @@ function parseDynamicKeyObject(
115 if (rejectsUnmatched) {
116 unrecognizedKeys.push(key);
117 } else if (validatesUnmatched) {
155 - const parsed = additionalProperties!.safeParse(value[key]);
118 + const parsed = backend.run(additionalProperties!, value[key]);
119 if (!parsed.success) {
157 - ctx.addIssue({
158 - path: [...ctx.path, key],
159 - code: 'custom',
160 - message: `Invalid input: key "${key}" must match the additionalProperties schema`,
161 - params: { issues: parsed.error.issues },
120 + issues.custom(`Invalid input: key "${key}" must match the additionalProperties schema`, {
121 + path: [key],
122 + params: { issues: parsed.failure.issues },
123 });
124 } else {
125 result[key] = parsed.data;
@@ -167,81 +128,79 @@ function parseDynamicKeyObject(
128 }
129
130 if (unrecognizedKeys.length > 0) {
170 - ctx.addIssue({
171 - path: [...ctx.path],
172 - code: 'unrecognized_keys',
173 - keys: unrecognizedKeys,
174 - message: `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`,
175 - });
131 + issues.unrecognizedKeys(
132 + unrecognizedKeys,
133 + `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`
134 + );
135 }
136
137 return result;
138 });
139 }
140
182 -export function parseObject(
141 +export function parseObject<S>(
142 objectSchema: JsonSchemaObject & { type?: 'object' },
184 - refs: Refs
185 -): z.ZodTypeAny {
143 + ctx: ParseContext<S>
144 +): S {
145 + const { backend } = ctx;
146 const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
147
148 // Ensure type is set to 'object' if not already
149 const normalizedSchema =
150 objectSchema.type === 'object' ? objectSchema : { ...objectSchema, type: 'object' as const };
151
192 - const propertiesSchema:
193 - z.ZodObject<Record<string, z.ZodTypeAny>, 'strip', z.ZodTypeAny> | undefined =
194 - parseObjectProperties(normalizedSchema, refs);
152 + const shape = parseObjectProperties(normalizedSchema, ctx);
153
154 const additionalProperties =
155 normalizedSchema.additionalProperties !== undefined
156 ? parseSchema(normalizedSchema.additionalProperties, {
199 - ...refs,
200 - path: [...refs.path, 'additionalProperties'],
157 + ...ctx,
158 + path: [...ctx.path, 'additionalProperties'],
159 })
160 : undefined;
161
162 // Track if additionalProperties was explicitly set to true
163 const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
164
207 - let output: z.ZodTypeAny;
165 + let output: S;
166 if (hasPatternProperties) {
209 - output = parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs);
210 - } else if (propertiesSchema) {
167 + output = parseDynamicKeyObject(normalizedSchema, shape, additionalProperties, ctx);
168 + } else if (shape) {
169 if (additionalProperties) {
212 - if (additionalProperties instanceof z.ZodNever) {
213 - output = propertiesSchema.strict();
170 + if (backend.isNever(additionalProperties)) {
171 + output = backend.object(shape, { kind: 'strict' });
172 } else if (isAdditionalPropertiesTrue) {
173 // When additionalProperties was explicitly true, use passthrough
216 - output = propertiesSchema.passthrough();
174 + output = backend.object(shape, { kind: 'loose' });
175 } else {
218 - output = propertiesSchema.catchall(additionalProperties);
176 + output = backend.object(shape, { kind: 'catchall', schema: additionalProperties });
177 }
178 } else {
179 // Named properties with an omitted `additionalProperties` stay strict for
180 // tool inputs, even though JSON Schema itself would allow unknown keys.
223 - output = propertiesSchema.strict();
181 + output = backend.object(shape, { kind: 'strict' });
182 }
183 } else {
184 if (additionalProperties) {
227 - if (additionalProperties instanceof z.ZodNever) {
185 + if (backend.isNever(additionalProperties)) {
186 // When additionalProperties is false, create strict empty object
229 - output = z.object({}).strict();
187 + output = backend.object({}, { kind: 'strict' });
188 } else if (isAdditionalPropertiesTrue) {
189 // When additionalProperties was explicitly true, use empty object with passthrough
232 - output = z.object({}).passthrough();
190 + output = backend.object({}, { kind: 'loose' });
191 } else {
234 - output = z.record(additionalProperties);
192 + output = backend.record(additionalProperties);
193 }
194 } else {
195 // A property-less object with no `additionalProperties` keyword is open:
196 // arbitrary content is accepted and preserved verbatim.
239 - output = z.object({}).passthrough();
197 + output = backend.object({}, { kind: 'loose' });
198 }
199 }
200
201 if (its.an.anyOf(objectSchema)) {
244 - output = output.and(
202 + output = backend.intersection(
203 + output,
204 parseAnyOf(
205 {
206 ...objectSchema,
@@ -253,13 +212,14 @@ export function parseObject(
212 : x
213 ),
214 },
256 - refs
215 + ctx
216 )
217 );
218 }
219
220 if (its.a.oneOf(objectSchema)) {
262 - output = output.and(
221 + output = backend.intersection(
222 + output,
223 parseOneOf(
224 {
225 ...objectSchema,
@@ -271,13 +231,14 @@ export function parseObject(
231 : x
232 ),
233 },
274 - refs
234 + ctx
235 )
236 );
237 }
238
239 if (its.an.allOf(objectSchema)) {
280 - output = output.and(
240 + output = backend.intersection(
241 + output,
242 parseAllOf(
243 {
244 ...objectSchema,
@@ -289,7 +250,7 @@ export function parseObject(
250 : x
251 ),
252 },
292 - refs
253 + ctx
254 )
255 );
256 }
ts/packages/json-schema-to-zod/src/parsers/parse-one-of.ts
+19 -21
@@ -1,41 +1,39 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseSchema } from './parse-schema';
4 -import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
2 +import type { RunFailure } from '../backend/types';
3 +import type { ParseContext } from '../context';
4 +import type { JsonSchemaObject, JsonSchema } from '../types';
5
6 -export const parseOneOf = (jsonSchema: JsonSchemaObject & { oneOf: JsonSchema[] }, refs: Refs) => {
6 +export const parseOneOf = <S>(
7 + jsonSchema: JsonSchemaObject & { oneOf: JsonSchema[] },
8 + ctx: ParseContext<S>
9 +): S => {
10 + const { backend } = ctx;
11 if (!jsonSchema.oneOf.length) {
8 - return z.any();
12 + return backend.any();
13 }
14
15 if (jsonSchema.oneOf.length === 1) {
16 return parseSchema(jsonSchema.oneOf[0], {
13 - ...refs,
14 - path: [...refs.path, 'oneOf', 0],
17 + ...ctx,
18 + path: [...ctx.path, 'oneOf', 0],
19 });
20 }
21
18 - return z.any().superRefine((x, ctx) => {
22 + return backend.superRefine<unknown>(backend.any(), (x, issues) => {
23 const schemas = jsonSchema.oneOf.map((schema, i) =>
24 parseSchema(schema, {
21 - ...refs,
22 - path: [...refs.path, 'oneOf', i],
25 + ...ctx,
26 + path: [...ctx.path, 'oneOf', i],
27 })
28 );
29
26 - const unionErrors = schemas.reduce<z.ZodError[]>(
27 - (errors, schema) =>
28 - (result => (result.error ? [...errors, result.error] : errors))(schema.safeParse(x)),
29 - []
30 - );
30 + const unionErrors = schemas.reduce<RunFailure[]>((errors, schema) => {
31 + const result = backend.run(schema, x);
32 + return result.success ? errors : [...errors, result.failure];
33 + }, []);
34
35 if (schemas.length - unionErrors.length !== 1) {
33 - ctx.addIssue({
34 - path: ctx.path,
35 - code: 'invalid_union',
36 - unionErrors,
37 - message: 'Invalid input: Should pass single schema',
38 - });
36 + issues.invalidUnion('Invalid input: Should pass single schema', unionErrors);
37 }
38 });
39 };
ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
+54 -76
@@ -1,5 +1,3 @@
1 -import * as z from 'zod/v3';
2 -
1 import { parseAllOf } from './parse-all-of';
2 import { parseAnyOf } from './parse-any-of';
3 import { parseArray } from './parse-array';
@@ -20,55 +18,33 @@ import {
18 hasTypelessScalarConstraints,
19 parseTypelessConstraints,
20 } from './parse-typeless-constraints';
23 -import type { ParserSelector, Refs, JsonSchemaObject, JsonSchema } from '../types';
21 +import { collectAnnotations, describeText } from '../annotations';
22 +import type { ParseContext } from '../context';
23 +import type { JsonSchemaObject, JsonSchema } from '../types';
24 import { its } from '../utils/its';
25 import {
26 + createWholeSchemaGuard,
27 guardSchemaAt,
28 requiresPermissiveMaterialization,
28 - withWholeSchemaValidation,
29 } from '../whole-schema-validation';
30
31 -const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
32 - let description = '';
33 -
34 - if (jsonSchema.description) {
35 - description = jsonSchema.description;
36 - } else if (jsonSchema.title) {
37 - description = jsonSchema.title;
38 - }
39 -
40 - // Append example(s) if they exist
41 - if (jsonSchema.example !== undefined) {
42 - const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
43 - description = description ? `${description}\n${exampleText}` : exampleText;
44 - } else if (jsonSchema.examples !== undefined && Array.isArray(jsonSchema.examples)) {
45 - const examples = jsonSchema.examples;
46 - if (examples.length > 0) {
47 - const exampleText =
48 - examples.length === 1
49 - ? `Example: ${JSON.stringify(examples[0])}`
50 - : `Examples:\n${examples.map((ex: unknown) => ` ${JSON.stringify(ex)}`).join('\n')}`;
51 - description = description ? `${description}\n${exampleText}` : exampleText;
52 - }
53 - }
31 +const addDecorations = <S>(jsonSchema: JsonSchemaObject, zodSchema: S, ctx: ParseContext<S>): S => {
32 + const description = ctx.withoutDescribes ? undefined : describeText(jsonSchema);
33 + const annotations = ctx.withoutAnnotations ? undefined : collectAnnotations(jsonSchema);
34
55 - if (description) {
56 - zodSchema = zodSchema.describe(description);
35 + if (description === undefined && annotations === undefined) {
36 + return zodSchema;
37 }
38
59 - return zodSchema;
39 + return ctx.backend.decorate(zodSchema, { description, annotations });
40 };
41
62 -const addDefaults = (
63 - jsonSchema: JsonSchemaObject,
64 - zodSchema: z.ZodTypeAny,
65 - refs?: Refs
66 -): z.ZodTypeAny => {
42 +const addDefaults = <S>(jsonSchema: JsonSchemaObject, zodSchema: S, ctx: ParseContext<S>): S => {
43 if (jsonSchema.default !== undefined) {
44 // Don't apply null defaults to non-nullable types within anyOf/oneOf contexts
45 if (jsonSchema.default === null) {
46 // Check if we're in an anyOf/oneOf context by examining the path
71 - const inAnyOfOrOneOf = refs?.path.some(segment => segment === 'anyOf' || segment === 'oneOf');
47 + const inAnyOfOrOneOf = ctx.path.some(segment => segment === 'anyOf' || segment === 'oneOf');
48
49 // If we're in anyOf/oneOf and this is a non-nullable type, skip the default
50 if (
@@ -82,107 +58,109 @@ const addDefaults = (
58 }
59 }
60
85 - zodSchema = zodSchema.default(jsonSchema.default);
61 + return ctx.backend.withDefault(zodSchema, jsonSchema.default);
62 }
63
64 return zodSchema;
65 };
66
91 -const addAnnotations = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
67 +const addAnnotations = <S>(jsonSchema: JsonSchemaObject, zodSchema: S, ctx: ParseContext<S>): S => {
68 if (jsonSchema.readOnly) {
93 - zodSchema = zodSchema.readonly();
69 + return ctx.backend.readonly(zodSchema);
70 }
71
72 return zodSchema;
73 };
74
99 -const selectParser: ParserSelector = (schema, refs) => {
75 +const selectParser = <S>(schema: JsonSchemaObject, ctx: ParseContext<S>): S => {
76 if (requiresPermissiveMaterialization(schema)) {
77 // Widen only this node, and let it guard itself so combinators such as
78 // `oneOf` still discriminate between branches that were widened.
103 - return withWholeSchemaValidation(guardSchemaAt(schema, refs), z.any());
79 + return ctx.backend.attachGuard(
80 + ctx.backend.any(),
81 + createWholeSchemaGuard(guardSchemaAt(schema, ctx))
82 + );
83 } else if (its.a.nullable(schema)) {
105 - return parseNullable(schema, refs);
84 + return parseNullable(schema, ctx);
85 } else if (its.an.enum(schema)) {
86 // `enum`/`const` intersect the declared type, so they must win over the
87 // object and array parsers or a literal object/array value is never checked.
109 - return parseEnum(schema, refs);
88 + return parseEnum(schema, ctx);
89 } else if (its.a.const(schema)) {
111 - return parseConst(schema, refs);
90 + return parseConst(schema, ctx);
91 } else if (its.an.object(schema)) {
113 - return parseObject(schema, refs);
92 + return parseObject(schema, ctx);
93 } else if (its.an.array(schema)) {
115 - return parseArray(schema, refs);
94 + return parseArray(schema, ctx);
95 } else if (its.an.anyOf(schema)) {
117 - return parseAnyOf(schema, refs);
96 + return parseAnyOf(schema, ctx);
97 } else if (its.an.allOf(schema)) {
119 - return parseAllOf(schema, refs);
98 + return parseAllOf(schema, ctx);
99 } else if (its.a.oneOf(schema)) {
121 - return parseOneOf(schema, refs);
100 + return parseOneOf(schema, ctx);
101 } else if (its.a.not(schema)) {
123 - return parseNot(schema, refs);
102 + return parseNot(schema, ctx);
103 } else if (hasTypelessScalarConstraints(schema)) {
125 - return parseTypelessConstraints(schema, refs);
104 + return parseTypelessConstraints(schema, ctx);
105 } else if (its.a.multipleType(schema)) {
127 - return parseMultipleType(schema, refs);
106 + return parseMultipleType(schema, ctx);
107 } else if (its.a.primitive(schema, 'string')) {
129 - return parseString(schema, refs);
108 + return parseString(schema, ctx);
109 } else if (its.a.primitive(schema, 'number') || its.a.primitive(schema, 'integer')) {
131 - return parseNumber(schema);
110 + return parseNumber(schema, ctx.backend);
111 } else if (its.a.primitive(schema, 'boolean')) {
133 - return parseBoolean(schema);
112 + return parseBoolean(schema, ctx);
113 } else if (its.a.primitive(schema, 'null')) {
135 - return parseNull(schema);
114 + return parseNull(schema, ctx);
115 } else if (its.a.conditional(schema)) {
137 - return parseIfThenElse(schema, refs);
116 + return parseIfThenElse(schema, ctx);
117 } else {
139 - return parseDefault(schema);
118 + return parseDefault(schema, ctx);
119 }
120 };
121
143 -export const parseSchema = (
122 +export const parseSchema = <S>(
123 jsonSchema: JsonSchema,
145 - refs: Refs = { seen: new Map(), path: [] },
124 + ctx: ParseContext<S>,
125 blockMeta?: boolean
147 -): z.ZodType => {
148 - if (typeof jsonSchema !== 'object') return jsonSchema ? z.any() : z.never();
126 +): S => {
127 + const { backend } = ctx;
128 + if (typeof jsonSchema !== 'object') return jsonSchema ? backend.any() : backend.never();
129
150 - if (refs.parserOverride) {
151 - const custom = refs.parserOverride(jsonSchema, refs);
130 + if (ctx.parserOverride) {
131 + const custom = ctx.parserOverride(jsonSchema, ctx);
132
153 - if (custom instanceof z.ZodType) {
133 + if (backend.isSchema(custom)) {
134 return custom;
135 }
136 }
137
158 - let seen = refs.seen.get(jsonSchema);
138 + let seen = ctx.seen.get(jsonSchema);
139
140 if (seen) {
141 if (seen.r !== undefined) {
142 return seen.r;
143 }
144
165 - if (refs.depth === undefined || seen.n >= refs.depth) {
166 - return z.any();
145 + if (ctx.depth === undefined || seen.n >= ctx.depth) {
146 + return backend.any();
147 }
148
149 seen.n += 1;
150 } else {
151 seen = { r: undefined, n: 0 };
172 - refs.seen.set(jsonSchema, seen);
152 + ctx.seen.set(jsonSchema, seen);
153 }
154
175 - let parsedZodSchema = selectParser(jsonSchema, refs);
155 + let parsedZodSchema = selectParser(jsonSchema, ctx);
156 if (!blockMeta) {
177 - if (!refs.withoutDescribes) {
178 - parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
179 - }
157 + parsedZodSchema = addDecorations(jsonSchema, parsedZodSchema, ctx);
158
181 - if (!refs.withoutDefaults) {
182 - parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
159 + if (!ctx.withoutDefaults) {
160 + parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, ctx);
161 }
162
185 - parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
163 + parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema, ctx);
164 }
165
166 seen.r = parsedZodSchema;
ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
+24 -42
@@ -1,41 +1,19 @@
1 -import { z } from 'zod/v3';
2 -
3 -import type { JsonSchemaObject, Refs } from '../types';
1 +import { isAssertedStringFormat } from '../annotations';
2 +import type { ParseContext } from '../context';
3 +import type { JsonSchemaObject } from '../types';
4 import { compilePattern } from '../utils/compile-pattern';
5 import { extendSchemaWithMessage } from '../utils/extend-schema';
6
7 -export const parseString = (
7 +export const parseString = <S>(
8 jsonSchema: JsonSchemaObject & { type: 'string' },
9 - refs: Pick<Refs, 'path'>
10 -) => {
11 - let zodSchema = z.string();
9 + ctx: Pick<ParseContext<S>, 'path' | 'backend'>
10 +): S => {
11 + const { backend } = ctx;
12 + let zodSchema = backend.string();
13
13 - zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, format, errorMsg) => {
14 - switch (format) {
15 - case 'email':
16 - return zs.email(errorMsg);
17 - case 'ip':
18 - return zs.ip(errorMsg);
19 - case 'ipv4':
20 - return zs.ip({ version: 'v4', message: errorMsg });
21 - case 'ipv6':
22 - return zs.ip({ version: 'v6', message: errorMsg });
23 - case 'uri':
24 - return zs.url(errorMsg);
25 - case 'uuid':
26 - return zs.uuid(errorMsg);
27 - case 'date-time':
28 - return zs.datetime({ offset: true, message: errorMsg });
29 - case 'time':
30 - return zs.time(errorMsg);
31 - case 'date':
32 - return zs.date(errorMsg);
33 - case 'duration':
34 - return zs.duration(errorMsg);
35 - default:
36 - return zs;
37 - }
38 - });
14 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, format, errorMsg) =>
15 + isAssertedStringFormat(format) ? backend.stringFormat(zs, format, errorMsg) : zs
16 + );
17
18 // `contentEncoding` names how the string encodes its bytes; only base64 is
19 // checked. Other encodings (base16, base32, quoted-printable, ...) are left
@@ -45,10 +23,10 @@ export const parseString = (
23 zodSchema,
24 jsonSchema,
25 'contentEncoding',
48 - (zs, encoding, errorMsg) => (isBase64Encoding(encoding) ? zs.base64(errorMsg) : zs)
26 + (zs, encoding, errorMsg) => (isBase64Encoding(encoding) ? backend.base64(zs, errorMsg) : zs)
27 );
28 zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'pattern', (zs, pattern, errorMsg) =>
51 - zs.regex(compilePattern('pattern', pattern, refs), errorMsg)
29 + backend.regex(zs, compilePattern('pattern', pattern, ctx), errorMsg)
30 );
31 // JSON Schema length constraints count Unicode code points, while Zod's
32 // built-in `.min()`/`.max()` count UTF-16 code units and overcount astral
@@ -68,16 +46,20 @@ export const parseString = (
46 ? jsonSchema.max
47 : undefined;
48
71 - let result: z.ZodTypeAny = zodSchema;
49 + let result = zodSchema;
50 if (minLength !== undefined) {
73 - result = result.refine(value => codePointLength(value) >= minLength, {
74 - message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)`,
75 - });
51 + result = backend.refine<string>(
52 + result,
53 + value => codePointLength(value) >= minLength,
54 + errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)`
55 + );
56 }
57 if (maxLength !== undefined) {
78 - result = result.refine(value => codePointLength(value) <= maxLength, {
79 - message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)`,
80 - });
58 + result = backend.refine<string>(
59 + result,
60 + value => codePointLength(value) <= maxLength,
61 + errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)`
62 + );
63 }
64
65 return result;
ts/packages/json-schema-to-zod/src/parsers/parse-typeless-constraints.ts
+11 -13
@@ -1,8 +1,7 @@
1 -import { z } from 'zod/v3';
2 -
1 import { parseNumber } from './parse-number';
2 import { parseString } from './parse-string';
5 -import type { JsonSchemaObject, Refs } from '../types';
3 +import type { ParseContext } from '../context';
4 +import type { JsonSchemaObject } from '../types';
5
6 const SCALAR_CONSTRAINT_KEYS = [
7 'minLength',
@@ -23,14 +22,15 @@ export const hasTypelessScalarConstraints = (schema: JsonSchemaObject): boolean
22 * schema declares no `type`: `{ "minLength": 2 }` restricts strings while
23 * leaving every non-string value untouched.
24 */
26 -export const parseTypelessConstraints = (
25 +export const parseTypelessConstraints = <S>(
26 schema: JsonSchemaObject,
28 - refs: Pick<Refs, 'path'>
29 -): z.ZodTypeAny => {
30 - const stringSchema = parseString({ ...schema, type: 'string' }, refs);
31 - const numberSchema = parseNumber({ ...schema, type: 'number' });
27 + ctx: Pick<ParseContext<S>, 'path' | 'backend'>
28 +): S => {
29 + const { backend } = ctx;
30 + const stringSchema = parseString({ ...schema, type: 'string' }, ctx);
31 + const numberSchema = parseNumber({ ...schema, type: 'number' }, backend);
32
33 - return z.any().superRefine((value, ctx) => {
33 + return backend.superRefine<unknown>(backend.any(), (value, issues) => {
34 const applicable =
35 typeof value === 'string'
36 ? stringSchema
@@ -39,11 +39,9 @@ export const parseTypelessConstraints = (
39 : undefined;
40 if (applicable === undefined) return;
41
42 - const result = applicable.safeParse(value);
42 + const result = backend.run(applicable, value);
43 if (!result.success) {
44 - for (const issue of result.error.issues) {
45 - ctx.addIssue(issue);
46 - }
44 + issues.forward(result.failure);
45 }
46 });
47 };
ts/packages/json-schema-to-zod/src/parsers/property-presence.ts new
+43
@@ -0,0 +1,43 @@
1 +import type { ZodBackend } from '../backend/types';
2 +import type { JsonSchema, JsonSchemaObject } from '../types';
3 +
4 +const admitsNull = (branches: JsonSchema[] | undefined): boolean =>
5 + Array.isArray(branches) &&
6 + branches.some(
7 + (schema: JsonSchema) => typeof schema === 'object' && schema !== null && schema.type === 'null'
8 + );
9 +
10 +/**
11 + * Wraps a parsed property for its place in an object: required properties
12 + * stay as parsed, optional ones become optional, and an optional property
13 + * with a `default` carries it. A `null` default makes the property nullable
14 + * unless its schema already admits `null` through `anyOf`, `oneOf`, or
15 + * `nullable`.
16 + */
17 +export const applyPropertyPresence = <S>(
18 + backend: ZodBackend<S>,
19 + propJsonSchema: JsonSchema,
20 + parsed: S,
21 + required: boolean
22 +): S => {
23 + if (
24 + !required &&
25 + propJsonSchema &&
26 + typeof propJsonSchema === 'object' &&
27 + 'default' in propJsonSchema
28 + ) {
29 + if (propJsonSchema.default === null) {
30 + const isNullable =
31 + 'nullable' in propJsonSchema &&
32 + (propJsonSchema as JsonSchemaObject & { nullable?: boolean }).nullable === true;
33 +
34 + if (admitsNull(propJsonSchema.anyOf) || admitsNull(propJsonSchema.oneOf) || isNullable) {
35 + return backend.withDefault(backend.optional(parsed), null);
36 + }
37 + return backend.withDefault(backend.optional(backend.nullable(parsed)), null);
38 + }
39 + return backend.withDefault(backend.optional(parsed), propJsonSchema.default);
40 + }
41 +
42 + return required ? parsed : backend.optional(parsed);
43 +};
ts/packages/json-schema-to-zod/src/types.ts
+10 -13
@@ -1,6 +1,8 @@
1 import type { ZodTypeAny } from 'zod/v3';
2 import type { JSONSchema7 } from 'json-schema';
3
4 +import type { OptionsOf, ParserOverrideOf, RefsOf } from './context';
5 +
6 export type Serializable =
7 { [key: string]: Serializable } | Serializable[] | string | number | boolean | null;
8
@@ -27,10 +29,15 @@ export interface JsonSchemaObject extends Omit<
29 | 'oneOf'
30 | 'not'
31 | 'definitions'
32 + | 'exclusiveMinimum'
33 + | 'exclusiveMaximum'
34 > {
35 min?: number;
36 max?: number;
37 example?: Serializable;
38 + /** Draft 4/OpenAPI boolean spellings ride beside the Draft 7 numeric ones. */
39 + exclusiveMinimum?: number | boolean;
40 + exclusiveMaximum?: number | boolean;
41
42 $defs?: JsonSchemaDefinitions;
43 definitions?: JsonSchemaDefinitions;
@@ -51,18 +58,8 @@ export interface JsonSchemaObject extends Omit<
58 not?: JsonSchema;
59 }
60 export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny;
54 -export type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny | undefined;
61 +export type ParserOverride = ParserOverrideOf<ZodTypeAny>;
62
56 -export type JsonSchemaToZodOptions = {
57 - withoutDefaults?: boolean;
58 - withoutDescribes?: boolean;
59 - parserOverride?: ParserOverride;
60 - depth?: number;
61 -};
63 +export type JsonSchemaToZodOptions = OptionsOf<ZodTypeAny>;
64
63 -export type Refs = JsonSchemaToZodOptions & {
64 - path: Array<string | number>;
65 - seen: Map<object | boolean, { n: number; r: ZodTypeAny | undefined }>;
66 - /** The document that local `$ref` pointers resolve against. */
67 - root?: JsonSchema;
68 -};
65 +export type Refs = RefsOf<ZodTypeAny>;
ts/packages/json-schema-to-zod/src/utils/compile-pattern.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import type { Refs } from '../types';
1 +import type { RefsOf } from '../context';
2 import { createPatternMatcher, patternMatches, type PatternMatcher } from './linear-pattern';
3
4 /**
@@ -98,7 +98,7 @@ export class SchemaPatternRegExp extends RegExp {
98 export const compilePattern = (
99 keyword: 'pattern' | 'patternProperties',
100 pattern: string,
101 - refs: Pick<Refs, 'path'>
101 + refs: Pick<RefsOf<unknown>, 'path'>
102 ): SchemaPatternRegExp => {
103 const path = keyword === 'pattern' ? refs.path : [...refs.path, 'patternProperties', pattern];
104
ts/packages/json-schema-to-zod/src/utils/extend-schema.ts
+1 -3
@@ -1,9 +1,7 @@
1 -import type { z } from 'zod/v3';
2 -
1 import type { JsonSchemaObject } from '../types';
2
3 export function extendSchemaWithMessage<
6 - TZod extends z.ZodTypeAny,
4 + TZod,
5 TJson extends JsonSchemaObject,
6 TKey extends keyof TJson,
7 >(
ts/packages/json-schema-to-zod/src/v4.ts new
+40
@@ -0,0 +1,40 @@
1 +import type { ZodType } from 'zod/v4';
2 +import { version } from 'zod/v4/core';
3 +
4 +import { zodV4Backend } from './backend/zod-v4';
5 +import { ZOD_V4_FLOOR, formatZodVersion, meetsZodV4Floor } from './backend/zod-v4-floor';
6 +import type { OptionsOf, ParserOverrideOf, RefsOf } from './context';
7 +import { createConverter } from './convert';
8 +import type { JsonSchema, JsonSchemaObject } from './types';
9 +
10 +export type { Serializable, JsonSchema, JsonSchemaObject } from './types';
11 +export { InvalidPatternError, type InvalidPatternReason } from './utils/compile-pattern';
12 +
13 +if (!meetsZodV4Floor(version)) {
14 + throw new Error(
15 + `@composio/json-schema-to-zod/v4 requires zod >= ${formatZodVersion(ZOD_V4_FLOOR)}; found ${formatZodVersion(version)}`
16 + );
17 +}
18 +
19 +export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodType;
20 +export type ParserOverride = ParserOverrideOf<ZodType>;
21 +export type JsonSchemaToZodOptions = OptionsOf<ZodType> & {
22 + /** Leave out the forwarded `format`, `contentEncoding`, `contentMediaType`, and integer annotations. */
23 + withoutAnnotations?: boolean;
24 +};
25 +export type Refs = RefsOf<ZodType>;
26 +
27 +/** A raw shape over zod v4 schemas, for APIs that take a shape rather than an object schema. */
28 +export type SimpleZodRawShape = Record<string, ZodType>;
29 +
30 +const converter = createConverter(zodV4Backend);
31 +
32 +export const jsonSchemaToZod = (
33 + schema: JsonSchema,
34 + options: JsonSchemaToZodOptions = {}
35 +): ZodType => converter.jsonSchemaToZod(schema, options);
36 +
37 +export const jsonSchemaToZodShape = (
38 + schema: JsonSchema,
39 + options: JsonSchemaToZodOptions = {}
40 +): SimpleZodRawShape => converter.jsonSchemaToZodShape(schema, options);
ts/packages/json-schema-to-zod/src/whole-schema-validation.ts
+10 -57
@@ -7,8 +7,8 @@ import {
7 Validator,
8 } from '@cfworker/json-schema';
9 import type { Schema as InterpreterSchema } from '@cfworker/json-schema';
10 -import { z } from 'zod/v3';
10
11 +import type { WholeSchemaGuard } from './backend/types';
12 import type { JsonSchema, JsonSchemaObject } from './types';
13 import { InvalidPatternError } from './utils/compile-pattern';
14 import { createPatternMatcher, patternMatches, type PatternMatcher } from './utils/linear-pattern';
@@ -564,49 +564,6 @@ const prepareInterpreterSchema = (
564 }
565 };
566
567 -type WholeSchemaGuard = (value: unknown) => string | undefined;
568 -type GuardedDef = z.ZodTypeDef & { wholeSchemaGuard?: WholeSchemaGuard };
569 -type ZodSchemaClass = {
570 - new (def: z.ZodTypeDef): z.ZodTypeAny;
571 - prototype: z.ZodTypeAny;
572 -};
573 -
574 -const guardedSchemaClasses = new WeakMap<ZodSchemaClass, ZodSchemaClass>();
575 -
576 -/**
577 - * A subclass of the parsed schema's own class that checks the source value
578 - * against the guard before parsing it. Keeping the class, rather than wrapping
579 - * it in a pipeline, keeps the schema's kind: a guarded object is still a
580 - * `ZodObject` with a `shape`, which is what zod-to-json-schema and the MCP SDK
581 - * need to emit a root `type: "object"` for LLM tool parameters. The guard lives
582 - * on `_def`, so copies such as `.describe()` keep it.
583 - */
584 -const guardedSchemaClass = (Base: ZodSchemaClass): ZodSchemaClass => {
585 - const cached = guardedSchemaClasses.get(Base);
586 - if (cached) {
587 - return cached;
588 - }
589 -
590 - const parseAsBase = Base.prototype._parse;
591 - class Guarded extends Base {
592 - override _parse(input: z.ParseInput): z.ParseReturnType<unknown> {
593 - const failure = (this._def as GuardedDef).wholeSchemaGuard?.(input.data);
594 - if (failure === undefined) {
595 - return parseAsBase.call(this, input);
596 - }
597 - z.addIssueToContext(this._getOrReturnCtx(input), {
598 - code: z.ZodIssueCode.custom,
599 - message: failure,
600 - });
601 - return z.DIRTY(input.data);
602 - }
603 - }
604 - guardedSchemaClasses.set(Base, Guarded);
605 - // Guarding an already guarded schema reuses its class and composes guards.
606 - guardedSchemaClasses.set(Guarded, Guarded);
607 - return Guarded;
608 -};
609 -
567 type PreparedInterpreter = {
568 validator: Validator;
569 formats: PatternFormats;
@@ -614,10 +571,13 @@ type PreparedInterpreter = {
571 renamed: ReadonlyMap<string, string>;
572 };
573
617 -export const withWholeSchemaValidation = (
618 - jsonSchema: JsonSchema,
619 - parsedSchema: z.ZodTypeAny
620 -): z.ZodTypeAny => {
574 +/**
575 + * The Draft 7 guard for `jsonSchema`: validates a source value against the
576 + * complete schema with the interpreter, with patterns spelled as the native
577 + * parsers match them. The backend attaches it to the parsed schema so it runs
578 + * before defaults and other transforms.
579 + */
580 +export const createWholeSchemaGuard = (jsonSchema: JsonSchema): WholeSchemaGuard => {
581 const patternMatchers = new Map<string, PatternMatcher>();
582 const originalNodes = [...interpreterSchemaNodes(jsonSchema)];
583 const schemaObjects = new WeakSet(originalNodes.map(node => node.value));
@@ -672,11 +632,7 @@ export const withWholeSchemaValidation = (
632 });
633 };
634
675 - // Validate the source value before defaults and other Zod transforms run.
676 - // Otherwise a missing required field can be synthesized and incorrectly
677 - // appear valid to the JSON Schema interpreter.
678 - const innerGuard = (parsedSchema._def as GuardedDef).wholeSchemaGuard;
679 - const wholeSchemaGuard: WholeSchemaGuard = value => {
635 + return value => {
636 // The interpreter only reads formats from its process-wide table. This
637 // guard's pattern formats live there only for this synchronous call, so
638 // the table does not grow with every distinct pattern ever converted.
@@ -704,9 +660,6 @@ export const withWholeSchemaValidation = (
660 });
661 return error;
662 }
707 - return innerGuard?.(value);
663 + return undefined;
664 };
709 -
710 - const Guarded = guardedSchemaClass(parsedSchema.constructor as ZodSchemaClass);
711 - return new Guarded({ ...parsedSchema._def, wholeSchemaGuard } as GuardedDef);
665 };
ts/packages/json-schema-to-zod/test/__snapshots__/v3-output-fingerprint.test.ts.snap new
+7481
@@ -0,0 +1,7481 @@
1 +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2 +
3 +exports[`v3 output fingerprint > matches the pinned snapshot for the local cases 1`] = `
4 +[
5 + {
6 + "fingerprint": {
7 + "def": {
8 + "catchall": {
9 + "typeName": "ZodNever",
10 + },
11 + "shape": {
12 + "aliases": {
13 + "innerType": {
14 + "effect": "refinement",
15 + "schema": {
16 + "effect": "refinement",
17 + "schema": {
18 + "checks": [],
19 + "typeName": "ZodString",
20 + },
21 + "typeName": "ZodEffects",
22 + },
23 + "typeName": "ZodEffects",
24 + },
25 + "typeName": "ZodOptional",
26 + },
27 + "base64": {
28 + "innerType": {
29 + "checks": [
30 + {
31 + "kind": "base64",
32 + },
33 + ],
34 + "typeName": "ZodString",
35 + },
36 + "typeName": "ZodOptional",
37 + },
38 + "binary": {
39 + "innerType": {
40 + "checks": [],
41 + "typeName": "ZodString",
42 + },
43 + "typeName": "ZodOptional",
44 + },
45 + "byte": {
46 + "innerType": {
47 + "checks": [],
48 + "typeName": "ZodString",
49 + },
50 + "typeName": "ZodOptional",
51 + },
52 + "date": {
53 + "innerType": {
54 + "checks": [
55 + {
56 + "kind": "date",
57 + "message": undefined,
58 + },
59 + ],
60 + "typeName": "ZodString",
61 + },
62 + "typeName": "ZodOptional",
63 + },
64 + "dateTime": {
65 + "innerType": {
66 + "checks": [
67 + {
68 + "kind": "datetime",
69 + "local": false,
70 + "offset": true,
71 + "precision": null,
72 + },
73 + ],
74 + "typeName": "ZodString",
75 + },
76 + "typeName": "ZodOptional",
77 + },
78 + "duration": {
79 + "innerType": {
80 + "checks": [
81 + {
82 + "kind": "duration",
83 + },
84 + ],
85 + "typeName": "ZodString",
86 + },
87 + "typeName": "ZodOptional",
88 + },
89 + "email": {
90 + "checks": [
91 + {
92 + "kind": "email",
93 + },
94 + ],
95 + "typeName": "ZodString",
96 + },
97 + "hex": {
98 + "innerType": {
99 + "checks": [],
100 + "typeName": "ZodString",
101 + },
102 + "typeName": "ZodOptional",
103 + },
104 + "ip": {
105 + "innerType": {
106 + "checks": [
107 + {
108 + "kind": "ip",
109 + },
110 + ],
111 + "typeName": "ZodString",
112 + },
113 + "typeName": "ZodOptional",
114 + },
115 + "ipv4": {
116 + "innerType": {
117 + "checks": [
118 + {
119 + "kind": "ip",
120 + "message": undefined,
121 + "version": "v4",
122 + },
123 + ],
124 + "typeName": "ZodString",
125 + },
126 + "typeName": "ZodOptional",
127 + },
128 + "ipv6": {
129 + "innerType": {
130 + "checks": [
131 + {
132 + "kind": "ip",
133 + "message": undefined,
134 + "version": "v6",
135 + },
136 + ],
137 + "typeName": "ZodString",
138 + },
139 + "typeName": "ZodOptional",
140 + },
141 + "pattern": {
142 + "innerType": {
143 + "effect": "refinement",
144 + "schema": {
145 + "effect": "refinement",
146 + "schema": {
147 + "checks": [
148 + {
149 + "kind": "regex",
150 + "regex": "^[a-z\\_]+$",
151 + },
152 + ],
153 + "typeName": "ZodString",
154 + },
155 + "typeName": "ZodEffects",
156 + },
157 + "typeName": "ZodEffects",
158 + },
159 + "typeName": "ZodOptional",
160 + },
161 + "time": {
162 + "innerType": {
163 + "checks": [
164 + {
165 + "kind": "time",
166 + "precision": null,
167 + },
168 + ],
169 + "typeName": "ZodString",
170 + },
171 + "typeName": "ZodOptional",
172 + },
173 + "uri": {
174 + "innerType": {
175 + "checks": [
176 + {
177 + "kind": "url",
178 + },
179 + ],
180 + "typeName": "ZodString",
181 + },
182 + "typeName": "ZodOptional",
183 + },
184 + "uuid": {
185 + "innerType": {
186 + "checks": [
187 + {
188 + "kind": "uuid",
189 + },
190 + ],
191 + "typeName": "ZodString",
192 + },
193 + "typeName": "ZodOptional",
194 + },
195 + },
196 + "typeName": "ZodObject",
197 + "unknownKeys": "strict",
198 + },
199 + "jsonSchema": {
200 + "$schema": "http://json-schema.org/draft-07/schema#",
201 + "additionalProperties": false,
202 + "properties": {
203 + "aliases": {
204 + "type": "string",
205 + },
206 + "base64": {
207 + "contentEncoding": "base64",
208 + "type": "string",
209 + },
210 + "binary": {
211 + "type": "string",
212 + },
213 + "byte": {
214 + "type": "string",
215 + },
216 + "date": {
217 + "format": "date",
218 + "type": "string",
219 + },
220 + "dateTime": {
221 + "format": "date-time",
222 + "type": "string",
223 + },
224 + "duration": {
225 + "format": "duration",
226 + "type": "string",
227 + },
228 + "email": {
229 + "format": "email",
230 + "type": "string",
231 + },
232 + "hex": {
233 + "type": "string",
234 + },
235 + "ip": {
236 + "anyOf": [
237 + {
238 + "format": "ipv4",
239 + },
240 + {
241 + "format": "ipv6",
242 + },
243 + ],
244 + "type": "string",
245 + },
246 + "ipv4": {
247 + "format": "ipv4",
248 + "type": "string",
249 + },
250 + "ipv6": {
251 + "format": "ipv6",
252 + "type": "string",
253 + },
254 + "pattern": {
255 + "pattern": "^[a-z\\_]+$",
256 + "type": "string",
257 + },
258 + "time": {
259 + "format": "time",
260 + "type": "string",
261 + },
262 + "uri": {
263 + "format": "uri",
264 + "type": "string",
265 + },
266 + "uuid": {
267 + "format": "uuid",
268 + "type": "string",
269 + },
270 + },
271 + "required": [
272 + "email",
273 + ],
274 + "type": "object",
275 + },
276 + },
277 + "id": "string-formats",
278 + },
279 + {
280 + "fingerprint": {
281 + "def": {
282 + "catchall": {
283 + "typeName": "ZodNever",
284 + },
285 + "shape": {
286 + "aliases": {
287 + "innerType": {
288 + "checks": [
289 + {
290 + "inclusive": true,
291 + "kind": "min",
292 + "message": undefined,
293 + "value": 0,
294 + },
295 + {
296 + "inclusive": true,
297 + "kind": "max",
298 + "message": undefined,
299 + "value": 1,
300 + },
301 + ],
302 + "typeName": "ZodNumber",
303 + },
304 + "typeName": "ZodOptional",
305 + },
306 + "decimal": {
307 + "innerType": {
308 + "effect": "refinement",
309 + "schema": {
310 + "checks": [],
311 + "typeName": "ZodNumber",
312 + },
313 + "typeName": "ZodEffects",
314 + },
315 + "typeName": "ZodOptional",
316 + },
317 + "draft4": {
318 + "innerType": {
319 + "checks": [
320 + {
321 + "inclusive": false,
322 + "kind": "min",
323 + "message": undefined,
324 + "value": 0,
325 + },
326 + {
327 + "inclusive": true,
328 + "kind": "max",
329 + "message": undefined,
330 + "value": 1,
331 + },
332 + ],
333 + "typeName": "ZodNumber",
334 + },
335 + "typeName": "ZodOptional",
336 + },
337 + "exclusive": {
338 + "innerType": {
339 + "checks": [
340 + {
341 + "inclusive": false,
342 + "kind": "min",
343 + "message": undefined,
344 + "value": 0,
345 + },
346 + {
347 + "inclusive": false,
348 + "kind": "max",
349 + "message": undefined,
350 + "value": 100,
351 + },
352 + ],
353 + "typeName": "ZodNumber",
354 + },
355 + "typeName": "ZodOptional",
356 + },
357 + "int64": {
358 + "innerType": {
359 + "checks": [
360 + {
361 + "kind": "int",
362 + "message": undefined,
363 + },
364 + ],
365 + "typeName": "ZodNumber",
366 + },
367 + "typeName": "ZodOptional",
368 + },
369 + "integer": {
370 + "innerType": {
371 + "checks": [
372 + {
373 + "kind": "int",
374 + "message": undefined,
375 + },
376 + {
377 + "inclusive": true,
378 + "kind": "min",
379 + "message": undefined,
380 + "value": 1,
381 + },
382 + {
383 + "inclusive": true,
384 + "kind": "max",
385 + "message": undefined,
386 + "value": 10,
387 + },
388 + ],
389 + "typeName": "ZodNumber",
390 + },
391 + "typeName": "ZodOptional",
392 + },
393 + "unit": {
394 + "innerType": {
395 + "checks": [
396 + {
397 + "kind": "int",
398 + "message": undefined,
399 + },
400 + ],
401 + "typeName": "ZodNumber",
402 + },
403 + "typeName": "ZodOptional",
404 + },
405 + },
406 + "typeName": "ZodObject",
407 + "unknownKeys": "strict",
408 + },
409 + "jsonSchema": {
410 + "$schema": "http://json-schema.org/draft-07/schema#",
411 + "additionalProperties": false,
412 + "properties": {
413 + "aliases": {
414 + "maximum": 1,
415 + "minimum": 0,
416 + "type": "number",
417 + },
418 + "decimal": {
419 + "type": "number",
420 + },
421 + "draft4": {
422 + "exclusiveMinimum": 0,
423 + "maximum": 1,
424 + "type": "number",
425 + },
426 + "exclusive": {
427 + "exclusiveMaximum": 100,
428 + "exclusiveMinimum": 0,
429 + "type": "number",
430 + },
431 + "int64": {
432 + "type": "integer",
433 + },
434 + "integer": {
435 + "maximum": 10,
436 + "minimum": 1,
437 + "type": "integer",
438 + },
439 + "unit": {
440 + "type": "integer",
441 + },
442 + },
443 + "type": "object",
444 + },
445 + },
446 + "id": "number-constraints",
447 + },
448 + {
449 + "fingerprint": {
450 + "def": {
451 + "catchall": {
452 + "typeName": "ZodNever",
453 + },
454 + "description": "A request",
455 + "guarded": true,
456 + "shape": {
457 + "anyOfNull": {
458 + "defaultValue": null,
459 + "innerType": {
460 + "innerType": {
461 + "defaultValue": null,
462 + "innerType": {
463 + "options": [
464 + {
465 + "checks": [],
466 + "typeName": "ZodString",
467 + },
468 + {
469 + "typeName": "ZodNull",
470 + },
471 + ],
472 + "typeName": "ZodUnion",
473 + },
474 + "typeName": "ZodDefault",
475 + },
476 + "typeName": "ZodOptional",
477 + },
478 + "typeName": "ZodDefault",
479 + },
480 + "defaulted": {
481 + "defaultValue": "x",
482 + "innerType": {
483 + "innerType": {
484 + "defaultValue": "x",
485 + "innerType": {
486 + "checks": [],
487 + "typeName": "ZodString",
488 + },
489 + "typeName": "ZodDefault",
490 + },
491 + "typeName": "ZodOptional",
492 + },
493 + "typeName": "ZodDefault",
494 + },
495 + "described": {
496 + "description": "Named
497 +Example: "x"",
498 + "innerType": {
499 + "checks": [],
500 + "description": "Named
501 +Example: "x"",
502 + "typeName": "ZodString",
503 + },
504 + "typeName": "ZodOptional",
505 + },
506 + "nullDefault": {
507 + "defaultValue": null,
508 + "innerType": {
509 + "innerType": {
510 + "innerType": {
511 + "defaultValue": null,
512 + "innerType": {
513 + "checks": [],
514 + "typeName": "ZodString",
515 + },
516 + "typeName": "ZodDefault",
517 + },
518 + "typeName": "ZodNullable",
519 + },
520 + "typeName": "ZodOptional",
521 + },
522 + "typeName": "ZodDefault",
523 + },
524 + "nullable": {
525 + "description": "Maybe",
526 + "innerType": {
527 + "description": "Maybe",
528 + "innerType": {
529 + "checks": [
530 + {
531 + "kind": "int",
532 + "message": undefined,
533 + },
534 + ],
535 + "typeName": "ZodNumber",
536 + },
537 + "typeName": "ZodNullable",
538 + },
539 + "typeName": "ZodOptional",
540 + },
541 + "nullableNullDefault": {
542 + "defaultValue": null,
543 + "innerType": {
544 + "innerType": {
545 + "defaultValue": null,
546 + "innerType": {
547 + "defaultValue": null,
548 + "innerType": {
549 + "innerType": {
550 + "checks": [],
551 + "typeName": "ZodString",
552 + },
553 + "typeName": "ZodNullable",
554 + },
555 + "typeName": "ZodDefault",
556 + },
557 + "typeName": "ZodDefault",
558 + },
559 + "typeName": "ZodOptional",
560 + },
561 + "typeName": "ZodDefault",
562 + },
563 + "readOnly": {
564 + "innerType": {
565 + "innerType": {
566 + "checks": [],
567 + "typeName": "ZodString",
568 + },
569 + "typeName": "ZodReadonly",
570 + },
571 + "typeName": "ZodOptional",
572 + },
573 + "titled": {
574 + "description": "Title only
575 +Examples:
576 + "a"
577 + "b"",
578 + "innerType": {
579 + "checks": [],
580 + "description": "Title only
581 +Examples:
582 + "a"
583 + "b"",
584 + "typeName": "ZodString",
585 + },
586 + "typeName": "ZodOptional",
587 + },
588 + },
589 + "typeName": "ZodObject",
590 + "unknownKeys": "strict",
591 + },
592 + "jsonSchema": {
593 + "$schema": "http://json-schema.org/draft-07/schema#",
594 + "additionalProperties": false,
595 + "description": "A request",
596 + "properties": {
597 + "anyOfNull": {
598 + "default": null,
599 + "type": [
600 + "string",
601 + "null",
602 + ],
603 + },
604 + "defaulted": {
605 + "default": "x",
606 + "type": "string",
607 + },
608 + "described": {
609 + "description": "Named
610 +Example: "x"",
611 + "type": "string",
612 + },
613 + "nullDefault": {
614 + "anyOf": [
615 + {
616 + "default": null,
617 + "type": "string",
618 + },
619 + {
620 + "type": "null",
621 + },
622 + ],
623 + "default": null,
624 + },
625 + "nullable": {
626 + "anyOf": [
627 + {
628 + "type": "integer",
629 + },
630 + {
631 + "type": "null",
632 + },
633 + ],
634 + "description": "Maybe",
635 + },
636 + "nullableNullDefault": {
637 + "default": null,
638 + "type": [
639 + "string",
640 + "null",
641 + ],
642 + },
643 + "readOnly": {
644 + "type": "string",
645 + },
646 + "titled": {
647 + "description": "Title only
648 +Examples:
649 + "a"
650 + "b"",
651 + "type": "string",
652 + },
653 + },
654 + "type": "object",
655 + },
656 + },
657 + "id": "metadata-and-wrappers",
658 + },
659 + {
660 + "fingerprint": {
661 + "def": {
662 + "catchall": {
663 + "typeName": "ZodNever",
664 + },
665 + "guarded": true,
666 + "shape": {
667 + "allOf": {
668 + "innerType": {
669 + "left": {
670 + "checks": [
671 + {
672 + "inclusive": true,
673 + "kind": "min",
674 + "message": undefined,
675 + "value": 0,
676 + },
677 + ],
678 + "typeName": "ZodNumber",
679 + },
680 + "right": {
681 + "checks": [
682 + {
683 + "inclusive": true,
684 + "kind": "max",
685 + "message": undefined,
686 + "value": 1,
687 + },
688 + ],
689 + "typeName": "ZodNumber",
690 + },
691 + "typeName": "ZodIntersection",
692 + },
693 + "typeName": "ZodOptional",
694 + },
695 + "anyOf": {
696 + "innerType": {
697 + "options": [
698 + {
699 + "checks": [],
700 + "typeName": "ZodString",
701 + },
702 + {
703 + "checks": [],
704 + "typeName": "ZodNumber",
705 + },
706 + ],
707 + "typeName": "ZodUnion",
708 + },
709 + "typeName": "ZodOptional",
710 + },
711 + "conditional": {
712 + "innerType": {
713 + "guarded": true,
714 + "typeName": "ZodAny",
715 + },
716 + "typeName": "ZodOptional",
717 + },
718 + "constObject": {
719 + "innerType": {
720 + "left": {
721 + "typeName": "ZodAny",
722 + },
723 + "right": {
724 + "effect": "refinement",
725 + "schema": {
726 + "typeName": "ZodAny",
727 + },
728 + "typeName": "ZodEffects",
729 + },
730 + "typeName": "ZodIntersection",
731 + },
732 + "typeName": "ZodOptional",
733 + },
734 + "constString": {
735 + "innerType": {
736 + "left": {
737 + "typeName": "ZodAny",
738 + },
739 + "right": {
740 + "typeName": "ZodLiteral",
741 + "value": "a",
742 + },
743 + "typeName": "ZodIntersection",
744 + },
745 + "typeName": "ZodOptional",
746 + },
747 + "enumMixed": {
748 + "innerType": {
749 + "left": {
750 + "typeName": "ZodAny",
751 + },
752 + "right": {
753 + "options": [
754 + {
755 + "typeName": "ZodLiteral",
756 + "value": "a",
757 + },
758 + {
759 + "typeName": "ZodLiteral",
760 + "value": 1,
761 + },
762 + {
763 + "typeName": "ZodLiteral",
764 + "value": true,
765 + },
766 + {
767 + "typeName": "ZodLiteral",
768 + "value": null,
769 + },
770 + ],
771 + "typeName": "ZodUnion",
772 + },
773 + "typeName": "ZodIntersection",
774 + },
775 + "typeName": "ZodOptional",
776 + },
777 + "enumObject": {
778 + "innerType": {
779 + "left": {
780 + "typeName": "ZodAny",
781 + },
782 + "right": {
783 + "effect": "refinement",
784 + "schema": {
785 + "typeName": "ZodAny",
786 + },
787 + "typeName": "ZodEffects",
788 + },
789 + "typeName": "ZodIntersection",
790 + },
791 + "typeName": "ZodOptional",
792 + },
793 + "enumStrings": {
794 + "innerType": {
795 + "left": {
796 + "checks": [],
797 + "typeName": "ZodString",
798 + },
799 + "right": {
800 + "typeName": "ZodEnum",
801 + "values": [
802 + "a",
803 + "b",
804 + ],
805 + },
806 + "typeName": "ZodIntersection",
807 + },
808 + "typeName": "ZodOptional",
809 + },
810 + "multiple": {
811 + "innerType": {
812 + "options": [
813 + {
814 + "checks": [],
815 + "typeName": "ZodString",
816 + },
817 + {
818 + "typeName": "ZodNull",
819 + },
820 + ],
821 + "typeName": "ZodUnion",
822 + },
823 + "typeName": "ZodOptional",
824 + },
825 + "not": {
826 + "innerType": {
827 + "guarded": true,
828 + "typeName": "ZodAny",
829 + },
830 + "typeName": "ZodOptional",
831 + },
832 + "oneOf": {
833 + "innerType": {
834 + "effect": "refinement",
835 + "schema": {
836 + "typeName": "ZodAny",
837 + },
838 + "typeName": "ZodEffects",
839 + },
840 + "typeName": "ZodOptional",
841 + },
842 + "typeless": {
843 + "innerType": {
844 + "effect": "refinement",
845 + "schema": {
846 + "typeName": "ZodAny",
847 + },
848 + "typeName": "ZodEffects",
849 + },
850 + "typeName": "ZodOptional",
851 + },
852 + },
853 + "typeName": "ZodObject",
854 + "unknownKeys": "strict",
855 + },
856 + "jsonSchema": {
857 + "$schema": "http://json-schema.org/draft-07/schema#",
858 + "additionalProperties": false,
859 + "properties": {
860 + "allOf": {
861 + "allOf": [
862 + {
863 + "minimum": 0,
864 + "type": "number",
865 + },
866 + {
867 + "maximum": 1,
868 + "type": "number",
869 + },
870 + ],
871 + },
872 + "anyOf": {
873 + "type": [
874 + "string",
875 + "number",
876 + ],
877 + },
878 + "conditional": {},
879 + "constObject": {
880 + "allOf": [
881 + {},
882 + {},
883 + ],
884 + },
885 + "constString": {
886 + "allOf": [
887 + {},
888 + {
889 + "const": "a",
890 + "type": "string",
891 + },
892 + ],
893 + },
894 + "enumMixed": {
895 + "allOf": [
896 + {},
897 + {
898 + "enum": [
899 + "a",
900 + 1,
901 + true,
902 + null,
903 + ],
904 + "type": [
905 + "string",
906 + "number",
907 + "boolean",
908 + "null",
909 + ],
910 + },
911 + ],
912 + },
913 + "enumObject": {
914 + "allOf": [
915 + {},
916 + {},
917 + ],
918 + },
919 + "enumStrings": {
920 + "allOf": [
921 + {
922 + "type": "string",
923 + },
924 + {
925 + "enum": [
926 + "a",
927 + "b",
928 + ],
929 + "type": "string",
930 + },
931 + ],
932 + },
933 + "multiple": {
934 + "type": [
935 + "string",
936 + "null",
937 + ],
938 + },
939 + "not": {},
940 + "oneOf": {},
941 + "typeless": {},
942 + },
943 + "type": "object",
944 + },
945 + },
946 + "id": "combinators",
947 + },
948 + {
949 + "fingerprint": {
950 + "def": {
951 + "catchall": {
952 + "typeName": "ZodNever",
953 + },
954 + "guarded": true,
955 + "shape": {
956 + "aliases": {
957 + "innerType": {
958 + "element": {
959 + "checks": [],
960 + "typeName": "ZodString",
961 + },
962 + "maxLength": {
963 + "message": undefined,
964 + "value": 3,
965 + },
966 + "minLength": {
967 + "message": undefined,
968 + "value": 1,
969 + },
970 + "typeName": "ZodArray",
971 + },
972 + "typeName": "ZodOptional",
973 + },
974 + "anyOfArray": {
975 + "innerType": {
976 + "element": {
977 + "options": [
978 + {
979 + "checks": [],
980 + "typeName": "ZodString",
981 + },
982 + {
983 + "checks": [],
984 + "typeName": "ZodNumber",
985 + },
986 + ],
987 + "typeName": "ZodUnion",
988 + },
989 + "typeName": "ZodArray",
990 + },
991 + "typeName": "ZodOptional",
992 + },
993 + "bare": {
994 + "innerType": {
995 + "element": {
996 + "typeName": "ZodAny",
997 + },
998 + "typeName": "ZodArray",
999 + },
1000 + "typeName": "ZodOptional",
1001 + },
1002 + "closedTuple": {
1003 + "innerType": {
1004 + "effect": "refinement",
1005 + "schema": {
1006 + "effect": "refinement",
1007 + "schema": {
1008 + "options": [
1009 + {
1010 + "items": [],
1011 + "rest": null,
1012 + "typeName": "ZodTuple",
1013 + },
1014 + {
1015 + "items": [
1016 + {
1017 + "checks": [],
1018 + "typeName": "ZodString",
1019 + },
1020 + ],
1021 + "rest": null,
1022 + "typeName": "ZodTuple",
1023 + },
1024 + ],
1025 + "typeName": "ZodUnion",
1026 + },
1027 + "typeName": "ZodEffects",
1028 + },
1029 + "typeName": "ZodEffects",
1030 + },
1031 + "typeName": "ZodOptional",
1032 + },
1033 + "emptyOpen": {
1034 + "innerType": {
1035 + "catchall": {
1036 + "typeName": "ZodNever",
1037 + },
1038 + "shape": {},
1039 + "typeName": "ZodObject",
1040 + "unknownKeys": "passthrough",
1041 + },
1042 + "typeName": "ZodOptional",
1043 + },
1044 + "emptyStrict": {
1045 + "innerType": {
1046 + "catchall": {
1047 + "typeName": "ZodNever",
1048 + },
1049 + "shape": {},
1050 + "typeName": "ZodObject",
1051 + "unknownKeys": "strict",
1052 + },
1053 + "typeName": "ZodOptional",
1054 + },
1055 + "implicit": {
1056 + "innerType": {
1057 + "guarded": true,
1058 + "typeName": "ZodAny",
1059 + },
1060 + "typeName": "ZodOptional",
1061 + },
1062 + "list": {
1063 + "innerType": {
1064 + "element": {
1065 + "checks": [],
1066 + "typeName": "ZodString",
1067 + },
1068 + "maxLength": {
1069 + "message": undefined,
1070 + "value": 3,
1071 + },
1072 + "minLength": {
1073 + "message": undefined,
1074 + "value": 1,
1075 + },
1076 + "typeName": "ZodArray",
1077 + },
1078 + "typeName": "ZodOptional",
1079 + },
1080 + "open": {
1081 + "innerType": {
1082 + "catchall": {
1083 + "typeName": "ZodNever",
1084 + },
1085 + "shape": {
1086 + "a": {
1087 + "innerType": {
1088 + "checks": [],
1089 + "typeName": "ZodString",
1090 + },
1091 + "typeName": "ZodOptional",
1092 + },
1093 + },
1094 + "typeName": "ZodObject",
1095 + "unknownKeys": "passthrough",
1096 + },
1097 + "typeName": "ZodOptional",
1098 + },
1099 + "patterns": {
1100 + "innerType": {
1101 + "effect": "transform",
1102 + "schema": {
1103 + "catchall": {
1104 + "typeName": "ZodNever",
1105 + },
1106 + "shape": {
1107 + "a": {
1108 + "innerType": {
1109 + "checks": [],
1110 + "typeName": "ZodString",
1111 + },
1112 + "typeName": "ZodOptional",
1113 + },
1114 + },
1115 + "typeName": "ZodObject",
1116 + "unknownKeys": "passthrough",
1117 + },
1118 + "typeName": "ZodEffects",
1119 + },
1120 + "typeName": "ZodOptional",
1121 + },
1122 + "patternsOnly": {
1123 + "innerType": {
1124 + "effect": "transform",
1125 + "schema": {
1126 + "catchall": {
1127 + "typeName": "ZodNever",
1128 + },
1129 + "shape": {},
1130 + "typeName": "ZodObject",
1131 + "unknownKeys": "passthrough",
1132 + },
1133 + "typeName": "ZodEffects",
1134 + },
1135 + "typeName": "ZodOptional",
1136 + },
1137 + "record": {
1138 + "innerType": {
1139 + "keyType": {
1140 + "checks": [],
1141 + "typeName": "ZodString",
1142 + },
1143 + "typeName": "ZodRecord",
1144 + "valueType": {
1145 + "checks": [],
1146 + "typeName": "ZodNumber",
1147 + },
1148 + },
1149 + "typeName": "ZodOptional",
1150 + },
1151 + "strict": {
1152 + "innerType": {
1153 + "catchall": {
1154 + "typeName": "ZodNever",
1155 + },
1156 + "shape": {
1157 + "a": {
1158 + "innerType": {
1159 + "checks": [],
1160 + "typeName": "ZodString",
1161 + },
1162 + "typeName": "ZodOptional",
1163 + },
1164 + },
1165 + "typeName": "ZodObject",
1166 + "unknownKeys": "strict",
1167 + },
1168 + "typeName": "ZodOptional",
1169 + },
1170 + "tuple": {
1171 + "innerType": {
1172 + "options": [
1173 + {
1174 + "items": [],
1175 + "rest": null,
1176 + "typeName": "ZodTuple",
1177 + },
1178 + {
1179 + "items": [
1180 + {
1181 + "checks": [],
1182 + "typeName": "ZodString",
1183 + },
1184 + ],
1185 + "rest": null,
1186 + "typeName": "ZodTuple",
1187 + },
1188 + {
1189 + "items": [
1190 + {
1191 + "checks": [],
1192 + "typeName": "ZodString",
1193 + },
1194 + {
1195 + "checks": [
1196 + {
1197 + "kind": "int",
1198 + "message": undefined,
1199 + },
1200 + ],
1201 + "typeName": "ZodNumber",
1202 + },
1203 + ],
1204 + "rest": {
1205 + "typeName": "ZodAny",
1206 + },
1207 + "typeName": "ZodTuple",
1208 + },
1209 + ],
1210 + "typeName": "ZodUnion",
1211 + },
1212 + "typeName": "ZodOptional",
1213 + },
1214 + "typed": {
1215 + "innerType": {
1216 + "catchall": {
1217 + "checks": [],
1218 + "typeName": "ZodNumber",
1219 + },
1220 + "shape": {
1221 + "a": {
1222 + "innerType": {
1223 + "checks": [],
1224 + "typeName": "ZodString",
1225 + },
1226 + "typeName": "ZodOptional",
1227 + },
1228 + },
1229 + "typeName": "ZodObject",
1230 + "unknownKeys": "strip",
1231 + },
1232 + "typeName": "ZodOptional",
1233 + },
1234 + "typedRest": {
1235 + "innerType": {
1236 + "options": [
1237 + {
1238 + "items": [],
1239 + "rest": null,
1240 + "typeName": "ZodTuple",
1241 + },
1242 + {
1243 + "items": [
1244 + {
1245 + "checks": [],
1246 + "typeName": "ZodString",
1247 + },
1248 + ],
1249 + "rest": {
1250 + "checks": [],
1251 + "typeName": "ZodNumber",
1252 + },
1253 + "typeName": "ZodTuple",
1254 + },
1255 + ],
1256 + "typeName": "ZodUnion",
1257 + },
1258 + "typeName": "ZodOptional",
1259 + },
1260 + },
1261 + "typeName": "ZodObject",
1262 + "unknownKeys": "strict",
1263 + },
1264 + "jsonSchema": {
1265 + "$schema": "http://json-schema.org/draft-07/schema#",
1266 + "additionalProperties": false,
1267 + "properties": {
1268 + "aliases": {
1269 + "items": {
1270 + "type": "string",
1271 + },
1272 + "maxItems": 3,
1273 + "minItems": 1,
1274 + "type": "array",
1275 + },
1276 + "anyOfArray": {
1277 + "items": {
1278 + "type": [
1279 + "string",
1280 + "number",
1281 + ],
1282 + },
1283 + "type": "array",
1284 + },
1285 + "bare": {
1286 + "type": "array",
1287 + },
1288 + "closedTuple": {
1289 + "anyOf": [
1290 + {
1291 + "items": [],
1292 + "maxItems": 0,
1293 + "minItems": 0,
1294 + "type": "array",
1295 + },
1296 + {
1297 + "items": [
1298 + {
1299 + "type": "string",
1300 + },
1301 + ],
1302 + "maxItems": 1,
1303 + "minItems": 1,
1304 + "type": "array",
1305 + },
1306 + ],
1307 + },
1308 + "emptyOpen": {
1309 + "additionalProperties": true,
1310 + "properties": {},
1311 + "type": "object",
1312 + },
1313 + "emptyStrict": {
1314 + "additionalProperties": false,
1315 + "properties": {},
1316 + "type": "object",
1317 + },
1318 + "implicit": {},
1319 + "list": {
1320 + "items": {
1321 + "type": "string",
1322 + },
1323 + "maxItems": 3,
1324 + "minItems": 1,
1325 + "type": "array",
1326 + },
1327 + "open": {
1328 + "additionalProperties": true,
1329 + "properties": {
1330 + "a": {
1331 + "type": "string",
1332 + },
1333 + },
1334 + "type": "object",
1335 + },
1336 + "patterns": {
1337 + "additionalProperties": true,
1338 + "properties": {
1339 + "a": {
1340 + "type": "string",
1341 + },
1342 + },
1343 + "type": "object",
1344 + },
1345 + "patternsOnly": {
1346 + "additionalProperties": true,
1347 + "properties": {},
1348 + "type": "object",
1349 + },
1350 + "record": {
1351 + "additionalProperties": {
1352 + "type": "number",
1353 + },
1354 + "type": "object",
1355 + },
1356 + "strict": {
1357 + "additionalProperties": false,
1358 + "properties": {
1359 + "a": {
1360 + "type": "string",
1361 + },
1362 + },
1363 + "type": "object",
1364 + },
1365 + "tuple": {
1366 + "anyOf": [
1367 + {
1368 + "items": [],
1369 + "maxItems": 0,
1370 + "minItems": 0,
1371 + "type": "array",
1372 + },
1373 + {
1374 + "items": [
1375 + {
1376 + "type": "string",
1377 + },
1378 + ],
1379 + "maxItems": 1,
1380 + "minItems": 1,
1381 + "type": "array",
1382 + },
1383 + {
1384 + "additionalItems": {},
1385 + "items": [
1386 + {
1387 + "$ref": "#/properties/tuple/anyOf/1/items/0",
1388 + },
1389 + {
1390 + "type": "integer",
1391 + },
1392 + ],
1393 + "minItems": 2,
1394 + "type": "array",
1395 + },
1396 + ],
1397 + },
1398 + "typed": {
1399 + "additionalProperties": {
1400 + "type": "number",
1401 + },
1402 + "properties": {
1403 + "a": {
1404 + "type": "string",
1405 + },
1406 + },
1407 + "type": "object",
1408 + },
1409 + "typedRest": {
1410 + "anyOf": [
1411 + {
1412 + "items": [],
1413 + "maxItems": 0,
1414 + "minItems": 0,
1415 + "type": "array",
1416 + },
1417 + {
1418 + "additionalItems": {
1419 + "type": "number",
1420 + },
1421 + "items": [
1422 + {
1423 + "type": "string",
1424 + },
1425 + ],
1426 + "minItems": 1,
1427 + "type": "array",
1428 + },
1429 + ],
1430 + },
1431 + },
1432 + "type": "object",
1433 + },
1434 + },
1435 + "id": "containers",
1436 + },
1437 + {
1438 + "fingerprint": {
1439 + "def": {
1440 + "catchall": {
1441 + "typeName": "ZodNever",
1442 + },
1443 + "guarded": true,
1444 + "shape": {
1445 + "bounded": {
1446 + "innerType": {
1447 + "catchall": {
1448 + "typeName": "ZodNever",
1449 + },
1450 + "shape": {},
1451 + "typeName": "ZodObject",
1452 + "unknownKeys": "passthrough",
1453 + },
1454 + "typeName": "ZodOptional",
1455 + },
1456 + "nested": {
1457 + "innerType": {
1458 + "catchall": {
1459 + "typeName": "ZodNever",
1460 + },
1461 + "shape": {
1462 + "ref": {
1463 + "innerType": {
1464 + "guarded": true,
1465 + "typeName": "ZodAny",
1466 + },
1467 + "typeName": "ZodOptional",
1468 + },
1469 + },
1470 + "typeName": "ZodObject",
1471 + "unknownKeys": "strict",
1472 + },
1473 + "typeName": "ZodOptional",
1474 + },
1475 + "ref": {
1476 + "guarded": true,
1477 + "typeName": "ZodAny",
1478 + },
1479 + "unique": {
1480 + "innerType": {
1481 + "element": {
1482 + "typeName": "ZodAny",
1483 + },
1484 + "typeName": "ZodArray",
1485 + },
1486 + "typeName": "ZodOptional",
1487 + },
1488 + },
1489 + "typeName": "ZodObject",
1490 + "unknownKeys": "strict",
1491 + },
1492 + "jsonSchema": {
1493 + "$schema": "http://json-schema.org/draft-07/schema#",
1494 + "additionalProperties": false,
1495 + "properties": {
1496 + "bounded": {
1497 + "additionalProperties": true,
1498 + "properties": {},
1499 + "type": "object",
1500 + },
1501 + "nested": {
1502 + "additionalProperties": false,
1503 + "properties": {
1504 + "ref": {},
1505 + },
1506 + "type": "object",
1507 + },
1508 + "ref": {},
1509 + "unique": {
1510 + "type": "array",
1511 + },
1512 + },
1513 + "required": [
1514 + "ref",
1515 + ],
1516 + "type": "object",
1517 + },
1518 + },
1519 + "id": "references-and-guards",
1520 + },
1521 + {
1522 + "fingerprint": {
1523 + "def": {
1524 + "typeName": "ZodAny",
1525 + },
1526 + "jsonSchema": {
1527 + "$schema": "http://json-schema.org/draft-07/schema#",
1528 + },
1529 + },
1530 + "id": "boolean-true",
1531 + },
1532 + {
1533 + "fingerprint": {
1534 + "def": {
1535 + "typeName": "ZodNever",
1536 + },
1537 + "jsonSchema": {
1538 + "$schema": "http://json-schema.org/draft-07/schema#",
1539 + "not": {},
1540 + },
1541 + },
1542 + "id": "boolean-false",
1543 + },
1544 + {
1545 + "fingerprint": {
1546 + "def": {
1547 + "checks": [],
1548 + "description": "root",
1549 + "typeName": "ZodString",
1550 + },
1551 + "jsonSchema": {
1552 + "$schema": "http://json-schema.org/draft-07/schema#",
1553 + "description": "root",
1554 + "type": "string",
1555 + },
1556 + },
1557 + "id": "root-string",
1558 + },
1559 + {
1560 + "fingerprint": {
1561 + "def": {
1562 + "defaultValue": null,
1563 + "innerType": {
1564 + "defaultValue": null,
1565 + "innerType": {
1566 + "innerType": {
1567 + "checks": [],
1568 + "typeName": "ZodString",
1569 + },
1570 + "typeName": "ZodNullable",
1571 + },
1572 + "typeName": "ZodDefault",
1573 + },
1574 + "typeName": "ZodDefault",
1575 + },
1576 + "jsonSchema": {
1577 + "$schema": "http://json-schema.org/draft-07/schema#",
1578 + "default": null,
1579 + "type": [
1580 + "string",
1581 + "null",
1582 + ],
1583 + },
1584 + },
1585 + "id": "root-nullable",
1586 + },
1587 + {
1588 + "fingerprint": {
1589 + "def": {
1590 + "guarded": true,
1591 + "typeName": "ZodAny",
1592 + },
1593 + "jsonSchema": {
1594 + "$schema": "http://json-schema.org/draft-07/schema#",
1595 + },
1596 + },
1597 + "id": "root-ref",
1598 + },
1599 +]
1600 +`;
1601 +
1602 +exports[`v3 output fingerprint > matches the pinned snapshot for the shared object corpus 1`] = `
1603 +[
1604 + {
1605 + "fingerprint": {
1606 + "def": {
1607 + "catchall": {
1608 + "typeName": "ZodNever",
1609 + },
1610 + "shape": {
1611 + "dataset_query": {
1612 + "innerType": {
1613 + "catchall": {
1614 + "typeName": "ZodNever",
1615 + },
1616 + "shape": {},
1617 + "typeName": "ZodObject",
1618 + "unknownKeys": "passthrough",
1619 + },
1620 + "typeName": "ZodOptional",
1621 + },
1622 + },
1623 + "typeName": "ZodObject",
1624 + "unknownKeys": "strict",
1625 + },
1626 + "jsonSchema": {
1627 + "$schema": "http://json-schema.org/draft-07/schema#",
1628 + "additionalProperties": false,
1629 + "properties": {
1630 + "dataset_query": {
1631 + "additionalProperties": true,
1632 + "properties": {},
1633 + "type": "object",
1634 + },
1635 + },
1636 + "type": "object",
1637 + },
1638 + },
1639 + "id": "nested-free-form-object",
1640 + },
1641 + {
1642 + "fingerprint": {
1643 + "def": {
1644 + "catchall": {
1645 + "typeName": "ZodNever",
1646 + },
1647 + "shape": {},
1648 + "typeName": "ZodObject",
1649 + "unknownKeys": "passthrough",
1650 + },
1651 + "jsonSchema": {
1652 + "$schema": "http://json-schema.org/draft-07/schema#",
1653 + "additionalProperties": true,
1654 + "properties": {},
1655 + "type": "object",
1656 + },
1657 + },
1658 + "id": "root-free-form-absent-properties",
1659 + },
1660 + {
1661 + "fingerprint": {
1662 + "def": {
1663 + "catchall": {
1664 + "typeName": "ZodNever",
1665 + },
1666 + "shape": {},
1667 + "typeName": "ZodObject",
1668 + "unknownKeys": "passthrough",
1669 + },
1670 + "jsonSchema": {
1671 + "$schema": "http://json-schema.org/draft-07/schema#",
1672 + "additionalProperties": true,
1673 + "properties": {},
1674 + "type": "object",
1675 + },
1676 + },
1677 + "id": "root-free-form-empty-properties",
1678 + },
1679 + {
1680 + "fingerprint": {
1681 + "def": {
1682 + "catchall": {
1683 + "typeName": "ZodNever",
1684 + },
1685 + "shape": {
1686 + "records": {
1687 + "innerType": {
1688 + "element": {
1689 + "catchall": {
1690 + "typeName": "ZodNever",
1691 + },
1692 + "shape": {},
1693 + "typeName": "ZodObject",
1694 + "unknownKeys": "passthrough",
1695 + },
1696 + "typeName": "ZodArray",
1697 + },
1698 + "typeName": "ZodOptional",
1699 + },
1700 + },
1701 + "typeName": "ZodObject",
1702 + "unknownKeys": "strict",
1703 + },
1704 + "jsonSchema": {
1705 + "$schema": "http://json-schema.org/draft-07/schema#",
1706 + "additionalProperties": false,
1707 + "properties": {
1708 + "records": {
1709 + "items": {
1710 + "additionalProperties": true,
1711 + "properties": {},
1712 + "type": "object",
1713 + },
1714 + "type": "array",
1715 + },
1716 + },
1717 + "type": "object",
1718 + },
1719 + },
1720 + "id": "free-form-object-in-array-items",
1721 + },
1722 + {
1723 + "fingerprint": {
1724 + "def": {
1725 + "catchall": {
1726 + "typeName": "ZodNever",
1727 + },
1728 + "shape": {
1729 + "payload": {
1730 + "effect": "transform",
1731 + "schema": {
1732 + "catchall": {
1733 + "typeName": "ZodNever",
1734 + },
1735 + "shape": {},
1736 + "typeName": "ZodObject",
1737 + "unknownKeys": "passthrough",
1738 + },
1739 + "typeName": "ZodEffects",
1740 + },
1741 + },
1742 + "typeName": "ZodObject",
1743 + "unknownKeys": "strict",
1744 + },
1745 + "jsonSchema": {
1746 + "$schema": "http://json-schema.org/draft-07/schema#",
1747 + "additionalProperties": false,
1748 + "properties": {
1749 + "payload": {
1750 + "additionalProperties": true,
1751 + "properties": {},
1752 + "type": "object",
1753 + },
1754 + },
1755 + "required": [
1756 + "payload",
1757 + ],
1758 + "type": "object",
1759 + },
1760 + },
1761 + "id": "nested-pattern-properties-object",
1762 + },
1763 + {
1764 + "fingerprint": {
1765 + "def": {
1766 + "catchall": {
1767 + "typeName": "ZodNever",
1768 + },
1769 + "shape": {
1770 + "records": {
1771 + "element": {
1772 + "keyType": {
1773 + "checks": [],
1774 + "typeName": "ZodString",
1775 + },
1776 + "typeName": "ZodRecord",
1777 + "valueType": {
1778 + "checks": [],
1779 + "typeName": "ZodNumber",
1780 + },
1781 + },
1782 + "typeName": "ZodArray",
1783 + },
1784 + },
1785 + "typeName": "ZodObject",
1786 + "unknownKeys": "strict",
1787 + },
1788 + "jsonSchema": {
1789 + "$schema": "http://json-schema.org/draft-07/schema#",
1790 + "additionalProperties": false,
1791 + "properties": {
1792 + "records": {
1793 + "items": {
1794 + "additionalProperties": {
1795 + "type": "number",
1796 + },
1797 + "type": "object",
1798 + },
1799 + "type": "array",
1800 + },
1801 + },
1802 + "required": [
1803 + "records",
1804 + ],
1805 + "type": "object",
1806 + },
1807 + },
1808 + "id": "schema-valued-additional-properties-in-array-items",
1809 + },
1810 + {
1811 + "fingerprint": {
1812 + "def": {
1813 + "catchall": {
1814 + "typeName": "ZodNever",
1815 + },
1816 + "shape": {},
1817 + "typeName": "ZodObject",
1818 + "unknownKeys": "strict",
1819 + },
1820 + "jsonSchema": {
1821 + "$schema": "http://json-schema.org/draft-07/schema#",
1822 + "additionalProperties": false,
1823 + "properties": {},
1824 + "type": "object",
1825 + },
1826 + },
1827 + "id": "explicit-additional-properties-false",
1828 + },
1829 + {
1830 + "fingerprint": {
1831 + "def": {
1832 + "catchall": {
1833 + "typeName": "ZodNever",
1834 + },
1835 + "shape": {
1836 + "name": {
1837 + "innerType": {
1838 + "checks": [],
1839 + "typeName": "ZodString",
1840 + },
1841 + "typeName": "ZodOptional",
1842 + },
1843 + },
1844 + "typeName": "ZodObject",
1845 + "unknownKeys": "passthrough",
1846 + },
1847 + "jsonSchema": {
1848 + "$schema": "http://json-schema.org/draft-07/schema#",
1849 + "additionalProperties": true,
1850 + "properties": {
1851 + "name": {
1852 + "type": "string",
1853 + },
1854 + },
1855 + "type": "object",
1856 + },
1857 + },
1858 + "id": "explicit-additional-properties-true",
1859 + },
1860 + {
1861 + "fingerprint": {
1862 + "def": {
1863 + "catchall": {
1864 + "typeName": "ZodNever",
1865 + },
1866 + "shape": {
1867 + "name": {
1868 + "checks": [],
1869 + "typeName": "ZodString",
1870 + },
1871 + },
1872 + "typeName": "ZodObject",
1873 + "unknownKeys": "strict",
1874 + },
1875 + "jsonSchema": {
1876 + "$schema": "http://json-schema.org/draft-07/schema#",
1877 + "additionalProperties": false,
1878 + "properties": {
1879 + "name": {
1880 + "type": "string",
1881 + },
1882 + },
1883 + "required": [
1884 + "name",
1885 + ],
1886 + "type": "object",
1887 + },
1888 + },
1889 + "id": "named-properties-strict-by-default",
1890 + },
1891 + {
1892 + "fingerprint": {
1893 + "def": {
1894 + "effect": "transform",
1895 + "schema": {
1896 + "catchall": {
1897 + "typeName": "ZodNever",
1898 + },
1899 + "shape": {
1900 + "name": {
1901 + "innerType": {
1902 + "checks": [],
1903 + "typeName": "ZodString",
1904 + },
1905 + "typeName": "ZodOptional",
1906 + },
1907 + },
1908 + "typeName": "ZodObject",
1909 + "unknownKeys": "passthrough",
1910 + },
1911 + "typeName": "ZodEffects",
1912 + },
1913 + "jsonSchema": {
1914 + "$schema": "http://json-schema.org/draft-07/schema#",
1915 + "additionalProperties": true,
1916 + "properties": {
1917 + "name": {
1918 + "type": "string",
1919 + },
1920 + },
1921 + "type": "object",
1922 + },
1923 + },
1924 + "id": "named-properties-with-pattern-properties",
1925 + },
1926 + {
1927 + "fingerprint": {
1928 + "def": {
1929 + "catchall": {
1930 + "checks": [],
1931 + "typeName": "ZodNumber",
1932 + },
1933 + "shape": {
1934 + "name": {
1935 + "innerType": {
1936 + "checks": [],
1937 + "typeName": "ZodString",
1938 + },
1939 + "typeName": "ZodOptional",
1940 + },
1941 + },
1942 + "typeName": "ZodObject",
1943 + "unknownKeys": "strip",
1944 + },
1945 + "jsonSchema": {
1946 + "$schema": "http://json-schema.org/draft-07/schema#",
1947 + "additionalProperties": {
1948 + "type": "number",
1949 + },
1950 + "properties": {
1951 + "name": {
1952 + "type": "string",
1953 + },
1954 + },
1955 + "type": "object",
1956 + },
1957 + },
1958 + "id": "root-additional-properties-schema-valued",
1959 + },
1960 + {
1961 + "fingerprint": {
1962 + "def": {
1963 + "effect": "transform",
1964 + "schema": {
1965 + "catchall": {
1966 + "typeName": "ZodNever",
1967 + },
1968 + "shape": {},
1969 + "typeName": "ZodObject",
1970 + "unknownKeys": "passthrough",
1971 + },
1972 + "typeName": "ZodEffects",
1973 + },
1974 + "jsonSchema": {
1975 + "$schema": "http://json-schema.org/draft-07/schema#",
1976 + "additionalProperties": true,
1977 + "properties": {},
1978 + "type": "object",
1979 + },
1980 + },
1981 + "id": "pattern-only-object",
1982 + },
1983 + {
1984 + "fingerprint": {
1985 + "def": {
1986 + "effect": "transform",
1987 + "schema": {
1988 + "catchall": {
1989 + "typeName": "ZodNever",
1990 + },
1991 + "shape": {},
1992 + "typeName": "ZodObject",
1993 + "unknownKeys": "passthrough",
1994 + },
1995 + "typeName": "ZodEffects",
1996 + },
1997 + "jsonSchema": {
1998 + "$schema": "http://json-schema.org/draft-07/schema#",
1999 + "additionalProperties": true,
2000 + "properties": {},
2001 + "type": "object",
2002 + },
2003 + },
2004 + "id": "multiple-matching-patterns",
2005 + },
2006 + {
2007 + "fingerprint": {
2008 + "def": {
2009 + "effect": "transform",
2010 + "schema": {
2011 + "catchall": {
2012 + "typeName": "ZodNever",
2013 + },
2014 + "shape": {
2015 + "x_id": {
2016 + "innerType": {
2017 + "checks": [],
2018 + "typeName": "ZodString",
2019 + },
2020 + "typeName": "ZodOptional",
2021 + },
2022 + },
2023 + "typeName": "ZodObject",
2024 + "unknownKeys": "passthrough",
2025 + },
2026 + "typeName": "ZodEffects",
2027 + },
2028 + "jsonSchema": {
2029 + "$schema": "http://json-schema.org/draft-07/schema#",
2030 + "additionalProperties": true,
2031 + "properties": {
2032 + "x_id": {
2033 + "type": "string",
2034 + },
2035 + },
2036 + "type": "object",
2037 + },
2038 + },
2039 + "id": "declared-property-also-matching-a-pattern",
2040 + },
2041 + {
2042 + "fingerprint": {
2043 + "def": {
2044 + "effect": "transform",
2045 + "schema": {
2046 + "catchall": {
2047 + "typeName": "ZodNever",
2048 + },
2049 + "shape": {
2050 + "name": {
2051 + "innerType": {
2052 + "checks": [],
2053 + "typeName": "ZodString",
2054 + },
2055 + "typeName": "ZodOptional",
2056 + },
2057 + },
2058 + "typeName": "ZodObject",
2059 + "unknownKeys": "passthrough",
2060 + },
2061 + "typeName": "ZodEffects",
2062 + },
2063 + "jsonSchema": {
2064 + "$schema": "http://json-schema.org/draft-07/schema#",
2065 + "additionalProperties": true,
2066 + "properties": {
2067 + "name": {
2068 + "type": "string",
2069 + },
2070 + },
2071 + "type": "object",
2072 + },
2073 + },
2074 + "id": "schema-valued-additional-applies-only-to-unmatched-keys",
2075 + },
2076 + {
2077 + "fingerprint": {
2078 + "def": {
2079 + "catchall": {
2080 + "typeName": "ZodAny",
2081 + },
2082 + "shape": {
2083 + "name": {
2084 + "innerType": {
2085 + "checks": [],
2086 + "typeName": "ZodString",
2087 + },
2088 + "typeName": "ZodOptional",
2089 + },
2090 + },
2091 + "typeName": "ZodObject",
2092 + "unknownKeys": "strip",
2093 + },
2094 + "jsonSchema": {
2095 + "$schema": "http://json-schema.org/draft-07/schema#",
2096 + "additionalProperties": {},
2097 + "properties": {
2098 + "name": {
2099 + "type": "string",
2100 + },
2101 + },
2102 + "type": "object",
2103 + },
2104 + },
2105 + "id": "empty-schema-additional-properties",
2106 + },
2107 + {
2108 + "fingerprint": {
2109 + "def": {
2110 + "effect": "transform",
2111 + "schema": {
2112 + "catchall": {
2113 + "typeName": "ZodNever",
2114 + },
2115 + "shape": {},
2116 + "typeName": "ZodObject",
2117 + "unknownKeys": "passthrough",
2118 + },
2119 + "typeName": "ZodEffects",
2120 + },
2121 + "jsonSchema": {
2122 + "$schema": "http://json-schema.org/draft-07/schema#",
2123 + "additionalProperties": true,
2124 + "properties": {},
2125 + "type": "object",
2126 + },
2127 + },
2128 + "id": "pattern-property-enum",
2129 + },
2130 + {
2131 + "fingerprint": {
2132 + "def": {
2133 + "effect": "transform",
2134 + "schema": {
2135 + "catchall": {
2136 + "typeName": "ZodNever",
2137 + },
2138 + "shape": {},
2139 + "typeName": "ZodObject",
2140 + "unknownKeys": "passthrough",
2141 + },
2142 + "typeName": "ZodEffects",
2143 + },
2144 + "jsonSchema": {
2145 + "$schema": "http://json-schema.org/draft-07/schema#",
2146 + "additionalProperties": true,
2147 + "properties": {},
2148 + "type": "object",
2149 + },
2150 + },
2151 + "id": "pattern-property-strict-nested-array",
2152 + },
2153 + {
2154 + "fingerprint": {
2155 + "def": {
2156 + "effect": "transform",
2157 + "schema": {
2158 + "catchall": {
2159 + "typeName": "ZodNever",
2160 + },
2161 + "shape": {},
2162 + "typeName": "ZodObject",
2163 + "unknownKeys": "passthrough",
2164 + },
2165 + "typeName": "ZodEffects",
2166 + },
2167 + "jsonSchema": {
2168 + "$schema": "http://json-schema.org/draft-07/schema#",
2169 + "additionalProperties": true,
2170 + "properties": {},
2171 + "type": "object",
2172 + },
2173 + },
2174 + "id": "false-pattern-property-schema",
2175 + },
2176 + {
2177 + "fingerprint": {
2178 + "def": {
2179 + "effect": "transform",
2180 + "schema": {
2181 + "catchall": {
2182 + "typeName": "ZodNever",
2183 + },
2184 + "shape": {},
2185 + "typeName": "ZodObject",
2186 + "unknownKeys": "passthrough",
2187 + },
2188 + "typeName": "ZodEffects",
2189 + },
2190 + "jsonSchema": {
2191 + "$schema": "http://json-schema.org/draft-07/schema#",
2192 + "additionalProperties": true,
2193 + "properties": {},
2194 + "type": "object",
2195 + },
2196 + },
2197 + "id": "pattern-property-type-union",
2198 + },
2199 + {
2200 + "fingerprint": {
2201 + "def": {
2202 + "effect": "transform",
2203 + "schema": {
2204 + "catchall": {
2205 + "typeName": "ZodNever",
2206 + },
2207 + "shape": {},
2208 + "typeName": "ZodObject",
2209 + "unknownKeys": "passthrough",
2210 + },
2211 + "typeName": "ZodEffects",
2212 + },
2213 + "jsonSchema": {
2214 + "$schema": "http://json-schema.org/draft-07/schema#",
2215 + "additionalProperties": true,
2216 + "properties": {},
2217 + "type": "object",
2218 + },
2219 + },
2220 + "id": "pattern-property-json-integer",
2221 + },
2222 + {
2223 + "fingerprint": {
2224 + "def": {
2225 + "effect": "transform",
2226 + "guarded": true,
2227 + "schema": {
2228 + "catchall": {
2229 + "typeName": "ZodNever",
2230 + },
2231 + "shape": {},
2232 + "typeName": "ZodObject",
2233 + "unknownKeys": "passthrough",
2234 + },
2235 + "typeName": "ZodEffects",
2236 + },
2237 + "jsonSchema": {
2238 + "$schema": "http://json-schema.org/draft-07/schema#",
2239 + "additionalProperties": true,
2240 + "properties": {},
2241 + "type": "object",
2242 + },
2243 + },
2244 + "id": "pattern-property-composed-const-exclusion",
2245 + },
2246 + {
2247 + "fingerprint": {
2248 + "def": {
2249 + "effect": "transform",
2250 + "schema": {
2251 + "catchall": {
2252 + "typeName": "ZodNever",
2253 + },
2254 + "shape": {},
2255 + "typeName": "ZodObject",
2256 + "unknownKeys": "passthrough",
2257 + },
2258 + "typeName": "ZodEffects",
2259 + },
2260 + "jsonSchema": {
2261 + "$schema": "http://json-schema.org/draft-07/schema#",
2262 + "additionalProperties": true,
2263 + "properties": {},
2264 + "type": "object",
2265 + },
2266 + },
2267 + "id": "pattern-property-default-materialization",
2268 + },
2269 + {
2270 + "fingerprint": {
2271 + "def": {
2272 + "catchall": {
2273 + "typeName": "ZodNever",
2274 + },
2275 + "shape": {
2276 + "allowed": {
2277 + "typeName": "ZodAny",
2278 + },
2279 + "forbidden": {
2280 + "innerType": {
2281 + "typeName": "ZodNever",
2282 + },
2283 + "typeName": "ZodOptional",
2284 + },
2285 + },
2286 + "typeName": "ZodObject",
2287 + "unknownKeys": "strict",
2288 + },
2289 + "jsonSchema": {
2290 + "$schema": "http://json-schema.org/draft-07/schema#",
2291 + "additionalProperties": false,
2292 + "properties": {
2293 + "allowed": {},
2294 + "forbidden": {
2295 + "not": {},
2296 + },
2297 + },
2298 + "type": "object",
2299 + },
2300 + },
2301 + "id": "primitive-boolean-property-schemas",
2302 + },
2303 + {
2304 + "fingerprint": {
2305 + "def": {
2306 + "catchall": {
2307 + "typeName": "ZodNever",
2308 + },
2309 + "shape": {
2310 + "anything": {
2311 + "typeName": "ZodAny",
2312 + },
2313 + "nullOnly": {
2314 + "typeName": "ZodNull",
2315 + },
2316 + },
2317 + "typeName": "ZodObject",
2318 + "unknownKeys": "strict",
2319 + },
2320 + "jsonSchema": {
2321 + "$schema": "http://json-schema.org/draft-07/schema#",
2322 + "additionalProperties": false,
2323 + "properties": {
2324 + "anything": {},
2325 + "nullOnly": {
2326 + "type": "null",
2327 + },
2328 + },
2329 + "required": [
2330 + "nullOnly",
2331 + ],
2332 + "type": "object",
2333 + },
2334 + },
2335 + "id": "primitive-empty-and-null-schemas",
2336 + },
2337 + {
2338 + "fingerprint": {
2339 + "def": {
2340 + "catchall": {
2341 + "typeName": "ZodNever",
2342 + },
2343 + "shape": {
2344 + "value": {
2345 + "options": [
2346 + {
2347 + "checks": [],
2348 + "typeName": "ZodString",
2349 + },
2350 + {
2351 + "checks": [
2352 + {
2353 + "kind": "int",
2354 + "message": undefined,
2355 + },
2356 + ],
2357 + "typeName": "ZodNumber",
2358 + },
2359 + {
2360 + "typeName": "ZodNull",
2361 + },
2362 + ],
2363 + "typeName": "ZodUnion",
2364 + },
2365 + },
2366 + "typeName": "ZodObject",
2367 + "unknownKeys": "strict",
2368 + },
2369 + "jsonSchema": {
2370 + "$schema": "http://json-schema.org/draft-07/schema#",
2371 + "additionalProperties": false,
2372 + "properties": {
2373 + "value": {
2374 + "anyOf": [
2375 + {
2376 + "type": "string",
2377 + },
2378 + {
2379 + "type": "integer",
2380 + },
2381 + {
2382 + "type": "null",
2383 + },
2384 + ],
2385 + },
2386 + },
2387 + "required": [
2388 + "value",
2389 + ],
2390 + "type": "object",
2391 + },
2392 + },
2393 + "id": "primitive-type-array-union",
2394 + },
2395 + {
2396 + "fingerprint": {
2397 + "def": {
2398 + "catchall": {
2399 + "typeName": "ZodNever",
2400 + },
2401 + "shape": {
2402 + "value": {
2403 + "left": {
2404 + "checks": [],
2405 + "typeName": "ZodString",
2406 + },
2407 + "right": {
2408 + "options": [
2409 + {
2410 + "typeName": "ZodLiteral",
2411 + "value": 1,
2412 + },
2413 + {
2414 + "typeName": "ZodLiteral",
2415 + "value": "ready",
2416 + },
2417 + ],
2418 + "typeName": "ZodUnion",
2419 + },
2420 + "typeName": "ZodIntersection",
2421 + },
2422 + },
2423 + "typeName": "ZodObject",
2424 + "unknownKeys": "strict",
2425 + },
2426 + "jsonSchema": {
2427 + "$schema": "http://json-schema.org/draft-07/schema#",
2428 + "additionalProperties": false,
2429 + "properties": {
2430 + "value": {
2431 + "allOf": [
2432 + {
2433 + "type": "string",
2434 + },
2435 + {
2436 + "enum": [
2437 + 1,
2438 + "ready",
2439 + ],
2440 + "type": [
2441 + "number",
2442 + "string",
2443 + ],
2444 + },
2445 + ],
2446 + },
2447 + },
2448 + "required": [
2449 + "value",
2450 + ],
2451 + "type": "object",
2452 + },
2453 + },
2454 + "id": "primitive-enum-intersects-declared-type",
2455 + },
2456 + {
2457 + "fingerprint": {
2458 + "def": {
2459 + "catchall": {
2460 + "typeName": "ZodNever",
2461 + },
2462 + "guarded": true,
2463 + "shape": {
2464 + "anyOf": {
2465 + "typeName": "ZodNull",
2466 + },
2467 + "typeArray": {
2468 + "options": [
2469 + {
2470 + "typeName": "ZodNull",
2471 + },
2472 + ],
2473 + "typeName": "ZodUnion",
2474 + },
2475 + },
2476 + "typeName": "ZodObject",
2477 + "unknownKeys": "strict",
2478 + },
2479 + "jsonSchema": {
2480 + "$schema": "http://json-schema.org/draft-07/schema#",
2481 + "additionalProperties": false,
2482 + "properties": {
2483 + "anyOf": {
2484 + "type": "null",
2485 + },
2486 + "typeArray": {
2487 + "type": "null",
2488 + },
2489 + },
2490 + "required": [
2491 + "typeArray",
2492 + "anyOf",
2493 + ],
2494 + "type": "object",
2495 + },
2496 + },
2497 + "id": "primitive-null-only-unions",
2498 + },
2499 + {
2500 + "fingerprint": {
2501 + "def": {
2502 + "catchall": {
2503 + "typeName": "ZodNever",
2504 + },
2505 + "shape": {
2506 + "code": {
2507 + "effect": "refinement",
2508 + "schema": {
2509 + "effect": "refinement",
2510 + "schema": {
2511 + "checks": [
2512 + {
2513 + "kind": "regex",
2514 + "regex": "^[A-Z]{2}$",
2515 + },
2516 + ],
2517 + "typeName": "ZodString",
2518 + },
2519 + "typeName": "ZodEffects",
2520 + },
2521 + "typeName": "ZodEffects",
2522 + },
2523 + "count": {
2524 + "effect": "refinement",
2525 + "schema": {
2526 + "checks": [
2527 + {
2528 + "inclusive": false,
2529 + "kind": "min",
2530 + "message": undefined,
2531 + "value": 0,
2532 + },
2533 + ],
2534 + "typeName": "ZodNumber",
2535 + },
2536 + "typeName": "ZodEffects",
2537 + },
2538 + },
2539 + "typeName": "ZodObject",
2540 + "unknownKeys": "strict",
2541 + },
2542 + "jsonSchema": {
2543 + "$schema": "http://json-schema.org/draft-07/schema#",
2544 + "additionalProperties": false,
2545 + "properties": {
2546 + "code": {
2547 + "pattern": "^[A-Z]{2}$",
2548 + "type": "string",
2549 + },
2550 + "count": {
2551 + "exclusiveMinimum": 0,
2552 + "type": "number",
2553 + },
2554 + },
2555 + "required": [
2556 + "code",
2557 + "count",
2558 + ],
2559 + "type": "object",
2560 + },
2561 + },
2562 + "id": "primitive-scalar-constraints",
2563 + },
2564 + {
2565 + "fingerprint": {
2566 + "def": {
2567 + "catchall": {
2568 + "typeName": "ZodNever",
2569 + },
2570 + "shape": {
2571 + "lower": {
2572 + "checks": [
2573 + {
2574 + "inclusive": true,
2575 + "kind": "min",
2576 + "message": undefined,
2577 + "value": 0,
2578 + },
2579 + {
2580 + "inclusive": false,
2581 + "kind": "min",
2582 + "message": undefined,
2583 + "value": 5,
2584 + },
2585 + ],
2586 + "typeName": "ZodNumber",
2587 + },
2588 + "upper": {
2589 + "checks": [
2590 + {
2591 + "inclusive": true,
2592 + "kind": "max",
2593 + "message": undefined,
2594 + "value": 10,
2595 + },
2596 + {
2597 + "inclusive": false,
2598 + "kind": "max",
2599 + "message": undefined,
2600 + "value": 5,
2601 + },
2602 + ],
2603 + "typeName": "ZodNumber",
2604 + },
2605 + },
2606 + "typeName": "ZodObject",
2607 + "unknownKeys": "strict",
2608 + },
2609 + "jsonSchema": {
2610 + "$schema": "http://json-schema.org/draft-07/schema#",
2611 + "additionalProperties": false,
2612 + "properties": {
2613 + "lower": {
2614 + "exclusiveMinimum": 5,
2615 + "minimum": 0,
2616 + "type": "number",
2617 + },
2618 + "upper": {
2619 + "exclusiveMaximum": 5,
2620 + "maximum": 10,
2621 + "type": "number",
2622 + },
2623 + },
2624 + "required": [
2625 + "lower",
2626 + "upper",
2627 + ],
2628 + "type": "object",
2629 + },
2630 + },
2631 + "id": "primitive-independent-numeric-bounds",
2632 + },
2633 + {
2634 + "fingerprint": {
2635 + "def": {
2636 + "catchall": {
2637 + "typeName": "ZodNever",
2638 + },
2639 + "shape": {
2640 + "value": {
2641 + "left": {
2642 + "checks": [],
2643 + "typeName": "ZodString",
2644 + },
2645 + "right": {
2646 + "typeName": "ZodLiteral",
2647 + "value": 1,
2648 + },
2649 + "typeName": "ZodIntersection",
2650 + },
2651 + },
2652 + "typeName": "ZodObject",
2653 + "unknownKeys": "strict",
2654 + },
2655 + "jsonSchema": {
2656 + "$schema": "http://json-schema.org/draft-07/schema#",
2657 + "additionalProperties": false,
2658 + "properties": {
2659 + "value": {
2660 + "allOf": [
2661 + {
2662 + "type": "string",
2663 + },
2664 + {
2665 + "const": 1,
2666 + "type": "number",
2667 + },
2668 + ],
2669 + },
2670 + },
2671 + "required": [
2672 + "value",
2673 + ],
2674 + "type": "object",
2675 + },
2676 + },
2677 + "id": "primitive-const-intersects-declared-type",
2678 + },
2679 + {
2680 + "fingerprint": {
2681 + "def": {
2682 + "catchall": {
2683 + "typeName": "ZodNever",
2684 + },
2685 + "shape": {
2686 + "value": {
2687 + "left": {
2688 + "typeName": "ZodAny",
2689 + },
2690 + "right": {
2691 + "effect": "refinement",
2692 + "schema": {
2693 + "typeName": "ZodAny",
2694 + },
2695 + "typeName": "ZodEffects",
2696 + },
2697 + "typeName": "ZodIntersection",
2698 + },
2699 + },
2700 + "typeName": "ZodObject",
2701 + "unknownKeys": "strict",
2702 + },
2703 + "jsonSchema": {
2704 + "$schema": "http://json-schema.org/draft-07/schema#",
2705 + "additionalProperties": false,
2706 + "properties": {
2707 + "value": {
2708 + "allOf": [
2709 + {},
2710 + {},
2711 + ],
2712 + },
2713 + },
2714 + "required": [
2715 + "value",
2716 + ],
2717 + "type": "object",
2718 + },
2719 + },
2720 + "id": "primitive-compound-enum-values",
2721 + },
2722 + {
2723 + "fingerprint": {
2724 + "def": {
2725 + "catchall": {
2726 + "typeName": "ZodNever",
2727 + },
2728 + "shape": {
2729 + "flag": {
2730 + "left": {
2731 + "typeName": "ZodAny",
2732 + },
2733 + "right": {
2734 + "typeName": "ZodLiteral",
2735 + "value": false,
2736 + },
2737 + "typeName": "ZodIntersection",
2738 + },
2739 + "maybe": {
2740 + "left": {
2741 + "typeName": "ZodAny",
2742 + },
2743 + "right": {
2744 + "typeName": "ZodLiteral",
2745 + "value": null,
2746 + },
2747 + "typeName": "ZodIntersection",
2748 + },
2749 + },
2750 + "typeName": "ZodObject",
2751 + "unknownKeys": "strict",
2752 + },
2753 + "jsonSchema": {
2754 + "$schema": "http://json-schema.org/draft-07/schema#",
2755 + "additionalProperties": false,
2756 + "properties": {
2757 + "flag": {
2758 + "allOf": [
2759 + {},
2760 + {
2761 + "const": false,
2762 + "type": "boolean",
2763 + },
2764 + ],
2765 + },
2766 + "maybe": {
2767 + "allOf": [
2768 + {},
2769 + {
2770 + "type": "object",
2771 + },
2772 + ],
2773 + },
2774 + },
2775 + "required": [
2776 + "maybe",
2777 + "flag",
2778 + ],
2779 + "type": "object",
2780 + },
2781 + },
2782 + "id": "primitive-const-null-and-false",
2783 + },
2784 + {
2785 + "fingerprint": {
2786 + "def": {
2787 + "catchall": {
2788 + "typeName": "ZodNever",
2789 + },
2790 + "shape": {
2791 + "bits": {
2792 + "left": {
2793 + "typeName": "ZodAny",
2794 + },
2795 + "right": {
2796 + "options": [
2797 + {
2798 + "typeName": "ZodLiteral",
2799 + "value": 0,
2800 + },
2801 + {
2802 + "typeName": "ZodLiteral",
2803 + "value": 1,
2804 + },
2805 + ],
2806 + "typeName": "ZodUnion",
2807 + },
2808 + "typeName": "ZodIntersection",
2809 + },
2810 + "toggle": {
2811 + "left": {
2812 + "typeName": "ZodAny",
2813 + },
2814 + "right": {
2815 + "typeName": "ZodLiteral",
2816 + "value": true,
2817 + },
2818 + "typeName": "ZodIntersection",
2819 + },
2820 + },
2821 + "typeName": "ZodObject",
2822 + "unknownKeys": "strict",
2823 + },
2824 + "jsonSchema": {
2825 + "$schema": "http://json-schema.org/draft-07/schema#",
2826 + "additionalProperties": false,
2827 + "properties": {
2828 + "bits": {
2829 + "allOf": [
2830 + {},
2831 + {
2832 + "enum": [
2833 + 0,
2834 + 1,
2835 + ],
2836 + "type": "number",
2837 + },
2838 + ],
2839 + },
2840 + "toggle": {
2841 + "allOf": [
2842 + {},
2843 + {
2844 + "const": true,
2845 + "type": "boolean",
2846 + },
2847 + ],
2848 + },
2849 + },
2850 + "required": [
2851 + "bits",
2852 + "toggle",
2853 + ],
2854 + "type": "object",
2855 + },
2856 + },
2857 + "id": "primitive-enum-boolean-number-identity",
2858 + },
2859 + {
2860 + "fingerprint": {
2861 + "def": {
2862 + "catchall": {
2863 + "typeName": "ZodNever",
2864 + },
2865 + "shape": {
2866 + "value": {
2867 + "left": {
2868 + "typeName": "ZodAny",
2869 + },
2870 + "right": {
2871 + "options": [
2872 + {
2873 + "typeName": "ZodLiteral",
2874 + "value": "a",
2875 + },
2876 + {
2877 + "typeName": "ZodLiteral",
2878 + "value": null,
2879 + },
2880 + ],
2881 + "typeName": "ZodUnion",
2882 + },
2883 + "typeName": "ZodIntersection",
2884 + },
2885 + },
2886 + "typeName": "ZodObject",
2887 + "unknownKeys": "strict",
2888 + },
2889 + "jsonSchema": {
2890 + "$schema": "http://json-schema.org/draft-07/schema#",
2891 + "additionalProperties": false,
2892 + "properties": {
2893 + "value": {
2894 + "allOf": [
2895 + {},
2896 + {
2897 + "enum": [
2898 + "a",
2899 + null,
2900 + ],
2901 + "type": [
2902 + "string",
2903 + "null",
2904 + ],
2905 + },
2906 + ],
2907 + },
2908 + },
2909 + "required": [
2910 + "value",
2911 + ],
2912 + "type": "object",
2913 + },
2914 + },
2915 + "id": "primitive-enum-with-null-member",
2916 + },
2917 + {
2918 + "fingerprint": {
2919 + "def": {
2920 + "catchall": {
2921 + "typeName": "ZodNever",
2922 + },
2923 + "shape": {
2924 + "code": {
2925 + "left": {
2926 + "effect": "refinement",
2927 + "schema": {
2928 + "checks": [],
2929 + "typeName": "ZodString",
2930 + },
2931 + "typeName": "ZodEffects",
2932 + },
2933 + "right": {
2934 + "typeName": "ZodLiteral",
2935 + "value": "a",
2936 + },
2937 + "typeName": "ZodIntersection",
2938 + },
2939 + },
2940 + "typeName": "ZodObject",
2941 + "unknownKeys": "strict",
2942 + },
2943 + "jsonSchema": {
2944 + "$schema": "http://json-schema.org/draft-07/schema#",
2945 + "additionalProperties": false,
2946 + "properties": {
2947 + "code": {
2948 + "allOf": [
2949 + {
2950 + "type": "string",
2951 + },
2952 + {
2953 + "const": "a",
2954 + "type": "string",
2955 + },
2956 + ],
2957 + },
2958 + },
2959 + "required": [
2960 + "code",
2961 + ],
2962 + "type": "object",
2963 + },
2964 + },
2965 + "id": "primitive-const-constraint-conjunction",
2966 + },
2967 + {
2968 + "fingerprint": {
2969 + "def": {
2970 + "catchall": {
2971 + "typeName": "ZodNever",
2972 + },
2973 + "shape": {
2974 + "count": {
2975 + "checks": [
2976 + {
2977 + "kind": "int",
2978 + "message": undefined,
2979 + },
2980 + {
2981 + "inclusive": true,
2982 + "kind": "min",
2983 + "message": undefined,
2984 + "value": 5,
2985 + },
2986 + {
2987 + "inclusive": true,
2988 + "kind": "max",
2989 + "message": undefined,
2990 + "value": 10,
2991 + },
2992 + ],
2993 + "typeName": "ZodNumber",
2994 + },
2995 + },
2996 + "typeName": "ZodObject",
2997 + "unknownKeys": "strict",
2998 + },
2999 + "jsonSchema": {
3000 + "$schema": "http://json-schema.org/draft-07/schema#",
3001 + "additionalProperties": false,
3002 + "properties": {
3003 + "count": {
3004 + "maximum": 10,
3005 + "minimum": 5,
3006 + "type": "integer",
3007 + },
3008 + },
3009 + "required": [
3010 + "count",
3011 + ],
3012 + "type": "object",
3013 + },
3014 + },
3015 + "id": "primitive-inclusive-numeric-boundaries",
3016 + },
3017 + {
3018 + "fingerprint": {
3019 + "def": {
3020 + "catchall": {
3021 + "typeName": "ZodNever",
3022 + },
3023 + "shape": {
3024 + "value": {
3025 + "left": {
3026 + "left": {
3027 + "typeName": "ZodAny",
3028 + },
3029 + "right": {
3030 + "typeName": "ZodLiteral",
3031 + "value": "b",
3032 + },
3033 + "typeName": "ZodIntersection",
3034 + },
3035 + "right": {
3036 + "typeName": "ZodEnum",
3037 + "values": [
3038 + "a",
3039 + "b",
3040 + ],
3041 + },
3042 + "typeName": "ZodIntersection",
3043 + },
3044 + },
3045 + "typeName": "ZodObject",
3046 + "unknownKeys": "strict",
3047 + },
3048 + "jsonSchema": {
3049 + "$schema": "http://json-schema.org/draft-07/schema#",
3050 + "additionalProperties": false,
3051 + "properties": {
3052 + "value": {
3053 + "allOf": [
3054 + {},
3055 + {
3056 + "const": "b",
3057 + "type": "string",
3058 + },
3059 + {
3060 + "enum": [
3061 + "a",
3062 + "b",
3063 + ],
3064 + "type": "string",
3065 + },
3066 + ],
3067 + },
3068 + },
3069 + "required": [
3070 + "value",
3071 + ],
3072 + "type": "object",
3073 + },
3074 + },
3075 + "id": "primitive-const-narrows-enum",
3076 + },
3077 + {
3078 + "fingerprint": {
3079 + "def": {
3080 + "catchall": {
3081 + "typeName": "ZodNever",
3082 + },
3083 + "shape": {
3084 + "value": {
3085 + "left": {
3086 + "typeName": "ZodAny",
3087 + },
3088 + "right": {
3089 + "effect": "refinement",
3090 + "schema": {
3091 + "typeName": "ZodAny",
3092 + },
3093 + "typeName": "ZodEffects",
3094 + },
3095 + "typeName": "ZodIntersection",
3096 + },
3097 + },
3098 + "typeName": "ZodObject",
3099 + "unknownKeys": "strict",
3100 + },
3101 + "jsonSchema": {
3102 + "$schema": "http://json-schema.org/draft-07/schema#",
3103 + "additionalProperties": false,
3104 + "properties": {
3105 + "value": {
3106 + "allOf": [
3107 + {},
3108 + {},
3109 + ],
3110 + },
3111 + },
3112 + "required": [
3113 + "value",
3114 + ],
3115 + "type": "object",
3116 + },
3117 + },
3118 + "id": "primitive-compound-const-deep-equality",
3119 + },
3120 + {
3121 + "fingerprint": {
3122 + "def": {
3123 + "catchall": {
3124 + "typeName": "ZodNever",
3125 + },
3126 + "shape": {
3127 + "glyph": {
3128 + "effect": "refinement",
3129 + "schema": {
3130 + "checks": [],
3131 + "typeName": "ZodString",
3132 + },
3133 + "typeName": "ZodEffects",
3134 + },
3135 + },
3136 + "typeName": "ZodObject",
3137 + "unknownKeys": "strict",
3138 + },
3139 + "jsonSchema": {
3140 + "$schema": "http://json-schema.org/draft-07/schema#",
3141 + "additionalProperties": false,
3142 + "properties": {
3143 + "glyph": {
3144 + "type": "string",
3145 + },
3146 + },
3147 + "required": [
3148 + "glyph",
3149 + ],
3150 + "type": "object",
3151 + },
3152 + },
3153 + "id": "primitive-unicode-code-point-length",
3154 + },
3155 + {
3156 + "fingerprint": {
3157 + "def": {
3158 + "catchall": {
3159 + "typeName": "ZodNever",
3160 + },
3161 + "shape": {
3162 + "value": {
3163 + "left": {
3164 + "effect": "refinement",
3165 + "schema": {
3166 + "typeName": "ZodAny",
3167 + },
3168 + "typeName": "ZodEffects",
3169 + },
3170 + "right": {
3171 + "typeName": "ZodEnum",
3172 + "values": [
3173 + "a",
3174 + "abc",
3175 + ],
3176 + },
3177 + "typeName": "ZodIntersection",
3178 + },
3179 + },
3180 + "typeName": "ZodObject",
3181 + "unknownKeys": "strict",
3182 + },
3183 + "jsonSchema": {
3184 + "$schema": "http://json-schema.org/draft-07/schema#",
3185 + "additionalProperties": false,
3186 + "properties": {
3187 + "value": {
3188 + "allOf": [
3189 + {},
3190 + {
3191 + "enum": [
3192 + "a",
3193 + "abc",
3194 + ],
3195 + "type": "string",
3196 + },
3197 + ],
3198 + },
3199 + },
3200 + "required": [
3201 + "value",
3202 + ],
3203 + "type": "object",
3204 + },
3205 + },
3206 + "id": "primitive-typeless-constraint-scoping",
3207 + },
3208 + {
3209 + "fingerprint": {
3210 + "def": {
3211 + "catchall": {
3212 + "typeName": "ZodNever",
3213 + },
3214 + "shape": {
3215 + "step": {
3216 + "effect": "refinement",
3217 + "schema": {
3218 + "checks": [],
3219 + "typeName": "ZodNumber",
3220 + },
3221 + "typeName": "ZodEffects",
3222 + },
3223 + },
3224 + "typeName": "ZodObject",
3225 + "unknownKeys": "strict",
3226 + },
3227 + "jsonSchema": {
3228 + "$schema": "http://json-schema.org/draft-07/schema#",
3229 + "additionalProperties": false,
3230 + "properties": {
3231 + "step": {
3232 + "type": "number",
3233 + },
3234 + },
3235 + "required": [
3236 + "step",
3237 + ],
3238 + "type": "object",
3239 + },
3240 + },
3241 + "id": "primitive-float-multiple-of",
3242 + },
3243 + {
3244 + "fingerprint": {
3245 + "def": {
3246 + "catchall": {
3247 + "typeName": "ZodNever",
3248 + },
3249 + "shape": {
3250 + "lower": {
3251 + "checks": [
3252 + {
3253 + "inclusive": false,
3254 + "kind": "min",
3255 + "message": undefined,
3256 + "value": 5,
3257 + },
3258 + ],
3259 + "typeName": "ZodNumber",
3260 + },
3261 + "upper": {
3262 + "checks": [
3263 + {
3264 + "inclusive": false,
3265 + "kind": "max",
3266 + "message": undefined,
3267 + "value": 5,
3268 + },
3269 + ],
3270 + "typeName": "ZodNumber",
3271 + },
3272 + },
3273 + "typeName": "ZodObject",
3274 + "unknownKeys": "strict",
3275 + },
3276 + "jsonSchema": {
3277 + "$schema": "http://json-schema.org/draft-07/schema#",
3278 + "additionalProperties": false,
3279 + "properties": {
3280 + "lower": {
3281 + "exclusiveMinimum": 5,
3282 + "type": "number",
3283 + },
3284 + "upper": {
3285 + "exclusiveMaximum": 5,
3286 + "type": "number",
3287 + },
3288 + },
3289 + "required": [
3290 + "lower",
3291 + "upper",
3292 + ],
3293 + "type": "object",
3294 + },
3295 + },
3296 + "id": "primitive-draft4-boolean-exclusive-bounds",
3297 + },
3298 + {
3299 + "fingerprint": {
3300 + "def": {
3301 + "catchall": {
3302 + "typeName": "ZodNever",
3303 + },
3304 + "shape": {
3305 + "value": {
3306 + "options": [
3307 + {
3308 + "effect": "refinement",
3309 + "schema": {
3310 + "checks": [],
3311 + "typeName": "ZodString",
3312 + },
3313 + "typeName": "ZodEffects",
3314 + },
3315 + {
3316 + "checks": [
3317 + {
3318 + "inclusive": true,
3319 + "kind": "min",
3320 + "message": undefined,
3321 + "value": 10,
3322 + },
3323 + ],
3324 + "typeName": "ZodNumber",
3325 + },
3326 + ],
3327 + "typeName": "ZodUnion",
3328 + },
3329 + },
3330 + "typeName": "ZodObject",
3331 + "unknownKeys": "strict",
3332 + },
3333 + "jsonSchema": {
3334 + "$schema": "http://json-schema.org/draft-07/schema#",
3335 + "additionalProperties": false,
3336 + "properties": {
3337 + "value": {
3338 + "anyOf": [
3339 + {
3340 + "type": "string",
3341 + },
3342 + {
3343 + "minimum": 10,
3344 + "type": "number",
3345 + },
3346 + ],
3347 + },
3348 + },
3349 + "required": [
3350 + "value",
3351 + ],
3352 + "type": "object",
3353 + },
3354 + },
3355 + "id": "primitive-type-array-constraint-scoping",
3356 + },
3357 + {
3358 + "fingerprint": {
3359 + "def": {
3360 + "catchall": {
3361 + "typeName": "ZodNever",
3362 + },
3363 + "shape": {
3364 + "value": {
3365 + "innerType": {
3366 + "left": {
3367 + "typeName": "ZodAny",
3368 + },
3369 + "right": {
3370 + "typeName": "ZodNever",
3371 + },
3372 + "typeName": "ZodIntersection",
3373 + },
3374 + "typeName": "ZodOptional",
3375 + },
3376 + },
3377 + "typeName": "ZodObject",
3378 + "unknownKeys": "strict",
3379 + },
3380 + "jsonSchema": {
3381 + "$schema": "http://json-schema.org/draft-07/schema#",
3382 + "additionalProperties": false,
3383 + "properties": {
3384 + "value": {
3385 + "allOf": [
3386 + {},
3387 + {
3388 + "not": {},
3389 + },
3390 + ],
3391 + },
3392 + },
3393 + "type": "object",
3394 + },
3395 + },
3396 + "id": "primitive-empty-enum-optional-property",
3397 + },
3398 + {
3399 + "fingerprint": {
3400 + "def": {
3401 + "catchall": {
3402 + "catchall": {
3403 + "typeName": "ZodNever",
3404 + },
3405 + "shape": {
3406 + "enabled": {
3407 + "defaultValue": false,
3408 + "innerType": {
3409 + "innerType": {
3410 + "defaultValue": false,
3411 + "innerType": {
3412 + "typeName": "ZodBoolean",
3413 + },
3414 + "typeName": "ZodDefault",
3415 + },
3416 + "typeName": "ZodOptional",
3417 + },
3418 + "typeName": "ZodDefault",
3419 + },
3420 + },
3421 + "typeName": "ZodObject",
3422 + "unknownKeys": "strict",
3423 + },
3424 + "shape": {
3425 + "name": {
3426 + "innerType": {
3427 + "checks": [],
3428 + "typeName": "ZodString",
3429 + },
3430 + "typeName": "ZodOptional",
3431 + },
3432 + },
3433 + "typeName": "ZodObject",
3434 + "unknownKeys": "strip",
3435 + },
3436 + "jsonSchema": {
3437 + "$schema": "http://json-schema.org/draft-07/schema#",
3438 + "additionalProperties": {
3439 + "additionalProperties": false,
3440 + "properties": {
3441 + "enabled": {
3442 + "default": false,
3443 + "type": "boolean",
3444 + },
3445 + },
3446 + "type": "object",
3447 + },
3448 + "properties": {
3449 + "name": {
3450 + "type": "string",
3451 + },
3452 + },
3453 + "type": "object",
3454 + },
3455 + },
3456 + "id": "additional-property-default-materialization",
3457 + },
3458 + {
3459 + "fingerprint": {
3460 + "def": {
3461 + "catchall": {
3462 + "typeName": "ZodNever",
3463 + },
3464 + "guarded": true,
3465 + "shape": {
3466 + "value": {
3467 + "options": [
3468 + {
3469 + "items": [],
3470 + "rest": null,
3471 + "typeName": "ZodTuple",
3472 + },
3473 + {
3474 + "items": [
3475 + {
3476 + "checks": [],
3477 + "typeName": "ZodString",
3478 + },
3479 + ],
3480 + "rest": null,
3481 + "typeName": "ZodTuple",
3482 + },
3483 + {
3484 + "items": [
3485 + {
3486 + "checks": [],
3487 + "typeName": "ZodString",
3488 + },
3489 + {
3490 + "checks": [
3491 + {
3492 + "kind": "int",
3493 + "message": undefined,
3494 + },
3495 + ],
3496 + "typeName": "ZodNumber",
3497 + },
3498 + ],
3499 + "rest": null,
3500 + "typeName": "ZodTuple",
3501 + },
3502 + ],
3503 + "typeName": "ZodUnion",
3504 + },
3505 + },
3506 + "typeName": "ZodObject",
3507 + "unknownKeys": "strict",
3508 + },
3509 + "jsonSchema": {
3510 + "$schema": "http://json-schema.org/draft-07/schema#",
3511 + "additionalProperties": false,
3512 + "properties": {
3513 + "value": {
3514 + "anyOf": [
3515 + {
3516 + "items": [],
3517 + "maxItems": 0,
3518 + "minItems": 0,
3519 + "type": "array",
3520 + },
3521 + {
3522 + "items": [
3523 + {
3524 + "type": "string",
3525 + },
3526 + ],
3527 + "maxItems": 1,
3528 + "minItems": 1,
3529 + "type": "array",
3530 + },
3531 + {
3532 + "items": [
3533 + {
3534 + "$ref": "#/properties/value/anyOf/1/items/0",
3535 + },
3536 + {
3537 + "type": "integer",
3538 + },
3539 + ],
3540 + "maxItems": 2,
3541 + "minItems": 2,
3542 + "type": "array",
3543 + },
3544 + ],
3545 + },
3546 + },
3547 + "required": [
3548 + "value",
3549 + ],
3550 + "type": "object",
3551 + },
3552 + },
3553 + "id": "composition-fixed-tuple-items",
3554 + },
3555 + {
3556 + "fingerprint": {
3557 + "def": {
3558 + "catchall": {
3559 + "typeName": "ZodNever",
3560 + },
3561 + "shape": {
3562 + "value": {
3563 + "options": [
3564 + {
3565 + "items": [],
3566 + "rest": null,
3567 + "typeName": "ZodTuple",
3568 + },
3569 + {
3570 + "items": [
3571 + {
3572 + "checks": [],
3573 + "typeName": "ZodString",
3574 + },
3575 + ],
3576 + "rest": null,
3577 + "typeName": "ZodTuple",
3578 + },
3579 + {
3580 + "items": [
3581 + {
3582 + "checks": [],
3583 + "typeName": "ZodString",
3584 + },
3585 + {
3586 + "checks": [
3587 + {
3588 + "kind": "int",
3589 + "message": undefined,
3590 + },
3591 + ],
3592 + "typeName": "ZodNumber",
3593 + },
3594 + ],
3595 + "rest": {
3596 + "typeName": "ZodAny",
3597 + },
3598 + "typeName": "ZodTuple",
3599 + },
3600 + ],
3601 + "typeName": "ZodUnion",
3602 + },
3603 + },
3604 + "typeName": "ZodObject",
3605 + "unknownKeys": "strict",
3606 + },
3607 + "jsonSchema": {
3608 + "$schema": "http://json-schema.org/draft-07/schema#",
3609 + "additionalProperties": false,
3610 + "properties": {
3611 + "value": {
3612 + "anyOf": [
3613 + {
3614 + "items": [],
3615 + "maxItems": 0,
3616 + "minItems": 0,
3617 + "type": "array",
3618 + },
3619 + {
3620 + "items": [
3621 + {
3622 + "type": "string",
3623 + },
3624 + ],
3625 + "maxItems": 1,
3626 + "minItems": 1,
3627 + "type": "array",
3628 + },
3629 + {
3630 + "additionalItems": {},
3631 + "items": [
3632 + {
3633 + "$ref": "#/properties/value/anyOf/1/items/0",
3634 + },
3635 + {
3636 + "type": "integer",
3637 + },
3638 + ],
3639 + "minItems": 2,
3640 + "type": "array",
3641 + },
3642 + ],
3643 + },
3644 + },
3645 + "required": [
3646 + "value",
3647 + ],
3648 + "type": "object",
3649 + },
3650 + },
3651 + "id": "composition-open-tuple-items",
3652 + },
3653 + {
3654 + "fingerprint": {
3655 + "def": {
3656 + "catchall": {
3657 + "typeName": "ZodNever",
3658 + },
3659 + "guarded": true,
3660 + "shape": {
3661 + "value": {
3662 + "options": [
3663 + {
3664 + "items": [],
3665 + "rest": null,
3666 + "typeName": "ZodTuple",
3667 + },
3668 + {
3669 + "items": [
3670 + {
3671 + "checks": [],
3672 + "typeName": "ZodString",
3673 + },
3674 + ],
3675 + "rest": null,
3676 + "typeName": "ZodTuple",
3677 + },
3678 + {
3679 + "items": [
3680 + {
3681 + "checks": [],
3682 + "typeName": "ZodString",
3683 + },
3684 + {
3685 + "typeName": "ZodNever",
3686 + },
3687 + ],
3688 + "rest": null,
3689 + "typeName": "ZodTuple",
3690 + },
3691 + ],
3692 + "typeName": "ZodUnion",
3693 + },
3694 + },
3695 + "typeName": "ZodObject",
3696 + "unknownKeys": "strict",
3697 + },
3698 + "jsonSchema": {
3699 + "$schema": "http://json-schema.org/draft-07/schema#",
3700 + "additionalProperties": false,
3701 + "properties": {
3702 + "value": {
3703 + "anyOf": [
3704 + {
3705 + "items": [],
3706 + "maxItems": 0,
3707 + "minItems": 0,
3708 + "type": "array",
3709 + },
3710 + {
3711 + "items": [
3712 + {
3713 + "type": "string",
3714 + },
3715 + ],
3716 + "maxItems": 1,
3717 + "minItems": 1,
3718 + "type": "array",
3719 + },
3720 + {
3721 + "items": [
3722 + {
3723 + "$ref": "#/properties/value/anyOf/1/items/0",
3724 + },
3725 + {
3726 + "not": {},
3727 + },
3728 + ],
3729 + "maxItems": 2,
3730 + "minItems": 2,
3731 + "type": "array",
3732 + },
3733 + ],
3734 + },
3735 + },
3736 + "required": [
3737 + "value",
3738 + ],
3739 + "type": "object",
3740 + },
3741 + },
3742 + "id": "composition-false-tuple-position",
3743 + },
3744 + {
3745 + "fingerprint": {
3746 + "def": {
3747 + "catchall": {
3748 + "typeName": "ZodNever",
3749 + },
3750 + "guarded": true,
3751 + "shape": {
3752 + "value": {
3753 + "left": {
3754 + "catchall": {
3755 + "typeName": "ZodNever",
3756 + },
3757 + "shape": {
3758 + "a": {
3759 + "checks": [],
3760 + "typeName": "ZodString",
3761 + },
3762 + },
3763 + "typeName": "ZodObject",
3764 + "unknownKeys": "passthrough",
3765 + },
3766 + "right": {
3767 + "catchall": {
3768 + "typeName": "ZodNever",
3769 + },
3770 + "shape": {
3771 + "b": {
3772 + "checks": [
3773 + {
3774 + "kind": "int",
3775 + "message": undefined,
3776 + },
3777 + ],
3778 + "typeName": "ZodNumber",
3779 + },
3780 + },
3781 + "typeName": "ZodObject",
3782 + "unknownKeys": "passthrough",
3783 + },
3784 + "typeName": "ZodIntersection",
3785 + },
3786 + },
3787 + "typeName": "ZodObject",
3788 + "unknownKeys": "strict",
3789 + },
3790 + "jsonSchema": {
3791 + "$schema": "http://json-schema.org/draft-07/schema#",
3792 + "additionalProperties": false,
3793 + "properties": {
3794 + "value": {
3795 + "allOf": [
3796 + {
3797 + "additionalProperties": true,
3798 + "properties": {
3799 + "a": {
3800 + "type": "string",
3801 + },
3802 + },
3803 + "required": [
3804 + "a",
3805 + ],
3806 + "type": "object",
3807 + },
3808 + {
3809 + "additionalProperties": true,
3810 + "properties": {
3811 + "b": {
3812 + "type": "integer",
3813 + },
3814 + },
3815 + "required": [
3816 + "b",
3817 + ],
3818 + "type": "object",
3819 + },
3820 + ],
3821 + },
3822 + },
3823 + "required": [
3824 + "value",
3825 + ],
3826 + "type": "object",
3827 + },
3828 + },
3829 + "id": "composition-allof-object-intersection",
3830 + },
3831 + {
3832 + "fingerprint": {
3833 + "def": {
3834 + "catchall": {
3835 + "typeName": "ZodNever",
3836 + },
3837 + "guarded": true,
3838 + "shape": {
3839 + "value": {
3840 + "effect": "refinement",
3841 + "schema": {
3842 + "left": {
3843 + "catchall": {
3844 + "typeName": "ZodNever",
3845 + },
3846 + "shape": {
3847 + "a": {
3848 + "checks": [],
3849 + "typeName": "ZodString",
3850 + },
3851 + },
3852 + "typeName": "ZodObject",
3853 + "unknownKeys": "passthrough",
3854 + },
3855 + "right": {
3856 + "catchall": {
3857 + "typeName": "ZodNever",
3858 + },
3859 + "shape": {
3860 + "b": {
3861 + "checks": [],
3862 + "typeName": "ZodString",
3863 + },
3864 + },
3865 + "typeName": "ZodObject",
3866 + "unknownKeys": "passthrough",
3867 + },
3868 + "typeName": "ZodIntersection",
3869 + },
3870 + "typeName": "ZodEffects",
3871 + },
3872 + },
3873 + "typeName": "ZodObject",
3874 + "unknownKeys": "strict",
3875 + },
3876 + "jsonSchema": {
3877 + "$schema": "http://json-schema.org/draft-07/schema#",
3878 + "additionalProperties": false,
3879 + "properties": {
3880 + "value": {
3881 + "allOf": [
3882 + {
3883 + "additionalProperties": true,
3884 + "properties": {
3885 + "a": {
3886 + "type": "string",
3887 + },
3888 + },
3889 + "required": [
3890 + "a",
3891 + ],
3892 + "type": "object",
3893 + },
3894 + {
3895 + "additionalProperties": true,
3896 + "properties": {
3897 + "b": {
3898 + "type": "string",
3899 + },
3900 + },
3901 + "required": [
3902 + "b",
3903 + ],
3904 + "type": "object",
3905 + },
3906 + ],
3907 + },
3908 + },
3909 + "required": [
3910 + "value",
3911 + ],
3912 + "type": "object",
3913 + },
3914 + },
3915 + "id": "composition-allof-closed-object-branches",
3916 + },
3917 + {
3918 + "fingerprint": {
3919 + "def": {
3920 + "catchall": {
3921 + "typeName": "ZodNever",
3922 + },
3923 + "guarded": true,
3924 + "shape": {
3925 + "value": {
3926 + "left": {
3927 + "effect": "refinement",
3928 + "schema": {
3929 + "checks": [],
3930 + "typeName": "ZodString",
3931 + },
3932 + "typeName": "ZodEffects",
3933 + },
3934 + "right": {
3935 + "checks": [
3936 + {
3937 + "kind": "regex",
3938 + "regex": "^[A-Z]+$",
3939 + },
3940 + ],
3941 + "typeName": "ZodString",
3942 + },
3943 + "typeName": "ZodIntersection",
3944 + },
3945 + },
3946 + "typeName": "ZodObject",
3947 + "unknownKeys": "strict",
3948 + },
3949 + "jsonSchema": {
3950 + "$schema": "http://json-schema.org/draft-07/schema#",
3951 + "additionalProperties": false,
3952 + "properties": {
3953 + "value": {
3954 + "allOf": [
3955 + {
3956 + "type": "string",
3957 + },
3958 + {
3959 + "pattern": "^[A-Z]+$",
3960 + "type": "string",
3961 + },
3962 + ],
3963 + },
3964 + },
3965 + "required": [
3966 + "value",
3967 + ],
3968 + "type": "object",
3969 + },
3970 + },
3971 + "id": "composition-scalar-allof",
3972 + },
3973 + {
3974 + "fingerprint": {
3975 + "def": {
3976 + "catchall": {
3977 + "typeName": "ZodNever",
3978 + },
3979 + "guarded": true,
3980 + "shape": {
3981 + "value": {
3982 + "effect": "refinement",
3983 + "schema": {
3984 + "typeName": "ZodAny",
3985 + },
3986 + "typeName": "ZodEffects",
3987 + },
3988 + },
3989 + "typeName": "ZodObject",
3990 + "unknownKeys": "strict",
3991 + },
3992 + "jsonSchema": {
3993 + "$schema": "http://json-schema.org/draft-07/schema#",
3994 + "additionalProperties": false,
3995 + "properties": {
3996 + "value": {},
3997 + },
3998 + "required": [
3999 + "value",
4000 + ],
4001 + "type": "object",
4002 + },
4003 + },
4004 + "id": "composition-oneof-exclusive-match",
4005 + },
4006 +]
4007 +`;
4008 +
4009 +exports[`v3 output fingerprint > matches the pinned snapshot for the shared strict corpus 1`] = `
4010 +[
4011 + {
4012 + "fingerprint": {
4013 + "def": {
4014 + "catchall": {
4015 + "typeName": "ZodNever",
4016 + },
4017 + "shape": {
4018 + "query": {
4019 + "checks": [],
4020 + "typeName": "ZodString",
4021 + },
4022 + },
4023 + "typeName": "ZodObject",
4024 + "unknownKeys": "strict",
4025 + },
4026 + "jsonSchema": {
4027 + "$schema": "http://json-schema.org/draft-07/schema#",
4028 + "additionalProperties": false,
4029 + "properties": {
4030 + "query": {
4031 + "type": "string",
4032 + },
4033 + },
4034 + "required": [
4035 + "query",
4036 + ],
4037 + "type": "object",
4038 + },
4039 + },
4040 + "id": "flat-all-required-unchanged",
4041 + },
4042 + {
4043 + "fingerprint": {
4044 + "def": {
4045 + "catchall": {
4046 + "typeName": "ZodNever",
4047 + },
4048 + "shape": {
4049 + "cfg": {
4050 + "catchall": {
4051 + "typeName": "ZodNever",
4052 + },
4053 + "shape": {
4054 + "note": {
4055 + "description": "optional note",
4056 + "innerType": {
4057 + "checks": [],
4058 + "description": "optional note",
4059 + "typeName": "ZodString",
4060 + },
4061 + "typeName": "ZodOptional",
4062 + },
4063 + "url": {
4064 + "checks": [],
4065 + "typeName": "ZodString",
4066 + },
4067 + },
4068 + "typeName": "ZodObject",
4069 + "unknownKeys": "strict",
4070 + },
4071 + },
4072 + "typeName": "ZodObject",
4073 + "unknownKeys": "strict",
4074 + },
4075 + "jsonSchema": {
4076 + "$schema": "http://json-schema.org/draft-07/schema#",
4077 + "additionalProperties": false,
4078 + "properties": {
4079 + "cfg": {
4080 + "additionalProperties": false,
4081 + "properties": {
4082 + "note": {
4083 + "description": "optional note",
4084 + "type": "string",
4085 + },
4086 + "url": {
4087 + "type": "string",
4088 + },
4089 + },
4090 + "required": [
4091 + "url",
4092 + ],
4093 + "type": "object",
4094 + },
4095 + },
4096 + "required": [
4097 + "cfg",
4098 + ],
4099 + "type": "object",
4100 + },
4101 + },
4102 + "id": "nested-optional-property-widened",
4103 + },
4104 + {
4105 + "fingerprint": {
4106 + "def": {
4107 + "catchall": {
4108 + "typeName": "ZodNever",
4109 + },
4110 + "shape": {
4111 + "a": {
4112 + "innerType": {
4113 + "checks": [],
4114 + "typeName": "ZodString",
4115 + },
4116 + "typeName": "ZodOptional",
4117 + },
4118 + "b": {
4119 + "innerType": {
4120 + "checks": [],
4121 + "typeName": "ZodNumber",
4122 + },
4123 + "typeName": "ZodOptional",
4124 + },
4125 + },
4126 + "typeName": "ZodObject",
4127 + "unknownKeys": "strict",
4128 + },
4129 + "jsonSchema": {
4130 + "$schema": "http://json-schema.org/draft-07/schema#",
4131 + "additionalProperties": false,
4132 + "properties": {
4133 + "a": {
4134 + "type": "string",
4135 + },
4136 + "b": {
4137 + "type": "number",
4138 + },
4139 + },
4140 + "type": "object",
4141 + },
4142 + },
4143 + "id": "no-required-array-widens-every-property",
4144 + },
4145 + {
4146 + "fingerprint": {
4147 + "def": {
4148 + "catchall": {
4149 + "typeName": "ZodNever",
4150 + },
4151 + "shape": {
4152 + "a": {
4153 + "innerType": {
4154 + "checks": [],
4155 + "typeName": "ZodString",
4156 + },
4157 + "typeName": "ZodOptional",
4158 + },
4159 + },
4160 + "typeName": "ZodObject",
4161 + "unknownKeys": "strict",
4162 + },
4163 + "jsonSchema": {
4164 + "$schema": "http://json-schema.org/draft-07/schema#",
4165 + "additionalProperties": false,
4166 + "properties": {
4167 + "a": {
4168 + "type": "string",
4169 + },
4170 + },
4171 + "type": "object",
4172 + },
4173 + },
4174 + "id": "required-empty-array-widens-every-property",
4175 + },
4176 + {
4177 + "fingerprint": {
4178 + "def": {
4179 + "catchall": {
4180 + "typeName": "ZodNever",
4181 + },
4182 + "shape": {
4183 + "id": {
4184 + "description": "identifier",
4185 + "options": [
4186 + {
4187 + "checks": [],
4188 + "description": "identifier",
4189 + "typeName": "ZodString",
4190 + },
4191 + {
4192 + "description": "identifier",
4193 + "typeName": "ZodNull",
4194 + },
4195 + ],
4196 + "typeName": "ZodUnion",
4197 + },
4198 + },
4199 + "typeName": "ZodObject",
4200 + "unknownKeys": "strict",
4201 + },
4202 + "jsonSchema": {
4203 + "$schema": "http://json-schema.org/draft-07/schema#",
4204 + "additionalProperties": false,
4205 + "properties": {
4206 + "id": {
4207 + "description": "identifier",
4208 + "type": [
4209 + "string",
4210 + "null",
4211 + ],
4212 + },
4213 + },
4214 + "required": [
4215 + "id",
4216 + ],
4217 + "type": "object",
4218 + },
4219 + },
4220 + "id": "nullable-type-array-kept",
4221 + },
4222 + {
4223 + "fingerprint": {
4224 + "def": {
4225 + "catchall": {
4226 + "typeName": "ZodNever",
4227 + },
4228 + "shape": {
4229 + "cfg": {
4230 + "options": [
4231 + {
4232 + "catchall": {
4233 + "typeName": "ZodNever",
4234 + },
4235 + "shape": {
4236 + "a": {
4237 + "checks": [],
4238 + "typeName": "ZodString",
4239 + },
4240 + },
4241 + "typeName": "ZodObject",
4242 + "unknownKeys": "strict",
4243 + },
4244 + {
4245 + "typeName": "ZodNull",
4246 + },
4247 + ],
4248 + "typeName": "ZodUnion",
4249 + },
4250 + },
4251 + "typeName": "ZodObject",
4252 + "unknownKeys": "strict",
4253 + },
4254 + "jsonSchema": {
4255 + "$schema": "http://json-schema.org/draft-07/schema#",
4256 + "additionalProperties": false,
4257 + "properties": {
4258 + "cfg": {
4259 + "anyOf": [
4260 + {
4261 + "additionalProperties": false,
4262 + "properties": {
4263 + "a": {
4264 + "type": "string",
4265 + },
4266 + },
4267 + "required": [
4268 + "a",
4269 + ],
4270 + "type": "object",
4271 + },
4272 + {
4273 + "type": "null",
4274 + },
4275 + ],
4276 + },
4277 + },
4278 + "required": [
4279 + "cfg",
4280 + ],
4281 + "type": "object",
4282 + },
4283 + },
4284 + "id": "nullable-object-stays-nullable",
4285 + },
4286 + {
4287 + "fingerprint": {
4288 + "def": {
4289 + "catchall": {
4290 + "typeName": "ZodNever",
4291 + },
4292 + "shape": {
4293 + "xs": {
4294 + "options": [
4295 + {
4296 + "element": {
4297 + "checks": [],
4298 + "typeName": "ZodString",
4299 + },
4300 + "typeName": "ZodArray",
4301 + },
4302 + {
4303 + "typeName": "ZodNull",
4304 + },
4305 + ],
4306 + "typeName": "ZodUnion",
4307 + },
4308 + },
4309 + "typeName": "ZodObject",
4310 + "unknownKeys": "strict",
4311 + },
4312 + "jsonSchema": {
4313 + "$schema": "http://json-schema.org/draft-07/schema#",
4314 + "additionalProperties": false,
4315 + "properties": {
4316 + "xs": {
4317 + "anyOf": [
4318 + {
4319 + "items": {
4320 + "type": "string",
4321 + },
4322 + "type": "array",
4323 + },
4324 + {
4325 + "type": "null",
4326 + },
4327 + ],
4328 + },
4329 + },
4330 + "required": [
4331 + "xs",
4332 + ],
4333 + "type": "object",
4334 + },
4335 + },
4336 + "id": "nullable-array-kept",
4337 + },
4338 + {
4339 + "fingerprint": {
4340 + "def": {
4341 + "catchall": {
4342 + "typeName": "ZodNever",
4343 + },
4344 + "guarded": true,
4345 + "shape": {
4346 + "value": {
4347 + "innerType": {
4348 + "options": [
4349 + {
4350 + "checks": [],
4351 + "typeName": "ZodString",
4352 + },
4353 + {
4354 + "checks": [],
4355 + "typeName": "ZodNumber",
4356 + },
4357 + ],
4358 + "typeName": "ZodUnion",
4359 + },
4360 + "typeName": "ZodOptional",
4361 + },
4362 + },
4363 + "typeName": "ZodObject",
4364 + "unknownKeys": "strict",
4365 + },
4366 + "jsonSchema": {
4367 + "$schema": "http://json-schema.org/draft-07/schema#",
4368 + "additionalProperties": false,
4369 + "properties": {
4370 + "value": {
4371 + "type": [
4372 + "string",
4373 + "number",
4374 + ],
4375 + },
4376 + },
4377 + "type": "object",
4378 + },
4379 + },
4380 + "id": "optional-any-of-gets-null-branch",
4381 + },
4382 + {
4383 + "fingerprint": {
4384 + "def": {
4385 + "catchall": {
4386 + "typeName": "ZodNever",
4387 + },
4388 + "guarded": true,
4389 + "shape": {
4390 + "value": {
4391 + "innerType": {
4392 + "options": [
4393 + {
4394 + "checks": [],
4395 + "typeName": "ZodString",
4396 + },
4397 + {
4398 + "typeName": "ZodNull",
4399 + },
4400 + ],
4401 + "typeName": "ZodUnion",
4402 + },
4403 + "typeName": "ZodOptional",
4404 + },
4405 + },
4406 + "typeName": "ZodObject",
4407 + "unknownKeys": "strict",
4408 + },
4409 + "jsonSchema": {
4410 + "$schema": "http://json-schema.org/draft-07/schema#",
4411 + "additionalProperties": false,
4412 + "properties": {
4413 + "value": {
4414 + "type": [
4415 + "string",
4416 + "null",
4417 + ],
4418 + },
4419 + },
4420 + "type": "object",
4421 + },
4422 + },
4423 + "id": "any-of-already-nullable-unchanged",
4424 + },
4425 + {
4426 + "fingerprint": {
4427 + "def": {
4428 + "catchall": {
4429 + "typeName": "ZodNever",
4430 + },
4431 + "shape": {
4432 + "choice": {
4433 + "description": "pick one",
4434 + "innerType": {
4435 + "description": "pick one",
4436 + "left": {
4437 + "typeName": "ZodAny",
4438 + },
4439 + "right": {
4440 + "typeName": "ZodEnum",
4441 + "values": [
4442 + "a",
4443 + "b",
4444 + ],
4445 + },
4446 + "typeName": "ZodIntersection",
4447 + },
4448 + "typeName": "ZodOptional",
4449 + },
4450 + },
4451 + "typeName": "ZodObject",
4452 + "unknownKeys": "strict",
4453 + },
4454 + "jsonSchema": {
4455 + "$schema": "http://json-schema.org/draft-07/schema#",
4456 + "additionalProperties": false,
4457 + "properties": {
4458 + "choice": {
4459 + "allOf": [
4460 + {},
4461 + {
4462 + "enum": [
4463 + "a",
4464 + "b",
4465 + ],
4466 + "type": "string",
4467 + },
4468 + ],
4469 + "description": "pick one",
4470 + },
4471 + },
4472 + "type": "object",
4473 + },
4474 + },
4475 + "id": "optional-enum-only-wrapped",
4476 + },
4477 + {
4478 + "fingerprint": {
4479 + "def": {
4480 + "catchall": {
4481 + "typeName": "ZodNever",
4482 + },
4483 + "shape": {
4484 + "kind": {
4485 + "innerType": {
4486 + "left": {
4487 + "typeName": "ZodAny",
4488 + },
4489 + "right": {
4490 + "typeName": "ZodLiteral",
4491 + "value": "fixed",
4492 + },
4493 + "typeName": "ZodIntersection",
4494 + },
4495 + "typeName": "ZodOptional",
4496 + },
4497 + },
4498 + "typeName": "ZodObject",
4499 + "unknownKeys": "strict",
4500 + },
4501 + "jsonSchema": {
4502 + "$schema": "http://json-schema.org/draft-07/schema#",
4503 + "additionalProperties": false,
4504 + "properties": {
4505 + "kind": {
4506 + "allOf": [
4507 + {},
4508 + {
4509 + "const": "fixed",
4510 + "type": "string",
4511 + },
4512 + ],
4513 + },
4514 + },
4515 + "type": "object",
4516 + },
4517 + },
4518 + "id": "optional-const-wrapped",
4519 + },
4520 + {
4521 + "fingerprint": {
4522 + "def": {
4523 + "catchall": {
4524 + "typeName": "ZodNever",
4525 + },
4526 + "shape": {
4527 + "anything": {
4528 + "innerType": {
4529 + "typeName": "ZodAny",
4530 + },
4531 + "typeName": "ZodOptional",
4532 + },
4533 + },
4534 + "typeName": "ZodObject",
4535 + "unknownKeys": "strict",
4536 + },
4537 + "jsonSchema": {
4538 + "$schema": "http://json-schema.org/draft-07/schema#",
4539 + "additionalProperties": false,
4540 + "properties": {
4541 + "anything": {},
4542 + },
4543 + "type": "object",
4544 + },
4545 + },
4546 + "id": "optional-empty-schema-unchanged",
4547 + },
4548 + {
4549 + "fingerprint": {
4550 + "def": {
4551 + "catchall": {
4552 + "typeName": "ZodNever",
4553 + },
4554 + "shape": {
4555 + "value": {
4556 + "innerType": {
4557 + "options": [
4558 + {
4559 + "checks": [],
4560 + "typeName": "ZodString",
4561 + },
4562 + {
4563 + "checks": [],
4564 + "typeName": "ZodNumber",
4565 + },
4566 + ],
4567 + "typeName": "ZodUnion",
4568 + },
4569 + "typeName": "ZodOptional",
4570 + },
4571 + },
4572 + "typeName": "ZodObject",
4573 + "unknownKeys": "strict",
4574 + },
4575 + "jsonSchema": {
4576 + "$schema": "http://json-schema.org/draft-07/schema#",
4577 + "additionalProperties": false,
4578 + "properties": {
4579 + "value": {
4580 + "type": [
4581 + "string",
4582 + "number",
4583 + ],
4584 + },
4585 + },
4586 + "type": "object",
4587 + },
4588 + },
4589 + "id": "multi-type-array-gains-null",
4590 + },
4591 + {
4592 + "fingerprint": {
4593 + "def": {
4594 + "catchall": {
4595 + "typeName": "ZodNever",
4596 + },
4597 + "guarded": true,
4598 + "shape": {
4599 + "either": {
4600 + "effect": "refinement",
4601 + "schema": {
4602 + "typeName": "ZodAny",
4603 + },
4604 + "typeName": "ZodEffects",
4605 + },
4606 + },
4607 + "typeName": "ZodObject",
4608 + "unknownKeys": "strict",
4609 + },
4610 + "jsonSchema": {
4611 + "$schema": "http://json-schema.org/draft-07/schema#",
4612 + "additionalProperties": false,
4613 + "properties": {
4614 + "either": {},
4615 + },
4616 + "required": [
4617 + "either",
4618 + ],
4619 + "type": "object",
4620 + },
4621 + },
4622 + "id": "one-of-converted-to-any-of",
4623 + },
4624 + {
4625 + "fingerprint": {
4626 + "def": {
4627 + "catchall": {
4628 + "typeName": "ZodNever",
4629 + },
4630 + "shape": {
4631 + "rows": {
4632 + "element": {
4633 + "catchall": {
4634 + "typeName": "ZodNever",
4635 + },
4636 + "shape": {
4637 + "id": {
4638 + "checks": [],
4639 + "typeName": "ZodString",
4640 + },
4641 + "tag": {
4642 + "innerType": {
4643 + "checks": [],
4644 + "typeName": "ZodString",
4645 + },
4646 + "typeName": "ZodOptional",
4647 + },
4648 + },
4649 + "typeName": "ZodObject",
4650 + "unknownKeys": "strict",
4651 + },
4652 + "typeName": "ZodArray",
4653 + },
4654 + },
4655 + "typeName": "ZodObject",
4656 + "unknownKeys": "strict",
4657 + },
4658 + "jsonSchema": {
4659 + "$schema": "http://json-schema.org/draft-07/schema#",
4660 + "additionalProperties": false,
4661 + "properties": {
4662 + "rows": {
4663 + "items": {
4664 + "additionalProperties": false,
4665 + "properties": {
4666 + "id": {
4667 + "type": "string",
4668 + },
4669 + "tag": {
4670 + "type": "string",
4671 + },
4672 + },
4673 + "required": [
4674 + "id",
4675 + ],
4676 + "type": "object",
4677 + },
4678 + "type": "array",
4679 + },
4680 + },
4681 + "required": [
4682 + "rows",
4683 + ],
4684 + "type": "object",
4685 + },
4686 + },
4687 + "id": "array-items-object-normalized",
4688 + },
4689 + {
4690 + "fingerprint": {
4691 + "def": {
4692 + "catchall": {
4693 + "typeName": "ZodNever",
4694 + },
4695 + "guarded": true,
4696 + "shape": {
4697 + "name": {
4698 + "defaultValue": "x",
4699 + "description": "Example: "a"",
4700 + "innerType": {
4701 + "checks": [],
4702 + "description": "Example: "a"",
4703 + "typeName": "ZodString",
4704 + },
4705 + "typeName": "ZodDefault",
4706 + },
4707 + },
4708 + "typeName": "ZodObject",
4709 + "unknownKeys": "strict",
4710 + },
4711 + "jsonSchema": {
4712 + "$schema": "http://json-schema.org/draft-07/schema#",
4713 + "additionalProperties": false,
4714 + "properties": {
4715 + "name": {
4716 + "default": "x",
4717 + "description": "Example: "a"",
4718 + "type": "string",
4719 + },
4720 + },
4721 + "type": "object",
4722 + },
4723 + },
4724 + "id": "default-and-examples-stripped",
4725 + },
4726 + {
4727 + "fingerprint": {
4728 + "def": {
4729 + "catchall": {
4730 + "typeName": "ZodNever",
4731 + },
4732 + "shape": {
4733 + "opts": {
4734 + "left": {
4735 + "typeName": "ZodAny",
4736 + },
4737 + "right": {
4738 + "effect": "refinement",
4739 + "schema": {
4740 + "typeName": "ZodAny",
4741 + },
4742 + "typeName": "ZodEffects",
4743 + },
4744 + "typeName": "ZodIntersection",
4745 + },
4746 + },
4747 + "typeName": "ZodObject",
4748 + "unknownKeys": "strict",
4749 + },
4750 + "jsonSchema": {
4751 + "$schema": "http://json-schema.org/draft-07/schema#",
4752 + "additionalProperties": false,
4753 + "properties": {
4754 + "opts": {
4755 + "allOf": [
4756 + {},
4757 + {},
4758 + ],
4759 + },
4760 + },
4761 + "required": [
4762 + "opts",
4763 + ],
4764 + "type": "object",
4765 + },
4766 + },
4767 + "id": "enum-values-are-data-not-keywords",
4768 + },
4769 + {
4770 + "fingerprint": {
4771 + "def": {
4772 + "catchall": {
4773 + "typeName": "ZodNever",
4774 + },
4775 + "shape": {
4776 + "$ref": {
4777 + "innerType": {
4778 + "checks": [],
4779 + "typeName": "ZodString",
4780 + },
4781 + "typeName": "ZodOptional",
4782 + },
4783 + "default": {
4784 + "innerType": {
4785 + "checks": [],
4786 + "typeName": "ZodString",
4787 + },
4788 + "typeName": "ZodOptional",
4789 + },
4790 + "properties": {
4791 + "innerType": {
4792 + "catchall": {
4793 + "typeName": "ZodNever",
4794 + },
4795 + "shape": {
4796 + "x": {
4797 + "innerType": {
4798 + "checks": [],
4799 + "typeName": "ZodString",
4800 + },
4801 + "typeName": "ZodOptional",
4802 + },
4803 + },
4804 + "typeName": "ZodObject",
4805 + "unknownKeys": "strict",
4806 + },
4807 + "typeName": "ZodOptional",
4808 + },
4809 + "type": {
4810 + "innerType": {
4811 + "checks": [],
4812 + "typeName": "ZodString",
4813 + },
4814 + "typeName": "ZodOptional",
4815 + },
4816 + },
4817 + "typeName": "ZodObject",
4818 + "unknownKeys": "strict",
4819 + },
4820 + "jsonSchema": {
4821 + "$schema": "http://json-schema.org/draft-07/schema#",
4822 + "additionalProperties": false,
4823 + "properties": {
4824 + "$ref": {
4825 + "type": "string",
4826 + },
4827 + "default": {
4828 + "type": "string",
4829 + },
4830 + "properties": {
4831 + "additionalProperties": false,
4832 + "properties": {
4833 + "x": {
4834 + "type": "string",
4835 + },
4836 + },
4837 + "type": "object",
4838 + },
4839 + "type": {
4840 + "type": "string",
4841 + },
4842 + },
4843 + "type": "object",
4844 + },
4845 + },
4846 + "id": "property-names-are-not-keywords",
4847 + },
4848 + {
4849 + "fingerprint": {
4850 + "def": {
4851 + "catchall": {
4852 + "typeName": "ZodNever",
4853 + },
4854 + "shape": {
4855 + "constructor": {
4856 + "innerType": {
4857 + "checks": [],
4858 + "typeName": "ZodNumber",
4859 + },
4860 + "typeName": "ZodOptional",
4861 + },
4862 + },
4863 + "typeName": "ZodObject",
4864 + "unknownKeys": "strict",
4865 + },
4866 + "jsonSchema": {
4867 + "$schema": "http://json-schema.org/draft-07/schema#",
4868 + "additionalProperties": false,
4869 + "properties": {
4870 + "constructor": {
4871 + "type": "number",
4872 + },
4873 + },
4874 + "type": "object",
4875 + },
4876 + },
4877 + "id": "prototype-key-property-name",
4878 + },
4879 + {
4880 + "fingerprint": {
4881 + "def": {
4882 + "catchall": {
4883 + "typeName": "ZodNever",
4884 + },
4885 + "shape": {
4886 + "headers": {
4887 + "keyType": {
4888 + "checks": [],
4889 + "typeName": "ZodString",
4890 + },
4891 + "typeName": "ZodRecord",
4892 + "valueType": {
4893 + "checks": [],
4894 + "typeName": "ZodString",
4895 + },
4896 + },
4897 + },
4898 + "typeName": "ZodObject",
4899 + "unknownKeys": "strict",
4900 + },
4901 + "jsonSchema": {
4902 + "$schema": "http://json-schema.org/draft-07/schema#",
4903 + "additionalProperties": false,
4904 + "properties": {
4905 + "headers": {
4906 + "additionalProperties": {
4907 + "type": "string",
4908 + },
4909 + "type": "object",
4910 + },
4911 + },
4912 + "required": [
4913 + "headers",
4914 + ],
4915 + "type": "object",
4916 + },
4917 + },
4918 + "id": "schema-valued-additional-properties-unsupported",
4919 + },
4920 + {
4921 + "fingerprint": {
4922 + "def": {
4923 + "catchall": {
4924 + "typeName": "ZodNever",
4925 + },
4926 + "shape": {
4927 + "open": {
4928 + "catchall": {
4929 + "typeName": "ZodNever",
4930 + },
4931 + "shape": {},
4932 + "typeName": "ZodObject",
4933 + "unknownKeys": "passthrough",
4934 + },
4935 + },
4936 + "typeName": "ZodObject",
4937 + "unknownKeys": "strict",
4938 + },
4939 + "jsonSchema": {
4940 + "$schema": "http://json-schema.org/draft-07/schema#",
4941 + "additionalProperties": false,
4942 + "properties": {
4943 + "open": {
4944 + "additionalProperties": true,
4945 + "properties": {},
4946 + "type": "object",
4947 + },
4948 + },
4949 + "required": [
4950 + "open",
4951 + ],
4952 + "type": "object",
4953 + },
4954 + },
4955 + "id": "additional-properties-true-unsupported",
4956 + },
4957 + {
4958 + "fingerprint": {
4959 + "def": {
4960 + "catchall": {
4961 + "typeName": "ZodNever",
4962 + },
4963 + "shape": {
4964 + "open": {
4965 + "keyType": {
4966 + "checks": [],
4967 + "typeName": "ZodString",
4968 + },
4969 + "typeName": "ZodRecord",
4970 + "valueType": {
4971 + "typeName": "ZodAny",
4972 + },
4973 + },
4974 + },
4975 + "typeName": "ZodObject",
4976 + "unknownKeys": "strict",
4977 + },
4978 + "jsonSchema": {
4979 + "$schema": "http://json-schema.org/draft-07/schema#",
4980 + "additionalProperties": false,
4981 + "properties": {
4982 + "open": {
4983 + "additionalProperties": {},
4984 + "type": "object",
4985 + },
4986 + },
4987 + "required": [
4988 + "open",
4989 + ],
4990 + "type": "object",
4991 + },
4992 + },
4993 + "id": "additional-properties-empty-schema-unsupported",
4994 + },
4995 + {
4996 + "fingerprint": {
4997 + "def": {
4998 + "catchall": {
4999 + "typeName": "ZodNever",

This file is too large to show in full.

ts/packages/json-schema-to-zod/test/compile-pattern.test.ts
+8 -7
@@ -1,7 +1,8 @@
1 import { describe, expect, it } from 'vitest';
2
3 -import { InvalidPatternError, jsonSchemaToZod } from '../src/index';
3 +import { InvalidPatternError } from '../src/index';
4 import { MAX_PATTERN_LENGTH, compilePattern } from '../src/utils/compile-pattern';
5 +import { builders } from './support/builders';
6
7 const invalidPatternAt = (build: () => unknown): InvalidPatternError => {
8 try {
@@ -47,10 +48,10 @@ describe('compilePattern', () => {
48 });
49 });
50
50 -describe('jsonSchemaToZod pattern guard', () => {
51 +describe.each(builders)('jsonSchemaToZod pattern guard ($name)', builder => {
52 it('reports a malformed property pattern with its path instead of a raw SyntaxError', () => {
53 const error = invalidPatternAt(() =>
53 - jsonSchemaToZod({
54 + builder.convert({
55 type: 'object',
56 properties: { name: { type: 'string', pattern: '(' } },
57 })
@@ -63,7 +64,7 @@ describe('jsonSchemaToZod pattern guard', () => {
64
65 it('reports a typeless pattern with the path of the node carrying it', () => {
66 const error = invalidPatternAt(() =>
66 - jsonSchemaToZod({
67 + builder.convert({
68 type: 'object',
69 properties: { slug: { pattern: '[' } },
70 })
@@ -73,7 +74,7 @@ describe('jsonSchemaToZod pattern guard', () => {
74
75 it('reports a malformed patternProperties key with its path', () => {
76 const error = invalidPatternAt(() =>
76 - jsonSchemaToZod({
77 + builder.convert({
78 type: 'object',
79 properties: {
80 labels: {
@@ -89,7 +90,7 @@ describe('jsonSchemaToZod pattern guard', () => {
90 });
91
92 it('keeps compiling quantified groups that backtrack linearly', () => {
92 - const schema = jsonSchemaToZod({
93 + const schema = builder.convert({
94 type: 'object',
95 properties: { version: { type: 'string', pattern: '^(\\d+\\.)*\\d+$' } },
96 required: ['version'],
@@ -102,7 +103,7 @@ describe('jsonSchemaToZod pattern guard', () => {
103 });
104
105 it('still enforces valid patterns', () => {
105 - const schema = jsonSchemaToZod({
106 + const schema = builder.convert({
107 type: 'object',
108 properties: {
109 id: { type: 'string', pattern: '^[a-z]{3}-\\d+$' },
ts/packages/json-schema-to-zod/test/fixtures/corpus.ts
+2
@@ -11,7 +11,9 @@ export {
11 acceptedFor,
12 assertCorpusInvariants,
13 loadObjectCases,
14 + loadStrictCases,
15 type CorpusCase,
16 type CorpusInstance,
17 type CorpusLanguage,
18 + type StrictCase,
19 } from '../../../core/test/fixtures/json-schema-conversion/corpus';
ts/packages/json-schema-to-zod/test/guard-attach.test.ts new
+116
@@ -0,0 +1,116 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { version } from 'zod/v4/core';
3 +
4 +import type { ZodBackend } from '../src/backend/types';
5 +import { zodV3Backend } from '../src/backend/zod-v3';
6 +import { zodV4Backend } from '../src/backend/zod-v4';
7 +import { meetsZodV4Floor } from '../src/backend/zod-v4-floor';
8 +import type { ParseContext } from '../src/context';
9 +import { parseObjectShape } from '../src/parsers/parse-object-shape';
10 +import type { JsonSchemaObject } from '../src/types';
11 +
12 +/**
13 + * Counts how many whole-schema guards a shape parse attaches. A permissive
14 + * property ($ref, typeless constraints) gets its guard from the permissive
15 + * branch of `selectParser`, so the shape parser must not attach the identical
16 + * guard a second time; a whole-schema property that parses normally still
17 + * needs the property-level guard, and a plain property needs none.
18 + */
19 +const countGuardAttachments = <S>(backend: ZodBackend<S>, schema: JsonSchemaObject): number => {
20 + let attachments = 0;
21 + const counting: ZodBackend<S> = {
22 + ...backend,
23 + attachGuard: (parsed, guard) => {
24 + attachments += 1;
25 + return backend.attachGuard(parsed, guard);
26 + },
27 + };
28 + const ctx: ParseContext<S> = {
29 + path: [],
30 + seen: new Map(),
31 + root: schema,
32 + backend: counting,
33 + };
34 + parseObjectShape(schema, ctx);
35 + return attachments;
36 +};
37 +
38 +/**
39 + * Whether a typeless `{ not: { type: 'string' } }` property, replaced by a
40 + * `parserOverride` with an unconstrained schema, accepts `value`. The override
41 + * skips the parser that would guard the property, so the shape parser must
42 + * still guard it.
43 + */
44 +const overriddenPropertyAccepts = <S extends { safeParse(value: unknown): { success: boolean } }>(
45 + backend: ZodBackend<S>,
46 + value: unknown
47 +): boolean => {
48 + const schema: JsonSchemaObject = { properties: { p: { not: { type: 'string' } } } };
49 + const shape = parseObjectShape(schema, {
50 + path: [],
51 + seen: new Map(),
52 + root: schema,
53 + backend,
54 + parserOverride: node => ('not' in node ? backend.any() : undefined),
55 + });
56 + return shape.p.safeParse(value).success;
57 +};
58 +
59 +const backends: ReadonlyArray<{
60 + name: string;
61 + attachmentsOf: (schema: JsonSchemaObject) => number;
62 + overrideAccepts: (value: unknown) => boolean;
63 +}> = [
64 + {
65 + name: 'zod-v3',
66 + attachmentsOf: schema => countGuardAttachments(zodV3Backend, schema),
67 + overrideAccepts: value => overriddenPropertyAccepts(zodV3Backend, value),
68 + },
69 + // The `/v4` backend cannot load below the floor (an embedded zod 4.0.0 core
70 + // inside zod 3.25.x), so it joins only where the installed copy meets it.
71 + ...(meetsZodV4Floor(version)
72 + ? [
73 + {
74 + name: 'zod-v4',
75 + attachmentsOf: (schema: JsonSchemaObject) => countGuardAttachments(zodV4Backend, schema),
76 + overrideAccepts: (value: unknown) => overriddenPropertyAccepts(zodV4Backend, value),
77 + },
78 + ]
79 + : []),
80 +];
81 +
82 +describe.each(backends)('parseObjectShape guard attachments ($name)', ({ attachmentsOf }) => {
83 + it('attaches the guard once for a permissive $ref property', () => {
84 + const attachments = attachmentsOf({
85 + properties: { p: { $ref: '#/$defs/x' } },
86 + $defs: { x: { type: 'string' } },
87 + });
88 + expect(attachments).toBe(1);
89 + });
90 +
91 + it('attaches the guard once for a typeless permissive property', () => {
92 + const attachments = attachmentsOf({
93 + properties: { p: { properties: { a: { type: 'string' } } } },
94 + });
95 + expect(attachments).toBe(1);
96 + });
97 +
98 + it('attaches the guard once for a whole-schema property that parses normally', () => {
99 + const attachments = attachmentsOf({
100 + properties: { p: { type: 'array', uniqueItems: true } },
101 + });
102 + expect(attachments).toBe(1);
103 + });
104 +
105 + it('attaches no guard for a plain property', () => {
106 + const attachments = attachmentsOf({ properties: { p: { type: 'string' } } });
107 + expect(attachments).toBe(0);
108 + });
109 +});
110 +
111 +describe.each(backends)('parseObjectShape with a parserOverride ($name)', ({ overrideAccepts }) => {
112 + it('keeps the guard on a permissive property the override replaces', () => {
113 + expect(overrideAccepts('text')).toBe(false);
114 + expect(overrideAccepts(1)).toBe(true);
115 + });
116 +});
ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
+170 -99
@@ -1,17 +1,17 @@
1 import { describe, it, expect } from 'vitest';
2 -import { z } from 'zod/v3';
3 -import { jsonSchemaToZod } from '../src/json-schema-to-zod';
2 import type { JsonSchema } from '../src/types';
3 import { acceptedFor, loadObjectCases } from './fixtures/corpus';
4 +import { builders } from './support/builders';
5 +import { testFor } from './support/divergences';
6
7 -describe('jsonSchemaToZod', () => {
7 +describe.each(builders)('jsonSchemaToZod ($name)', builder => {
8 describe('Basic Types', () => {
9 it('should convert string schema', () => {
10 const schema: JsonSchema = {
11 type: 'string',
12 };
13 - const zodSchema = jsonSchemaToZod(schema);
14 - expect(zodSchema).toBeInstanceOf(z.ZodString);
13 + const zodSchema = builder.convert(schema);
14 + expect(builder.kind(zodSchema)).toBe('string');
15 expect(zodSchema.parse('test')).toBe('test');
16 expect(() => zodSchema.parse(123)).toThrow();
17 });
@@ -20,8 +20,8 @@ describe('jsonSchemaToZod', () => {
20 const schema: JsonSchema = {
21 type: 'number',
22 };
23 - const zodSchema = jsonSchemaToZod(schema);
24 - expect(zodSchema).toBeInstanceOf(z.ZodNumber);
23 + const zodSchema = builder.convert(schema);
24 + expect(builder.kind(zodSchema)).toBe('number');
25 expect(zodSchema.parse(123)).toBe(123);
26 expect(() => zodSchema.parse('123')).toThrow();
27 });
@@ -30,7 +30,7 @@ describe('jsonSchemaToZod', () => {
30 const schema: JsonSchema = {
31 type: 'integer',
32 };
33 - const zodSchema = jsonSchemaToZod(schema);
33 + const zodSchema = builder.convert(schema);
34 expect(zodSchema.parse(123)).toBe(123);
35 expect(() => zodSchema.parse(123.45)).toThrow();
36 });
@@ -39,8 +39,8 @@ describe('jsonSchemaToZod', () => {
39 const schema: JsonSchema = {
40 type: 'boolean',
41 };
42 - const zodSchema = jsonSchemaToZod(schema);
43 - expect(zodSchema).toBeInstanceOf(z.ZodBoolean);
42 + const zodSchema = builder.convert(schema);
43 + expect(builder.kind(zodSchema)).toBe('boolean');
44 expect(zodSchema.parse(true)).toBe(true);
45 expect(() => zodSchema.parse('true')).toThrow();
46 });
@@ -49,8 +49,8 @@ describe('jsonSchemaToZod', () => {
49 const schema: JsonSchema = {
50 type: 'null',
51 };
52 - const zodSchema = jsonSchemaToZod(schema);
53 - expect(zodSchema).toBeInstanceOf(z.ZodNull);
52 + const zodSchema = builder.convert(schema);
53 + expect(builder.kind(zodSchema)).toBe('null');
54 expect(zodSchema.parse(null)).toBe(null);
55 expect(() => zodSchema.parse(undefined)).toThrow();
56 });
@@ -62,7 +62,7 @@ describe('jsonSchemaToZod', () => {
62 type: 'string',
63 format: 'email',
64 };
65 - const zodSchema = jsonSchemaToZod(schema);
65 + const zodSchema = builder.convert(schema);
66 expect(zodSchema.parse('test@example.com')).toBe('test@example.com');
67 expect(() => zodSchema.parse('invalid-email')).toThrow();
68 });
@@ -72,7 +72,7 @@ describe('jsonSchemaToZod', () => {
72 type: 'string',
73 format: 'date-time',
74 };
75 - const zodSchema = jsonSchemaToZod(schema);
75 + const zodSchema = builder.convert(schema);
76 expect(zodSchema.parse('2024-03-20T12:00:00Z')).toBe('2024-03-20T12:00:00Z');
77 expect(() => zodSchema.parse('invalid-date')).toThrow();
78 });
@@ -82,7 +82,7 @@ describe('jsonSchemaToZod', () => {
82 type: 'string',
83 format: 'uuid',
84 };
85 - const zodSchema = jsonSchemaToZod(schema);
85 + const zodSchema = builder.convert(schema);
86 expect(zodSchema.parse('123e4567-e89b-12d3-a456-426614174000')).toBe(
87 '123e4567-e89b-12d3-a456-426614174000'
88 );
@@ -97,7 +97,7 @@ describe('jsonSchemaToZod', () => {
97 minimum: 0,
98 maximum: 100,
99 };
100 - const zodSchema = jsonSchemaToZod(schema);
100 + const zodSchema = builder.convert(schema);
101 expect(zodSchema.parse(50)).toBe(50);
102 expect(() => zodSchema.parse(-1)).toThrow();
103 expect(() => zodSchema.parse(101)).toThrow();
@@ -109,7 +109,7 @@ describe('jsonSchemaToZod', () => {
109 exclusiveMinimum: 0,
110 exclusiveMaximum: 100,
111 };
112 - const zodSchema = jsonSchemaToZod(schema);
112 + const zodSchema = builder.convert(schema);
113 expect(zodSchema.parse(50)).toBe(50);
114 expect(() => zodSchema.parse(0)).toThrow();
115 expect(() => zodSchema.parse(100)).toThrow();
@@ -120,7 +120,7 @@ describe('jsonSchemaToZod', () => {
120 type: 'number',
121 multipleOf: 5,
122 };
123 - const zodSchema = jsonSchemaToZod(schema);
123 + const zodSchema = builder.convert(schema);
124 expect(zodSchema.parse(15)).toBe(15);
125 expect(() => zodSchema.parse(17)).toThrow();
126 });
@@ -131,7 +131,7 @@ describe('jsonSchemaToZod', () => {
131 min: 0,
132 max: 100,
133 } satisfies JsonSchema;
134 - const zodSchema = jsonSchemaToZod(schema);
134 + const zodSchema = builder.convert(schema);
135 expect(zodSchema.parse(50)).toBe(50);
136 expect(() => zodSchema.parse(-1)).toThrow();
137 expect(() => zodSchema.parse(101)).toThrow();
@@ -145,7 +145,7 @@ describe('jsonSchemaToZod', () => {
145 min: 0,
146 max: 100,
147 } satisfies JsonSchema;
148 - const zodSchema = jsonSchemaToZod(schema);
148 + const zodSchema = builder.convert(schema);
149 expect(zodSchema.parse(50)).toBe(50);
150 expect(zodSchema.parse(10)).toBe(10);
151 expect(zodSchema.parse(90)).toBe(90);
@@ -161,7 +161,7 @@ describe('jsonSchemaToZod', () => {
161 min: 3,
162 max: 10,
163 } satisfies JsonSchema;
164 - const zodSchema = jsonSchemaToZod(schema);
164 + const zodSchema = builder.convert(schema);
165 expect(zodSchema.parse('hello')).toBe('hello');
166 expect(() => zodSchema.parse('hi')).toThrow();
167 expect(() => zodSchema.parse('this is too long')).toThrow();
@@ -175,7 +175,7 @@ describe('jsonSchemaToZod', () => {
175 min: 3,
176 max: 10,
177 } satisfies JsonSchema;
178 - const zodSchema = jsonSchemaToZod(schema);
178 + const zodSchema = builder.convert(schema);
179 expect(zodSchema.parse('hello')).toBe('hello');
180 expect(zodSchema.parse('testing')).toBe('testing');
181 expect(() => zodSchema.parse('test')).toThrow(); // Uses minLength (5), not min (3)
@@ -198,12 +198,12 @@ describe('jsonSchemaToZod', () => {
198 required: ['username'],
199 } satisfies JsonSchema;
200
201 - const zodSchema = jsonSchemaToZod(schema) as z.ZodObject<z.ZodRawShape>;
201 + const zodSchema = builder.convert(schema);
202
203 expect(zodSchema.parse({ username: 'john_doe' })).toEqual({ username: 'john_doe' });
204 expect(() => zodSchema.parse({ username: 'ab' })).toThrow();
205 expect(() => zodSchema.parse({ username: 'a very long username' })).toThrow();
206 - expect(zodSchema.shape.username.description).toBe('Example: "john_doe"');
206 + expect(builder.description(builder.shape(zodSchema).username)).toBe('Example: "john_doe"');
207 });
208
209 it('should validate required properties', () => {
@@ -215,7 +215,7 @@ describe('jsonSchemaToZod', () => {
215 },
216 required: ['name'],
217 };
218 - const zodSchema = jsonSchemaToZod(schema);
218 + const zodSchema = builder.convert(schema);
219 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
220 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
221 expect(() => zodSchema.parse({ age: 30 })).toThrow();
@@ -229,7 +229,7 @@ describe('jsonSchemaToZod', () => {
229 },
230 additionalProperties: false,
231 };
232 - const zodSchema = jsonSchemaToZod(schema);
232 + const zodSchema = builder.convert(schema);
233 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
234 expect(() => zodSchema.parse({ name: 'John', extra: 'field' })).toThrow();
235 });
@@ -242,7 +242,7 @@ describe('jsonSchemaToZod', () => {
242 },
243 additionalProperties: true,
244 };
245 - const zodSchema = jsonSchemaToZod(schema);
245 + const zodSchema = builder.convert(schema);
246 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
247 expect(zodSchema.parse({ name: 'John', extra: 'field' })).toEqual({
248 name: 'John',
@@ -263,7 +263,7 @@ describe('jsonSchemaToZod', () => {
263 },
264 additionalProperties: { type: 'number' },
265 };
266 - const zodSchema = jsonSchemaToZod(schema);
266 + const zodSchema = builder.convert(schema);
267 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
268 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({
269 name: 'John',
@@ -287,7 +287,7 @@ describe('jsonSchemaToZod', () => {
287 required: ['value'],
288 },
289 };
290 - const zodSchema = jsonSchemaToZod(schema);
290 + const zodSchema = builder.convert(schema);
291 expect(
292 zodSchema.parse({
293 name: 'John',
@@ -321,7 +321,7 @@ describe('jsonSchemaToZod', () => {
321 name: { type: 'string' },
322 },
323 };
324 - const zodSchema = jsonSchemaToZod(schema);
324 + const zodSchema = builder.convert(schema);
325 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
326 expect(() => zodSchema.parse({ name: 'John', extra: 'field' })).toThrow();
327 });
@@ -337,7 +337,7 @@ describe('jsonSchemaToZod', () => {
337 },
338 additionalProperties: { type: 'number' },
339 };
340 - const zodSchema = jsonSchemaToZod(schema);
340 + const zodSchema = builder.convert(schema);
341
342 // Should allow defined properties
343 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
@@ -378,7 +378,7 @@ describe('jsonSchemaToZod', () => {
378 type: 'object',
379 additionalProperties: { type: 'string' },
380 };
381 - const zodSchema = jsonSchemaToZod(schema);
381 + const zodSchema = builder.convert(schema);
382 expect(zodSchema.parse({})).toEqual({});
383 expect(zodSchema.parse({ key1: 'value1', key2: 'value2' })).toEqual({
384 key1: 'value1',
@@ -398,7 +398,7 @@ describe('jsonSchemaToZod', () => {
398 },
399 additionalProperties: false,
400 };
401 - const zodSchema = jsonSchemaToZod(schema);
401 + const zodSchema = builder.convert(schema);
402
403 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
404 expect(
@@ -425,7 +425,7 @@ describe('jsonSchemaToZod', () => {
425 type: 'object',
426 additionalProperties: true,
427 };
428 - const zodSchema = jsonSchemaToZod(schema);
428 + const zodSchema = builder.convert(schema);
429 expect(zodSchema.parse({})).toEqual({});
430 expect(zodSchema.parse({ any: 'value', another: 123 })).toEqual({
431 any: 'value',
@@ -438,7 +438,7 @@ describe('jsonSchemaToZod', () => {
438 type: 'object',
439 additionalProperties: false,
440 };
441 - const zodSchema = jsonSchemaToZod(schema);
441 + const zodSchema = builder.convert(schema);
442 expect(zodSchema.parse({})).toEqual({});
443 expect(() => zodSchema.parse({ any: 'value' })).toThrow();
444 });
@@ -457,7 +457,7 @@ describe('jsonSchemaToZod', () => {
457 },
458 additionalProperties: { type: 'string' },
459 };
460 - const zodSchema = jsonSchemaToZod(schema);
460 + const zodSchema = builder.convert(schema);
461
462 expect(
463 zodSchema.parse({
@@ -492,7 +492,7 @@ describe('jsonSchemaToZod', () => {
492 '^prefix_': { type: 'string' },
493 },
494 };
495 - const zodSchema = jsonSchemaToZod(schema);
495 + const zodSchema = builder.convert(schema);
496 expect(zodSchema.parse({ prefix_one: 'value1', prefix_two: 'value2' })).toEqual({
497 prefix_one: 'value1',
498 prefix_two: 'value2',
@@ -507,7 +507,7 @@ describe('jsonSchemaToZod', () => {
507 type: 'array',
508 items: { type: 'string' },
509 };
510 - const zodSchema = jsonSchemaToZod(schema);
510 + const zodSchema = builder.convert(schema);
511 expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
512 expect(() => zodSchema.parse(['one', 2])).toThrow();
513 });
@@ -517,7 +517,7 @@ describe('jsonSchemaToZod', () => {
517 type: 'array',
518 items: [{ type: 'string' }, { type: 'number' }],
519 };
520 - const zodSchema = jsonSchemaToZod(schema);
520 + const zodSchema = builder.convert(schema);
521 expect(zodSchema.parse(['test', 123])).toEqual(['test', 123]);
522 expect(() => zodSchema.parse(['test', 'wrong'])).toThrow();
523 });
@@ -529,7 +529,7 @@ describe('jsonSchemaToZod', () => {
529 minItems: 1,
530 maxItems: 3,
531 };
532 - const zodSchema = jsonSchemaToZod(schema);
532 + const zodSchema = builder.convert(schema);
533 expect(zodSchema.parse(['one'])).toEqual(['one']);
534 expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
535 expect(() => zodSchema.parse([])).toThrow();
@@ -543,7 +543,7 @@ describe('jsonSchemaToZod', () => {
543 min: 1,
544 max: 3,
545 } satisfies JsonSchema;
546 - const zodSchema = jsonSchemaToZod(schema);
546 + const zodSchema = builder.convert(schema);
547 expect(zodSchema.parse(['one'])).toEqual(['one']);
548 expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
549 expect(() => zodSchema.parse([])).toThrow();
@@ -559,7 +559,7 @@ describe('jsonSchemaToZod', () => {
559 min: 1,
560 max: 3,
561 } satisfies JsonSchema;
562 - const zodSchema = jsonSchemaToZod(schema);
562 + const zodSchema = builder.convert(schema);
563 expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
564 expect(zodSchema.parse(['one', 'two', 'three', 'four'])).toEqual([
565 'one',
@@ -585,7 +585,7 @@ describe('jsonSchemaToZod', () => {
585 },
586 ],
587 };
588 - const zodSchema = jsonSchemaToZod(schema);
588 + const zodSchema = builder.convert(schema);
589
590 // Should accept string arrays
591 expect(zodSchema.parse(['hello', 'world'])).toEqual(['hello', 'world']);
@@ -610,7 +610,7 @@ describe('jsonSchemaToZod', () => {
610 },
611 ],
612 };
613 - const zodSchema = jsonSchemaToZod(schema);
613 + const zodSchema = builder.convert(schema);
614
615 // Should accept string arrays
616 expect(zodSchema.parse(['hello', 'world'])).toEqual(['hello', 'world']);
@@ -631,7 +631,7 @@ describe('jsonSchemaToZod', () => {
631 required: ['name'],
632 },
633 };
634 - const zodSchema = jsonSchemaToZod(schema);
634 + const zodSchema = builder.convert(schema);
635
636 // Should apply default null for missing status
637 expect(zodSchema.parse([{ name: 'test1' }, { name: 'test2', status: 'active' }])).toEqual([
@@ -651,7 +651,7 @@ describe('jsonSchemaToZod', () => {
651 items: { type: 'number' },
652 },
653 };
654 - const zodSchema = jsonSchemaToZod(schema);
654 + const zodSchema = builder.convert(schema);
655
656 expect(
657 zodSchema.parse([
@@ -672,7 +672,7 @@ describe('jsonSchemaToZod', () => {
672 type: 'string',
673 enum: ['one', 'two', 'three'],
674 };
675 - const zodSchema = jsonSchemaToZod(schema);
675 + const zodSchema = builder.convert(schema);
676 expect(zodSchema.parse('one')).toBe('one');
677 expect(() => zodSchema.parse('four')).toThrow();
678 });
@@ -681,7 +681,7 @@ describe('jsonSchemaToZod', () => {
681 const schema: JsonSchema = {
682 enum: ['string', 123, true],
683 };
684 - const zodSchema = jsonSchemaToZod(schema);
684 + const zodSchema = builder.convert(schema);
685 expect(zodSchema.parse('string')).toBe('string');
686 expect(zodSchema.parse(123)).toBe(123);
687 expect(zodSchema.parse(true)).toBe(true);
@@ -694,7 +694,7 @@ describe('jsonSchemaToZod', () => {
694 const schema: JsonSchema = {
695 anyOf: [{ type: 'string' }, { type: 'number' }],
696 };
697 - const zodSchema = jsonSchemaToZod(schema);
697 + const zodSchema = builder.convert(schema);
698 expect(zodSchema.parse('test')).toBe('test');
699 expect(zodSchema.parse(123)).toBe(123);
700 expect(() => zodSchema.parse(true)).toThrow();
@@ -707,7 +707,7 @@ describe('jsonSchemaToZod', () => {
707 { type: 'number', maximum: 0 },
708 ],
709 };
710 - const zodSchema = jsonSchemaToZod(schema);
710 + const zodSchema = builder.convert(schema);
711 expect(zodSchema.parse(1)).toBe(1);
712 expect(zodSchema.parse(-1)).toBe(-1);
713 expect(() => zodSchema.parse(0)).toThrow(); // Should fail as 0 matches both schemas
@@ -720,7 +720,7 @@ describe('jsonSchemaToZod', () => {
720 { type: 'number', maximum: 100 },
721 ],
722 };
723 - const zodSchema = jsonSchemaToZod(schema);
723 + const zodSchema = builder.convert(schema);
724 expect(zodSchema.parse(50)).toBe(50);
725 expect(() => zodSchema.parse(-1)).toThrow();
726 expect(() => zodSchema.parse(101)).toThrow();
@@ -753,7 +753,7 @@ describe('jsonSchemaToZod', () => {
753 },
754 required: ['user'],
755 };
756 - const zodSchema = jsonSchemaToZod(schema);
756 + const zodSchema = builder.convert(schema);
757
758 const validData = {
759 user: {
@@ -800,10 +800,10 @@ describe('jsonSchemaToZod', () => {
800 required: ['username', 'email'],
801 };
802
803 - const zodSchema = jsonSchemaToZod(schema);
803 + const zodSchema = builder.convert(schema);
804
805 // Test description
806 - expect(zodSchema.description).toBe('A user profile object');
806 + expect(builder.description(zodSchema)).toBe('A user profile object');
807
808 // Test required fields
809 expect(() => zodSchema.parse({})).toThrow();
@@ -856,7 +856,7 @@ describe('jsonSchemaToZod', () => {
856 },
857 };
858
859 - const zodSchema = jsonSchemaToZod(schema);
859 + const zodSchema = builder.convert(schema);
860
861 // Test property with type
862 expect(zodSchema.parse({ withType: 'test' })).toEqual({
@@ -920,7 +920,7 @@ describe('jsonSchemaToZod', () => {
920 },
921 };
922
923 - const zodSchema = jsonSchemaToZod(schema);
923 + const zodSchema = builder.convert(schema);
924
925 // Test default values for top-level property
926 expect(zodSchema.parse({})).toEqual({
@@ -965,7 +965,7 @@ describe('jsonSchemaToZod', () => {
965 required: ['name'],
966 };
967
968 - const zodSchema = jsonSchemaToZod(schema);
968 + const zodSchema = builder.convert(schema);
969
970 // Test with required field only - should include null default
971 expect(zodSchema.parse({ name: 'John' })).toEqual({
@@ -1003,10 +1003,10 @@ describe('jsonSchemaToZod', () => {
1003 title: 'GetUserRequest',
1004 };
1005
1006 - const zodSchema = jsonSchemaToZod(schema);
1006 + const zodSchema = builder.convert(schema);
1007
1008 // Test schema description/title
1009 - expect(zodSchema.description).toBe('GetUserRequest');
1009 + expect(builder.description(zodSchema)).toBe('GetUserRequest');
1010
1011 // Test required field validation
1012 expect(() => zodSchema.parse({})).toThrow();
@@ -1018,8 +1018,10 @@ describe('jsonSchemaToZod', () => {
1018 });
1019
1020 // Test property description
1021 - const shape = (zodSchema as z.ZodObject<z.ZodRawShape>).shape;
1022 - expect(shape.username.description).toBe('The username of the Hacker News user to retrieve.');
1021 + const shape = builder.shape(zodSchema);
1022 + expect(builder.description(shape.username)).toBe(
1023 + 'The username of the Hacker News user to retrieve.'
1024 + );
1025 });
1026
1027 it('should append example to description', () => {
@@ -1028,8 +1030,8 @@ describe('jsonSchemaToZod', () => {
1030 description: 'User name',
1031 example: 'john_doe',
1032 } satisfies JsonSchema;
1031 - const zodSchema = jsonSchemaToZod(schema);
1032 - expect(zodSchema.description).toBe('User name\nExample: "john_doe"');
1033 + const zodSchema = builder.convert(schema);
1034 + expect(builder.description(zodSchema)).toBe('User name\nExample: "john_doe"');
1035 });
1036
1037 it('should handle example without description', () => {
@@ -1037,8 +1039,8 @@ describe('jsonSchemaToZod', () => {
1039 type: 'number',
1040 example: 42,
1041 } satisfies JsonSchema;
1040 - const zodSchema = jsonSchemaToZod(schema);
1041 - expect(zodSchema.description).toBe('Example: 42');
1042 + const zodSchema = builder.convert(schema);
1043 + expect(builder.description(zodSchema)).toBe('Example: 42');
1044 });
1045
1046 it('should handle example with title but no description', () => {
@@ -1047,8 +1049,8 @@ describe('jsonSchemaToZod', () => {
1049 title: 'User Object',
1050 example: { name: 'John', age: 30 },
1051 } satisfies JsonSchema;
1050 - const zodSchema = jsonSchemaToZod(schema);
1051 - expect(zodSchema.description).toBe('User Object\nExample: {"name":"John","age":30}');
1052 + const zodSchema = builder.convert(schema);
1053 + expect(builder.description(zodSchema)).toBe('User Object\nExample: {"name":"John","age":30}');
1054 });
1055
1056 it('should handle single example in examples array', () => {
@@ -1057,8 +1059,8 @@ describe('jsonSchemaToZod', () => {
1059 description: 'Property name',
1060 examples: ['lifecyclestage'],
1061 } satisfies JsonSchema;
1060 - const zodSchema = jsonSchemaToZod(schema);
1061 - expect(zodSchema.description).toBe('Property name\nExample: "lifecyclestage"');
1062 + const zodSchema = builder.convert(schema);
1063 + expect(builder.description(zodSchema)).toBe('Property name\nExample: "lifecyclestage"');
1064 });
1065
1066 it('should handle multiple examples in examples array', () => {
@@ -1067,8 +1069,8 @@ describe('jsonSchemaToZod', () => {
1069 description: 'List of property names',
1070 examples: ["['lifecyclestage', 'hs_lead_status']", "['hubspot_owner_id']"],
1071 } satisfies JsonSchema;
1070 - const zodSchema = jsonSchemaToZod(schema);
1071 - expect(zodSchema.description).toBe(
1072 + const zodSchema = builder.convert(schema);
1073 + expect(builder.description(zodSchema)).toBe(
1074 "List of property names\nExamples:\n \"['lifecyclestage', 'hs_lead_status']\"\n \"['hubspot_owner_id']\""
1075 );
1076 });
@@ -1080,8 +1082,8 @@ describe('jsonSchemaToZod', () => {
1082 example: 'single_example',
1083 examples: ['example1', 'example2'],
1084 } satisfies JsonSchema;
1083 - const zodSchema = jsonSchemaToZod(schema);
1084 - expect(zodSchema.description).toBe('Property name\nExample: "single_example"');
1085 + const zodSchema = builder.convert(schema);
1086 + expect(builder.description(zodSchema)).toBe('Property name\nExample: "single_example"');
1087 });
1088
1089 it('should handle empty examples array', () => {
@@ -1090,8 +1092,8 @@ describe('jsonSchemaToZod', () => {
1092 description: 'Property name',
1093 examples: [],
1094 } satisfies JsonSchema;
1093 - const zodSchema = jsonSchemaToZod(schema);
1094 - expect(zodSchema.description).toBe('Property name');
1095 + const zodSchema = builder.convert(schema);
1096 + expect(builder.description(zodSchema)).toBe('Property name');
1097 });
1098
1099 it('should preserve array structure in examples', () => {
@@ -1104,8 +1106,8 @@ describe('jsonSchemaToZod', () => {
1106 ['created_date', 'modified_date', 'status'],
1107 ],
1108 } satisfies JsonSchema;
1107 - const zodSchema = jsonSchemaToZod(schema);
1108 - expect(zodSchema.description).toBe(
1109 + const zodSchema = builder.convert(schema);
1110 + expect(builder.description(zodSchema)).toBe(
1111 'Property combinations\nExamples:\n ["lifecyclestage","hs_lead_status"]\n ["hubspot_owner_id"]\n ["created_date","modified_date","status"]'
1112 );
1113 });
@@ -1116,8 +1118,8 @@ describe('jsonSchemaToZod', () => {
1118 description: 'Status values',
1119 examples: ['active', 'inactive', 'pending'],
1120 } satisfies JsonSchema;
1119 - const zodSchema = jsonSchemaToZod(schema);
1120 - expect(zodSchema.description).toBe(
1121 + const zodSchema = builder.convert(schema);
1122 + expect(builder.description(zodSchema)).toBe(
1123 'Status values\nExamples:\n "active"\n "inactive"\n "pending"'
1124 );
1125 });
@@ -1128,8 +1130,10 @@ describe('jsonSchemaToZod', () => {
1130 description: 'Various numbers',
1131 examples: [42, 3.14, 0, -5],
1132 } satisfies JsonSchema;
1131 - const zodSchema = jsonSchemaToZod(schema);
1132 - expect(zodSchema.description).toBe('Various numbers\nExamples:\n 42\n 3.14\n 0\n -5');
1133 + const zodSchema = builder.convert(schema);
1134 + expect(builder.description(zodSchema)).toBe(
1135 + 'Various numbers\nExamples:\n 42\n 3.14\n 0\n -5'
1136 + );
1137 });
1138 });
1139
@@ -1142,7 +1146,7 @@ describe('jsonSchemaToZod', () => {
1146 },
1147 required: ['name'],
1148 };
1145 - const zodSchema = jsonSchemaToZod(schema);
1149 + const zodSchema = builder.convert(schema);
1150
1151 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
1152 expect(zodSchema.parse({ name: 'Jane' })).toEqual({ name: 'Jane' });
@@ -1154,7 +1158,7 @@ describe('jsonSchemaToZod', () => {
1158 const schema: JsonSchema = {
1159 additionalProperties: { type: 'string' },
1160 };
1157 - const zodSchema = jsonSchemaToZod(schema);
1161 + const zodSchema = builder.convert(schema);
1162
1163 expect(zodSchema.parse({})).toEqual({});
1164 expect(zodSchema.parse({ key1: 'value1', key2: 'value2' })).toEqual({
@@ -1172,7 +1176,7 @@ describe('jsonSchemaToZod', () => {
1176 '^num_': { type: 'number' },
1177 },
1178 };
1175 - const zodSchema = jsonSchemaToZod(schema);
1179 + const zodSchema = builder.convert(schema);
1180
1181 expect(zodSchema.parse({})).toEqual({});
1182 expect(zodSchema.parse({ prefix_one: 'value', num_one: 123 })).toEqual({
@@ -1190,7 +1194,7 @@ describe('jsonSchemaToZod', () => {
1194 },
1195 additionalProperties: { type: 'number' },
1196 };
1193 - const zodSchema = jsonSchemaToZod(schema);
1197 + const zodSchema = builder.convert(schema);
1198
1199 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
1200 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
@@ -1207,7 +1211,7 @@ describe('jsonSchemaToZod', () => {
1211 },
1212 additionalProperties: false,
1213 };
1210 - const zodSchema = jsonSchemaToZod(schema);
1214 + const zodSchema = builder.convert(schema);
1215
1216 expect(zodSchema.parse({ name: 'John', data_age: 30 })).toEqual({
1217 name: 'John',
@@ -1235,7 +1239,7 @@ describe('jsonSchemaToZod', () => {
1239 },
1240 },
1241 };
1238 - const zodSchema = jsonSchemaToZod(schema);
1242 + const zodSchema = builder.convert(schema);
1243
1244 const validData = {
1245 user: { name: 'John', email: 'john@example.com' },
@@ -1269,7 +1273,7 @@ describe('jsonSchemaToZod', () => {
1273 required: ['id'],
1274 },
1275 };
1272 - const zodSchema = jsonSchemaToZod(schema);
1276 + const zodSchema = builder.convert(schema);
1277
1278 expect(zodSchema.parse([{ id: 1, name: 'Item 1' }, { id: 2 }])).toEqual([
1279 { id: 1, name: 'Item 1' },
@@ -1311,7 +1315,7 @@ describe('jsonSchemaToZod', () => {
1315 },
1316 },
1317 };
1314 - const zodSchema = jsonSchemaToZod(schema);
1318 + const zodSchema = builder.convert(schema);
1319
1320 const validData = {
1321 config: {
@@ -1339,7 +1343,7 @@ describe('jsonSchemaToZod', () => {
1343 },
1344 ],
1345 };
1342 - const zodSchema = jsonSchemaToZod(schema);
1346 + const zodSchema = builder.convert(schema);
1347
1348 expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
1349 expect(zodSchema.parse('just a string')).toBe('just a string');
@@ -1366,7 +1370,7 @@ describe('jsonSchemaToZod', () => {
1370 },
1371 ],
1372 };
1369 - const zodSchema = jsonSchemaToZod(schema);
1373 + const zodSchema = builder.convert(schema);
1374
1375 expect(zodSchema.parse({ type: 'user', name: 'John' })).toEqual({
1376 type: 'user',
@@ -1400,7 +1404,7 @@ describe('jsonSchemaToZod', () => {
1404 },
1405 ],
1406 };
1403 - const zodSchema = jsonSchemaToZod(schema);
1407 + const zodSchema = builder.convert(schema);
1408
1409 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
1410 expect(zodSchema.parse({ name: 'Jane' })).toEqual({ name: 'Jane' });
@@ -1429,7 +1433,7 @@ describe('jsonSchemaToZod', () => {
1433 },
1434 ],
1435 };
1432 - const zodSchema = jsonSchemaToZod(schema);
1436 + const zodSchema = builder.convert(schema);
1437
1438 // With additionalProperties: true, the intersection allows all properties
1439 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
@@ -1461,7 +1465,7 @@ describe('jsonSchemaToZod', () => {
1465 },
1466 },
1467 };
1464 - const zodSchema = jsonSchemaToZod(schema);
1468 + const zodSchema = builder.convert(schema);
1469
1470 const validData = {
1471 explicit: { a: 'test' },
@@ -1489,7 +1493,7 @@ describe('jsonSchemaToZod', () => {
1493 const schema: JsonSchema = {
1494 properties: {},
1495 };
1492 - const zodSchema = jsonSchemaToZod(schema);
1496 + const zodSchema = builder.convert(schema);
1497
1498 expect(zodSchema.parse({})).toEqual({});
1499 expect(zodSchema.parse('not an object')).toBe('not an object');
@@ -1503,7 +1507,7 @@ describe('jsonSchemaToZod', () => {
1507 },
1508 required: ['name', 'age'],
1509 };
1506 - const zodSchema = jsonSchemaToZod(schema);
1510 + const zodSchema = builder.convert(schema);
1511
1512 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
1513 expect(() => zodSchema.parse({ name: 'John' })).toThrow();
@@ -1512,14 +1516,81 @@ describe('jsonSchemaToZod', () => {
1516 });
1517 });
1518
1515 -describe('shared cross-SDK object corpus', () => {
1519 +describe.each(builders)('issue paths ($name)', builder => {
1520 + const issuePaths = (schema: JsonSchema, value: unknown) => {
1521 + const result = builder.convert(schema).safeParse(value);
1522 + expect(result.success).toBe(false);
1523 + return result.success ? [] : result.error.issues.map(issue => [issue.code, issue.path]);
1524 + };
1525 +
1526 + it('reports a nested patternProperties violation under its property once', () => {
1527 + const schema: JsonSchema = {
1528 + type: 'object',
1529 + properties: {
1530 + x: { type: 'object', patternProperties: { '^p_': { type: 'number' } } },
1531 + },
1532 + };
1533 + expect(issuePaths(schema, { x: { p_a: 'no' } })).toEqual([['custom', ['x', 'p_a']]]);
1534 + });
1535 +
1536 + it('reports a nested additionalProperties violation under its property once', () => {
1537 + const schema: JsonSchema = {
1538 + type: 'object',
1539 + properties: {
1540 + x: {
1541 + type: 'object',
1542 + patternProperties: { '^p_': { type: 'number' } },
1543 + additionalProperties: { type: 'string' },
1544 + },
1545 + },
1546 + };
1547 + expect(issuePaths(schema, { x: { other: 1 } })).toEqual([['custom', ['x', 'other']]]);
1548 + });
1549 +
1550 + it('reports nested unrecognized keys at the property that rejects them', () => {
1551 + const schema: JsonSchema = {
1552 + type: 'object',
1553 + properties: {
1554 + x: {
1555 + type: 'object',
1556 + properties: { a: { type: 'string' } },
1557 + patternProperties: { '^p_': { type: 'number' } },
1558 + additionalProperties: false,
1559 + },
1560 + },
1561 + };
1562 + expect(issuePaths(schema, { x: { zzz: 1 } })).toEqual([['unrecognized_keys', ['x']]]);
1563 + });
1564 +
1565 + it('reports a nested oneOf failure at the property once', () => {
1566 + // `contentEncoding` is an annotation to the Draft 7 guard but a check to
1567 + // the native string parser, so the guard accepts exactly one branch while
1568 + // the parser rejects both and the oneOf refinement itself reports.
1569 + const schema: JsonSchema = {
1570 + type: 'object',
1571 + properties: {
1572 + x: {
1573 + oneOf: [
1574 + { type: 'string', contentEncoding: 'base64' },
1575 + { type: 'string', maxLength: 1 },
1576 + ],
1577 + },
1578 + },
1579 + };
1580 + expect(issuePaths(schema, { x: '!!!' })).toEqual([['invalid_union', ['x']]]);
1581 + });
1582 +});
1583 +
1584 +describe.each(builders)('shared cross-SDK object corpus ($name)', builder => {
1585 for (const testCase of loadObjectCases()) {
1586 describe(testCase.id, () => {
1587 for (const [index, instance] of testCase.instances.entries()) {
1588 const expected = acceptedFor(instance, 'zod');
1589
1521 - it(`instance ${index} is ${expected ? 'accepted' : 'rejected'}`, () => {
1522 - const zodSchema = jsonSchemaToZod(testCase.schema as JsonSchema);
1590 + const name = `instance ${index} is ${expected ? 'accepted' : 'rejected'}`;
1591 +
1592 + testFor(builder, `${testCase.id} > ${name}`)(name, () => {
1593 + const zodSchema = builder.convert(testCase.schema as JsonSchema);
1594 const result = zodSchema.safeParse(instance.input);
1595
1596 expect(result.success).toBe(expected);
ts/packages/json-schema-to-zod/test/linear-pattern.test.ts
+35 -32
@@ -1,7 +1,7 @@
1 import fc from 'fast-check';
2 import { describe, expect, it, vi } from 'vitest';
3
4 -import { InvalidPatternError, jsonSchemaToZod } from '../src/index';
4 +import { InvalidPatternError } from '../src/index';
5 import type { JsonSchema } from '../src/types';
6 import { compilePattern } from '../src/utils/compile-pattern';
7 import {
@@ -11,6 +11,7 @@ import {
11 isSafeForBacktracking,
12 } from '../src/utils/linear-pattern';
13 import { toUnicodePattern } from '../src/utils/unicode-pattern';
14 +import { builders } from './support/builders';
15
16 /** Patterns whose RE2 translation must agree with the native Unicode engine. */
17 const TRANSLATED_PATTERNS = [
@@ -141,12 +142,31 @@ const finishesQuickly = (run: () => void): void => {
142
143 const ATTACK = `${'a'.repeat(40)}!`;
144
144 -describe('catastrophic backtracking (SEC-1178)', () => {
145 +describe('pattern matcher selection', () => {
146 + it('leaves a lookahead pattern that could backtrack catastrophically unenforced', () => {
147 + // Assembled at runtime so static analysis does not flag the test input
148 + // itself as an inefficient regular expression.
149 + const pattern = ['^(?=(a+)+', '$)a'].join('');
150 + const regex = compilePattern('pattern', pattern, { path: [] });
151 + expect(regex.matcher.kind).toBe('unenforced');
152 + finishesQuickly(() => expect(regex.test(ATTACK)).toBe(true));
153 + // The JSON Schema shown to the model still carries the pattern.
154 + expect(regex.source).toBe(pattern);
155 + });
156 +
157 + it('picks RE2 for every pattern it can express', () => {
158 + expect(createPatternMatcher('^(\\d+\\.)*\\d+$').kind).toBe('linear');
159 + expect(createPatternMatcher('^[a-z\\_]+$').kind).toBe('linear');
160 + expect(createPatternMatcher('^(?=.*[a-y])a').kind).toBe('backtracking');
161 + });
162 +});
163 +
164 +describe.each(builders)('catastrophic backtracking (SEC-1178) ($name)', builder => {
165 it.each(['^(?=a){1000000000}a$', `^z|(?=a)${'(?:a|aa)'.repeat(5)}a*a*b$`])(
166 'leaves unsafe fallback pattern %s unenforced',
167 pattern => {
168 expect(createPatternMatcher(pattern).kind).toBe('unenforced');
149 - const parsed = jsonSchemaToZod({ type: 'string', pattern });
169 + const parsed = builder.convert({ type: 'string', pattern });
170 expect(parsed.safeParse('a'.repeat(MAX_BACKTRACKING_INPUT_LENGTH)).success).toBe(true);
171 }
172 );
@@ -191,7 +211,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
211 },
212 $anchor: { extension: { x: { $anchor: 'target', ...target } }, ref: '#target' },
213 }[location]!;
194 - const parsed = jsonSchemaToZod({
214 + const parsed = builder.convert({
215 type: 'object',
216 properties: { value: { $ref: ref } },
217 ...extension,
@@ -221,7 +241,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
241 'rejects unsupported key patterns in extension reference targets (%s) during conversion',
242 (ref, identifier) => {
243 expect(() =>
224 - jsonSchemaToZod({
244 + builder.convert({
245 type: 'object',
246 properties: { value: { $ref: ref } },
247 x: {
@@ -235,7 +255,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
255 );
256
257 it('keeps references through renamed keys in extension schemas valid', () => {
238 - const parsed = jsonSchemaToZod({
258 + const parsed = builder.convert({
259 type: 'object',
260 properties: {
261 keys: { $ref: '#/x' },
@@ -248,7 +268,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
268 });
269
270 it('follows reference cycles without rewriting instance data as schemas', () => {
251 - const parsed = jsonSchemaToZod({
271 + const parsed = builder.convert({
272 type: 'object',
273 properties: { value: { $ref: '#/x' } },
274 x: {
@@ -261,13 +281,13 @@ describe('catastrophic backtracking (SEC-1178)', () => {
281 });
282
283 it('runs a nested-quantifier pattern in linear time', () => {
264 - const parsed = jsonSchemaToZod({ type: 'string', pattern: '^(a+)+$' });
284 + const parsed = builder.convert({ type: 'string', pattern: '^(a+)+$' });
285 finishesQuickly(() => expect(parsed.safeParse(ATTACK).success).toBe(false));
286 expect(parsed.safeParse('aaa').success).toBe(true);
287 });
288
289 it('runs a backtracking patternProperties key in linear time', () => {
270 - const parsed = jsonSchemaToZod({
290 + const parsed = builder.convert({
291 type: 'object',
292 patternProperties: { '^(a|a)*$': { type: 'integer' } },
293 additionalProperties: false,
@@ -290,7 +310,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
310 },
311 },
312 };
293 - const parsed = jsonSchemaToZod(schema);
313 + const parsed = builder.convert(schema);
314
315 finishesQuickly(() => {
316 expect(parsed.safeParse({ handle: ATTACK }).success).toBe(false);
@@ -301,7 +321,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
321 });
322
323 it('runs a backtracking propertyNames pattern in linear time', () => {
304 - const parsed = jsonSchemaToZod({
324 + const parsed = builder.convert({
325 type: 'object',
326 propertyNames: { pattern: '^(a+)+$' },
327 });
@@ -310,18 +330,18 @@ describe('catastrophic backtracking (SEC-1178)', () => {
330 });
331
332 it('reports the schema pattern, not its per-value spelling, in guard errors', () => {
313 - const parsed = jsonSchemaToZod({
333 + const parsed = builder.convert({
334 type: 'object',
335 properties: { tags: { $ref: '#/$defs/tags' } },
336 $defs: { tags: { type: 'object', patternProperties: { '^t_': { type: 'integer' } } } },
337 });
338 const result = parsed.safeParse({ tags: { t_1: 'x' } });
339 expect(result.success).toBe(false);
320 - expect(JSON.stringify(result.error?.issues)).not.toContain('t_1$');
340 + expect(JSON.stringify(result.success ? [] : result.error.issues)).not.toContain('t_1$');
341 });
342
343 it('keeps enforcing a lookahead pattern that is safe to backtrack', () => {
324 - const parsed = jsonSchemaToZod({
344 + const parsed = builder.convert({
345 type: 'string',
346 pattern: '^(?=.*[a-z])(?=.*\\d)[a-z\\d]{8,}$',
347 });
@@ -331,17 +351,6 @@ describe('catastrophic backtracking (SEC-1178)', () => {
351 expect(parsed.safeParse('a'.repeat(MAX_BACKTRACKING_INPUT_LENGTH + 1)).success).toBe(true);
352 });
353
334 - it('leaves a lookahead pattern that could backtrack catastrophically unenforced', () => {
335 - // Assembled at runtime so static analysis does not flag the test input
336 - // itself as an inefficient regular expression.
337 - const pattern = ['^(?=(a+)+', '$)a'].join('');
338 - const regex = compilePattern('pattern', pattern, { path: [] });
339 - expect(regex.matcher.kind).toBe('unenforced');
340 - finishesQuickly(() => expect(regex.test(ATTACK)).toBe(true));
341 - // The JSON Schema shown to the model still carries the pattern.
342 - expect(regex.source).toBe(pattern);
343 - });
344 -
354 it('rejects a patternProperties key that needs a backtracking engine', () => {
355 for (const schema of [
356 { type: 'object', patternProperties: { '^(?!x)': { type: 'string' } } },
@@ -351,7 +360,7 @@ describe('catastrophic backtracking (SEC-1178)', () => {
360 $defs: { v: { type: 'object', patternProperties: { '^(?!x)': { type: 'string' } } } },
361 },
362 ] as JsonSchema[]) {
354 - expect(() => jsonSchemaToZod(schema)).toThrow(InvalidPatternError);
363 + expect(() => builder.convert(schema)).toThrow(InvalidPatternError);
364 }
365 try {
366 compilePattern('patternProperties', '^(?!x)', { path: [] });
@@ -359,10 +368,4 @@ describe('catastrophic backtracking (SEC-1178)', () => {
368 expect((error as InvalidPatternError).reason).toBe('unsupported');
369 }
370 });
362 -
363 - it('picks RE2 for every pattern it can express', () => {
364 - expect(createPatternMatcher('^(\\d+\\.)*\\d+$').kind).toBe('linear');
365 - expect(createPatternMatcher('^[a-z\\_]+$').kind).toBe('linear');
366 - expect(createPatternMatcher('^(?=.*[a-y])a').kind).toBe('backtracking');
367 - });
371 });
ts/packages/json-schema-to-zod/test/property-semantics.test.ts
+4 -4
@@ -22,8 +22,8 @@ import Ajv from 'ajv';
22 import fc from 'fast-check';
23 import { describe, expect, it } from 'vitest';
24
25 -import { jsonSchemaToZod } from '../src/index';
25 import type { JsonSchema, Serializable } from '../src/types';
26 +import { builders } from './support/builders';
27
28 const SCALAR_TYPES = ['string', 'integer', 'number', 'boolean', 'null'] as const;
29 type ScalarType = (typeof SCALAR_TYPES)[number];
@@ -117,7 +117,7 @@ const schemaAndInstance: fc.Arbitrary<{ schema: SchemaRecord; value: Serializabl
117
118 const ajv = new Ajv({ strict: false });
119
120 -describe('scalar conversion matches the Draft 7 oracle', () => {
120 +describe.each(builders)('scalar conversion matches the Draft 7 oracle ($name)', builder => {
121 it('accepts exactly what Ajv accepts, standalone and object-wrapped', () => {
122 fc.assert(
123 fc.property(schemaAndInstance, ({ schema, value }) => {
@@ -130,14 +130,14 @@ describe('scalar conversion matches the Draft 7 oracle', () => {
130 const instance = { value };
131
132 const oracleScalar = ajv.compile(schema)(value);
133 - const zodScalar = jsonSchemaToZod(schema as JsonSchema).safeParse(value).success;
133 + const zodScalar = builder.convert(schema as JsonSchema).safeParse(value).success;
134 expect(
135 zodScalar,
136 `standalone schema=${JSON.stringify(schema)} value=${JSON.stringify(value)}`
137 ).toBe(oracleScalar);
138
139 const oracleObject = ajv.compile(objectSchema)(instance);
140 - const zodObject = jsonSchemaToZod(objectSchema as JsonSchema).safeParse(instance).success;
140 + const zodObject = builder.convert(objectSchema as JsonSchema).safeParse(instance).success;
141 expect(
142 zodObject,
143 `wrapped schema=${JSON.stringify(schema)} value=${JSON.stringify(value)}`
ts/packages/json-schema-to-zod/test/semantic-regressions.test.ts
+34 -31
@@ -2,10 +2,9 @@ import Ajv from 'ajv';
2 import { format } from '@cfworker/json-schema';
3 import { describe, expect, it } from 'vitest';
4
5 -import { z } from 'zod/v3';
6 -
7 -import { jsonSchemaToZod, jsonSchemaToZodShape } from '../src/index';
5 import type { JsonSchema } from '../src/types';
6 +import { builders } from './support/builders';
7 +import { testFor } from './support/divergences';
8
9 type RejectionCase = {
10 readonly name: string;
@@ -194,16 +193,20 @@ const acceptanceCases: ReadonlyArray<AcceptanceCase> = [
193 },
194 ];
195
197 -describe('whole-schema semantic regressions', () => {
198 - it.each(rejectionCases)('$name', ({ schema, value }) => {
199 - expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
200 - expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(false);
201 - });
196 +describe.each(builders)('whole-schema semantic regressions ($name)', builder => {
197 + for (const { name, schema, value } of rejectionCases) {
198 + testFor(builder, name)(name, () => {
199 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
200 + expect(builder.convert(schema).safeParse(value).success).toBe(false);
201 + });
202 + }
203
203 - it.each(acceptanceCases)('$name', ({ schema, value }) => {
204 - expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
205 - expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(true);
206 - });
204 + for (const { name, schema, value } of acceptanceCases) {
205 + testFor(builder, name)(name, () => {
206 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
207 + expect(builder.convert(schema).safeParse(value).success).toBe(true);
208 + });
209 + }
210
211 it('resolves local references from a raw shape against the enclosing document', () => {
212 const schema: JsonSchema = {
@@ -212,7 +215,7 @@ describe('whole-schema semantic regressions', () => {
215 required: ['name'],
216 $defs: { name: { type: 'string' } },
217 };
215 - const shape = z.object(jsonSchemaToZodShape(schema));
218 + const shape = builder.objectFromShape(builder.convertShape(schema));
219
220 expect(shape.safeParse({ name: 'Ada' }).success).toBe(true);
221 expect(shape.safeParse({ name: 1 }).success).toBe(false);
@@ -227,7 +230,7 @@ describe('whole-schema semantic regressions', () => {
230 },
231 $defs: { n: { type: 'string' } },
232 };
230 - const parsed = jsonSchemaToZod(schema);
233 + const parsed = builder.convert(schema);
234
235 expect(parsed.parse({ name: 'Ada' })).toEqual({ name: 'Ada', enabled: true });
236 expect(parsed.safeParse({ name: 1 }).success).toBe(false);
@@ -240,7 +243,7 @@ describe('whole-schema semantic regressions', () => {
243 { type: 'object', properties: { b: { type: 'string', default: 'set' } } },
244 ],
245 };
243 - const parsed = jsonSchemaToZod(schema);
246 + const parsed = builder.convert(schema);
247
248 expect(parsed.parse({ a: 'ready' })).toEqual({ a: 'ready', b: 'set' });
249 expect(parsed.safeParse({ a: 'ready', c: 1 }).success).toBe(false);
@@ -252,7 +255,7 @@ describe('whole-schema semantic regressions', () => {
255 propertyNames: { pattern: '^[a-z]+$' },
256 properties: { v: { type: 'number', minimum: 0, exclusiveMinimum: true } },
257 } as unknown as JsonSchema;
255 - const parsed = jsonSchemaToZod(schema);
258 + const parsed = builder.convert(schema);
259
260 expect(parsed.safeParse({ v: 0.5 }).success).toBe(true);
261 expect(parsed.safeParse({ v: 0 }).success).toBe(false);
@@ -269,7 +272,7 @@ describe('whole-schema semantic regressions', () => {
272 // Ajv intentionally cannot serve as the oracle for the Draft 4 boolean
273 // bound. This value isolates `contains`, which remains a Draft 7 assertion
274 // even when an OpenAPI 3.0 exporter emits the older bound spelling nearby.
272 - expect(jsonSchemaToZod(schema).safeParse([2]).success).toBe(false);
275 + expect(builder.convert(schema).safeParse([2]).success).toBe(false);
276 });
277
278 it('accepts every valid prefix of a closed Draft 7 tuple', () => {
@@ -278,7 +281,7 @@ describe('whole-schema semantic regressions', () => {
281 items: [{ type: 'string' }, { type: 'integer' }],
282 additionalItems: false,
283 };
281 - const parsed = jsonSchemaToZod(schema);
284 + const parsed = builder.convert(schema);
285
286 for (const value of [[], ['ready'], ['ready', 2]]) {
287 expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
@@ -301,7 +304,7 @@ describe('whole-schema semantic regressions', () => {
304 const value = ['ready', 2, { extra: true }];
305
306 expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
304 - expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(true);
307 + expect(builder.convert(schema).safeParse(value).success).toBe(true);
308 });
309
310 it('validates trailing tuple values against schema-valued additionalItems', () => {
@@ -310,7 +313,7 @@ describe('whole-schema semantic regressions', () => {
313 items: [{ type: 'string' }],
314 additionalItems: { type: 'integer' },
315 };
313 - const parsed = jsonSchemaToZod(schema);
316 + const parsed = builder.convert(schema);
317
318 expect(parsed.safeParse(['ready', 1, 2]).success).toBe(true);
319 expect(parsed.safeParse(['ready', 'wrong']).success).toBe(false);
@@ -321,7 +324,7 @@ describe('whole-schema semantic regressions', () => {
324 const value = 2 ** -1022;
325
326 expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
324 - expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(false);
327 + expect(builder.convert(schema).safeParse(value).success).toBe(false);
328 });
329
330 it('keeps a guarded object root a ZodObject with its shape', () => {
@@ -333,10 +336,10 @@ describe('whole-schema semantic regressions', () => {
336 },
337 required: ['q'],
338 };
336 - const parsed = jsonSchemaToZod(schema);
339 + const parsed = builder.convert(schema);
340
338 - expect(parsed).toBeInstanceOf(z.ZodObject);
339 - expect(Object.keys((parsed as z.AnyZodObject).shape)).toEqual(['q', 'limit']);
341 + expect(builder.kind(parsed)).toBe('object');
342 + expect(Object.keys(builder.shape(parsed))).toEqual(['q', 'limit']);
343 expect(parsed.safeParse({ q: 'cats', limit: null }).success).toBe(true);
344 expect(parsed.safeParse({ q: 'cats', limit: 'ten' }).success).toBe(false);
345 expect(parsed.describe('Search').safeParse({ q: 'cats', limit: 'ten' }).success).toBe(false);
@@ -352,7 +355,7 @@ describe('whole-schema semantic regressions', () => {
355 },
356 $defs: { handle: { type: 'string', pattern: '^\\@[a-z\\-]+$' } },
357 };
355 - const parsed = jsonSchemaToZod(schema);
358 + const parsed = builder.convert(schema);
359
360 expect(parsed.safeParse({ slug: 'a_b', ref: '@a-b' }).success).toBe(true);
361 expect(parsed.safeParse({ slug: 'A' }).success).toBe(false);
@@ -368,7 +371,7 @@ describe('whole-schema semantic regressions', () => {
371 properties: { handle: { $ref: '#/$defs/handle' } },
372 $defs: { handle: { type: 'string', pattern } },
373 };
371 - const parsed = jsonSchemaToZod(schema);
374 + const parsed = builder.convert(schema);
375
376 expect(parsed.safeParse({ handle: valid }).success).toBe(true);
377 expect(parsed.safeParse({ handle: invalid }).success).toBe(false);
@@ -380,7 +383,7 @@ describe('whole-schema semantic regressions', () => {
383 properties: { handle: { $ref: '#/$defs/handle' } },
384 $defs: { handle: { type: 'string', pattern: '^leak-check-\\d+$' } },
385 };
383 - const parsed = jsonSchemaToZod(schema);
386 + const parsed = builder.convert(schema);
387
388 expect(parsed.safeParse({ handle: 'leak-check-1' }).success).toBe(true);
389 expect(parsed.safeParse({ handle: 'wrong' }).success).toBe(false);
@@ -395,7 +398,7 @@ describe('whole-schema semantic regressions', () => {
398 '^\\k_$': { type: 'string' },
399 },
400 };
398 - const parsed = jsonSchemaToZod(schema);
401 + const parsed = builder.convert(schema);
402
403 expect(parsed.safeParse({ a_b: 12, k_: 'ok' }).success).toBe(true);
404 expect(parsed.safeParse({ a_b: 2 }).success).toBe(false);
@@ -408,7 +411,7 @@ describe('whole-schema semantic regressions', () => {
411 patternProperties: { '^x\\_': { $ref: '#/$defs/label' } },
412 $defs: { label: { type: 'string' } },
413 };
411 - const parsed = jsonSchemaToZod(schema);
414 + const parsed = builder.convert(schema);
415
416 expect(parsed.safeParse({ x_1: 'ok' }).success).toBe(true);
417 expect(parsed.safeParse({ x_1: 1 }).success).toBe(false);
@@ -420,7 +423,7 @@ describe('whole-schema semantic regressions', () => {
423 properties: { v: { $ref: `#/$defs/patternProperties/${encodeURI('^a\\_b$')}` } },
424 $defs: { patternProperties: { '^a\\_b$': { type: 'string', minLength: 2 } } },
425 } as unknown as JsonSchema;
423 - const parsed = jsonSchemaToZod(schema);
426 + const parsed = builder.convert(schema);
427
428 expect(parsed.safeParse({ v: 'ok' }).success).toBe(true);
429 expect(parsed.safeParse({ v: 'x' }).success).toBe(false);
@@ -428,6 +431,6 @@ describe('whole-schema semantic regressions', () => {
431
432 it('compares decimal multiples by their JSON number spelling', () => {
433 const schema: JsonSchema = { type: 'number', multipleOf: 0.1 };
431 - expect(jsonSchemaToZod(schema).safeParse(0.3).success).toBe(true);
434 + expect(builder.convert(schema).safeParse(0.3).success).toBe(true);
435 });
436 });
ts/packages/json-schema-to-zod/test/support/builder-v4.ts new
+28
@@ -0,0 +1,28 @@
1 +import * as z4 from 'zod/v4';
2 +
3 +import { jsonSchemaToZod as v4Convert, jsonSchemaToZodShape as v4ConvertShape } from '../../src/v4';
4 +import type { Builder, RuntimeSchema, SchemaKind } from './builders';
5 +
6 +const V4_KINDS: Record<string, SchemaKind> = {
7 + string: 'string',
8 + number: 'number',
9 + boolean: 'boolean',
10 + null: 'null',
11 + object: 'object',
12 + array: 'array',
13 +};
14 +
15 +const asV4 = (schema: RuntimeSchema): z4.ZodType => schema as unknown as z4.ZodType;
16 +
17 +export const v4: Builder = {
18 + name: 'zod-v4',
19 + convert: (schema, options) => v4Convert(schema, options) as unknown as RuntimeSchema,
20 + convertShape: (schema, options) =>
21 + v4ConvertShape(schema, options) as unknown as Record<string, RuntimeSchema>,
22 + objectFromShape: shape =>
23 + z4.object(shape as unknown as Record<string, z4.ZodType>) as unknown as RuntimeSchema,
24 + kind: schema => V4_KINDS[asV4(schema).def.type] ?? 'other',
25 + shape: schema => (asV4(schema) as z4.ZodObject).shape as unknown as Record<string, RuntimeSchema>,
26 + description: schema => asV4(schema).description,
27 + toJsonSchema: schema => z4.toJSONSchema(asV4(schema), { io: 'input' }) as Record<string, unknown>,
28 +};
ts/packages/json-schema-to-zod/test/support/builders.ts new
+82
@@ -0,0 +1,82 @@
1 +/**
2 + * The builders the shared suites run against. Each wraps one converter entry
3 + * behind the same small runtime surface, so a suite states JSON Schema
4 + * expectations once and every builder is held to them.
5 + */
6 +import type { ZodTypeAny } from 'zod/v3';
7 +import { version } from 'zod/v4/core';
8 +import { zodToJsonSchema } from 'zod-to-json-schema';
9 +
10 +import { meetsZodV4Floor } from '../../src/backend/zod-v4-floor';
11 +
12 +import {
13 + jsonSchemaToZod as v3Convert,
14 + jsonSchemaToZodShape as v3ConvertShape,
15 +} from '../../src/index';
16 +import type { JsonSchema } from '../../src/types';
17 +import * as z3 from 'zod/v3';
18 +
19 +export type Issue = {
20 + readonly code: string;
21 + readonly path: ReadonlyArray<string | number>;
22 + readonly message: string;
23 +};
24 +
25 +export type SafeParseResult =
26 + | { readonly success: true; readonly data: unknown }
27 + | { readonly success: false; readonly error: { readonly issues: ReadonlyArray<Issue> } };
28 +
29 +export interface RuntimeSchema {
30 + parse(value: unknown): unknown;
31 + safeParse(value: unknown): SafeParseResult;
32 + describe(description: string): RuntimeSchema;
33 +}
34 +
35 +export type ConvertOptions = {
36 + readonly withoutDefaults?: boolean;
37 + readonly withoutDescribes?: boolean;
38 + readonly depth?: number;
39 +};
40 +
41 +export type SchemaKind = 'string' | 'number' | 'boolean' | 'null' | 'object' | 'array' | 'other';
42 +
43 +export interface Builder {
44 + readonly name: 'zod-v3' | 'zod-v4';
45 + convert(schema: JsonSchema, options?: ConvertOptions): RuntimeSchema;
46 + convertShape(schema: JsonSchema, options?: ConvertOptions): Record<string, RuntimeSchema>;
47 + objectFromShape(shape: Record<string, RuntimeSchema>): RuntimeSchema;
48 + kind(schema: RuntimeSchema): SchemaKind;
49 + shape(schema: RuntimeSchema): Record<string, RuntimeSchema>;
50 + description(schema: RuntimeSchema): string | undefined;
51 + toJsonSchema(schema: RuntimeSchema): Record<string, unknown>;
52 +}
53 +
54 +const V3_KINDS: Record<string, SchemaKind> = {
55 + ZodString: 'string',
56 + ZodNumber: 'number',
57 + ZodBoolean: 'boolean',
58 + ZodNull: 'null',
59 + ZodObject: 'object',
60 + ZodArray: 'array',
61 +};
62 +
63 +const asV3 = (schema: RuntimeSchema): ZodTypeAny => schema as unknown as ZodTypeAny;
64 +
65 +export const v3: Builder = {
66 + name: 'zod-v3',
67 + convert: (schema, options) => v3Convert(schema, options) as RuntimeSchema,
68 + convertShape: (schema, options) =>
69 + v3ConvertShape(schema, options) as Record<string, RuntimeSchema>,
70 + objectFromShape: shape =>
71 + z3.object(shape as unknown as Record<string, ZodTypeAny>) as unknown as RuntimeSchema,
72 + kind: schema => V3_KINDS[asV3(schema)._def.typeName] ?? 'other',
73 + shape: schema => (asV3(schema) as z3.AnyZodObject).shape as Record<string, RuntimeSchema>,
74 + description: schema => asV3(schema).description,
75 + toJsonSchema: schema =>
76 + zodToJsonSchema(asV3(schema), { target: 'jsonSchema7' }) as Record<string, unknown>,
77 +};
78 +
79 +/** The v4 builder joins only where the installed zod copy meets the `/v4` floor. */
80 +export const builders: ReadonlyArray<Builder> = meetsZodV4Floor(version)
81 + ? [v3, (await import('./builder-v4')).v4]
82 + : [v3];
ts/packages/json-schema-to-zod/test/support/divergences.ts new
+24
@@ -0,0 +1,24 @@
1 +import { it } from 'vitest';
2 +
3 +import type { Builder } from './builders';
4 +
5 +/**
6 + * Cases one builder is known to get wrong. Each entry turns the named case
7 + * into a test that must keep failing for that builder, so a fix shows up as
8 + * a failing suite and the entry is removed. The target is an empty list.
9 + */
10 +export type Divergence = {
11 + readonly builder: Builder['name'];
12 + /** The test name as the suite registers it. */
13 + readonly case: string;
14 + readonly reason: string;
15 +};
16 +
17 +export const divergences: ReadonlyArray<Divergence> = [];
18 +
19 +const isDivergent = (builder: Builder, caseName: string): boolean =>
20 + divergences.some(entry => entry.builder === builder.name && entry.case === caseName);
21 +
22 +/** `it`, or `it.fails` for a case the builder is listed as diverging on. */
23 +export const testFor = (builder: Builder, caseName: string): typeof it | typeof it.fails =>
24 + isDivergent(builder, caseName) ? it.fails : it;
ts/packages/json-schema-to-zod/test/types.test.ts new
+26
@@ -0,0 +1,26 @@
1 +import { describe, expectTypeOf, it } from 'vitest';
2 +import type * as z3 from 'zod/v3';
3 +import type * as z4 from 'zod/v4';
4 +
5 +import * as root from '../src/index';
6 +import * as v4 from '../src/v4';
7 +
8 +describe('entry point types', () => {
9 + it('types the root entry against zod v3', () => {
10 + expectTypeOf(root.jsonSchemaToZod).returns.toEqualTypeOf<z3.ZodType>();
11 + expectTypeOf(root.jsonSchemaToZodShape).returns.toEqualTypeOf<Record<string, z3.ZodTypeAny>>();
12 + const schema = root.jsonSchemaToZod({ type: 'string' });
13 + // @ts-expect-error a v3 schema is not a v4 schema
14 + const asV4: z4.ZodType = schema;
15 + void asV4;
16 + });
17 +
18 + it('types the /v4 entry against zod v4', () => {
19 + expectTypeOf(v4.jsonSchemaToZod).returns.toEqualTypeOf<z4.ZodType>();
20 + expectTypeOf(v4.jsonSchemaToZodShape).returns.toEqualTypeOf<Record<string, z4.ZodType>>();
21 + const schema = v4.jsonSchemaToZod({ type: 'string' });
22 + // @ts-expect-error a v4 schema is not a v3 schema
23 + const asV3: z3.ZodTypeAny = schema;
24 + void asV3;
25 + });
26 +});
ts/packages/json-schema-to-zod/test/v3-output-fingerprint.test.ts new
+281
@@ -0,0 +1,281 @@
1 +/**
2 + * Pins the shape of every Zod v3 schema the root converter builds, as a JSON
3 + * Schema rendering plus a walk over `_def`. The snapshot is the reference
4 + * that structural refactors of the converter are checked against: a change
5 + * here is a change in what consumers receive, not an internal detail.
6 + */
7 +import { describe, expect, it } from 'vitest';
8 +import type { ZodTypeAny } from 'zod/v3';
9 +import { zodToJsonSchema } from 'zod-to-json-schema';
10 +
11 +import { jsonSchemaToZod } from '../src/index';
12 +import type { JsonSchema } from '../src/types';
13 +import { loadObjectCases, loadStrictCases } from './fixtures/corpus';
14 +
15 +type Fingerprint = Record<string, unknown>;
16 +
17 +const checkFingerprint = (check: Record<string, unknown>): Fingerprint => {
18 + const { regex, ...rest } = check;
19 + return regex instanceof RegExp ? { ...rest, regex: regex.source } : rest;
20 +};
21 +
22 +const defFingerprint = (schema: ZodTypeAny): Fingerprint => {
23 + const def = schema._def as Record<string, unknown> & { typeName: string };
24 + const node: Fingerprint = { typeName: def.typeName };
25 +
26 + if (def.description !== undefined) node.description = def.description;
27 + if ('wholeSchemaGuard' in def) node.guarded = true;
28 + if (Array.isArray(def.checks)) {
29 + node.checks = def.checks.map(check => checkFingerprint(check as Record<string, unknown>));
30 + }
31 +
32 + switch (def.typeName) {
33 + case 'ZodObject': {
34 + const shape = (def.shape as () => Record<string, ZodTypeAny>)();
35 + node.shape = Object.fromEntries(
36 + Object.entries(shape).map(([key, value]) => [key, defFingerprint(value)])
37 + );
38 + node.unknownKeys = def.unknownKeys;
39 + node.catchall = defFingerprint(def.catchall as ZodTypeAny);
40 + break;
41 + }
42 + case 'ZodArray':
43 + node.element = defFingerprint(def.type as ZodTypeAny);
44 + if (def.minLength) node.minLength = def.minLength;
45 + if (def.maxLength) node.maxLength = def.maxLength;
46 + if (def.exactLength) node.exactLength = def.exactLength;
47 + break;
48 + case 'ZodTuple':
49 + node.items = (def.items as ZodTypeAny[]).map(defFingerprint);
50 + node.rest = def.rest ? defFingerprint(def.rest as ZodTypeAny) : null;
51 + break;
52 + case 'ZodUnion':
53 + node.options = (def.options as ZodTypeAny[]).map(defFingerprint);
54 + break;
55 + case 'ZodIntersection':
56 + node.left = defFingerprint(def.left as ZodTypeAny);
57 + node.right = defFingerprint(def.right as ZodTypeAny);
58 + break;
59 + case 'ZodRecord':
60 + node.keyType = defFingerprint(def.keyType as ZodTypeAny);
61 + node.valueType = defFingerprint(def.valueType as ZodTypeAny);
62 + break;
63 + case 'ZodOptional':
64 + case 'ZodNullable':
65 + case 'ZodReadonly':
66 + node.innerType = defFingerprint(def.innerType as ZodTypeAny);
67 + break;
68 + case 'ZodDefault':
69 + node.innerType = defFingerprint(def.innerType as ZodTypeAny);
70 + node.defaultValue = (def.defaultValue as () => unknown)();
71 + break;
72 + case 'ZodEffects':
73 + node.effect = (def.effect as { type: string }).type;
74 + node.schema = defFingerprint(def.schema as ZodTypeAny);
75 + break;
76 + case 'ZodLiteral':
77 + node.value = def.value;
78 + break;
79 + case 'ZodEnum':
80 + node.values = def.values;
81 + break;
82 + default:
83 + break;
84 + }
85 +
86 + return node;
87 +};
88 +
89 +const fingerprint = (schema: JsonSchema): Fingerprint => {
90 + let converted: ZodTypeAny;
91 + try {
92 + converted = jsonSchemaToZod(schema);
93 + } catch (error) {
94 + return { conversionError: error instanceof Error ? error.name : String(error) };
95 + }
96 + return {
97 + jsonSchema: zodToJsonSchema(converted, { target: 'jsonSchema7' }),
98 + def: defFingerprint(converted),
99 + };
100 +};
101 +
102 +const localCases: ReadonlyArray<{ id: string; schema: JsonSchema }> = [
103 + {
104 + id: 'string-formats',
105 + schema: {
106 + type: 'object',
107 + properties: {
108 + email: { type: 'string', format: 'email' },
109 + ip: { type: 'string', format: 'ip' },
110 + ipv4: { type: 'string', format: 'ipv4' },
111 + ipv6: { type: 'string', format: 'ipv6' },
112 + uri: { type: 'string', format: 'uri' },
113 + uuid: { type: 'string', format: 'uuid' },
114 + dateTime: { type: 'string', format: 'date-time' },
115 + time: { type: 'string', format: 'time' },
116 + date: { type: 'string', format: 'date' },
117 + duration: { type: 'string', format: 'duration' },
118 + binary: { type: 'string', format: 'binary' },
119 + byte: { type: 'string', format: 'byte' },
120 + base64: { type: 'string', contentEncoding: 'base64', contentMediaType: 'image/png' },
121 + hex: { type: 'string', contentEncoding: 'base16' },
122 + pattern: { type: 'string', pattern: '^[a-z\\_]+$', minLength: 1, maxLength: 8 },
123 + aliases: { type: 'string', min: 2, max: 4 },
124 + },
125 + required: ['email'],
126 + },
127 + },
128 + {
129 + id: 'number-constraints',
130 + schema: {
131 + type: 'object',
132 + properties: {
133 + integer: { type: 'integer', minimum: 1, maximum: 10 },
134 + int64: { type: 'number', format: 'int64' },
135 + unit: { type: 'number', multipleOf: 1 },
136 + decimal: { type: 'number', multipleOf: 0.1 },
137 + exclusive: { type: 'number', exclusiveMinimum: 0, exclusiveMaximum: 100 },
138 + draft4: { type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 1 },
139 + aliases: { type: 'number', min: 0, max: 1 },
140 + },
141 + } as unknown as JsonSchema,
142 + },
143 + {
144 + id: 'metadata-and-wrappers',
145 + schema: {
146 + type: 'object',
147 + title: 'Request',
148 + description: 'A request',
149 + properties: {
150 + described: { type: 'string', description: 'Named', example: 'x' },
151 + titled: { type: 'string', title: 'Title only', examples: ['a', 'b'] },
152 + nullable: { type: 'integer', nullable: true, description: 'Maybe' },
153 + nullDefault: { type: 'string', default: null },
154 + defaulted: { type: 'string', default: 'x' },
155 + readOnly: { type: 'string', readOnly: true },
156 + nullableNullDefault: { type: 'string', nullable: true, default: null },
157 + anyOfNull: { anyOf: [{ type: 'string' }, { type: 'null' }], default: null },
158 + } as Record<string, JsonSchema>,
159 + },
160 + },
161 + {
162 + id: 'combinators',
163 + schema: {
164 + type: 'object',
165 + properties: {
166 + oneOf: { oneOf: [{ type: 'string' }, { type: 'number' }] },
167 + anyOf: { anyOf: [{ type: 'string' }, { type: 'number' }] },
168 + allOf: {
169 + allOf: [
170 + { type: 'number', minimum: 0 },
171 + { type: 'number', maximum: 1 },
172 + ],
173 + },
174 + not: { not: { type: 'string' } },
175 + conditional: { if: { type: 'string' }, then: { minLength: 1 }, else: { type: 'number' } },
176 + multiple: { type: ['string', 'null'] },
177 + typeless: { minLength: 2 },
178 + enumObject: { enum: [{ a: 1 }, [1]] },
179 + constObject: { const: { a: 1 } },
180 + enumMixed: { enum: ['a', 1, true, null] },
181 + enumStrings: { type: 'string', enum: ['a', 'b'] },
182 + constString: { const: 'a' },
183 + },
184 + },
185 + },
186 + {
187 + id: 'containers',
188 + schema: {
189 + type: 'object',
190 + properties: {
191 + tuple: { type: 'array', items: [{ type: 'string' }, { type: 'integer' }] },
192 + closedTuple: {
193 + type: 'array',
194 + items: [{ type: 'string' }],
195 + additionalItems: false,
196 + minItems: 1,
197 + maxItems: 1,
198 + },
199 + typedRest: {
200 + type: 'array',
201 + items: [{ type: 'string' }],
202 + additionalItems: { type: 'number' },
203 + },
204 + list: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 3 },
205 + aliases: { type: 'array', items: { type: 'string' }, min: 1, max: 3 },
206 + bare: { type: 'array' },
207 + anyOfArray: {
208 + type: 'array',
209 + anyOf: [{ items: { type: 'string' } }, { items: { type: 'number' } }],
210 + },
211 + strict: {
212 + type: 'object',
213 + properties: { a: { type: 'string' } },
214 + additionalProperties: false,
215 + },
216 + open: { type: 'object', properties: { a: { type: 'string' } }, additionalProperties: true },
217 + typed: {
218 + type: 'object',
219 + properties: { a: { type: 'string' } },
220 + additionalProperties: { type: 'number' },
221 + },
222 + record: { type: 'object', additionalProperties: { type: 'number' } },
223 + emptyStrict: { type: 'object', additionalProperties: false },
224 + emptyOpen: { type: 'object' },
225 + patterns: {
226 + type: 'object',
227 + properties: { a: { type: 'string' } },
228 + patternProperties: { '^p_': { type: 'number' } },
229 + additionalProperties: false,
230 + },
231 + patternsOnly: { type: 'object', patternProperties: { '^p_': { type: 'number' } } },
232 + implicit: { properties: { a: { type: 'string' } }, required: ['a'] },
233 + },
234 + },
235 + },
236 + {
237 + id: 'references-and-guards',
238 + schema: {
239 + type: 'object',
240 + properties: {
241 + ref: { $ref: '#/$defs/name' },
242 + nested: { type: 'object', properties: { ref: { $ref: '#/$defs/name' } } },
243 + unique: { type: 'array', uniqueItems: true },
244 + bounded: { type: 'object', minProperties: 1 },
245 + },
246 + required: ['ref'],
247 + $defs: { name: { type: 'string', pattern: '^[a-z]+$' } },
248 + },
249 + },
250 + { id: 'boolean-true', schema: true },
251 + { id: 'boolean-false', schema: false },
252 + { id: 'root-string', schema: { type: 'string', description: 'root' } },
253 + {
254 + id: 'root-nullable',
255 + schema: { type: 'string', nullable: true, default: null } as unknown as JsonSchema,
256 + },
257 + { id: 'root-ref', schema: { $defs: { n: { type: 'number' } }, $ref: '#/$defs/n' } },
258 +];
259 +
260 +describe('v3 output fingerprint', () => {
261 + it('matches the pinned snapshot for the shared object corpus', () => {
262 + const cases = loadObjectCases().map(({ id, schema }) => ({
263 + id,
264 + fingerprint: fingerprint(schema as JsonSchema),
265 + }));
266 + expect(cases).toMatchSnapshot();
267 + });
268 +
269 + it('matches the pinned snapshot for the shared strict corpus', () => {
270 + const cases = loadStrictCases().map(({ id, schema }) => ({
271 + id,
272 + fingerprint: fingerprint(schema as JsonSchema),
273 + }));
274 + expect(cases).toMatchSnapshot();
275 + });
276 +
277 + it('matches the pinned snapshot for the local cases', () => {
278 + const cases = localCases.map(({ id, schema }) => ({ id, fingerprint: fingerprint(schema) }));
279 + expect(cases).toMatchSnapshot();
280 + });
281 +});
ts/packages/json-schema-to-zod/test/v4-floor.test.ts new
+11
@@ -0,0 +1,11 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { version } from 'zod/v4/core';
3 +
4 +describe('the /v4 entry below the zod floor', () => {
5 + it('refuses to load and names the floor', async () => {
6 + expect(version).toEqual({ major: 4, minor: 0, patch: 0 });
7 + await expect(import('../src/v4')).rejects.toThrow(
8 + '@composio/json-schema-to-zod/v4 requires zod >= 4.1.13; found 4.0.0'
9 + );
10 + });
11 +});
ts/packages/json-schema-to-zod/test/v4/__snapshots__/corpus-snapshot.test.ts.snap new
+1052
@@ -0,0 +1,1052 @@
1 +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2 +
3 +exports[`v4 JSON Schema of the shared corpus > matches the pinned snapshot 1`] = `
4 +[
5 + {
6 + "id": "nested-free-form-object",
7 + "jsonSchema": {
8 + "$schema": "http://json-schema.org/draft-07/schema#",
9 + "additionalProperties": false,
10 + "properties": {
11 + "dataset_query": {
12 + "additionalProperties": {},
13 + "properties": {},
14 + "type": "object",
15 + },
16 + },
17 + "type": "object",
18 + },
19 + },
20 + {
21 + "id": "root-free-form-absent-properties",
22 + "jsonSchema": {
23 + "$schema": "http://json-schema.org/draft-07/schema#",
24 + "additionalProperties": {},
25 + "properties": {},
26 + "type": "object",
27 + },
28 + },
29 + {
30 + "id": "root-free-form-empty-properties",
31 + "jsonSchema": {
32 + "$schema": "http://json-schema.org/draft-07/schema#",
33 + "additionalProperties": {},
34 + "properties": {},
35 + "type": "object",
36 + },
37 + },
38 + {
39 + "id": "free-form-object-in-array-items",
40 + "jsonSchema": {
41 + "$schema": "http://json-schema.org/draft-07/schema#",
42 + "additionalProperties": false,
43 + "properties": {
44 + "records": {
45 + "items": {
46 + "additionalProperties": {},
47 + "properties": {},
48 + "type": "object",
49 + },
50 + "type": "array",
51 + },
52 + },
53 + "type": "object",
54 + },
55 + },
56 + {
57 + "id": "nested-pattern-properties-object",
58 + "jsonSchema": {
59 + "$schema": "http://json-schema.org/draft-07/schema#",
60 + "additionalProperties": false,
61 + "properties": {
62 + "payload": {
63 + "additionalProperties": {},
64 + "properties": {},
65 + "type": "object",
66 + },
67 + },
68 + "required": [
69 + "payload",
70 + ],
71 + "type": "object",
72 + },
73 + },
74 + {
75 + "id": "schema-valued-additional-properties-in-array-items",
76 + "jsonSchema": {
77 + "$schema": "http://json-schema.org/draft-07/schema#",
78 + "additionalProperties": false,
79 + "properties": {
80 + "records": {
81 + "items": {
82 + "additionalProperties": {
83 + "type": "number",
84 + },
85 + "propertyNames": {
86 + "type": "string",
87 + },
88 + "type": "object",
89 + },
90 + "type": "array",
91 + },
92 + },
93 + "required": [
94 + "records",
95 + ],
96 + "type": "object",
97 + },
98 + },
99 + {
100 + "id": "explicit-additional-properties-false",
101 + "jsonSchema": {
102 + "$schema": "http://json-schema.org/draft-07/schema#",
103 + "additionalProperties": false,
104 + "properties": {},
105 + "type": "object",
106 + },
107 + },
108 + {
109 + "id": "explicit-additional-properties-true",
110 + "jsonSchema": {
111 + "$schema": "http://json-schema.org/draft-07/schema#",
112 + "additionalProperties": {},
113 + "properties": {
114 + "name": {
115 + "type": "string",
116 + },
117 + },
118 + "type": "object",
119 + },
120 + },
121 + {
122 + "id": "named-properties-strict-by-default",
123 + "jsonSchema": {
124 + "$schema": "http://json-schema.org/draft-07/schema#",
125 + "additionalProperties": false,
126 + "properties": {
127 + "name": {
128 + "type": "string",
129 + },
130 + },
131 + "required": [
132 + "name",
133 + ],
134 + "type": "object",
135 + },
136 + },
137 + {
138 + "id": "named-properties-with-pattern-properties",
139 + "jsonSchema": {
140 + "$schema": "http://json-schema.org/draft-07/schema#",
141 + "additionalProperties": {},
142 + "properties": {
143 + "name": {
144 + "type": "string",
145 + },
146 + },
147 + "type": "object",
148 + },
149 + },
150 + {
151 + "id": "root-additional-properties-schema-valued",
152 + "jsonSchema": {
153 + "$schema": "http://json-schema.org/draft-07/schema#",
154 + "additionalProperties": {
155 + "type": "number",
156 + },
157 + "properties": {
158 + "name": {
159 + "type": "string",
160 + },
161 + },
162 + "type": "object",
163 + },
164 + },
165 + {
166 + "id": "pattern-only-object",
167 + "jsonSchema": {
168 + "$schema": "http://json-schema.org/draft-07/schema#",
169 + "additionalProperties": {},
170 + "properties": {},
171 + "type": "object",
172 + },
173 + },
174 + {
175 + "id": "multiple-matching-patterns",
176 + "jsonSchema": {
177 + "$schema": "http://json-schema.org/draft-07/schema#",
178 + "additionalProperties": {},
179 + "properties": {},
180 + "type": "object",
181 + },
182 + },
183 + {
184 + "id": "declared-property-also-matching-a-pattern",
185 + "jsonSchema": {
186 + "$schema": "http://json-schema.org/draft-07/schema#",
187 + "additionalProperties": {},
188 + "properties": {
189 + "x_id": {
190 + "type": "string",
191 + },
192 + },
193 + "type": "object",
194 + },
195 + },
196 + {
197 + "id": "schema-valued-additional-applies-only-to-unmatched-keys",
198 + "jsonSchema": {
199 + "$schema": "http://json-schema.org/draft-07/schema#",
200 + "additionalProperties": {},
201 + "properties": {
202 + "name": {
203 + "type": "string",
204 + },
205 + },
206 + "type": "object",
207 + },
208 + },
209 + {
210 + "id": "empty-schema-additional-properties",
211 + "jsonSchema": {
212 + "$schema": "http://json-schema.org/draft-07/schema#",
213 + "additionalProperties": {},
214 + "properties": {
215 + "name": {
216 + "type": "string",
217 + },
218 + },
219 + "type": "object",
220 + },
221 + },
222 + {
223 + "id": "pattern-property-enum",
224 + "jsonSchema": {
225 + "$schema": "http://json-schema.org/draft-07/schema#",
226 + "additionalProperties": {},
227 + "properties": {},
228 + "type": "object",
229 + },
230 + },
231 + {
232 + "id": "pattern-property-strict-nested-array",
233 + "jsonSchema": {
234 + "$schema": "http://json-schema.org/draft-07/schema#",
235 + "additionalProperties": {},
236 + "properties": {},
237 + "type": "object",
238 + },
239 + },
240 + {
241 + "id": "false-pattern-property-schema",
242 + "jsonSchema": {
243 + "$schema": "http://json-schema.org/draft-07/schema#",
244 + "additionalProperties": {},
245 + "properties": {},
246 + "type": "object",
247 + },
248 + },
249 + {
250 + "id": "pattern-property-type-union",
251 + "jsonSchema": {
252 + "$schema": "http://json-schema.org/draft-07/schema#",
253 + "additionalProperties": {},
254 + "properties": {},
255 + "type": "object",
256 + },
257 + },
258 + {
259 + "id": "pattern-property-json-integer",
260 + "jsonSchema": {
261 + "$schema": "http://json-schema.org/draft-07/schema#",
262 + "additionalProperties": {},
263 + "properties": {},
264 + "type": "object",
265 + },
266 + },
267 + {
268 + "id": "pattern-property-composed-const-exclusion",
269 + "jsonSchema": {
270 + "$schema": "http://json-schema.org/draft-07/schema#",
271 + "additionalProperties": {},
272 + "properties": {},
273 + "type": "object",
274 + },
275 + },
276 + {
277 + "id": "pattern-property-default-materialization",
278 + "jsonSchema": {
279 + "$schema": "http://json-schema.org/draft-07/schema#",
280 + "additionalProperties": {},
281 + "properties": {},
282 + "type": "object",
283 + },
284 + },
285 + {
286 + "id": "primitive-boolean-property-schemas",
287 + "jsonSchema": {
288 + "$schema": "http://json-schema.org/draft-07/schema#",
289 + "additionalProperties": false,
290 + "properties": {
291 + "allowed": {},
292 + "forbidden": {
293 + "not": {},
294 + },
295 + },
296 + "required": [
297 + "allowed",
298 + ],
299 + "type": "object",
300 + },
301 + },
302 + {
303 + "id": "primitive-empty-and-null-schemas",
304 + "jsonSchema": {
305 + "$schema": "http://json-schema.org/draft-07/schema#",
306 + "additionalProperties": false,
307 + "properties": {
308 + "anything": {},
309 + "nullOnly": {
310 + "type": "null",
311 + },
312 + },
313 + "required": [
314 + "anything",
315 + "nullOnly",
316 + ],
317 + "type": "object",
318 + },
319 + },
320 + {
321 + "id": "primitive-type-array-union",
322 + "jsonSchema": {
323 + "$schema": "http://json-schema.org/draft-07/schema#",
324 + "additionalProperties": false,
325 + "properties": {
326 + "value": {
327 + "type": [
328 + "string",
329 + "integer",
330 + "null",
331 + ],
332 + },
333 + },
334 + "required": [
335 + "value",
336 + ],
337 + "type": "object",
338 + },
339 + },
340 + {
341 + "id": "primitive-enum-intersects-declared-type",
342 + "jsonSchema": {
343 + "$schema": "http://json-schema.org/draft-07/schema#",
344 + "additionalProperties": false,
345 + "properties": {
346 + "value": {
347 + "allOf": [
348 + {
349 + "type": "string",
350 + },
351 + {
352 + "anyOf": [
353 + {
354 + "const": 1,
355 + "type": "number",
356 + },
357 + {
358 + "const": "ready",
359 + "type": "string",
360 + },
361 + ],
362 + },
363 + ],
364 + },
365 + },
366 + "required": [
367 + "value",
368 + ],
369 + "type": "object",
370 + },
371 + },
372 + {
373 + "id": "primitive-null-only-unions",
374 + "jsonSchema": {
375 + "$schema": "http://json-schema.org/draft-07/schema#",
376 + "additionalProperties": false,
377 + "properties": {
378 + "anyOf": {
379 + "type": "null",
380 + },
381 + "typeArray": {
382 + "type": "null",
383 + },
384 + },
385 + "required": [
386 + "typeArray",
387 + "anyOf",
388 + ],
389 + "type": "object",
390 + },
391 + },
392 + {
393 + "id": "primitive-scalar-constraints",
394 + "jsonSchema": {
395 + "$schema": "http://json-schema.org/draft-07/schema#",
396 + "additionalProperties": false,
397 + "properties": {
398 + "code": {
399 + "pattern": "^[A-Z]{2}$",
400 + "type": "string",
401 + },
402 + "count": {
403 + "exclusiveMinimum": 0,
404 + "type": "number",
405 + },
406 + },
407 + "required": [
408 + "code",
409 + "count",
410 + ],
411 + "type": "object",
412 + },
413 + },
414 + {
415 + "id": "primitive-independent-numeric-bounds",
416 + "jsonSchema": {
417 + "$schema": "http://json-schema.org/draft-07/schema#",
418 + "additionalProperties": false,
419 + "properties": {
420 + "lower": {
421 + "exclusiveMinimum": 5,
422 + "type": "number",
423 + },
424 + "upper": {
425 + "exclusiveMaximum": 5,
426 + "type": "number",
427 + },
428 + },
429 + "required": [
430 + "lower",
431 + "upper",
432 + ],
433 + "type": "object",
434 + },
435 + },
436 + {
437 + "id": "primitive-const-intersects-declared-type",
438 + "jsonSchema": {
439 + "$schema": "http://json-schema.org/draft-07/schema#",
440 + "additionalProperties": false,
441 + "properties": {
442 + "value": {
443 + "allOf": [
444 + {
445 + "type": "string",
446 + },
447 + {
448 + "const": 1,
449 + "type": "number",
450 + },
451 + ],
452 + },
453 + },
454 + "required": [
455 + "value",
456 + ],
457 + "type": "object",
458 + },
459 + },
460 + {
461 + "id": "primitive-compound-enum-values",
462 + "jsonSchema": {
463 + "$schema": "http://json-schema.org/draft-07/schema#",
464 + "additionalProperties": false,
465 + "properties": {
466 + "value": {
467 + "allOf": [
468 + {},
469 + {},
470 + ],
471 + },
472 + },
473 + "required": [
474 + "value",
475 + ],
476 + "type": "object",
477 + },
478 + },
479 + {
480 + "id": "primitive-const-null-and-false",
481 + "jsonSchema": {
482 + "$schema": "http://json-schema.org/draft-07/schema#",
483 + "additionalProperties": false,
484 + "properties": {
485 + "flag": {
486 + "allOf": [
487 + {},
488 + {
489 + "const": false,
490 + "type": "boolean",
491 + },
492 + ],
493 + },
494 + "maybe": {
495 + "allOf": [
496 + {},
497 + {
498 + "const": null,
499 + "type": "null",
500 + },
501 + ],
502 + },
503 + },
504 + "required": [
505 + "maybe",
506 + "flag",
507 + ],
508 + "type": "object",
509 + },
510 + },
511 + {
512 + "id": "primitive-enum-boolean-number-identity",
513 + "jsonSchema": {
514 + "$schema": "http://json-schema.org/draft-07/schema#",
515 + "additionalProperties": false,
516 + "properties": {
517 + "bits": {
518 + "allOf": [
519 + {},
520 + {
521 + "anyOf": [
522 + {
523 + "const": 0,
524 + "type": "number",
525 + },
526 + {
527 + "const": 1,
528 + "type": "number",
529 + },
530 + ],
531 + },
532 + ],
533 + },
534 + "toggle": {
535 + "allOf": [
536 + {},
537 + {
538 + "const": true,
539 + "type": "boolean",
540 + },
541 + ],
542 + },
543 + },
544 + "required": [
545 + "bits",
546 + "toggle",
547 + ],
548 + "type": "object",
549 + },
550 + },
551 + {
552 + "id": "primitive-enum-with-null-member",
553 + "jsonSchema": {
554 + "$schema": "http://json-schema.org/draft-07/schema#",
555 + "additionalProperties": false,
556 + "properties": {
557 + "value": {
558 + "allOf": [
559 + {},
560 + {
561 + "anyOf": [
562 + {
563 + "const": "a",
564 + "type": "string",
565 + },
566 + {
567 + "const": null,
568 + "type": "null",
569 + },
570 + ],
571 + },
572 + ],
573 + },
574 + },
575 + "required": [
576 + "value",
577 + ],
578 + "type": "object",
579 + },
580 + },
581 + {
582 + "id": "primitive-const-constraint-conjunction",
583 + "jsonSchema": {
584 + "$schema": "http://json-schema.org/draft-07/schema#",
585 + "additionalProperties": false,
586 + "properties": {
587 + "code": {
588 + "allOf": [
589 + {
590 + "type": "string",
591 + },
592 + {
593 + "const": "a",
594 + "type": "string",
595 + },
596 + ],
597 + },
598 + },
599 + "required": [
600 + "code",
601 + ],
602 + "type": "object",
603 + },
604 + },
605 + {
606 + "id": "primitive-inclusive-numeric-boundaries",
607 + "jsonSchema": {
608 + "$schema": "http://json-schema.org/draft-07/schema#",
609 + "additionalProperties": false,
610 + "properties": {
611 + "count": {
612 + "maximum": 10,
613 + "minimum": 5,
614 + "type": "integer",
615 + },
616 + },
617 + "required": [
618 + "count",
619 + ],
620 + "type": "object",
621 + },
622 + },
623 + {
624 + "id": "primitive-const-narrows-enum",
625 + "jsonSchema": {
626 + "$schema": "http://json-schema.org/draft-07/schema#",
627 + "additionalProperties": false,
628 + "properties": {
629 + "value": {
630 + "allOf": [
631 + {},
632 + {
633 + "const": "b",
634 + "type": "string",
635 + },
636 + {
637 + "enum": [
638 + "a",
639 + "b",
640 + ],
641 + "type": "string",
642 + },
643 + ],
644 + },
645 + },
646 + "required": [
647 + "value",
648 + ],
649 + "type": "object",
650 + },
651 + },
652 + {
653 + "id": "primitive-compound-const-deep-equality",
654 + "jsonSchema": {
655 + "$schema": "http://json-schema.org/draft-07/schema#",
656 + "additionalProperties": false,
657 + "properties": {
658 + "value": {
659 + "allOf": [
660 + {},
661 + {},
662 + ],
663 + },
664 + },
665 + "required": [
666 + "value",
667 + ],
668 + "type": "object",
669 + },
670 + },
671 + {
672 + "id": "primitive-unicode-code-point-length",
673 + "jsonSchema": {
674 + "$schema": "http://json-schema.org/draft-07/schema#",
675 + "additionalProperties": false,
676 + "properties": {
677 + "glyph": {
678 + "type": "string",
679 + },
680 + },
681 + "required": [
682 + "glyph",
683 + ],
684 + "type": "object",
685 + },
686 + },
687 + {
688 + "id": "primitive-typeless-constraint-scoping",
689 + "jsonSchema": {
690 + "$schema": "http://json-schema.org/draft-07/schema#",
691 + "additionalProperties": false,
692 + "properties": {
693 + "value": {
694 + "allOf": [
695 + {},
696 + {
697 + "enum": [
698 + "a",
699 + "abc",
700 + ],
701 + "type": "string",
702 + },
703 + ],
704 + },
705 + },
706 + "required": [
707 + "value",
708 + ],
709 + "type": "object",
710 + },
711 + },
712 + {
713 + "id": "primitive-float-multiple-of",
714 + "jsonSchema": {
715 + "$schema": "http://json-schema.org/draft-07/schema#",
716 + "additionalProperties": false,
717 + "properties": {
718 + "step": {
719 + "type": "number",
720 + },
721 + },
722 + "required": [
723 + "step",
724 + ],
725 + "type": "object",
726 + },
727 + },
728 + {
729 + "id": "primitive-draft4-boolean-exclusive-bounds",
730 + "jsonSchema": {
731 + "$schema": "http://json-schema.org/draft-07/schema#",
732 + "additionalProperties": false,
733 + "properties": {
734 + "lower": {
735 + "exclusiveMinimum": 5,
736 + "type": "number",
737 + },
738 + "upper": {
739 + "exclusiveMaximum": 5,
740 + "type": "number",
741 + },
742 + },
743 + "required": [
744 + "lower",
745 + "upper",
746 + ],
747 + "type": "object",
748 + },
749 + },
750 + {
751 + "id": "primitive-type-array-constraint-scoping",
752 + "jsonSchema": {
753 + "$schema": "http://json-schema.org/draft-07/schema#",
754 + "additionalProperties": false,
755 + "properties": {
756 + "value": {
757 + "anyOf": [
758 + {
759 + "type": "string",
760 + },
761 + {
762 + "minimum": 10,
763 + "type": "number",
764 + },
765 + ],
766 + },
767 + },
768 + "required": [
769 + "value",
770 + ],
771 + "type": "object",
772 + },
773 + },
774 + {
775 + "id": "primitive-empty-enum-optional-property",
776 + "jsonSchema": {
777 + "$schema": "http://json-schema.org/draft-07/schema#",
778 + "additionalProperties": false,
779 + "properties": {
780 + "value": {
781 + "allOf": [
782 + {},
783 + {
784 + "not": {},
785 + },
786 + ],
787 + },
788 + },
789 + "type": "object",
790 + },
791 + },
792 + {
793 + "id": "additional-property-default-materialization",
794 + "jsonSchema": {
795 + "$schema": "http://json-schema.org/draft-07/schema#",
796 + "additionalProperties": {
797 + "additionalProperties": false,
798 + "properties": {
799 + "enabled": {
800 + "default": false,
801 + "type": "boolean",
802 + },
803 + },
804 + "type": "object",
805 + },
806 + "properties": {
807 + "name": {
808 + "type": "string",
809 + },
810 + },
811 + "type": "object",
812 + },
813 + },
814 + {
815 + "id": "composition-fixed-tuple-items",
816 + "jsonSchema": {
817 + "$schema": "http://json-schema.org/draft-07/schema#",
818 + "additionalProperties": false,
819 + "properties": {
820 + "value": {
821 + "anyOf": [
822 + {
823 + "additionalItems": false,
824 + "items": [],
825 + "maxItems": 0,
826 + "type": "array",
827 + },
828 + {
829 + "additionalItems": false,
830 + "items": [
831 + {
832 + "type": "string",
833 + },
834 + ],
835 + "maxItems": 1,
836 + "minItems": 1,
837 + "type": "array",
838 + },
839 + {
840 + "additionalItems": false,
841 + "items": [
842 + {
843 + "type": "string",
844 + },
845 + {
846 + "type": "integer",
847 + },
848 + ],
849 + "maxItems": 2,
850 + "minItems": 2,
851 + "type": "array",
852 + },
853 + ],
854 + },
855 + },
856 + "required": [
857 + "value",
858 + ],
859 + "type": "object",
860 + },
861 + },
862 + {
863 + "id": "composition-open-tuple-items",
864 + "jsonSchema": {
865 + "$schema": "http://json-schema.org/draft-07/schema#",
866 + "additionalProperties": false,
867 + "properties": {
868 + "value": {
869 + "anyOf": [
870 + {
871 + "additionalItems": false,
872 + "items": [],
873 + "maxItems": 0,
874 + "type": "array",
875 + },
876 + {
877 + "additionalItems": false,
878 + "items": [
879 + {
880 + "type": "string",
881 + },
882 + ],
883 + "maxItems": 1,
884 + "minItems": 1,
885 + "type": "array",
886 + },
887 + {
888 + "additionalItems": {},
889 + "items": [
890 + {
891 + "type": "string",
892 + },
893 + {
894 + "type": "integer",
895 + },
896 + ],
897 + "minItems": 2,
898 + "type": "array",
899 + },
900 + ],
901 + },
902 + },
903 + "required": [
904 + "value",
905 + ],
906 + "type": "object",
907 + },
908 + },
909 + {
910 + "id": "composition-false-tuple-position",
911 + "jsonSchema": {
912 + "$schema": "http://json-schema.org/draft-07/schema#",
913 + "additionalProperties": false,
914 + "properties": {
915 + "value": {
916 + "anyOf": [
917 + {
918 + "additionalItems": false,
919 + "items": [],
920 + "maxItems": 0,
921 + "type": "array",
922 + },
923 + {
924 + "additionalItems": false,
925 + "items": [
926 + {
927 + "type": "string",
928 + },
929 + ],
930 + "maxItems": 1,
931 + "minItems": 1,
932 + "type": "array",
933 + },
934 + {
935 + "additionalItems": false,
936 + "items": [
937 + {
938 + "type": "string",
939 + },
940 + {
941 + "not": {},
942 + },
943 + ],
944 + "maxItems": 2,
945 + "minItems": 2,
946 + "type": "array",
947 + },
948 + ],
949 + },
950 + },
951 + "required": [
952 + "value",
953 + ],
954 + "type": "object",
955 + },
956 + },
957 + {
958 + "id": "composition-allof-object-intersection",
959 + "jsonSchema": {
960 + "$schema": "http://json-schema.org/draft-07/schema#",
961 + "additionalProperties": false,
962 + "properties": {
963 + "value": {
964 + "properties": {
965 + "a": {
966 + "type": "string",
967 + },
968 + "b": {
969 + "type": "integer",
970 + },
971 + },
972 + "required": [
973 + "a",
974 + "b",
975 + ],
976 + "type": "object",
977 + },
978 + },
979 + "required": [
980 + "value",
981 + ],
982 + "type": "object",
983 + },
984 + },
985 + {
986 + "id": "composition-allof-closed-object-branches",
987 + "jsonSchema": {
988 + "$schema": "http://json-schema.org/draft-07/schema#",
989 + "additionalProperties": false,
990 + "properties": {
991 + "value": {
992 + "properties": {
993 + "a": {
994 + "type": "string",
995 + },
996 + "b": {
997 + "type": "string",
998 + },
999 + },
1000 + "required": [
1001 + "a",
1002 + "b",
1003 + ],
1004 + "type": "object",
1005 + },
1006 + },
1007 + "required": [
1008 + "value",
1009 + ],
1010 + "type": "object",
1011 + },
1012 + },
1013 + {
1014 + "id": "composition-scalar-allof",
1015 + "jsonSchema": {
1016 + "$schema": "http://json-schema.org/draft-07/schema#",
1017 + "additionalProperties": false,
1018 + "properties": {
1019 + "value": {
1020 + "allOf": [
1021 + {
1022 + "type": "string",
1023 + },
1024 + {
1025 + "pattern": "^[A-Z]+$",
1026 + "type": "string",
1027 + },
1028 + ],
1029 + },
1030 + },
1031 + "required": [
1032 + "value",
1033 + ],
1034 + "type": "object",
1035 + },
1036 + },
1037 + {
1038 + "id": "composition-oneof-exclusive-match",
1039 + "jsonSchema": {
1040 + "$schema": "http://json-schema.org/draft-07/schema#",
1041 + "additionalProperties": false,
1042 + "properties": {
1043 + "value": {},
1044 + },
1045 + "required": [
1046 + "value",
1047 + ],
1048 + "type": "object",
1049 + },
1050 + },
1051 +]
1052 +`;
ts/packages/json-schema-to-zod/test/v4/acceptance.test.ts new
+50
@@ -0,0 +1,50 @@
1 +import Ajv from 'ajv';
2 +import { describe, expect, it } from 'vitest';
3 +
4 +import { jsonSchemaToZod as toV3 } from '../../src/index';
5 +import { jsonSchemaToZod as toV4 } from '../../src/v4';
6 +import type { JsonSchema } from '../../src/types';
7 +
8 +const ajv = new Ajv({ strict: false });
9 +
10 +describe('v4 acceptance matches v3 without rewriting the input', () => {
11 + it.each([
12 + { name: 'a uri with surrounding spaces', value: ' https://example.com/a b ' },
13 + { name: 'a uri with a mixed-case host', value: 'https://Example.COM/Path?Q=1' },
14 + { name: 'a uri with a trailing newline', value: 'https://example.com/\n' },
15 + ])('keeps $name as given', ({ value }) => {
16 + const schema: JsonSchema = { type: 'string', format: 'uri' };
17 + const v3 = toV3(schema).safeParse(value);
18 + const v4 = toV4(schema).safeParse(value);
19 + expect(v4.success).toBe(v3.success);
20 + expect(v4.success && v4.data).toBe(v3.success && v3.data);
21 + expect(v4.success && v4.data).toBe(value);
22 + });
23 +
24 + it('accepts a uuid with a non-RFC variant, as v3 does', () => {
25 + const schema: JsonSchema = { type: 'string', format: 'uuid' };
26 + const value = '123e4567-e89b-12d3-c456-426614174000';
27 + expect(toV3(schema).safeParse(value).success).toBe(true);
28 + expect(toV4(schema).safeParse(value).success).toBe(true);
29 + expect(toV4(schema).safeParse('not-a-uuid').success).toBe(false);
30 + });
31 +
32 + it('accepts an integer above 2^53, as v3 and Ajv do', () => {
33 + const schema: JsonSchema = { type: 'integer' };
34 + const value = 2 ** 53 + 2;
35 + expect(ajv.compile(schema)(value)).toBe(true);
36 + expect(toV3(schema).safeParse(value).success).toBe(true);
37 + expect(toV4(schema).safeParse(value).success).toBe(true);
38 + expect(toV4(schema).safeParse(1.5).success).toBe(false);
39 + expect(toV4({ type: 'number', format: 'int64' }).safeParse(value).success).toBe(true);
40 + expect(toV4({ type: 'number', multipleOf: 1 }).safeParse(value).success).toBe(true);
41 + });
42 +
43 + it.each(['127.0.0.1', '::1', '2001:db8::ff00:42:8329'])('accepts ip %s', value => {
44 + expect(toV4({ type: 'string', format: 'ip' }).safeParse(value).success).toBe(true);
45 + });
46 +
47 + it('rejects a value that is neither an IPv4 nor an IPv6 address', () => {
48 + expect(toV4({ type: 'string', format: 'ip' }).safeParse('999.1.1.1').success).toBe(false);
49 + });
50 +});
ts/packages/json-schema-to-zod/test/v4/annotations.test.ts new
+185
@@ -0,0 +1,185 @@
1 +import Ajv from 'ajv';
2 +import { describe, expect, it } from 'vitest';
3 +import * as z4 from 'zod/v4';
4 +
5 +import { jsonSchemaToZod } from '../../src/v4';
6 +import { zodV4Backend } from '../../src/backend/zod-v4';
7 +import type { JsonSchema } from '../../src/types';
8 +
9 +type Json = Record<string, unknown>;
10 +
11 +const render = (schema: JsonSchema, io: 'input' | 'output' = 'input'): Json =>
12 + z4.toJSONSchema(jsonSchemaToZod(schema), { io, target: 'draft-7' }) as Json;
13 +
14 +const property = (json: Json, key: string): Json => (json.properties as Record<string, Json>)[key];
15 +
16 +const ajv = new Ajv({ strict: false, validateFormats: false });
17 +
18 +describe('v4 annotation forwarding', () => {
19 + it.each(['input', 'output'] as const)(
20 + 'keeps the source format, encoding, and media type (io %s)',
21 + io => {
22 + const json = render(
23 + {
24 + type: 'object',
25 + properties: {
26 + file: { type: 'string', format: 'binary' },
27 + hex: { type: 'string', contentEncoding: 'base16' },
28 + image: { type: 'string', contentEncoding: 'BASE64', contentMediaType: 'image/png' },
29 + at: { type: 'string', format: 'time' },
30 + big: { type: 'number', format: 'int64' },
31 + when: { type: 'string', format: 'date-time', description: 'When' },
32 + },
33 + },
34 + io
35 + );
36 + expect(property(json, 'file')).toEqual({ type: 'string', format: 'binary' });
37 + expect(property(json, 'hex')).toEqual({ type: 'string', contentEncoding: 'base16' });
38 + expect(property(json, 'image')).toMatchObject({
39 + type: 'string',
40 + contentEncoding: 'BASE64',
41 + contentMediaType: 'image/png',
42 + });
43 + // zod adds its own `pattern` for the ISO formats; the source `format` rides along.
44 + expect(property(json, 'at')).toMatchObject({ type: 'string', format: 'time' });
45 + expect(property(json, 'big')).toEqual({ type: 'integer', format: 'int64' });
46 + expect(property(json, 'when')).toMatchObject({
47 + type: 'string',
48 + format: 'date-time',
49 + description: 'When',
50 + });
51 + }
52 + );
53 +
54 + it('forwards annotations on nested properties and under a guarded root', () => {
55 + const json = render({
56 + type: 'object',
57 + properties: {
58 + inner: {
59 + type: 'object',
60 + properties: { blob: { type: 'string', format: 'binary' } },
61 + },
62 + linked: { $ref: '#/$defs/count' },
63 + total: { type: 'integer' },
64 + },
65 + $defs: { count: { type: 'integer' } },
66 + });
67 + expect(property(property(json, 'inner'), 'blob')).toEqual({ type: 'string', format: 'binary' });
68 + expect(property(json, 'total')).toEqual({ type: 'integer' });
69 + });
70 +
71 + it('leaves the annotations out with withoutAnnotations', () => {
72 + const json = z4.toJSONSchema(
73 + jsonSchemaToZod(
74 + {
75 + type: 'object',
76 + properties: {
77 + file: { type: 'string', format: 'binary', description: 'A file' },
78 + count: { type: 'integer' },
79 + },
80 + },
81 + { withoutAnnotations: true }
82 + ),
83 + { io: 'input', target: 'draft-7' }
84 + ) as Json;
85 + expect(property(json, 'file')).toEqual({ type: 'string', description: 'A file' });
86 + expect(property(json, 'count')).toEqual({ type: 'number' });
87 + });
88 +
89 + it.each([
90 + {
91 + name: 'a nullable integer',
92 + schema: { type: 'integer', nullable: true, description: 'N' },
93 + accepted: 7,
94 + rejected: 7.5,
95 + },
96 + {
97 + name: 'a nullable date-time',
98 + schema: { type: 'string', format: 'date-time', nullable: true, description: 'D' },
99 + accepted: '2024-03-20T12:00:00Z',
100 + rejected: 12,
101 + },
102 + ])('keeps $name nullable in the rendered schema', ({ schema, accepted, rejected }) => {
103 + const converted = jsonSchemaToZod(schema as unknown as JsonSchema);
104 + const json = z4.toJSONSchema(converted, { io: 'input', target: 'draft-7' }) as Json;
105 + // The annotations sit on the inner node: a scalar `type` or `format`
106 + // next to the wrapper's own rendering would reject `null`. zod 4.5
107 + // folds `anyOf: [inner, null]` into a type array when the inner node
108 + // carries only a `type`; 4.1 keeps the `anyOf`.
109 + expect(typeof json.type).not.toBe('string');
110 + expect(json).not.toHaveProperty('format');
111 + expect(json.description).toBe(schema.description);
112 + expect(converted.description).toBe(schema.description);
113 + const { $schema: _schema, ...plain } = json;
114 + const validate = ajv.compile(plain);
115 + expect(validate(null)).toBe(true);
116 + expect(validate(accepted)).toBe(true);
117 + expect(validate(rejected)).toBe(false);
118 + expect(converted.safeParse(null).success).toBe(true);
119 + expect(converted.safeParse(accepted).success).toBe(true);
120 + expect(converted.safeParse(rejected).success).toBe(false);
121 + });
122 +
123 + it('keeps type integer next to bounds', () => {
124 + const json = render({ type: 'integer', minimum: 1, maximum: 10 });
125 + expect(json).toMatchObject({ type: 'integer', minimum: 1, maximum: 10 });
126 + expect(render({ type: 'number', multipleOf: 1 })).toMatchObject({ type: 'integer' });
127 + });
128 +
129 + it('forwards annotations on a constrained value', () => {
130 + const json = render({ type: 'string', enum: ['a', 'b'], format: 'custom', description: 'E' });
131 + expect(json.format).toBe('custom');
132 + expect(json.description).toBe('E');
133 + });
134 +
135 + it('forwards nothing from the keywords next to a $ref', () => {
136 + const schema: JsonSchema = {
137 + type: 'object',
138 + $defs: { text: { type: 'string' } },
139 + properties: {
140 + x: { $ref: '#/$defs/text', type: 'integer', format: 'int64', contentEncoding: 'base64' },
141 + },
142 + required: ['x'],
143 + };
144 + expect(jsonSchemaToZod(schema).safeParse({ x: 'hi' }).success).toBe(true);
145 + expect(property(render(schema), 'x')).toEqual({});
146 + });
147 +
148 + it('writes the description together with the annotations', () => {
149 + const converted = jsonSchemaToZod({ type: 'string', format: 'binary', description: 'Bytes' });
150 + expect(converted.description).toBe('Bytes');
151 + expect(converted.meta()).toEqual({ description: 'Bytes', format: 'binary' });
152 + });
153 +});
154 +
155 +describe('v4 decorate across wrapper kinds', () => {
156 + /** Every wrapper kind `annotateInnermost` can receive, built through the backend itself. */
157 + it.each([
158 + ['optional', (inner: z4.ZodString) => zodV4Backend.optional(inner)],
159 + ['nullable', (inner: z4.ZodString) => zodV4Backend.nullable(inner)],
160 + ['prefault', (inner: z4.ZodString) => zodV4Backend.withDefault(inner, 'fallback')],
161 + ['readonly', (inner: z4.ZodString) => zodV4Backend.readonly(inner)],
162 + ] as const)(
163 + 'puts forwarded annotations on the innermost node under a %s wrapper',
164 + (_name, make) => {
165 + const inner = z4.string();
166 + const decorated = zodV4Backend.decorate(make(inner).meta({ title: 'Wrapper' }), {
167 + annotations: { format: 'binary' },
168 + });
169 +
170 + // A validation-shaped annotation on the wrapper would sit beside the
171 + // wrapper's own rendering (`anyOf`, `default`, `readOnly`) and change
172 + // what the schema accepts; it must land on the innermost node.
173 + let deepest = decorated;
174 + for (;;) {
175 + const def = (deepest as unknown as { _zod: { def: { innerType?: z4.ZodType } } })._zod.def;
176 + if (!def.innerType) break;
177 + deepest = def.innerType;
178 + }
179 + expect(z4.globalRegistry.get(deepest)).toMatchObject({ format: 'binary' });
180 + // The wrapper keeps the metadata it already carried through the rewrap.
181 + expect(z4.globalRegistry.get(decorated)).toMatchObject({ title: 'Wrapper' });
182 + expect(decorated.safeParse('data').success).toBe(true);
183 + }
184 + );
185 +});
ts/packages/json-schema-to-zod/test/v4/corpus-snapshot.test.ts new
+23
@@ -0,0 +1,23 @@
1 +/**
2 + * The JSON Schema the v4 builder renders for the shared corpus, as the
3 + * review artifact for moving core and the providers onto it.
4 + */
5 +import { describe, expect, it } from 'vitest';
6 +import * as z4 from 'zod/v4';
7 +
8 +import { jsonSchemaToZod } from '../../src/v4';
9 +import type { JsonSchema } from '../../src/types';
10 +import { loadObjectCases } from '../fixtures/corpus';
11 +
12 +describe('v4 JSON Schema of the shared corpus', () => {
13 + it('matches the pinned snapshot', () => {
14 + const cases = loadObjectCases().map(({ id, schema }) => ({
15 + id,
16 + jsonSchema: z4.toJSONSchema(jsonSchemaToZod(schema as JsonSchema), {
17 + io: 'input',
18 + target: 'draft-7',
19 + }),
20 + }));
21 + expect(cases).toMatchSnapshot();
22 + });
23 +});
ts/packages/json-schema-to-zod/test/v4/frameworks.test.ts new
+45
@@ -0,0 +1,45 @@
1 +import { zodSchema } from '@ai-sdk/provider-utils';
2 +import { toJsonSchema } from '@langchain/core/utils/json_schema';
3 +import { describe, expect, it } from 'vitest';
4 +
5 +import { jsonSchemaToZod } from '../../src/v4';
6 +import type { JsonSchema } from '../../src/types';
7 +
8 +type Json = Record<string, unknown>;
9 +
10 +const tool: JsonSchema = {
11 + type: 'object',
12 + description: 'Upload',
13 + properties: {
14 + file: { type: 'string', format: 'binary', description: 'The bytes' },
15 + name: { type: 'string', default: 'upload.bin' },
16 + retries: { type: 'integer', minimum: 0 },
17 + },
18 + required: ['file'],
19 +};
20 +
21 +describe('v4 schemas in frameworks', () => {
22 + it('keeps the annotations through the AI SDK schema wrapper', () => {
23 + const json = zodSchema(jsonSchemaToZod(tool)).jsonSchema as Json;
24 + const properties = json.properties as Record<string, Json>;
25 + expect(json.description).toBe('Upload');
26 + expect(properties.file).toMatchObject({
27 + type: 'string',
28 + format: 'binary',
29 + description: 'The bytes',
30 + });
31 + expect(properties.name).toMatchObject({ type: 'string', default: 'upload.bin' });
32 + expect(properties.retries).toMatchObject({ type: 'integer', minimum: 0 });
33 + expect(json.required).toEqual(['file']);
34 + });
35 +
36 + it('renders the output side for LangChain, where defaulted fields are required', () => {
37 + const json = toJsonSchema(jsonSchemaToZod(tool)) as Json;
38 + const properties = json.properties as Record<string, Json>;
39 + expect(json.description).toBe('Upload');
40 + expect(properties.file).toMatchObject({ type: 'string', format: 'binary' });
41 + expect(properties.retries).toMatchObject({ type: 'integer', minimum: 0 });
42 + expect(properties.name).not.toHaveProperty('default');
43 + expect(json.required).toEqual(['file', 'name']);
44 + });
45 +});
ts/packages/json-schema-to-zod/test/v4/intersection.test.ts new
+30
@@ -0,0 +1,30 @@
1 +import { describe, expect, it } from 'vitest';
2 +import * as z4 from 'zod/v4';
3 +
4 +import { jsonSchemaToZod as toV3 } from '../../src/index';
5 +import { jsonSchemaToZod as toV4 } from '../../src/v4';
6 +import type { JsonSchema } from '../../src/types';
7 +
8 +describe('v4 intersections', () => {
9 + const conflicting: JsonSchema = {
10 + allOf: [
11 + { type: 'object', properties: { a: { type: 'string', default: 'left' } } },
12 + { type: 'object', properties: { a: { type: 'string', default: 'right' } } },
13 + ],
14 + };
15 +
16 + it('reports a failure instead of throwing when the branches cannot merge', () => {
17 + expect(() =>
18 + z4.intersection(z4.any().prefault('left'), z4.any().prefault('right')).safeParse(undefined)
19 + ).toThrow('Unmergable intersection');
20 + expect(toV3(conflicting).safeParse({}).success).toBe(false);
21 + const result = toV4(conflicting).safeParse({});
22 + expect(result.success).toBe(false);
23 + expect(result.success ? [] : result.error.issues.map(issue => issue.code)).toEqual(['custom']);
24 + });
25 +
26 + it('keeps the failure through a described clone', () => {
27 + expect(toV4(conflicting).describe('conflict').safeParse({}).success).toBe(false);
28 + expect(toV4(conflicting).describe('conflict').safeParse({ a: 'same' }).success).toBe(true);
29 + });
30 +});
ts/packages/json-schema-to-zod/test/v4/kind-and-guard.test.ts new
+123
@@ -0,0 +1,123 @@
1 +import { interopZodObjectStrict } from '@langchain/core/utils/types';
2 +import { afterEach, describe, expect, it } from 'vitest';
3 +import * as z4 from 'zod/v4';
4 +
5 +import { jsonSchemaToZod, jsonSchemaToZodShape } from '../../src/v4';
6 +import type { JsonSchema } from '../../src/types';
7 +
8 +const guarded: JsonSchema = {
9 + type: 'object',
10 + properties: {
11 + q: { type: 'string' },
12 + limit: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
13 + },
14 + required: ['q'],
15 +};
16 +
17 +const rejects = (schema: z4.ZodType, value: unknown) => {
18 + const result = schema.safeParse(value);
19 + expect(result.success).toBe(false);
20 + return result.success ? [] : result.error.issues;
21 +};
22 +
23 +describe('v4 kind and guard survival', () => {
24 + afterEach(() => {
25 + z4.config({ jitless: false });
26 + });
27 +
28 + it('keeps a guarded object root a ZodObject with its shape', () => {
29 + const parsed = jsonSchemaToZod(guarded);
30 + expect(parsed).toBeInstanceOf(z4.ZodObject);
31 + expect(Object.keys((parsed as z4.ZodObject).shape)).toEqual(['q', 'limit']);
32 + expect(parsed.safeParse({ q: 'cats', limit: null }).success).toBe(true);
33 + rejects(parsed, { q: 'cats', limit: 'ten' });
34 + });
35 +
36 + it('keeps the guard through describe, meta, and a definition clone', () => {
37 + const parsed = jsonSchemaToZod({ ...guarded, description: 'Search' }) as z4.ZodObject;
38 + const copies: z4.ZodType[] = [
39 + parsed.describe('Renamed'),
40 + parsed.meta({ title: 'Search' }),
41 + z4.core.clone(parsed, { ...parsed.def }),
42 + z4.core.clone(parsed, { ...parsed.def, catchall: z4.never() }),
43 + ];
44 + for (const copy of copies) {
45 + expect(copy).toBeInstanceOf(z4.ZodObject);
46 + rejects(copy, { q: 'cats', limit: 'ten' });
47 + expect(copy.safeParse({ q: 'cats' }).success).toBe(true);
48 + }
49 + expect(copies[0].description).toBe('Renamed');
50 + expect(copies[1].description).toBe('Search');
51 + expect(copies[1].meta()?.title).toBe('Search');
52 + });
53 +
54 + it('keeps the guard through the LangChain strict clone', () => {
55 + const parsed = jsonSchemaToZod(guarded) as z4.ZodObject;
56 + const strict = interopZodObjectStrict(parsed, true) as unknown as z4.ZodType;
57 + expect(strict).toBeInstanceOf(z4.ZodObject);
58 + rejects(strict, { q: 'cats', limit: 'ten' });
59 + rejects(strict, { q: 'cats', extra: 1 });
60 + expect(strict.safeParse({ q: 'cats' }).success).toBe(true);
61 + });
62 +
63 + it.each([{ jitless: true }, { jitless: false }])(
64 + 'runs a guarded property under the object parser with jitless $jitless',
65 + ({ jitless }) => {
66 + z4.config({ jitless });
67 + // A raw shape guards each property on its own, so the enclosing object
68 + // is the plain `z.object()` a framework builds and the guard runs from
69 + // inside its property loop.
70 + const shape = jsonSchemaToZodShape({
71 + type: 'object',
72 + properties: {
73 + handle: { $ref: '#/$defs/handle' },
74 + count: { type: 'integer' },
75 + },
76 + $defs: { handle: { type: 'string', pattern: '^[a-z]+$' } },
77 + });
78 + const parsed = z4.object(shape);
79 + for (let round = 0; round < 3; round++) {
80 + expect(parsed.safeParse({ handle: 'ok', count: 1 }).success).toBe(true);
81 + const issues = rejects(parsed, { handle: 'NO', count: 1 });
82 + expect(issues.map(issue => [issue.code, issue.path])).toEqual([['custom', ['handle']]]);
83 + }
84 + }
85 + );
86 +
87 + it('reports exactly one issue when the guard fails', () => {
88 + const parsed = jsonSchemaToZod({
89 + type: 'object',
90 + properties: { x: { type: 'string', default: 'generated' } },
91 + required: ['x'],
92 + });
93 + const issues = rejects(parsed, {});
94 + expect(issues).toHaveLength(1);
95 + expect(issues[0].code).toBe('custom');
96 + expect(issues[0].path).toEqual([]);
97 + });
98 +
99 + it('keeps a nested guard when the parent object is cloned', () => {
100 + const parsed = jsonSchemaToZod({
101 + type: 'object',
102 + properties: { ref: { $ref: '#/$defs/n' } },
103 + $defs: { n: { type: 'number', minimum: 1 } },
104 + }) as z4.ZodObject;
105 + const extended = parsed.extend({ more: z4.string().optional() });
106 + rejects(extended, { ref: 0 });
107 + expect(extended.safeParse({ ref: 2, more: 'x' }).success).toBe(true);
108 + });
109 +
110 + it('does not fire the guard when zod runs the schema backward', () => {
111 + const parsed = jsonSchemaToZod(guarded);
112 + const forward = rejects(parsed, { q: 'cats', limit: 'ten' });
113 + expect(forward.some(issue => issue.code === 'custom')).toBe(true);
114 +
115 + // `.safeEncode()` runs zod's parse with direction `backward`. The
116 + // whole-schema guard steps aside on that axis; the schema's own checks
117 + // still reject the value, without the guard's custom issue on top.
118 + const backward = parsed.safeEncode({ q: 'cats', limit: 'ten' });
119 + expect(backward.success).toBe(false);
120 + const issues = backward.success ? [] : backward.error.issues;
121 + expect(issues.some(issue => issue.code === 'custom')).toBe(false);
122 + });
123 +});
ts/packages/json-schema-to-zod/test/v4/registry.test.ts new
+21
@@ -0,0 +1,21 @@
1 +import { describe, expect, it } from 'vitest';
2 +import * as z4 from 'zod/v4';
3 +import { version } from 'zod/v4/core';
4 +
5 +import { ZOD_V4_FLOOR, meetsZodV4Floor } from '../../src/backend/zod-v4-floor';
6 +
7 +describe('v4 registry', () => {
8 + it('shares the global registry through globalThis', () => {
9 + expect((globalThis as { __zod_globalRegistry?: unknown }).__zod_globalRegistry).toBe(
10 + z4.globalRegistry
11 + );
12 + });
13 +
14 + it('runs on a copy that meets the floor', () => {
15 + expect(meetsZodV4Floor(version)).toBe(true);
16 + expect(meetsZodV4Floor(ZOD_V4_FLOOR)).toBe(true);
17 + expect(meetsZodV4Floor({ major: 4, minor: 1, patch: 12 })).toBe(false);
18 + expect(meetsZodV4Floor({ major: 4, minor: 0, patch: 0 })).toBe(false);
19 + expect(meetsZodV4Floor({ major: 5, minor: 0, patch: 0 })).toBe(true);
20 + });
21 +});
ts/packages/json-schema-to-zod/test/v4/to-json-schema.test.ts new
+20
@@ -0,0 +1,20 @@
1 +import { describe, expect, it } from 'vitest';
2 +import * as z4 from 'zod/v4';
3 +
4 +import { jsonSchemaToZod } from '../../src/v4';
5 +import type { JsonSchema } from '../../src/types';
6 +import { loadObjectCases, loadStrictCases } from '../fixtures/corpus';
7 +
8 +const everyCase = [
9 + ...loadObjectCases().map(({ id, schema }) => ({ id: `object:${id}`, schema })),
10 + ...loadStrictCases().map(({ id, schema }) => ({ id: `strict:${id}`, schema })),
11 +];
12 +
13 +describe('v4 JSON Schema rendering', () => {
14 + describe.each(['input', 'output'] as const)('with io %s', io => {
15 + it.each(everyCase)('renders $id', ({ schema }) => {
16 + const converted = jsonSchemaToZod(schema as JsonSchema);
17 + expect(() => z4.toJSONSchema(converted, { io })).not.toThrow();
18 + });
19 + });
20 +});
ts/packages/json-schema-to-zod/tsdown.config.ts
+2
@@ -3,5 +3,7 @@ import { baseConfig } from '../../../tsdown.config.base.ts';
3
4 export default defineConfig({
5 ...baseConfig,
6 + entry: ['src/index.ts', 'src/v4.ts'],
7 tsconfig: 'tsconfig.src.json',
8 + attw: { ...baseConfig.attw, entrypoints: ['.', './v4'] },
9 });
ts/packages/json-schema-to-zod/vitest.config.ts
+32 -2
@@ -1,8 +1,38 @@
1 import { defineConfig } from 'vitest/config';
2
3 +// Exclude e2e directories - they are separate packages with their own test commands
4 +const exclude = ['**/node_modules/**', '**/dist/**', '**/test/e2e/**'];
5 +
6 +/** Only the zod 3.25 project runs it: it asserts the `/v4` entry refuses that copy. */
7 +const floorRejection = 'test/v4-floor.test.ts';
8 +/** The `/v4` entry cannot load below the floor, so the suites that import it skip the zod 3.25 project. */
9 +const v4Only = ['test/v4/**', 'test/types.test.ts'];
10 +/** Pinned against the package's own zod copy; older releases render JSON Schema differently. */
11 +const v4Snapshot = 'test/v4/corpus-snapshot.test.ts';
12 +
13 +/** Routes every `zod/v3` and `zod/v4` import, in sources and tests alike, to one aliased copy. */
14 +const zodCopy = (alias: string) => ({
15 + alias: [{ find: /^zod\/(v3|v4)(\/.*)?$/, replacement: `${alias}/$1$2` }],
16 +});
17 +
18 export default defineConfig({
19 test: {
5 - // Exclude e2e directories - they are separate packages with their own test commands
6 - exclude: ['**/node_modules/**', '**/dist/**', '**/test/e2e/**'],
20 + exclude,
21 + projects: [
22 + {
23 + extends: true,
24 + test: { name: 'zod-4.5', exclude: [...exclude, floorRejection] },
25 + },
26 + {
27 + extends: true,
28 + test: { name: 'zod-4.1.13', exclude: [...exclude, floorRejection, v4Snapshot] },
29 + resolve: zodCopy('zod-floor'),
30 + },
31 + {
32 + extends: true,
33 + test: { name: 'zod-3.25', exclude: [...exclude, ...v4Only] },
34 + resolve: zodCopy('zod-3-25'),
35 + },
36 + ],
37 },
38 });