@amritk/adapters 0.3.2 → 0.3.3

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.
@@ -1,156 +1,102 @@
1
- import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
2
- import { enforceTupleLength, normalizeDraftTuples } from './normalize-tuples.js';
3
- /**
4
- * Resolves `effect`'s `JSONSchema.make` from a runtime import, throwing a clear
5
- * error when it is missing.
6
- */
1
+ import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
2
+ import { enforceTupleLength, normalizeDraftTuples } from "./normalize-tuples.js";
7
3
  const loadMake = async () => {
8
- let mod;
9
- try {
10
- mod = (await import('effect'));
11
- }
12
- catch {
13
- throw new Error("The Effect adapter requires 'effect' to be installed in your project.");
14
- }
15
- const jsonSchema = mod['JSONSchema'];
16
- const make = jsonSchema?.['make'];
17
- if (typeof make !== 'function') {
18
- throw new Error("Effect's 'JSONSchema.make' was not found. The Effect adapter requires effect v3 or later.");
19
- }
20
- return make;
4
+ let mod;
5
+ try {
6
+ mod = await import("effect");
7
+ } catch {
8
+ throw new Error("The Effect adapter requires 'effect' to be installed in your project.");
9
+ }
10
+ const jsonSchema = mod["JSONSchema"];
11
+ const make = jsonSchema?.["make"];
12
+ if (typeof make !== "function") {
13
+ throw new Error("Effect's 'JSONSchema.make' was not found. The Effect adapter requires effect v3 or later.");
14
+ }
15
+ return make;
21
16
  };
22
- // The annotation key Effect stamps an identifier under (e.g. `"DateFromSelf"`).
23
- const IDENTIFIER_ANNOTATION = Symbol.for('effect/annotation/Identifier');
24
- /** Reads `node.ast`, the AST that backs every Effect `Schema`. */
17
+ const IDENTIFIER_ANNOTATION = /* @__PURE__ */ Symbol.for("effect/annotation/Identifier");
25
18
  const astOf = (source) => {
26
- const ast = source?.ast;
27
- return ast && typeof ast === 'object' ? ast : undefined;
19
+ const ast = source?.ast;
20
+ return ast && typeof ast === "object" ? ast : void 0;
28
21
  };
29
- /**
30
- * Effect models `bigint` and a runtime `Date` as types with no JSON Schema
31
- * representation, so `JSONSchema.make` throws — for a top-level value *and* for
32
- * one buried inside a struct, array, or union. To stay consistent with the Zod,
33
- * Valibot, and TypeBox adapters — which map those to the shared `x-mjst` hint —
34
- * we rescue them wherever they appear: `bigint` (`BigIntKeyword`) →
35
- * `primitive: 'bigint'`, and the `DateFromSelf` declaration → `instanceOf: 'Date'`.
36
- *
37
- * `Schema.Date` / `Schema.BigInt` decode from a string and already convert to a
38
- * `string` schema, so they are untouched — the walk below hands any such
39
- * fully-representable subtree straight to `make` and keeps its output verbatim.
40
- */
41
- const isDateFromSelf = (ast) => ast._tag === 'Declaration' && ast.annotations?.[IDENTIFIER_ANNOTATION] === 'DateFromSelf';
42
- // `make` stamps every schema with a dialect marker and hoists referenced types
43
- // into a sibling `$defs`. When we convert a nested subtree in isolation we strip
44
- // the marker and lift its `$defs` into the shared root map so `$ref`s (which use
45
- // absolute `#/$defs/...` paths) still resolve once everything is reassembled.
22
+ const isDateFromSelf = (ast) => ast._tag === "Declaration" && ast.annotations?.[IDENTIFIER_ANNOTATION] === "DateFromSelf";
46
23
  const hoistInto = (schema, rootDefs) => {
47
- delete schema['$schema'];
48
- const defs = schema['$defs'];
49
- if (defs && typeof defs === 'object') {
50
- Object.assign(rootDefs, defs);
51
- delete schema['$defs'];
52
- }
53
- return schema;
24
+ delete schema["$schema"];
25
+ const defs = schema["$defs"];
26
+ if (defs && typeof defs === "object") {
27
+ Object.assign(rootDefs, defs);
28
+ delete schema["$defs"];
29
+ }
30
+ return schema;
54
31
  };
