@amritk/adapters 0.2.16 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +219 -0
- package/dist/adapter.d.ts +16 -2
- package/dist/effect-to-json-schema.d.ts +3 -2
- package/dist/effect-to-json-schema.js +95 -28
- package/dist/report-lossy-constructs.d.ts +21 -0
- package/dist/report-lossy-constructs.js +33 -0
- package/dist/valibot-to-json-schema.d.ts +13 -6
- package/dist/valibot-to-json-schema.js +32 -7
- package/dist/zod-to-json-schema.d.ts +10 -1
- package/dist/zod-to-json-schema.js +173 -46
- package/package.json +11 -3
package/README.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# @amritk/adapters
|
|
4
|
+
|
|
5
|
+
**Convert schemas authored in TypeBox, Zod, Valibot, or Effect into Draft 2020-12 JSON Schema — the single input shape the mjst generators understand.**
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+

|
|
9
|
+

|
|
10
|
+

|
|
11
|
+

|
|
12
|
+

|
|
13
|
+
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Overview
|
|
19
|
+
|
|
20
|
+
mjst's generators — parsers, validators, types, docs, test data — all take **one** input: a Draft 2020-12 JSON Schema. This package lets you author that schema in a validation library you already use instead. It converts a **TypeBox**, **Zod**, **Valibot**, or **Effect** schema into JSON Schema, then hands the result straight to the generators.
|
|
21
|
+
|
|
22
|
+
The [`mjst`](../cli) CLI wires these in behind the `--input <format>` flag (`typebox`, `zod`, `valibot`, `effect`); with any of those the `--schema` path points at a JS/TS **module** that exports a schema rather than a `.json` file. You can also call the adapters directly — each is a small, pure async function.
|
|
23
|
+
|
|
24
|
+
Each adapter leans on its source library's own JSON Schema exporter (Zod 4's `toJSONSchema`, `@valibot/to-json-schema`, Effect's `JSONSchema.make`; TypeBox schemas are already JSON Schema at runtime) and then normalises the result:
|
|
25
|
+
|
|
26
|
+
- strips the dialect marker (`$schema`) the generators don't need,
|
|
27
|
+
- rewrites constructs JSON Schema can't express — runtime `Date`, `bigint` — into the shared [`x-mjst`](#the-x-mjst-extension) hint the generators read, and
|
|
28
|
+
- **warns and continues** on anything genuinely unrepresentable rather than throwing, so one unsupported field never blocks generation.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm install --save-dev @amritk/adapters
|
|
36
|
+
# or: pnpm add -D / yarn add -D / bun add -d
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Peer dependencies
|
|
40
|
+
|
|
41
|
+
The source libraries are **optional peer dependencies** — each adapter dynamically imports its library at runtime, so you install only the one(s) you actually use. TypeBox needs no peer dependency at all (its schemas are plain JSON Schema objects; the adapter never imports TypeBox).
|
|
42
|
+
|
|
43
|
+
| Input format | Install |
|
|
44
|
+
|:---|:---|
|
|
45
|
+
| `typebox` | *(nothing — see below)* |
|
|
46
|
+
| `zod` | `zod@>=4` |
|
|
47
|
+
| `valibot` | `valibot@>=1` **and** `@valibot/to-json-schema@>=1` |
|
|
48
|
+
| `effect` | `effect@>=3` |
|
|
49
|
+
|
|
50
|
+
If the required package is missing (or too old), the adapter throws a clear, actionable error naming what to install — e.g. *"The Zod adapter requires 'zod' (v4 or later) to be installed in your project."*
|
|
51
|
+
|
|
52
|
+
> [!NOTE]
|
|
53
|
+
> The TypeBox adapter deliberately does **not** import TypeBox. It works purely on the plain-object shape of the schema (via a JSON round-trip), so TypeBox stays a dependency of your schema module alone, never of mjst.
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Usage
|
|
58
|
+
|
|
59
|
+
Each adapter is a function `(source: unknown) => Promise<JSONSchema>` (TypeBox's is synchronous but is exposed with the same signature for uniformity). Import them by subpath:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { typeboxToJsonSchema } from '@amritk/adapters/typebox-to-json-schema'
|
|
63
|
+
import { zodToJsonSchema } from '@amritk/adapters/zod-to-json-schema'
|
|
64
|
+
import { valibotToJsonSchema } from '@amritk/adapters/valibot-to-json-schema'
|
|
65
|
+
import { effectToJsonSchema } from '@amritk/adapters/effect-to-json-schema'
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Or resolve one by name — matching the CLI's `--input` flag:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { getAdapter } from '@amritk/adapters/get-adapter'
|
|
72
|
+
|
|
73
|
+
const adapter = getAdapter('zod') // throws for an unimplemented / unknown format
|
|
74
|
+
const jsonSchema = await adapter.toJSONSchema(mySchema)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Adapters receive the **already-loaded** schema value (an imported module export), not a file path — loading the module is the caller's job, which keeps the adapters pure and trivial to test.
|
|
78
|
+
|
|
79
|
+
### TypeBox
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { Type } from '@sinclair/typebox'
|
|
83
|
+
import { typeboxToJsonSchema } from '@amritk/adapters/typebox-to-json-schema'
|
|
84
|
+
|
|
85
|
+
const User = Type.Object({
|
|
86
|
+
id: Type.Integer(),
|
|
87
|
+
name: Type.String({ minLength: 1 }),
|
|
88
|
+
createdAt: Type.Date(),
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
const jsonSchema = await typeboxToJsonSchema(User)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A TypeBox schema is already a JSON Schema object at runtime — it just carries non-enumerable symbol keys (`Kind`, `Optional`, …) for TypeBox's own machinery. A JSON round-trip drops those (and any `undefined` values), leaving a clean plain schema. The adapter then rewrites TypeBox's [extended types](#extended-types-typebox) into `x-mjst` hints.
|
|
95
|
+
|
|
96
|
+
### Zod
|
|
97
|
+
|
|
98
|
+
> [!IMPORTANT]
|
|
99
|
+
> **Zod 4 or later only.** The adapter relies on Zod's native `toJSONSchema`, which does not exist before Zod 4 (see [`src/zod-to-json-schema.ts`](./src/zod-to-json-schema.ts)). On Zod 3 you'll get a clear error rather than a silent miss.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { z } from 'zod'
|
|
103
|
+
import { zodToJsonSchema } from '@amritk/adapters/zod-to-json-schema'
|
|
104
|
+
|
|
105
|
+
const User = z.object({
|
|
106
|
+
id: z.number().int(),
|
|
107
|
+
name: z.string().min(1),
|
|
108
|
+
createdAt: z.date(),
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
const jsonSchema = await zodToJsonSchema(User)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`z.date()` and `z.bigint()` have no JSON Schema representation and would make Zod's exporter throw; the adapter runs it with `unrepresentable: 'any'` and uses the `override` hook to rescue them into [`x-mjst`](#the-x-mjst-extension) hints. It also repairs two Zod 4 quirks along the way: it restores the length bound on fixed tuples (Zod emits a bare, unbounded `prefixItems`), and it merges an object **intersection** that Zod emits as an unsatisfiable `allOf` of `additionalProperties: false` branches into a single closed object.
|
|
115
|
+
|
|
116
|
+
### Valibot
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import * as v from 'valibot'
|
|
120
|
+
import { valibotToJsonSchema } from '@amritk/adapters/valibot-to-json-schema'
|
|
121
|
+
|
|
122
|
+
const User = v.object({
|
|
123
|
+
id: v.pipe(v.number(), v.integer()),
|
|
124
|
+
name: v.pipe(v.string(), v.minLength(1)),
|
|
125
|
+
createdAt: v.date(),
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const jsonSchema = await valibotToJsonSchema(User)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Requires both `valibot` and `@valibot/to-json-schema`. As with Zod, `v.date()` / `v.bigint()` are rescued into `x-mjst` hints via the converter's `overrideSchema` hook. The converter runs in `errorMode: 'warn'`, so any other unsupported construct degrades to an open schema and is logged rather than throwing.
|
|
132
|
+
|
|
133
|
+
### Effect
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { Schema } from 'effect'
|
|
137
|
+
import { effectToJsonSchema } from '@amritk/adapters/effect-to-json-schema'
|
|
138
|
+
|
|
139
|
+
const User = Schema.Struct({
|
|
140
|
+
id: Schema.Number,
|
|
141
|
+
name: Schema.String,
|
|
142
|
+
createdAt: Schema.DateFromSelf, // runtime Date — see the caveat below
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
const jsonSchema = await effectToJsonSchema(User)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Requires `effect@>=3`. A top-level `Schema.BigIntFromSelf` / `Schema.DateFromSelf` is rescued into an `x-mjst` hint; everything else goes through `JSONSchema.make`. **Read the [encoded-representation caveat](#effect-encodes-the-wire-representation) before choosing between `Schema.Date` and `Schema.DateFromSelf`** — it changes whether you get a `string` or a runtime `Date`.
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## The `x-mjst` extension
|
|
153
|
+
|
|
154
|
+
JSON Schema's core vocabulary has no keyword for a runtime `Date` or a `bigint`. mjst carries those as a vendor extension, `x-mjst`, that the generators read to emit the right TypeScript type and runtime check. Every adapter maps to the **same** two hints, so a `Date` authored in any of the four libraries generates identically:
|
|
155
|
+
|
|
156
|
+
| Source construct | `x-mjst` hint | Generated handling |
|
|
157
|
+
|:---|:---|:---|
|
|
158
|
+
| a runtime `Date` | `{ instanceOf: 'Date' }` | typed as `Date`, checked with `instanceof` |
|
|
159
|
+
| a `bigint` | `{ primitive: 'bigint' }` | typed as `bigint`, checked with `typeof` |
|
|
160
|
+
|
|
161
|
+
Per library, the `Date` / `bigint` sources are:
|
|
162
|
+
|
|
163
|
+
| | `Date` → `instanceOf: 'Date'` | `bigint` → `primitive: 'bigint'` |
|
|
164
|
+
|:---|:---|:---|
|
|
165
|
+
| **TypeBox** | `Type.Date()` | `Type.BigInt()` |
|
|
166
|
+
| **Zod** | `z.date()` | `z.bigint()` |
|
|
167
|
+
| **Valibot** | `v.date()` | `v.bigint()` |
|
|
168
|
+
| **Effect** | `Schema.DateFromSelf` | `Schema.BigIntFromSelf` |
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## Lossy constructs & widening warnings
|
|
173
|
+
|
|
174
|
+
Some source types have no faithful JSON Schema representation and are **not** rescued into an `x-mjst` hint. Rather than fail the whole conversion, the adapters widen those to "accept anything" (`{}`) — which means **the generated type is wider than the source schema** — and emit a `[mjst]` warning to stderr so the widening is visible, never silent. Behaviour per library:
|
|
175
|
+
|
|
176
|
+
- **Zod.** These Zod types become "accept anything": `symbol`, `nan`, `void`, `undefined`, `never`, `map`, `set`, `promise`, `function`. When any appear, the adapter logs, e.g.: *"[mjst] Zod adapter: function, symbol have no JSON Schema representation and became 'accept anything'. The generated type will be wider than the Zod schema."*
|
|
177
|
+
- **Valibot.** The converter runs in `errorMode: 'warn'`: an unsupported construct degrades to an open schema and `@valibot/to-json-schema` logs which one, so the widening is reported by the converter itself.
|
|
178
|
+
- **TypeBox.** An extended `type` string with no mapping (see below) is left unchanged with a warning: *"[mjst] TypeBox type '…' has no JSON Schema or x-mjst mapping; leaving it unchanged."*
|
|
179
|
+
- **Effect.** Effect does not widen — it is stricter. `JSONSchema.make` **throws** on a *nested* unrepresentable type (a `BigIntFromSelf` / `DateFromSelf` below the top level with no `jsonSchema` annotation). The adapter catches that and re-throws an actionable message pointing you at the fix: use the string-encoded `Schema.Date` / `Schema.BigInt`, or add a `jsonSchema` annotation to that field.
|
|
180
|
+
|
|
181
|
+
If any of these matter to your schema, prefer a representable alternative (e.g. model a set as an array) or add the library's own JSON Schema annotation.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Caveats
|
|
186
|
+
|
|
187
|
+
### Extended types (TypeBox)
|
|
188
|
+
|
|
189
|
+
TypeBox emits non-standard `type` strings for its runtime classes (e.g. `Type.Date()` produces `{ type: 'Date' }`). The adapter recognises the seven core JSON Schema types and treats anything else in a `type` slot as a TypeBox **extended type**. The map of extended types it understands currently covers **only `Date` and `bigint`** (see [`src/typebox-to-json-schema.ts:11-19`](./src/typebox-to-json-schema.ts#L11-L19)):
|
|
190
|
+
|
|
191
|
+
| TypeBox extended `type` | mapped to |
|
|
192
|
+
|:---|:---|
|
|
193
|
+
| `Date` | `x-mjst` `instanceOf: 'Date'` |
|
|
194
|
+
| `bigint` | `x-mjst` `primitive: 'bigint'` |
|
|
195
|
+
|
|
196
|
+
Any other extended type (`Uint8Array`, `Symbol`, `Undefined`, …) is left untouched with the widening warning above; support is added by extending that map as the generators gain handling for more types.
|
|
197
|
+
|
|
198
|
+
### Effect encodes the *wire* representation
|
|
199
|
+
|
|
200
|
+
Effect models a value as a **decode/encode pair**, and `JSONSchema.make` describes the **encoded** (wire) representation — not the runtime type. This is the caveat most likely to surprise you:
|
|
201
|
+
|
|
202
|
+
- `Schema.Date` decodes a `Date` **from a string**, so it converts to a **`string`** schema — not a runtime `Date`. The adapter passes this through unchanged, because it accurately reflects what Effect expects on the wire.
|
|
203
|
+
- Only the `*FromSelf` variants — `Schema.DateFromSelf`, `Schema.BigIntFromSelf` — describe the runtime value itself, and those are the ones rescued into `x-mjst` runtime-type hints (see [`src/effect-to-json-schema.ts:63`](./src/effect-to-json-schema.ts#L63)).
|
|
204
|
+
|
|
205
|
+
So: want a generated `Date`? Author `Schema.DateFromSelf`. Want a string that Effect parses into a `Date`? Author `Schema.Date` and expect a `string` in the generated output. The same distinction applies to `Schema.BigInt` (→ `string`) vs `Schema.BigIntFromSelf` (→ `bigint`).
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Related packages
|
|
210
|
+
|
|
211
|
+
- [`@amritk/mjst`](../cli) — CLI that ingests these formats via `--input <format>`
|
|
212
|
+
- [`@amritk/generate-parsers`](../generate-parsers) · [`@amritk/generate-validators`](../generate-validators) · [`@amritk/generate-markdown`](../generate-markdown) · [`@amritk/generate-examples`](../generate-examples) — the generators these adapters feed
|
|
213
|
+
- [`@amritk/helpers`](../helpers) — defines the shared `x-mjst` extension
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
[MIT](../../LICENSE)
|
package/dist/adapter.d.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
2
|
import type { SourceFormat } from './source-format.js';
|
|
3
|
+
/**
|
|
4
|
+
* Options that tune how an adapter handles source constructs with no JSON
|
|
5
|
+
* Schema representation. Only the Zod and Valibot adapters read these today;
|
|
6
|
+
* adapters that ignore the argument simply keep their default behaviour.
|
|
7
|
+
*/
|
|
8
|
+
export type AdapterOptions = {
|
|
9
|
+
/**
|
|
10
|
+
* When `true`, a construct that cannot be fully represented in JSON Schema
|
|
11
|
+
* throws instead of silently widening the generated type. Defaults to `false`,
|
|
12
|
+
* where such constructs are widened and reported with a single batched warning.
|
|
13
|
+
*/
|
|
14
|
+
readonly strict?: boolean;
|
|
15
|
+
};
|
|
3
16
|
/**
|
|
4
17
|
* Converts a schema authored in some external library into a Draft 2020-12
|
|
5
18
|
* JSON Schema, which is the single input shape the mjst generators understand.
|
|
@@ -8,7 +21,8 @@ import type { SourceFormat } from './source-format.js';
|
|
|
8
21
|
* not a file path. Loading the module is the caller's job so adapters stay pure
|
|
9
22
|
* and trivial to unit test. When a source construct cannot be represented in
|
|
10
23
|
* JSON Schema, adapters should warn and continue on a best-effort basis rather
|
|
11
|
-
* than throw, so generation is not blocked by a single unsupported field
|
|
24
|
+
* than throw, so generation is not blocked by a single unsupported field — unless
|
|
25
|
+
* the caller opts into `{ strict: true }`.
|
|
12
26
|
*/
|
|
13
27
|
export type Adapter = {
|
|
14
28
|
/** The source format this adapter handles, matching the `--input` CLI flag. */
|
|
@@ -18,5 +32,5 @@ export type Adapter = {
|
|
|
18
32
|
* some adapters (e.g. Zod) dynamically import their source library to perform
|
|
19
33
|
* the conversion, so callers should always `await` the result.
|
|
20
34
|
*/
|
|
21
|
-
readonly toJSONSchema: (source: unknown) => JSONSchema | Promise<JSONSchema>;
|
|
35
|
+
readonly toJSONSchema: (source: unknown, options?: AdapterOptions) => JSONSchema | Promise<JSONSchema>;
|
|
22
36
|
};
|
|
@@ -6,7 +6,8 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
|
6
6
|
* the *encoded* (wire) representation. For example `Schema.Date` decodes from a
|
|
7
7
|
* string, so it converts to a string schema rather than a runtime `Date`. We
|
|
8
8
|
* pass that representation straight through — it accurately reflects what Effect
|
|
9
|
-
* expects on the wire — only stripping the dialect marker. A
|
|
10
|
-
* `
|
|
9
|
+
* expects on the wire — only stripping the dialect marker. A `BigIntFromSelf` /
|
|
10
|
+
* `DateFromSelf` anywhere in the tree (top level or nested) is rescued into an
|
|
11
|
+
* `x-mjst` hint instead of throwing.
|
|
11
12
|
*/
|
|
12
13
|
export declare const effectToJsonSchema: (source: unknown) => Promise<JSONSchema>;
|
|
@@ -27,20 +27,96 @@ const astOf = (source) => {
|
|
|
27
27
|
};
|
|
28
28
|
/**
|
|
29
29
|
* Effect models `bigint` and a runtime `Date` as types with no JSON Schema
|
|
30
|
-
* representation, so `JSONSchema.make` throws
|
|
31
|
-
*
|
|
32
|
-
* adapters — which map those to the shared `x-mjst` hint —
|
|
33
|
-
* `bigint` (`BigIntKeyword`) →
|
|
34
|
-
* declaration → `instanceOf: 'Date'`.
|
|
35
|
-
*
|
|
30
|
+
* representation, so `JSONSchema.make` throws — for a top-level value *and* for
|
|
31
|
+
* one buried inside a struct, array, or union. To stay consistent with the Zod,
|
|
32
|
+
* Valibot, and TypeBox adapters — which map those to the shared `x-mjst` hint —
|
|
33
|
+
* we rescue them wherever they appear: `bigint` (`BigIntKeyword`) →
|
|
34
|
+
* `primitive: 'bigint'`, and the `DateFromSelf` declaration → `instanceOf: 'Date'`.
|
|
35
|
+
*
|
|
36
|
+
* `Schema.Date` / `Schema.BigInt` decode from a string and already convert to a
|
|
37
|
+
* `string` schema, so they are untouched — the walk below hands any such
|
|
38
|
+
* fully-representable subtree straight to `make` and keeps its output verbatim.
|
|
36
39
|
*/
|
|
37
|
-
const
|
|
40
|
+
const isDateFromSelf = (ast) => ast._tag === 'Declaration' && ast.annotations?.[IDENTIFIER_ANNOTATION] === 'DateFromSelf';
|
|
41
|
+
// `make` stamps every schema with a dialect marker and hoists referenced types
|
|
42
|
+
// into a sibling `$defs`. When we convert a nested subtree in isolation we strip
|
|
43
|
+
// the marker and lift its `$defs` into the shared root map so `$ref`s (which use
|
|
44
|
+
// absolute `#/$defs/...` paths) still resolve once everything is reassembled.
|
|
45
|
+
const hoistInto = (schema, rootDefs) => {
|
|
46
|
+
delete schema['$schema'];
|
|
47
|
+
const defs = schema['$defs'];
|
|
48
|
+
if (defs && typeof defs === 'object') {
|
|
49
|
+
Object.assign(rootDefs, defs);
|
|
50
|
+
delete schema['$defs'];
|
|
51
|
+
}
|
|
52
|
+
return schema;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Recursively converts an Effect AST into JSON Schema, rescuing nested
|
|
56
|
+
* unrepresentable leaves into `x-mjst` hints along the way.
|
|
57
|
+
*
|
|
58
|
+
* The strategy is to lean on `make` as much as possible: any subtree it can
|
|
59
|
+
* convert is representable, so we take its output verbatim. Only when `make`
|
|
60
|
+
* throws do we descend structurally — reconstructing the container (struct,
|
|
61
|
+
* array, union, ...) and recursing into its children — until we reach the
|
|
62
|
+
* bigint / `Date` leaf that has no JSON Schema form and rescue it.
|
|
63
|
+
*/
|
|
64
|
+
const walk = (make, ast, rootDefs) => {
|
|
65
|
+
// A subtree `make` accepts is fully representable, so use its output as-is.
|
|
66
|
+
try {
|
|
67
|
+
return hoistInto(make({ ast }), rootDefs);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// `make` threw, so an unrepresentable node lives somewhere below. Fall through.
|
|
71
|
+
}
|
|
38
72
|
if (ast._tag === 'BigIntKeyword')
|
|
39
73
|
return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
|
|
40
|
-
if (ast
|
|
74
|
+
if (isDateFromSelf(ast))
|
|
41
75
|
return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
|
|
76
|
+
switch (ast._tag) {
|
|
77
|
+
case 'TypeLiteral': {
|
|
78
|
+
const properties = {};
|
|
79
|
+
const required = [];
|
|
80
|
+
for (const ps of ast.propertySignatures ?? []) {
|
|
81
|
+
properties[ps.name] = walk(make, ps.type, rootDefs);
|
|
82
|
+
if (!ps.isOptional)
|
|
83
|
+
required.push(ps.name);
|
|
84
|
+
}
|
|
85
|
+
return { type: 'object', required, properties, additionalProperties: false };
|
|
86
|
+
}
|
|
87
|
+
case 'TupleType': {
|
|
88
|
+
const elements = ast.elements ?? [];
|
|
89
|
+
const rest = ast.rest ?? [];
|
|
90
|
+
const [firstRest] = rest;
|
|
91
|
+
// `Schema.Array(x)` is a tuple with no fixed elements and a single rest.
|
|
92
|
+
if (elements.length === 0 && rest.length === 1 && firstRest) {
|
|
93
|
+
return { type: 'array', items: walk(make, firstRest.type, rootDefs) };
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
type: 'array',
|
|
97
|
+
minItems: elements.filter((e) => !e.isOptional).length,
|
|
98
|
+
items: elements.map((e) => walk(make, e.type, rootDefs)),
|
|
99
|
+
additionalItems: firstRest ? walk(make, firstRest.type, rootDefs) : false,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
case 'Union':
|
|
103
|
+
return { anyOf: (ast.types ?? []).map((t) => walk(make, t, rootDefs)) };
|
|
104
|
+
// `Refinement` and `Transformation` describe the encoded value via `from`;
|
|
105
|
+
// `Suspend` defers to a thunk. Follow through to reach the wrapped subtree.
|
|
106
|
+
case 'Refinement':
|
|
107
|
+
case 'Transformation':
|
|
108
|
+
if (ast.from)
|
|
109
|
+
return walk(make, ast.from, rootDefs);
|
|
110
|
+
break;
|
|
111
|
+
case 'Suspend':
|
|
112
|
+
if (ast.f)
|
|
113
|
+
return walk(make, ast.f(), rootDefs);
|
|
114
|
+
break;
|
|
42
115
|
}
|
|
43
|
-
|
|
116
|
+
// A genuinely unrepresentable type we do not know how to rescue (e.g. a raw
|
|
117
|
+
// `symbol`). Point the user at the fix rather than Effect's opaque message.
|
|
118
|
+
throw new Error(`Effect adapter failed to convert the schema. A ${ast._tag ?? 'nested'} type has no JSON Schema ` +
|
|
119
|
+
`representation — replace it with a JSON-representable type, or add a \`jsonSchema\` annotation to that field.`);
|
|
44
120
|
};
|
|
45
121
|
/**
|
|
46
122
|
* Converts an Effect `Schema` into a JSON Schema via `JSONSchema.make`.
|
|
@@ -49,8 +125,9 @@ const rescueXMjst = (ast) => {
|
|
|
49
125
|
* the *encoded* (wire) representation. For example `Schema.Date` decodes from a
|
|
50
126
|
* string, so it converts to a string schema rather than a runtime `Date`. We
|
|
51
127
|
* pass that representation straight through — it accurately reflects what Effect
|
|
52
|
-
* expects on the wire — only stripping the dialect marker. A
|
|
53
|
-
* `
|
|
128
|
+
* expects on the wire — only stripping the dialect marker. A `BigIntFromSelf` /
|
|
129
|
+
* `DateFromSelf` anywhere in the tree (top level or nested) is rescued into an
|
|
130
|
+
* `x-mjst` hint instead of throwing.
|
|
54
131
|
*/
|
|
55
132
|
export const effectToJsonSchema = async (source) => {
|
|
56
133
|
// Effect `Schema` values are callable, so they report as `function`, not `object`.
|
|
@@ -59,24 +136,14 @@ export const effectToJsonSchema = async (source) => {
|
|
|
59
136
|
throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`);
|
|
60
137
|
}
|
|
61
138
|
const ast = astOf(source);
|
|
62
|
-
if (ast) {
|
|
63
|
-
|
|
64
|
-
if (rescued)
|
|
65
|
-
return rescued;
|
|
139
|
+
if (!ast) {
|
|
140
|
+
throw new Error('Effect adapter expected an Effect Schema but the value has no `ast` property.');
|
|
66
141
|
}
|
|
67
142
|
const make = await loadMake();
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
// `make` throws on an unrepresentable type with no `jsonSchema` annotation —
|
|
74
|
-
// most often a nested `BigIntFromSelf` / `DateFromSelf`. Point the user at the
|
|
75
|
-
// fix rather than surfacing Effect's opaque "Missing annotation" message.
|
|
76
|
-
throw new Error(`Effect adapter failed to convert the schema. A nested bigint or runtime Date (BigIntFromSelf / DateFromSelf) ` +
|
|
77
|
-
`has no JSON Schema representation — use the string-encoded Schema.BigInt / Schema.Date, or add a ` +
|
|
78
|
-
`\`jsonSchema\` annotation to that field.\n${String(error)}`);
|
|
79
|
-
}
|
|
80
|
-
delete json['$schema'];
|
|
143
|
+
const rootDefs = {};
|
|
144
|
+
const json = walk(make, ast, rootDefs);
|
|
145
|
+
// Reattach the hoisted definitions once the whole tree is assembled.
|
|
146
|
+
if (Object.keys(rootDefs).length > 0)
|
|
147
|
+
json['$defs'] = rootDefs;
|
|
81
148
|
return json;
|
|
82
149
|
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits mjst's batched, branded notice for source constructs that could not be
|
|
3
|
+
* fully represented in JSON Schema and were therefore widened during conversion
|
|
4
|
+
* — an unsupported schema type degrades to an open ("accept anything") schema,
|
|
5
|
+
* and an unsupported refinement is dropped, so in both cases the result accepts
|
|
6
|
+
* more than the source did.
|
|
7
|
+
*
|
|
8
|
+
* The Zod and Valibot adapters both funnel their collected constructs through
|
|
9
|
+
* here so the two behave identically, instead of each inventing its own wording
|
|
10
|
+
* (or, in Valibot's case, delegating the reporting to a third-party converter
|
|
11
|
+
* that logs one line per construct).
|
|
12
|
+
*
|
|
13
|
+
* - Best-effort (the default): a single `console.warn` listing every widened
|
|
14
|
+
* construct, so the loss is visible in one line instead of silent or scattered.
|
|
15
|
+
* - Strict: throws instead, refusing to hand back a type that is wider than the
|
|
16
|
+
* source schema.
|
|
17
|
+
*
|
|
18
|
+
* Does nothing when no constructs were widened, so callers can invoke it
|
|
19
|
+
* unconditionally after a conversion.
|
|
20
|
+
*/
|
|
21
|
+
export declare const reportLossyConstructs: (adapter: 'Zod' | 'Valibot', constructs: ReadonlySet<string>, strict: boolean | undefined) => void;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits mjst's batched, branded notice for source constructs that could not be
|
|
3
|
+
* fully represented in JSON Schema and were therefore widened during conversion
|
|
4
|
+
* — an unsupported schema type degrades to an open ("accept anything") schema,
|
|
5
|
+
* and an unsupported refinement is dropped, so in both cases the result accepts
|
|
6
|
+
* more than the source did.
|
|
7
|
+
*
|
|
8
|
+
* The Zod and Valibot adapters both funnel their collected constructs through
|
|
9
|
+
* here so the two behave identically, instead of each inventing its own wording
|
|
10
|
+
* (or, in Valibot's case, delegating the reporting to a third-party converter
|
|
11
|
+
* that logs one line per construct).
|
|
12
|
+
*
|
|
13
|
+
* - Best-effort (the default): a single `console.warn` listing every widened
|
|
14
|
+
* construct, so the loss is visible in one line instead of silent or scattered.
|
|
15
|
+
* - Strict: throws instead, refusing to hand back a type that is wider than the
|
|
16
|
+
* source schema.
|
|
17
|
+
*
|
|
18
|
+
* Does nothing when no constructs were widened, so callers can invoke it
|
|
19
|
+
* unconditionally after a conversion.
|
|
20
|
+
*/
|
|
21
|
+
export const reportLossyConstructs = (adapter, constructs, strict) => {
|
|
22
|
+
if (constructs.size === 0)
|
|
23
|
+
return;
|
|
24
|
+
const list = [...constructs].sort().join(', ');
|
|
25
|
+
const plural = constructs.size !== 1;
|
|
26
|
+
const detail = `${list} ${plural ? 'have' : 'has'} no full JSON Schema representation and ${plural ? 'were' : 'was'} ` +
|
|
27
|
+
`widened. The generated type will be wider than the ${adapter} schema.`;
|
|
28
|
+
if (strict) {
|
|
29
|
+
throw new Error(`[mjst] ${adapter} adapter (strict mode): ${detail} ` +
|
|
30
|
+
'Remove the unsupported construct(s) from the schema, or disable strict mode to widen and warn instead.');
|
|
31
|
+
}
|
|
32
|
+
console.warn(`[mjst] ${adapter} adapter: ${detail}`);
|
|
33
|
+
};
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
+
import type { AdapterOptions } from './adapter.js';
|
|
2
3
|
/**
|
|
3
4
|
* Converts a Valibot schema into a Draft 2020-12 JSON Schema via
|
|
4
5
|
* `@valibot/to-json-schema`.
|
|
5
6
|
*
|
|
6
7
|
* Valibot's `date` schema has no JSON Schema representation and would otherwise
|
|
7
|
-
* throw, so we run
|
|
8
|
-
* to an open schema
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
8
|
+
* throw, so we run the converter in `errorMode: 'ignore'` (unsupported constructs
|
|
9
|
+
* degrade to an open schema instead of failing the whole conversion) and use the
|
|
10
|
+
* `overrideSchema` hook to rewrite dates and bigints into the shared `x-mjst`
|
|
11
|
+
* extension — the same handling TypeBox and Zod give them.
|
|
12
|
+
*
|
|
13
|
+
* `'ignore'` also silences the converter's own per-construct `console.warn`s.
|
|
14
|
+
* That is deliberate: instead of letting a third-party library log widening in
|
|
15
|
+
* its own words, we collect the constructs it could not represent (via the
|
|
16
|
+
* `errors` array handed to each override hook) and report them ourselves through
|
|
17
|
+
* {@link reportLossyConstructs} — one batched, mjst-branded warning, matching the
|
|
18
|
+
* Zod adapter. In strict mode that same collection throws instead.
|
|
12
19
|
*/
|
|
13
|
-
export declare const valibotToJsonSchema: (source: unknown) => Promise<JSONSchema>;
|
|
20
|
+
export declare const valibotToJsonSchema: (source: unknown, options?: AdapterOptions) => Promise<JSONSchema>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
|
|
2
|
+
import { reportLossyConstructs } from './report-lossy-constructs.js';
|
|
2
3
|
/**
|
|
3
4
|
* Resolves `@valibot/to-json-schema`'s `toJsonSchema` from a runtime import,
|
|
4
5
|
* throwing a clear error when the converter is missing.
|
|
@@ -24,27 +25,48 @@ const loadToJsonSchema = async () => {
|
|
|
24
25
|
* `@valibot/to-json-schema`.
|
|
25
26
|
*
|
|
26
27
|
* Valibot's `date` schema has no JSON Schema representation and would otherwise
|
|
27
|
-
* throw, so we run
|
|
28
|
-
* to an open schema
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
28
|
+
* throw, so we run the converter in `errorMode: 'ignore'` (unsupported constructs
|
|
29
|
+
* degrade to an open schema instead of failing the whole conversion) and use the
|
|
30
|
+
* `overrideSchema` hook to rewrite dates and bigints into the shared `x-mjst`
|
|
31
|
+
* extension — the same handling TypeBox and Zod give them.
|
|
32
|
+
*
|
|
33
|
+
* `'ignore'` also silences the converter's own per-construct `console.warn`s.
|
|
34
|
+
* That is deliberate: instead of letting a third-party library log widening in
|
|
35
|
+
* its own words, we collect the constructs it could not represent (via the
|
|
36
|
+
* `errors` array handed to each override hook) and report them ourselves through
|
|
37
|
+
* {@link reportLossyConstructs} — one batched, mjst-branded warning, matching the
|
|
38
|
+
* Zod adapter. In strict mode that same collection throws instead.
|
|
32
39
|
*/
|
|
33
|
-
export const valibotToJsonSchema = async (source) => {
|
|
40
|
+
export const valibotToJsonSchema = async (source, options) => {
|
|
34
41
|
if (typeof source !== 'object' || source === null) {
|
|
35
42
|
const received = source === null ? 'null' : typeof source;
|
|
36
43
|
throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
|
|
37
44
|
}
|
|
38
45
|
const toJsonSchema = await loadToJsonSchema();
|
|
46
|
+
// Every schema or action the converter could not fully represent, keyed by its
|
|
47
|
+
// Valibot construct name (e.g. `symbol`, `blob`, `transform`) so the report
|
|
48
|
+
// reads like the source rather than like internal error strings.
|
|
49
|
+
const droppedConstructs = new Set();
|
|
39
50
|
let json;
|
|
40
51
|
try {
|
|
41
52
|
json = toJsonSchema(source, {
|
|
42
|
-
errorMode: '
|
|
53
|
+
errorMode: 'ignore',
|
|
43
54
|
overrideSchema: (ctx) => {
|
|
55
|
+
// Rescued constructs are represented, not widened — return before we
|
|
56
|
+
// record anything so `date`/`bigint` never show up as lossy.
|
|
44
57
|
if (ctx.valibotSchema?.type === 'date')
|
|
45
58
|
return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
|
|
46
59
|
if (ctx.valibotSchema?.type === 'bigint')
|
|
47
60
|
return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
|
|
61
|
+
if (ctx.errors && ctx.valibotSchema?.type)
|
|
62
|
+
droppedConstructs.add(ctx.valibotSchema.type);
|
|
63
|
+
return undefined;
|
|
64
|
+
},
|
|
65
|
+
overrideAction: (ctx) => {
|
|
66
|
+
// A dropped refinement (e.g. a regex flag JSON Schema cannot express)
|
|
67
|
+
// also widens the result, so it belongs in the same report.
|
|
68
|
+
if (ctx.errors && ctx.valibotAction?.type)
|
|
69
|
+
droppedConstructs.add(ctx.valibotAction.type);
|
|
48
70
|
return undefined;
|
|
49
71
|
},
|
|
50
72
|
});
|
|
@@ -52,6 +74,9 @@ export const valibotToJsonSchema = async (source) => {
|
|
|
52
74
|
catch (error) {
|
|
53
75
|
throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`);
|
|
54
76
|
}
|
|
77
|
+
// Surface everything that widened in one batched, branded notice (or throw in
|
|
78
|
+
// strict mode).
|
|
79
|
+
reportLossyConstructs('Valibot', droppedConstructs, options?.strict);
|
|
55
80
|
// Valibot emits a draft-07 dialect marker; the generators target 2020-12.
|
|
56
81
|
delete json['$schema'];
|
|
57
82
|
return json;
|
|
@@ -1,2 +1,11 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
-
|
|
2
|
+
import type { AdapterOptions } from './adapter.js';
|
|
3
|
+
/**
|
|
4
|
+
* Converts a Zod schema into a Draft 2020-12 JSON Schema.
|
|
5
|
+
*
|
|
6
|
+
* Prefers Zod 4's native `toJSONSchema`. When the installed Zod lacks it (Zod 3),
|
|
7
|
+
* falls back to the optional `zod-to-json-schema` package, routing through the
|
|
8
|
+
* same `x-mjst` date/bigint mapping and lossy-type reporting. If neither path is
|
|
9
|
+
* available, throws a clear error explaining what to install.
|
|
10
|
+
*/
|
|
11
|
+
export declare const zodToJsonSchema: (source: unknown, options?: AdapterOptions) => Promise<JSONSchema>;
|
|
@@ -1,9 +1,27 @@
|
|
|
1
1
|
import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
|
|
2
|
+
import { reportLossyConstructs } from './report-lossy-constructs.js';
|
|
3
|
+
// Zod types that have no JSON Schema equivalent and become "accept anything"
|
|
4
|
+
// (`{}`) — the same widening the Zod 4 path performs with `unrepresentable:
|
|
5
|
+
// 'any'`. Reported through a warning so the loss is never silent. The Zod 4
|
|
6
|
+
// path keys these by Zod's lowercase type name; the fallback keys them by Zod
|
|
7
|
+
// 3's `ZodFirstPartyTypeKind`, mapped here to the same friendly labels.
|
|
8
|
+
const LOSSY_TYPES = new Set(['symbol', 'nan', 'void', 'undefined', 'never', 'map', 'set', 'promise', 'function']);
|
|
9
|
+
const LOSSY_TYPENAMES = {
|
|
10
|
+
ZodSymbol: 'symbol',
|
|
11
|
+
ZodNaN: 'nan',
|
|
12
|
+
ZodVoid: 'void',
|
|
13
|
+
ZodUndefined: 'undefined',
|
|
14
|
+
ZodNever: 'never',
|
|
15
|
+
ZodMap: 'map',
|
|
16
|
+
ZodSet: 'set',
|
|
17
|
+
ZodPromise: 'promise',
|
|
18
|
+
ZodFunction: 'function',
|
|
19
|
+
};
|
|
2
20
|
/**
|
|
3
21
|
* Resolves Zod's `toJSONSchema` from a runtime import, tolerating both the
|
|
4
22
|
* named export (`import { toJSONSchema }`) and the `z` namespace
|
|
5
|
-
* (`z.toJSONSchema`).
|
|
6
|
-
*
|
|
23
|
+
* (`z.toJSONSchema`). Returns `null` when Zod is missing or too old (Zod 3 has
|
|
24
|
+
* no `toJSONSchema`) so the caller can fall back to `zod-to-json-schema`.
|
|
7
25
|
*/
|
|
8
26
|
const loadToJsonSchema = async () => {
|
|
9
27
|
let mod;
|
|
@@ -11,20 +29,38 @@ const loadToJsonSchema = async () => {
|
|
|
11
29
|
mod = (await import('zod'));
|
|
12
30
|
}
|
|
13
31
|
catch {
|
|
14
|
-
|
|
32
|
+
return null;
|
|
15
33
|
}
|
|
16
34
|
const named = mod['toJSONSchema'];
|
|
17
35
|
const namespace = (mod['z'] ?? mod['default'] ?? mod);
|
|
18
36
|
const fromNamespace = namespace?.['toJSONSchema'];
|
|
19
37
|
const converter = typeof named === 'function' ? named : typeof fromNamespace === 'function' ? fromNamespace : undefined;
|
|
20
|
-
|
|
21
|
-
|
|
38
|
+
return converter ? converter : null;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Resolves the `zod-to-json-schema` package — the Zod 3 fallback used when the
|
|
42
|
+
* installed Zod lacks the native `toJSONSchema`. Returns `null` when the
|
|
43
|
+
* package is absent or does not expose the expected shape.
|
|
44
|
+
*/
|
|
45
|
+
const loadFallbackConverter = async () => {
|
|
46
|
+
let mod;
|
|
47
|
+
try {
|
|
48
|
+
mod = (await import('zod-to-json-schema'));
|
|
22
49
|
}
|
|
23
|
-
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const named = mod['zodToJsonSchema'];
|
|
54
|
+
const fromDefault = mod['default'];
|
|
55
|
+
const convert = typeof named === 'function' ? named : typeof fromDefault === 'function' ? fromDefault : undefined;
|
|
56
|
+
const ignoreOverride = mod['ignoreOverride'];
|
|
57
|
+
if (typeof convert !== 'function' || typeof ignoreOverride !== 'symbol')
|
|
58
|
+
return null;
|
|
59
|
+
return { convert: convert, ignoreOverride };
|
|
24
60
|
};
|
|
25
61
|
/**
|
|
26
|
-
*
|
|
27
|
-
* `
|
|
62
|
+
* Runs the Zod 4 native `toJSONSchema`, mapping `z.date()`/`z.bigint()` into the
|
|
63
|
+
* shared `x-mjst` hints and recording lossy (unrepresentable) types.
|
|
28
64
|
*
|
|
29
65
|
* Zod's `z.date()` has no JSON Schema representation and would otherwise throw.
|
|
30
66
|
* We pass `unrepresentable: 'any'` so conversion never fails on it, then use the
|
|
@@ -32,6 +68,98 @@ const loadToJsonSchema = async () => {
|
|
|
32
68
|
* same extension TypeBox dates use — so generated types and runtime checks treat
|
|
33
69
|
* them as `Date`.
|
|
34
70
|
*/
|
|
71
|
+
const convertWithZod4 = (source, toJSONSchema, droppedTypes) => {
|
|
72
|
+
try {
|
|
73
|
+
return toJSONSchema(source, {
|
|
74
|
+
unrepresentable: 'any',
|
|
75
|
+
override: (ctx) => {
|
|
76
|
+
const type = ctx.zodSchema?._zod?.def?.type;
|
|
77
|
+
if (type === 'date') {
|
|
78
|
+
for (const key of Object.keys(ctx.jsonSchema))
|
|
79
|
+
delete ctx.jsonSchema[key];
|
|
80
|
+
ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: 'Date' };
|
|
81
|
+
}
|
|
82
|
+
else if (type === 'bigint') {
|
|
83
|
+
for (const key of Object.keys(ctx.jsonSchema))
|
|
84
|
+
delete ctx.jsonSchema[key];
|
|
85
|
+
ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: 'bigint' };
|
|
86
|
+
}
|
|
87
|
+
else if (type && LOSSY_TYPES.has(type)) {
|
|
88
|
+
droppedTypes.add(type);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Runs the `zod-to-json-schema` fallback for Zod 3, reaching the same outcome as
|
|
99
|
+
* {@link convertWithZod4}: `z.date()`/`z.bigint()` become the shared `x-mjst`
|
|
100
|
+
* hints and lossy types are recorded for the warning. Zod 3's date/bigint would
|
|
101
|
+
* otherwise degrade to a string/integer schema, so the `override` hook rewrites
|
|
102
|
+
* them, and lossy leaf types (which the fallback silently drops) are turned into
|
|
103
|
+
* an open `{}` schema so the field survives — matching the Zod 4 widening.
|
|
104
|
+
*
|
|
105
|
+
* Emits refs under `$defs` (via `definitionPath`) to match the Zod 4 path; the
|
|
106
|
+
* shared finalize step normalises the fallback's draft-07 tuple form afterwards.
|
|
107
|
+
*/
|
|
108
|
+
const convertWithFallback = (source, fallback, droppedTypes) => {
|
|
109
|
+
try {
|
|
110
|
+
return fallback.convert(source, {
|
|
111
|
+
definitionPath: '$defs',
|
|
112
|
+
override: (def) => {
|
|
113
|
+
const typeName = def?.typeName;
|
|
114
|
+
if (typeName === 'ZodDate')
|
|
115
|
+
return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
|
|
116
|
+
if (typeName === 'ZodBigInt')
|
|
117
|
+
return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
|
|
118
|
+
const friendly = typeName ? LOSSY_TYPENAMES[typeName] : undefined;
|
|
119
|
+
if (friendly) {
|
|
120
|
+
droppedTypes.add(friendly);
|
|
121
|
+
return {};
|
|
122
|
+
}
|
|
123
|
+
return fallback.ignoreOverride;
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* `zod-to-json-schema` (the Zod 3 fallback) emits tuples in draft-07 form —
|
|
133
|
+
* `items` as an array plus `additionalItems` for the rest element. Rewrite those
|
|
134
|
+
* nodes into 2020-12 form (`prefixItems`, with `additionalItems` becoming
|
|
135
|
+
* `items`) so the rest of the pipeline — and {@link enforceTupleLength} below —
|
|
136
|
+
* sees the same shape the Zod 4 path produces. No-op on Zod 4 output, which
|
|
137
|
+
* already uses `prefixItems`.
|
|
138
|
+
*/
|
|
139
|
+
const normalizeDraftTuples = (node) => {
|
|
140
|
+
if (node === null || typeof node !== 'object')
|
|
141
|
+
return;
|
|
142
|
+
if (Array.isArray(node)) {
|
|
143
|
+
for (const item of node)
|
|
144
|
+
normalizeDraftTuples(item);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const obj = node;
|
|
148
|
+
if (Array.isArray(obj['items'])) {
|
|
149
|
+
obj['prefixItems'] = obj['items'];
|
|
150
|
+
if ('additionalItems' in obj) {
|
|
151
|
+
// A rest element (`.rest(...)`) — its schema (or `false`) becomes `items`.
|
|
152
|
+
obj['items'] = obj['additionalItems'];
|
|
153
|
+
delete obj['additionalItems'];
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
// No rest element: drop `items` so `enforceTupleLength` forbids extras.
|
|
157
|
+
delete obj['items'];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
for (const value of Object.values(obj))
|
|
161
|
+
normalizeDraftTuples(value);
|
|
162
|
+
};
|
|
35
163
|
/**
|
|
36
164
|
* Zod 4's `toJSONSchema` emits a fixed tuple as a bare `prefixItems` array with
|
|
37
165
|
* no length bound, so the result accepts a too-short array (positions past the
|
|
@@ -123,49 +251,48 @@ const mergeClosedObjectAllOf = (node) => {
|
|
|
123
251
|
}
|
|
124
252
|
return out;
|
|
125
253
|
};
|
|
126
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Shared post-processing applied to both the Zod 4 and Zod 3 conversion output:
|
|
256
|
+
* report widened lossy types (a batched warning, or a throw in strict mode),
|
|
257
|
+
* drop the dialect marker, normalise draft-07 tuples, restore tuple length
|
|
258
|
+
* bounds, and collapse unsatisfiable object intersections.
|
|
259
|
+
*/
|
|
260
|
+
const finalize = (json, droppedTypes, strict) => {
|
|
261
|
+
// Surface every widened type in one batched, branded notice (or throw in
|
|
262
|
+
// strict mode) so the loss is not silent — the same treatment the Valibot
|
|
263
|
+
// adapter gives its own unrepresentable constructs.
|
|
264
|
+
reportLossyConstructs('Zod', droppedTypes, strict);
|
|
265
|
+
// The dialect marker is noise for the generators, which already target 2020-12.
|
|
266
|
+
delete json['$schema'];
|
|
267
|
+
// The Zod 3 fallback emits draft-07 tuples; rewrite them to 2020-12 form.
|
|
268
|
+
normalizeDraftTuples(json);
|
|
269
|
+
// Zod under-constrains fixed tuples (bare `prefixItems`); restore their length.
|
|
270
|
+
enforceTupleLength(json);
|
|
271
|
+
// Collapse an unsatisfiable `allOf` of closed objects (object intersections).
|
|
272
|
+
return mergeClosedObjectAllOf(json);
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* Converts a Zod schema into a Draft 2020-12 JSON Schema.
|
|
276
|
+
*
|
|
277
|
+
* Prefers Zod 4's native `toJSONSchema`. When the installed Zod lacks it (Zod 3),
|
|
278
|
+
* falls back to the optional `zod-to-json-schema` package, routing through the
|
|
279
|
+
* same `x-mjst` date/bigint mapping and lossy-type reporting. If neither path is
|
|
280
|
+
* available, throws a clear error explaining what to install.
|
|
281
|
+
*/
|
|
282
|
+
export const zodToJsonSchema = async (source, options) => {
|
|
127
283
|
if (typeof source !== 'object' || source === null) {
|
|
128
284
|
const received = source === null ? 'null' : typeof source;
|
|
129
285
|
throw new Error(`Zod adapter expected a Zod schema but received ${received}.`);
|
|
130
286
|
}
|
|
131
|
-
const toJSONSchema = await loadToJsonSchema();
|
|
132
|
-
// Zod types with no JSON Schema equivalent that we do *not* rescue into an
|
|
133
|
-
// `x-mjst` hint. `unrepresentable: 'any'` turns these into `{}` (accepts
|
|
134
|
-
// anything), which silently widens the generated type — so we surface them.
|
|
135
|
-
const LOSSY_TYPES = new Set(['symbol', 'nan', 'void', 'undefined', 'never', 'map', 'set', 'promise', 'function']);
|
|
136
287
|
const droppedTypes = new Set();
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
unrepresentable: 'any',
|
|
141
|
-
override: (ctx) => {
|
|
142
|
-
const type = ctx.zodSchema?._zod?.def?.type;
|
|
143
|
-
if (type === 'date') {
|
|
144
|
-
for (const key of Object.keys(ctx.jsonSchema))
|
|
145
|
-
delete ctx.jsonSchema[key];
|
|
146
|
-
ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: 'Date' };
|
|
147
|
-
}
|
|
148
|
-
else if (type === 'bigint') {
|
|
149
|
-
for (const key of Object.keys(ctx.jsonSchema))
|
|
150
|
-
delete ctx.jsonSchema[key];
|
|
151
|
-
ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: 'bigint' };
|
|
152
|
-
}
|
|
153
|
-
else if (type && LOSSY_TYPES.has(type)) {
|
|
154
|
-
droppedTypes.add(type);
|
|
155
|
-
}
|
|
156
|
-
},
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
catch (error) {
|
|
160
|
-
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
|
|
288
|
+
const toJSONSchema = await loadToJsonSchema();
|
|
289
|
+
if (toJSONSchema) {
|
|
290
|
+
return finalize(convertWithZod4(source, toJSONSchema, droppedTypes), droppedTypes, options?.strict);
|
|
161
291
|
}
|
|
162
|
-
|
|
163
|
-
|
|
292
|
+
const fallback = await loadFallbackConverter();
|
|
293
|
+
if (fallback) {
|
|
294
|
+
return finalize(convertWithFallback(source, fallback, droppedTypes), droppedTypes, options?.strict);
|
|
164
295
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
// Zod under-constrains fixed tuples (bare `prefixItems`); restore their length.
|
|
168
|
-
enforceTupleLength(json);
|
|
169
|
-
// Collapse an unsatisfiable `allOf` of closed objects (object intersections).
|
|
170
|
-
return mergeClosedObjectAllOf(json);
|
|
296
|
+
throw new Error("The Zod adapter requires either 'zod' v4+ (for its native toJSONSchema) or the 'zod-to-json-schema' " +
|
|
297
|
+
'package (a fallback for Zod 3). Neither was found — install one in your project.');
|
|
171
298
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/adapters",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Convert schemas from external libraries (TypeBox, Zod, ...) into JSON Schema for mjst.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"json-schema-typed": "^8.0.1",
|
|
40
|
-
"@amritk/helpers": "0.
|
|
40
|
+
"@amritk/helpers": "0.13.0"
|
|
41
41
|
},
|
|
42
42
|
"exports": {
|
|
43
43
|
"./package.json": "./package.json",
|
|
@@ -71,15 +71,23 @@
|
|
|
71
71
|
}
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
|
-
"
|
|
74
|
+
"@sinclair/typebox": ">=0.34",
|
|
75
|
+
"zod": ">=3",
|
|
76
|
+
"zod-to-json-schema": ">=3",
|
|
75
77
|
"valibot": ">=1",
|
|
76
78
|
"@valibot/to-json-schema": ">=1",
|
|
77
79
|
"effect": ">=3"
|
|
78
80
|
},
|
|
79
81
|
"peerDependenciesMeta": {
|
|
82
|
+
"@sinclair/typebox": {
|
|
83
|
+
"optional": true
|
|
84
|
+
},
|
|
80
85
|
"zod": {
|
|
81
86
|
"optional": true
|
|
82
87
|
},
|
|
88
|
+
"zod-to-json-schema": {
|
|
89
|
+
"optional": true
|
|
90
|
+
},
|
|
83
91
|
"valibot": {
|
|
84
92
|
"optional": true
|
|
85
93
|
},
|