55
- /**
56
- * Recursively converts an Effect AST into JSON Schema, rescuing nested
57
- * unrepresentable leaves into `x-mjst` hints along the way.
58
- *
59
- * The strategy is to lean on `make` as much as possible: any subtree it can
60
- * convert is representable, so we take its output verbatim. Only when `make`
61
- * throws do we descend structurally — reconstructing the container (struct,
62
- * array, union, ...) and recursing into its children — until we reach the
63
- * bigint / `Date` leaf that has no JSON Schema form and rescue it.
64
- */
65
32
  const walk = (make, ast, rootDefs) => {
66
- // A subtree `make` accepts is fully representable, so use its output as-is.
67
- try {
68
- return hoistInto(make({ ast }), rootDefs);
33
+ try {
34
+ return hoistInto(make({ ast }), rootDefs);
35
+ } catch {
36
+ }
37
+ if (ast._tag === "BigIntKeyword")
38
+ return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
39
+ if (isDateFromSelf(ast))
40
+ return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
41
+ switch (ast._tag) {
42
+ case "TypeLiteral": {
43
+ const properties = {};
44
+ const required = [];
45
+ for (const ps of ast.propertySignatures ?? []) {
46
+ properties[ps.name] = walk(make, ps.type, rootDefs);
47
+ if (!ps.isOptional)
48
+ required.push(ps.name);
49
+ }
50
+ return { type: "object", required, properties, additionalProperties: false };
69
51
  }
70
- catch {
71
- // `make` threw, so an unrepresentable node lives somewhere below. Fall through.
52
+ case "TupleType": {
53
+ const elements = ast.elements ?? [];
54
+ const rest = ast.rest ?? [];
55
+ const [firstRest] = rest;
56
+ if (elements.length === 0 && rest.length === 1 && firstRest) {
57
+ return { type: "array", items: walk(make, firstRest.type, rootDefs) };
58
+ }
59
+ return {
60
+ type: "array",
61
+ minItems: elements.filter((e) => !e.isOptional).length,
62
+ items: elements.map((e) => walk(make, e.type, rootDefs)),
63
+ additionalItems: firstRest ? walk(make, firstRest.type, rootDefs) : false
64
+ };
72
65
  }
73
- if (ast._tag === 'BigIntKeyword')
74
- return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
75
- if (isDateFromSelf(ast))
76
- return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
77
- switch (ast._tag) {
78
- case 'TypeLiteral': {
79
- const properties = {};
80
- const required = [];
81
- for (const ps of ast.propertySignatures ?? []) {
82
- properties[ps.name] = walk(make, ps.type, rootDefs);
83
- if (!ps.isOptional)
84
- required.push(ps.name);
85
- }
86
- return { type: 'object', required, properties, additionalProperties: false };
87
- }
88
- case 'TupleType': {
89
- const elements = ast.elements ?? [];
90
- const rest = ast.rest ?? [];
91
- const [firstRest] = rest;
92
- // `Schema.Array(x)` is a tuple with no fixed elements and a single rest.
93
- if (elements.length === 0 && rest.length === 1 && firstRest) {
94
- return { type: 'array', items: walk(make, firstRest.type, rootDefs) };
95
- }
96
- return {
97
- type: 'array',
98
- minItems: elements.filter((e) => !e.isOptional).length,
99
- items: elements.map((e) => walk(make, e.type, rootDefs)),
100
- additionalItems: firstRest ? walk(make, firstRest.type, rootDefs) : false,
101
- };
102
- }
103
- case 'Union':
104
- return { anyOf: (ast.types ?? []).map((t) => walk(make, t, rootDefs)) };
105
- // `Refinement` and `Transformation` describe the encoded value via `from`;
106
- // `Suspend` defers to a thunk. Follow through to reach the wrapped subtree.
107
- case 'Refinement':
108
- case 'Transformation':
109
- if (ast.from)
110
- return walk(make, ast.from, rootDefs);
111
- break;
112
- case 'Suspend':
113
- if (ast.f)
114
- return walk(make, ast.f(), rootDefs);
115
- break;
116
- }
117
- // A genuinely unrepresentable type we do not know how to rescue (e.g. a raw
118
- // `symbol`). Point the user at the fix rather than Effect's opaque message.
119
- throw new Error(`Effect adapter failed to convert the schema. A ${ast._tag ?? 'nested'} type has no JSON Schema ` +
120
- `representation — replace it with a JSON-representable type, or add a \`jsonSchema\` annotation to that field.`);
66
+ case "Union":
67
+ return { anyOf: (ast.types ?? []).map((t) => walk(make, t, rootDefs)) };
68
+ // `Refinement` and `Transformation` describe the encoded value via `from`;
69
+ // `Suspend` defers to a thunk. Follow through to reach the wrapped subtree.
70
+ case "Refinement":
71
+ case "Transformation":
72
+ if (ast.from)
73
+ return walk(make, ast.from, rootDefs);
74
+ break;
75
+ case "Suspend":
76
+ if (ast.f)
77
+ return walk(make, ast.f(), rootDefs);
78
+ break;
79
+ }
80
+ throw new Error(`Effect adapter failed to convert the schema. A ${ast._tag ?? "nested"} type has no JSON Schema representation \u2014 replace it with a JSON-representable type, or add a \`jsonSchema\` annotation to that field.`);
121
81
  };
122
- /**
123
- * Converts an Effect `Schema` into a JSON Schema via `JSONSchema.make`.
124
- *
125
- * Effect models values as a decode/encode pair, so `JSONSchema.make` describes
126
- * the *encoded* (wire) representation. For example `Schema.Date` decodes from a
127
- * string, so it converts to a string schema rather than a runtime `Date`. We
128
- * pass that representation straight through — it accurately reflects what Effect
129
- * expects on the wire — only stripping the dialect marker. A `BigIntFromSelf` /
130
- * `DateFromSelf` anywhere in the tree (top level or nested) is rescued into an
131
- * `x-mjst` hint instead of throwing.
132
- */
133
- export const effectToJsonSchema = async (source) => {
134
- // Effect `Schema` values are callable, so they report as `function`, not `object`.
135
- if ((typeof source !== 'object' && typeof source !== 'function') || source === null) {
136
- const received = source === null ? 'null' : typeof source;
137
- throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`);
138
- }
139
- const ast = astOf(source);
140
- if (!ast) {
141
- throw new Error('Effect adapter expected an Effect Schema but the value has no `ast` property.');
142
- }
143
- const make = await loadMake();
144
- const rootDefs = {};
145
- const json = walk(make, ast, rootDefs);
146
- // Reattach the hoisted definitions once the whole tree is assembled.
147
- if (Object.keys(rootDefs).length > 0)
148
- json['$defs'] = rootDefs;
149
- // `JSONSchema.make` (and the structural rescue path) emit fixed tuples in
150
- // draft-07 form (`items: [...]` + `additionalItems`), which the generators do
151
- // not recognize as a tuple — element types and length would go unvalidated.
152
- // Normalize to 2020-12 `prefixItems`, then restore the length bound.
153
- normalizeDraftTuples(json);
154
- enforceTupleLength(json);
155
- return json;
82
+ const effectToJsonSchema = async (source) => {
83
+ if (typeof source !== "object" && typeof source !== "function" || source === null) {
84
+ const received = source === null ? "null" : typeof source;
85
+ throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`);
86
+ }
87
+ const ast = astOf(source);
88
+ if (!ast) {
89
+ throw new Error("Effect adapter expected an Effect Schema but the value has no `ast` property.");
90
+ }
91
+ const make = await loadMake();
92
+ const rootDefs = {};
93
+ const json = walk(make, ast, rootDefs);
94
+ if (Object.keys(rootDefs).length > 0)
95
+ json["$defs"] = rootDefs;
96
+ normalizeDraftTuples(json);
97
+ enforceTupleLength(json);
98
+ return json;
99
+ };
100
+ export {
101
+ effectToJsonSchema
156
102
  };
@@ -1,43 +1,37 @@
1
- import { effectToJsonSchema } from './effect-to-json-schema.js';
2
- import { typeboxToJsonSchema } from './typebox-to-json-schema.js';
3
- import { valibotToJsonSchema } from './valibot-to-json-schema.js';
4
- import { zodToJsonSchema } from './zod-to-json-schema.js';
1
+ import { effectToJsonSchema } from "./effect-to-json-schema.js";
2
+ import { typeboxToJsonSchema } from "./typebox-to-json-schema.js";
3
+ import { valibotToJsonSchema } from "./valibot-to-json-schema.js";
4
+ import { zodToJsonSchema } from "./zod-to-json-schema.js";
5
5
  const typeboxAdapter = {
6
- format: 'typebox',
7
- toJSONSchema: typeboxToJsonSchema,
6
+ format: "typebox",
7
+ toJSONSchema: typeboxToJsonSchema
8
8
  };
9
9
  const zodAdapter = {
10
- format: 'zod',
11
- toJSONSchema: zodToJsonSchema,
10
+ format: "zod",
11
+ toJSONSchema: zodToJsonSchema
12
12
  };
13
13
  const valibotAdapter = {
14
- format: 'valibot',
15
- toJSONSchema: valibotToJsonSchema,
14
+ format: "valibot",
15
+ toJSONSchema: valibotToJsonSchema
16
16
  };
17
17
  const effectAdapter = {
18
- format: 'effect',
19
- toJSONSchema: effectToJsonSchema,
18
+ format: "effect",
19
+ toJSONSchema: effectToJsonSchema
20
20
  };
21
- /**
22
- * Resolves the adapter for a non-JSON source format.
23
- *
24
- * Only formats with an implemented adapter resolve. The `'json'` format never
25
- * reaches here — the CLI reads JSON Schema files directly without an adapter —
26
- * and formats that are named but not yet built throw a clear, actionable error
27
- * so the CLI can fail fast with guidance instead of a cryptic crash.
28
- */
29
- export const getAdapter = (format) => {
30
- switch (format) {
31
- case 'typebox':
32
- return typeboxAdapter;
33
- case 'zod':
34
- return zodAdapter;
35
- case 'valibot':
36
- return valibotAdapter;
37
- case 'effect':
38
- return effectAdapter;
39
- default:
40
- throw new Error(`No adapter is available for input format '${format}'. ` +
41
- `Supported: 'typebox', 'zod', 'valibot', 'effect'. Use --input json for plain JSON Schema files.`);
42
- }
21
+ const getAdapter = (format) => {
22
+ switch (format) {
23
+ case "typebox":
24
+ return typeboxAdapter;
25
+ case "zod":
26
+ return zodAdapter;
27
+ case "valibot":
28
+ return valibotAdapter;
29
+ case "effect":
30
+ return effectAdapter;
31
+ default:
32
+ throw new Error(`No adapter is available for input format '${format}'. Supported: 'typebox', 'zod', 'valibot', 'effect'. Use --input json for plain JSON Schema files.`);
33
+ }
34
+ };
35
+ export {
36
+ getAdapter
43
37
  };
@@ -1,67 +1,45 @@
1
- /**
2
- * Shared tuple normalization for the adapters whose upstream converter emits
3
- * JSON Schema in a shape the mjst pipeline does not key tuple validation off of.
4
- * The pipeline recognizes a tuple only by 2020-12 `prefixItems`; a draft-07
5
- * `items: [...]` array is treated as a plain array, so element types and length
6
- * go unvalidated downstream. Both functions walk the whole tree.
7
- */
8
- /**
9
- * Rewrites draft-07 tuples (`items` as an array, with an optional
10
- * `additionalItems` rest element) into 2020-12 form: `items` becomes
11
- * `prefixItems`, and `additionalItems` becomes `items` (its schema, or `false`).
12
- * No-op on output that already uses `prefixItems`.
13
- */
14
- export const normalizeDraftTuples = (node) => {
15
- if (node === null || typeof node !== 'object')
16
- return;
17
- if (Array.isArray(node)) {
18
- for (const item of node)
19
- normalizeDraftTuples(item);
20
- return;
1
+ const normalizeDraftTuples = (node) => {
2
+ if (node === null || typeof node !== "object")
3
+ return;
4
+ if (Array.isArray(node)) {
5
+ for (const item of node)
6
+ normalizeDraftTuples(item);
7
+ return;
8
+ }
9
+ const obj = node;
10
+ if (Array.isArray(obj["items"])) {
11
+ obj["prefixItems"] = obj["items"];
12
+ if ("additionalItems" in obj) {
13
+ obj["items"] = obj["additionalItems"];
14
+ delete obj["additionalItems"];
15
+ } else {
16
+ delete obj["items"];
21
17
  }
22
- const obj = node;
23
- if (Array.isArray(obj['items'])) {
24
- obj['prefixItems'] = obj['items'];
25
- if ('additionalItems' in obj) {
26
- // A rest element — its schema (or `false`) becomes `items`.
27
- obj['items'] = obj['additionalItems'];
28
- delete obj['additionalItems'];
29
- }
30
- else {
31
- // No rest element: drop `items` so `enforceTupleLength` forbids extras.
32
- delete obj['items'];
33
- }
34
- }
35
- for (const value of Object.values(obj))
36
- normalizeDraftTuples(value);
18
+ }
19
+ for (const value of Object.values(obj))
20
+ normalizeDraftTuples(value);
37
21
  };
38
- /**
39
- * A fixed tuple expressed as a bare `prefixItems` array (no length bound) accepts
40
- * a too-short array (trailing positions unconstrained) and a too-long one
41
- * (nothing forbids extras). Restore the length: `minItems` forces the fixed
42
- * elements present, and — when the tuple has no rest element (no `items`) —
43
- * `items: false` forbids extras. Applied to every `prefixItems` node; existing
44
- * tighter bounds are never loosened.
45
- */
46
- export const enforceTupleLength = (node) => {
47
- if (node === null || typeof node !== 'object')
48
- return;
49
- if (Array.isArray(node)) {
50
- for (const item of node)
51
- enforceTupleLength(item);
52
- return;
53
- }
54
- const obj = node;
55
- if (Array.isArray(obj['prefixItems'])) {
56
- const fixed = obj['prefixItems'].length;
57
- const min = typeof obj['minItems'] === 'number' ? obj['minItems'] : 0;
58
- if (min < fixed)
59
- obj['minItems'] = fixed;
60
- // No `items` keyword means no rest element: the array may not exceed the
61
- // fixed tuple, so forbid additional items.
62
- if (!('items' in obj))
63
- obj['items'] = false;
64
- }
65
- for (const value of Object.values(obj))
66
- enforceTupleLength(value);
22
+ const enforceTupleLength = (node) => {
23
+ if (node === null || typeof node !== "object")
24
+ return;
25
+ if (Array.isArray(node)) {
26
+ for (const item of node)
27
+ enforceTupleLength(item);
28
+ return;
29
+ }
30
+ const obj = node;
31
+ if (Array.isArray(obj["prefixItems"])) {
32
+ const fixed = obj["prefixItems"].length;
33
+ const min = typeof obj["minItems"] === "number" ? obj["minItems"] : 0;
34
+ if (min < fixed)
35
+ obj["minItems"] = fixed;
36
+ if (!("items" in obj))
37
+ obj["items"] = false;
38
+ }
39
+ for (const value of Object.values(obj))
40
+ enforceTupleLength(value);
41
+ };
42
+ export {
43
+ enforceTupleLength,
44
+ normalizeDraftTuples
67
45
  };
@@ -1,33 +1,14 @@
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}`);
1
+ const reportLossyConstructs = (adapter, constructs, strict) => {
2
+ if (constructs.size === 0)
3
+ return;
4
+ const list = [...constructs].sort().join(", ");
5
+ const plural = constructs.size !== 1;
6
+ const detail = `${list} ${plural ? "have" : "has"} no full JSON Schema representation and ${plural ? "were" : "was"} widened. The generated type will be wider than the ${adapter} schema.`;
7
+ if (strict) {
8
+ throw new Error(`[mjst] ${adapter} adapter (strict mode): ${detail} Remove the unsupported construct(s) from the schema, or disable strict mode to widen and warn instead.`);
9
+ }
10
+ console.warn(`[mjst] ${adapter} adapter: ${detail}`);
11
+ };
12
+ export {
13
+ reportLossyConstructs
33
14
  };
@@ -1,73 +1,45 @@
1
- import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
2
- // The seven core JSON Schema 2020-12 types. Anything else in a `type` slot is a
3
- // TypeBox extended type with no native JSON Schema equivalent.
4
- const JSON_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null']);
5
- // Maps a TypeBox extended `type` string to the runtime class an `x-mjst`
6
- // instanceOf hint should reference. Add entries here as more extended types
7
- // gain generator support.
1
+ import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
2
+ const JSON_SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
8
3
  const EXTENDED_TYPE_TO_INSTANCE = {
9
- Date: 'Date',
4
+ Date: "Date"
10
5
  };
11
- // Maps a TypeBox extended `type` string to a non-JSON `x-mjst` primitive hint
12
- // (e.g. Type.BigInt() emits `{ type: 'bigint' }`).
13
6
  const EXTENDED_TYPE_TO_PRIMITIVE = {
14
- bigint: 'bigint',
7
+ bigint: "bigint"
15
8
  };
16
- /**
17
- * Recursively rewrites TypeBox extended types into an `x-mjst` instanceOf hint.
18
- *
19
- * TypeBox emits non-standard `type` strings for runtime classes (e.g.
20
- * `Type.Date()` produces `{ type: 'Date' }`). We drop the bogus `type` and
21
- * record the class under `x-mjst` so the generators can emit the right
22
- * TypeScript type and `instanceof` checks. Extended types we do not yet map are
23
- * left untouched with a warning, preserving a permissive best-effort fallback.
24
- */
25
9
  const rewriteExtendedTypes = (value) => {
26
- if (Array.isArray(value))
27
- return value.map(rewriteExtendedTypes);
28
- if (typeof value !== 'object' || value === null)
29
- return value;
30
- const source = value;
31
- const result = {};
32
- for (const [key, val] of Object.entries(source)) {
33
- result[key] = rewriteExtendedTypes(val);
10
+ if (Array.isArray(value))
11
+ return value.map(rewriteExtendedTypes);
12
+ if (typeof value !== "object" || value === null)
13
+ return value;
14
+ const source = value;
15
+ const result = {};
16
+ for (const [key, val] of Object.entries(source)) {
17
+ result[key] = rewriteExtendedTypes(val);
18
+ }
19
+ const type = result["type"];
20
+ if (typeof type === "string" && !JSON_SCHEMA_TYPES.has(type)) {
21
+ const primitive = EXTENDED_TYPE_TO_PRIMITIVE[type];
22
+ const instanceOf = EXTENDED_TYPE_TO_INSTANCE[type];
23
+ if (primitive) {
24
+ delete result["type"];
25
+ result[MJST_EXTENSION_KEY] = { primitive };
26
+ } else if (instanceOf) {
27
+ delete result["type"];
28
+ result[MJST_EXTENSION_KEY] = { instanceOf };
29
+ } else {
30
+ console.warn(`[mjst] TypeBox type '${type}' has no JSON Schema or x-mjst mapping; leaving it unchanged.`);
34
31
  }
35
- const type = result['type'];
36
- if (typeof type === 'string' && !JSON_SCHEMA_TYPES.has(type)) {
37
- const primitive = EXTENDED_TYPE_TO_PRIMITIVE[type];
38
- const instanceOf = EXTENDED_TYPE_TO_INSTANCE[type];
39
- if (primitive) {
40
- delete result['type'];
41
- result[MJST_EXTENSION_KEY] = { primitive };
42
- }
43
- else if (instanceOf) {
44
- delete result['type'];
45
- result[MJST_EXTENSION_KEY] = { instanceOf };
46
- }
47
- else {
48
- console.warn(`[mjst] TypeBox type '${type}' has no JSON Schema or x-mjst mapping; leaving it unchanged.`);
49
- }
50
- }
51
- return result;
32
+ }
33
+ return result;
52
34
  };
53
- /**
54
- * TypeBox schemas are already JSON Schema objects at runtime, but they carry
55
- * non-enumerable symbol keys (`Kind`, `Optional`, ...) that TypeBox uses for its
56
- * own type machinery. A JSON round-trip drops those symbols (and any `undefined`
57
- * values), leaving a clean, plain JSON Schema. We then rewrite TypeBox's
58
- * extended types (Date, ...) into `x-mjst` hints the generators understand.
59
- *
60
- * We deliberately do not import TypeBox here: the conversion only touches the
61
- * plain-object shape, so TypeBox stays an optional peer dependency used solely
62
- * by the consumer's schema module, never by mjst itself.
63
- */
64
- export const typeboxToJsonSchema = (source) => {
65
- if (typeof source !== 'object' || source === null) {
66
- const received = source === null ? 'null' : typeof source;
67
- throw new Error(`TypeBox adapter expected a schema object but received ${received}.`);
68
- }
69
- // Boundary cast: JSON.parse yields `unknown`, and the round-tripped, rewritten
70
- // TypeBox schema is a valid JSON Schema by construction.
71
- const sanitized = JSON.parse(JSON.stringify(source));
72
- return rewriteExtendedTypes(sanitized);
35
+ const typeboxToJsonSchema = (source) => {
36
+ if (typeof source !== "object" || source === null) {
37
+ const received = source === null ? "null" : typeof source;
38
+ throw new Error(`TypeBox adapter expected a schema object but received ${received}.`);
39
+ }
40
+ const sanitized = JSON.parse(JSON.stringify(source));
41
+ return rewriteExtendedTypes(sanitized);
42
+ };
43
+ export {
44
+ typeboxToJsonSchema
73
45
  };
@@ -1,89 +1,59 @@
1
- import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
2
- import { reportLossyConstructs } from './report-lossy-constructs.js';
3
- /**
4
- * Resolves `@valibot/to-json-schema`'s `toJsonSchema` from a runtime import,
5
- * throwing a clear error when the converter is missing.
6
- */
1
+ import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
2
+ import { reportLossyConstructs } from "./report-lossy-constructs.js";
7
3
  const loadToJsonSchema = async () => {
8
- let mod;
9
- try {
10
- mod = (await import('@valibot/to-json-schema'));
11
- }
12
- catch {
13
- throw new Error("The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.");
14
- }
15
- const named = mod['toJsonSchema'];
16
- const fromDefault = mod['default']?.['toJsonSchema'];
17
- const converter = typeof named === 'function' ? named : typeof fromDefault === 'function' ? fromDefault : undefined;
18
- if (!converter) {
19
- throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.");
20
- }
21
- return converter;
4
+ let mod;
5
+ try {
6
+ mod = await import("@valibot/to-json-schema");
7
+ } catch {
8
+ throw new Error("The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.");
9
+ }
10
+ const named = mod["toJsonSchema"];
11
+ const fromDefault = mod["default"]?.["toJsonSchema"];
12
+ const converter = typeof named === "function" ? named : typeof fromDefault === "function" ? fromDefault : void 0;
13
+ if (!converter) {
14
+ throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.");
15
+ }
16
+ return converter;
22
17
  };
23
- /**
24
- * Converts a Valibot schema into a Draft 2020-12 JSON Schema via
25
- * `@valibot/to-json-schema`.
26
- *
27
- * Valibot's `date` schema has no JSON Schema representation and would otherwise
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.
39
- */
40
- export const valibotToJsonSchema = async (source, options) => {
41
- if (typeof source !== 'object' || source === null) {
42
- const received = source === null ? 'null' : typeof source;
43
- throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
44
- }
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();
50
- let json;
51
- try {
52
- json = toJsonSchema(source, {
53
- errorMode: 'ignore',
54
- // The converter defaults to draft-07, which emits fixed tuples as
55
- // `items: [...]`; the generators key tuple validation off 2020-12
56
- // `prefixItems`, so a draft-07 tuple would be silently under-validated
57
- // (element types and length unchecked). Target 2020-12 explicitly.
58
- target: 'draft-2020-12',
59
- overrideSchema: (ctx) => {
60
- // Rescued constructs are represented, not widened — return before we
61
- // record anything so `date`/`bigint` never show up as lossy.
62
- if (ctx.valibotSchema?.type === 'date')
63
- return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
64
- if (ctx.valibotSchema?.type === 'bigint')
65
- return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
66
- if (ctx.errors && ctx.valibotSchema?.type)
67
- droppedConstructs.add(ctx.valibotSchema.type);
68
- return undefined;
69
- },
70
- overrideAction: (ctx) => {
71
- // A dropped refinement (e.g. a regex flag JSON Schema cannot express)
72
- // also widens the result, so it belongs in the same report.
73
- if (ctx.errors && ctx.valibotAction?.type)
74
- droppedConstructs.add(ctx.valibotAction.type);
75
- return undefined;
76
- },
77
- });
78
- }
79
- catch (error) {
80
- throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`);
81
- }
82
- // Surface everything that widened in one batched, branded notice (or throw in
83
- // strict mode).
84
- reportLossyConstructs('Valibot', droppedConstructs, options?.strict);
85
- // Drop the dialect marker the converter emits; the generators infer the
86
- // dialect from structure, not `$schema`.
87
- delete json['$schema'];
88
- return json;
18
+ const valibotToJsonSchema = async (source, options) => {
19
+ if (typeof source !== "object" || source === null) {
20
+ const received = source === null ? "null" : typeof source;
21
+ throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
22
+ }
23
+ const toJsonSchema = await loadToJsonSchema();
24
+ const droppedConstructs = /* @__PURE__ */ new Set();
25
+ let json;
26
+ try {
27
+ json = toJsonSchema(source, {
28
+ errorMode: "ignore",
29
+ // The converter defaults to draft-07, which emits fixed tuples as
30
+ // `items: [...]`; the generators key tuple validation off 2020-12
31
+ // `prefixItems`, so a draft-07 tuple would be silently under-validated
32
+ // (element types and length unchecked). Target 2020-12 explicitly.
33
+ target: "draft-2020-12",
34
+ overrideSchema: (ctx) => {
35
+ if (ctx.valibotSchema?.type === "date")
36
+ return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
37
+ if (ctx.valibotSchema?.type === "bigint")
38
+ return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
39
+ if (ctx.errors && ctx.valibotSchema?.type)
40
+ droppedConstructs.add(ctx.valibotSchema.type);
41
+ return void 0;
42
+ },
43
+ overrideAction: (ctx) => {
44
+ if (ctx.errors && ctx.valibotAction?.type)
45
+ droppedConstructs.add(ctx.valibotAction.type);
46
+ return void 0;
47
+ }
48
+ });
49
+ } catch (error) {
50
+ throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?
51
+ ${String(error)}`);
52
+ }
53
+ reportLossyConstructs("Valibot", droppedConstructs, options?.strict);
54
+ delete json["$schema"];
55
+ return json;
56
+ };
57
+ export {
58
+ valibotToJsonSchema
89
59
  };
@@ -1,236 +1,163 @@
1
- import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
2
- import { enforceTupleLength, normalizeDraftTuples } from './normalize-tuples.js';
3
- import { reportLossyConstructs } from './report-lossy-constructs.js';
4
- // Zod types that have no JSON Schema equivalent and become "accept anything"
5
- // (`{}`) — the same widening the Zod 4 path performs with `unrepresentable:
6
- // 'any'`. Reported through a warning so the loss is never silent. The Zod 4
7
- // path keys these by Zod's lowercase type name; the fallback keys them by Zod
8
- // 3's `ZodFirstPartyTypeKind`, mapped here to the same friendly labels.
9
- const LOSSY_TYPES = new Set(['symbol', 'nan', 'void', 'undefined', 'never', 'map', 'set', 'promise', 'function']);
1
+ import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
2
+ import { enforceTupleLength, normalizeDraftTuples } from "./normalize-tuples.js";
3
+ import { reportLossyConstructs } from "./report-lossy-constructs.js";
4
+ const LOSSY_TYPES = /* @__PURE__ */ new Set(["symbol", "nan", "void", "undefined", "never", "map", "set", "promise", "function"]);
10
5
  const LOSSY_TYPENAMES = {
11
- ZodSymbol: 'symbol',
12
- ZodNaN: 'nan',
13
- ZodVoid: 'void',
14
- ZodUndefined: 'undefined',
15
- ZodNever: 'never',
16
- ZodMap: 'map',
17
- ZodSet: 'set',
18
- ZodPromise: 'promise',
19
- ZodFunction: 'function',
6
+ ZodSymbol: "symbol",
7
+ ZodNaN: "nan",
8
+ ZodVoid: "void",
9
+ ZodUndefined: "undefined",
10
+ ZodNever: "never",
11
+ ZodMap: "map",
12
+ ZodSet: "set",
13
+ ZodPromise: "promise",
14
+ ZodFunction: "function"
20
15
  };
21
- /**
22
- * Resolves Zod's `toJSONSchema` from a runtime import, tolerating both the
23
- * named export (`import { toJSONSchema }`) and the `z` namespace
24
- * (`z.toJSONSchema`). Returns `null` when Zod is missing or too old (Zod 3 has
25
- * no `toJSONSchema`) so the caller can fall back to `zod-to-json-schema`.
26
- */
27
16
  const loadToJsonSchema = async () => {
28
- let mod;
29
- try {
30
- mod = (await import('zod'));
31
- }
32
- catch {
33
- return null;
34
- }
35
- const named = mod['toJSONSchema'];
36
- const namespace = (mod['z'] ?? mod['default'] ?? mod);
37
- const fromNamespace = namespace?.['toJSONSchema'];
38
- const converter = typeof named === 'function' ? named : typeof fromNamespace === 'function' ? fromNamespace : undefined;
39
- return converter ? converter : null;
17
+ let mod;
18
+ try {
19
+ mod = await import("zod");
20
+ } catch {
21
+ return null;
22
+ }
23
+ const named = mod["toJSONSchema"];
24
+ const namespace = mod["z"] ?? mod["default"] ?? mod;
25
+ const fromNamespace = namespace?.["toJSONSchema"];
26
+ const converter = typeof named === "function" ? named : typeof fromNamespace === "function" ? fromNamespace : void 0;
27
+ return converter ? converter : null;
40
28
  };
41
- /**
42
- * Resolves the `zod-to-json-schema` package — the Zod 3 fallback used when the
43
- * installed Zod lacks the native `toJSONSchema`. Returns `null` when the
44
- * package is absent or does not expose the expected shape.
45
- */
46
29
  const loadFallbackConverter = async () => {
47
- let mod;
48
- try {
49
- mod = (await import('zod-to-json-schema'));
50
- }
51
- catch {
52
- return null;
53
- }
54
- const named = mod['zodToJsonSchema'];
55
- const fromDefault = mod['default'];
56
- const convert = typeof named === 'function' ? named : typeof fromDefault === 'function' ? fromDefault : undefined;
57
- const ignoreOverride = mod['ignoreOverride'];
58
- if (typeof convert !== 'function' || typeof ignoreOverride !== 'symbol')
59
- return null;
60
- return { convert: convert, ignoreOverride };
30
+ let mod;
31
+ try {
32
+ mod = await import("zod-to-json-schema");
33
+ } catch {
34
+ return null;
35
+ }
36
+ const named = mod["zodToJsonSchema"];
37
+ const fromDefault = mod["default"];
38
+ const convert = typeof named === "function" ? named : typeof fromDefault === "function" ? fromDefault : void 0;
39
+ const ignoreOverride = mod["ignoreOverride"];
40
+ if (typeof convert !== "function" || typeof ignoreOverride !== "symbol")
41
+ return null;
42
+ return { convert, ignoreOverride };
61
43
  };
62
- /**
63
- * Runs the Zod 4 native `toJSONSchema`, mapping `z.date()`/`z.bigint()` into the
64
- * shared `x-mjst` hints and recording lossy (unrepresentable) types.
65
- *
66
- * Zod's `z.date()` has no JSON Schema representation and would otherwise throw.
67
- * We pass `unrepresentable: 'any'` so conversion never fails on it, then use the
68
- * `override` hook to rewrite date schemas into an `x-mjst` instanceOf hint — the
69
- * same extension TypeBox dates use — so generated types and runtime checks treat
70
- * them as `Date`.
71
- */
72
44
  const convertWithZod4 = (source, toJSONSchema, droppedTypes) => {
73
- try {
74
- return toJSONSchema(source, {
75
- unrepresentable: 'any',
76
- override: (ctx) => {
77
- const type = ctx.zodSchema?._zod?.def?.type;
78
- if (type === 'date') {
79
- for (const key of Object.keys(ctx.jsonSchema))
80
- delete ctx.jsonSchema[key];
81
- ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: 'Date' };
82
- }
83
- else if (type === 'bigint') {
84
- for (const key of Object.keys(ctx.jsonSchema))
85
- delete ctx.jsonSchema[key];
86
- ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: 'bigint' };
87
- }
88
- else if (type && LOSSY_TYPES.has(type)) {
89
- droppedTypes.add(type);
90
- }
91
- },
92
- });
93
- }
94
- catch (error) {
95
- throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
96
- }
45
+ try {
46
+ return toJSONSchema(source, {
47
+ unrepresentable: "any",
48
+ override: (ctx) => {
49
+ const type = ctx.zodSchema?._zod?.def?.type;
50
+ if (type === "date") {
51
+ for (const key of Object.keys(ctx.jsonSchema))
52
+ delete ctx.jsonSchema[key];
53
+ ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: "Date" };
54
+ } else if (type === "bigint") {
55
+ for (const key of Object.keys(ctx.jsonSchema))
56
+ delete ctx.jsonSchema[key];
57
+ ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: "bigint" };
58
+ } else if (type && LOSSY_TYPES.has(type)) {
59
+ droppedTypes.add(type);
60
+ }
61
+ }
62
+ });
63
+ } catch (error) {
64
+ throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?
65
+ ${String(error)}`);
66
+ }
97
67
  };
98
- /**
99
- * Runs the `zod-to-json-schema` fallback for Zod 3, reaching the same outcome as
100
- * {@link convertWithZod4}: `z.date()`/`z.bigint()` become the shared `x-mjst`
101
- * hints and lossy types are recorded for the warning. Zod 3's date/bigint would
102
- * otherwise degrade to a string/integer schema, so the `override` hook rewrites
103
- * them, and lossy leaf types (which the fallback silently drops) are turned into
104
- * an open `{}` schema so the field survives — matching the Zod 4 widening.
105
- *
106
- * Emits refs under `$defs` (via `definitionPath`) to match the Zod 4 path; the
107
- * shared finalize step normalises the fallback's draft-07 tuple form afterwards.
108
- */
109
68
  const convertWithFallback = (source, fallback, droppedTypes) => {
110
- try {
111
- return fallback.convert(source, {
112
- definitionPath: '$defs',
113
- override: (def) => {
114
- const typeName = def?.typeName;
115
- if (typeName === 'ZodDate')
116
- return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
117
- if (typeName === 'ZodBigInt')
118
- return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
119
- const friendly = typeName ? LOSSY_TYPENAMES[typeName] : undefined;
120
- if (friendly) {
121
- droppedTypes.add(friendly);
122
- return {};
123
- }
124
- return fallback.ignoreOverride;
125
- },
126
- });
127
- }
128
- catch (error) {
129
- throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
130
- }
69
+ try {
70
+ return fallback.convert(source, {
71
+ definitionPath: "$defs",
72
+ override: (def) => {
73
+ const typeName = def?.typeName;
74
+ if (typeName === "ZodDate")
75
+ return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
76
+ if (typeName === "ZodBigInt")
77
+ return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
78
+ const friendly = typeName ? LOSSY_TYPENAMES[typeName] : void 0;
79
+ if (friendly) {
80
+ droppedTypes.add(friendly);
81
+ return {};
82
+ }
83
+ return fallback.ignoreOverride;
84
+ }
85
+ });
86
+ } catch (error) {
87
+ throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?
88
+ ${String(error)}`);
89
+ }
131
90
  };
132
- // Keys a branch may carry and still be treated as a plain "closed object" that
133
- // is safe to merge. Anything else (patternProperties, a nested allOf, $ref, a
134
- // conditional, …) makes the merge unsafe, so we leave such an allOf alone.
135
- const CLOSED_OBJECT_KEYS = new Set(['type', 'properties', 'required', 'additionalProperties']);
91
+ const CLOSED_OBJECT_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]);
136
92
  const isClosedObject = (node) => {
137
- if (node === null || typeof node !== 'object' || Array.isArray(node))
138
- return false;
139
- const obj = node;
140
- if (obj['type'] !== 'object' || obj['additionalProperties'] !== false)
141
- return false;
142
- return Object.keys(obj).every((key) => CLOSED_OBJECT_KEYS.has(key));
93
+ if (node === null || typeof node !== "object" || Array.isArray(node))
94
+ return false;
95
+ const obj = node;
96
+ if (obj["type"] !== "object" || obj["additionalProperties"] !== false)
97
+ return false;
98
+ return Object.keys(obj).every((key) => CLOSED_OBJECT_KEYS.has(key));
143
99
  };
144
- /**
145
- * Zod emits an intersection of objects as an `allOf` where every branch carries
146
- * `additionalProperties: false`. That is unsatisfiable — each branch rejects the
147
- * keys the others contribute — even though the Zod intersection accepts the
148
- * combined object. When every `allOf` branch is a closed object we merge them
149
- * into one: properties are unioned (a key in several branches becomes an `allOf`
150
- * of its schemas), `required` is unioned, and `additionalProperties: false` is
151
- * kept over the combined key set. `allOf`s with a non-object branch (e.g. two
152
- * refined strings) are left untouched — those already combine correctly.
153
- */
154
100
  const mergeClosedObjectAllOf = (node) => {
155
- if (node === null || typeof node !== 'object')
156
- return node;
157
- if (Array.isArray(node))
158
- return node.map(mergeClosedObjectAllOf);
159
- const obj = node;
160
- const out = {};
161
- for (const [key, value] of Object.entries(obj))
162
- out[key] = mergeClosedObjectAllOf(value);
163
- const allOf = out['allOf'];
164
- if (Array.isArray(allOf) && allOf.length > 1 && allOf.every(isClosedObject)) {
165
- const properties = {};
166
- const required = new Set();
167
- for (const branch of allOf) {
168
- const props = (branch['properties'] ?? {});
169
- for (const [prop, schema] of Object.entries(props)) {
170
- const bucket = properties[prop];
171
- if (bucket)
172
- bucket.push(schema);
173
- else
174
- properties[prop] = [schema];
175
- }
176
- for (const r of (branch['required'] ?? []))
177
- required.add(r);
178
- }
179
- const mergedProps = {};
180
- for (const [prop, schemas] of Object.entries(properties)) {
181
- mergedProps[prop] = schemas.length === 1 ? schemas[0] : { allOf: schemas };
182
- }
183
- delete out['allOf'];
184
- out['type'] = 'object';
185
- out['properties'] = mergedProps;
186
- if (required.size > 0)
187
- out['required'] = [...required];
188
- out['additionalProperties'] = false;
101
+ if (node === null || typeof node !== "object")
102
+ return node;
103
+ if (Array.isArray(node))
104
+ return node.map(mergeClosedObjectAllOf);
105
+ const obj = node;
106
+ const out = {};
107
+ for (const [key, value] of Object.entries(obj))
108
+ out[key] = mergeClosedObjectAllOf(value);
109
+ const allOf = out["allOf"];
110
+ if (Array.isArray(allOf) && allOf.length > 1 && allOf.every(isClosedObject)) {
111
+ const properties = {};
112
+ const required = /* @__PURE__ */ new Set();
113
+ for (const branch of allOf) {
114
+ const props = branch["properties"] ?? {};
115
+ for (const [prop, schema] of Object.entries(props)) {
116
+ const bucket = properties[prop];
117
+ if (bucket)
118
+ bucket.push(schema);
119
+ else
120
+ properties[prop] = [schema];
121
+ }
122
+ for (const r of branch["required"] ?? [])
123
+ required.add(r);
124
+ }
125
+ const mergedProps = {};
126
+ for (const [prop, schemas] of Object.entries(properties)) {
127
+ mergedProps[prop] = schemas.length === 1 ? schemas[0] : { allOf: schemas };
189
128
  }
190
- return out;
129
+ delete out["allOf"];
130
+ out["type"] = "object";
131
+ out["properties"] = mergedProps;
132
+ if (required.size > 0)
133
+ out["required"] = [...required];
134
+ out["additionalProperties"] = false;
135
+ }
136
+ return out;
191
137
  };
192
- /**
193
- * Shared post-processing applied to both the Zod 4 and Zod 3 conversion output:
194
- * report widened lossy types (a batched warning, or a throw in strict mode),
195
- * drop the dialect marker, normalise draft-07 tuples, restore tuple length
196
- * bounds, and collapse unsatisfiable object intersections.
197
- */
198
138
  const finalize = (json, droppedTypes, strict) => {
199
- // Surface every widened type in one batched, branded notice (or throw in
200
- // strict mode) so the loss is not silent — the same treatment the Valibot
201
- // adapter gives its own unrepresentable constructs.
202
- reportLossyConstructs('Zod', droppedTypes, strict);
203
- // The dialect marker is noise for the generators, which already target 2020-12.
204
- delete json['$schema'];
205
- // The Zod 3 fallback emits draft-07 tuples; rewrite them to 2020-12 form.
206
- normalizeDraftTuples(json);
207
- // Zod under-constrains fixed tuples (bare `prefixItems`); restore their length.
208
- enforceTupleLength(json);
209
- // Collapse an unsatisfiable `allOf` of closed objects (object intersections).
210
- return mergeClosedObjectAllOf(json);
139
+ reportLossyConstructs("Zod", droppedTypes, strict);
140
+ delete json["$schema"];
141
+ normalizeDraftTuples(json);
142
+ enforceTupleLength(json);
143
+ return mergeClosedObjectAllOf(json);
211
144
  };
212
- /**
213
- * Converts a Zod schema into a Draft 2020-12 JSON Schema.
214
- *
215
- * Prefers Zod 4's native `toJSONSchema`. When the installed Zod lacks it (Zod 3),
216
- * falls back to the optional `zod-to-json-schema` package, routing through the
217
- * same `x-mjst` date/bigint mapping and lossy-type reporting. If neither path is
218
- * available, throws a clear error explaining what to install.
219
- */
220
- export const zodToJsonSchema = async (source, options) => {
221
- if (typeof source !== 'object' || source === null) {
222
- const received = source === null ? 'null' : typeof source;
223
- throw new Error(`Zod adapter expected a Zod schema but received ${received}.`);
224
- }
225
- const droppedTypes = new Set();
226
- const toJSONSchema = await loadToJsonSchema();
227
- if (toJSONSchema) {
228
- return finalize(convertWithZod4(source, toJSONSchema, droppedTypes), droppedTypes, options?.strict);
229
- }
230
- const fallback = await loadFallbackConverter();
231
- if (fallback) {
232
- return finalize(convertWithFallback(source, fallback, droppedTypes), droppedTypes, options?.strict);
233
- }
234
- throw new Error("The Zod adapter requires either 'zod' v4+ (for its native toJSONSchema) or the 'zod-to-json-schema' " +
235
- 'package (a fallback for Zod 3). Neither was found — install one in your project.');
145
+ const zodToJsonSchema = async (source, options) => {
146
+ if (typeof source !== "object" || source === null) {
147
+ const received = source === null ? "null" : typeof source;
148
+ throw new Error(`Zod adapter expected a Zod schema but received ${received}.`);
149
+ }
150
+ const droppedTypes = /* @__PURE__ */ new Set();
151
+ const toJSONSchema = await loadToJsonSchema();
152
+ if (toJSONSchema) {
153
+ return finalize(convertWithZod4(source, toJSONSchema, droppedTypes), droppedTypes, options?.strict);
154
+ }
155
+ const fallback = await loadFallbackConverter();
156
+ if (fallback) {
157
+ return finalize(convertWithFallback(source, fallback, droppedTypes), droppedTypes, options?.strict);
158
+ }
159
+ throw new Error("The Zod adapter requires either 'zod' v4+ (for its native toJSONSchema) or the 'zod-to-json-schema' package (a fallback for Zod 3). Neither was found \u2014 install one in your project.");
160
+ };
161
+ export {
162
+ zodToJsonSchema
236
163
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/adapters",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Convert schemas from external libraries (TypeBox, Zod, ...) into JSON Schema for mjst.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,13 +31,13 @@
31
31
  "access": "public"
32
32
  },
33
33
  "scripts": {
34
- "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
34
+ "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f && node ../../scripts/strip-comments.mjs",
35
35
  "types:check": "tsgo -p . --noEmit",
36
36
  "test": "NODE_ENV=production vitest run --root ../.. adapters"
37
37
  },
38
38
  "dependencies": {
39
39
  "json-schema-typed": "^8.0.1",
40
- "@amritk/helpers": "0.13.2"
40
+ "@amritk/helpers": "0.13.3"
41
41
  },
42
42
  "exports": {
43
43
  "./package.json": "./package.json",