@composio/json-schema-to-zod 0.3.4 → 0.4.1

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/dist/v4.d.mts ADDED
@@ -0,0 +1,14 @@
1
+ import { d as ParserOverrideOf, f as RefsOf, i as JsonSchemaObject, l as Serializable, n as InvalidPatternReason, r as JsonSchema, t as InvalidPatternError, u as OptionsOf } from "./compile-pattern-D-zr7Yui.mjs";
2
+ import { ZodType } from "zod/v4";
3
+ export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodType;
4
+ export type ParserOverride = ParserOverrideOf<ZodType>;
5
+ export type JsonSchemaToZodOptions = OptionsOf<ZodType> & {
6
+ /** Leave out the forwarded `format`, `contentEncoding`, `contentMediaType`, and integer annotations. */
7
+ withoutAnnotations?: boolean;
8
+ };
9
+ export type Refs = RefsOf<ZodType>;
10
+ /** A raw shape over zod v4 schemas, for APIs that take a shape rather than an object schema. */
11
+ export type SimpleZodRawShape = Record<string, ZodType>;
12
+ export declare const jsonSchemaToZod: (schema: JsonSchema, options?: JsonSchemaToZodOptions) => ZodType;
13
+ export declare const jsonSchemaToZodShape: (schema: JsonSchema, options?: JsonSchemaToZodOptions) => SimpleZodRawShape;
14
+ export { InvalidPatternError, type InvalidPatternReason, type JsonSchema, type JsonSchemaObject, type Serializable };
package/dist/v4.mjs ADDED
@@ -0,0 +1,246 @@
1
+ import { a as composeGuards, i as buildTuple, n as InvalidPatternError, o as run, r as applyObjectPolicy, s as withPath, t as createConverter } from "./convert-Cte4lEaK.mjs";
2
+ import { version } from "zod/v4/core";
3
+ import * as z from "zod/v4";
4
+
5
+ // src/backend/zod-v4.ts
6
+ const internals = (schema) => schema._zod;
7
+ const isUnmergeable = (error) => error instanceof Error && error.message.startsWith("Unmergable intersection");
8
+ const instrumentedClasses = /* @__PURE__ */ new WeakMap();
9
+ const baseClasses = /* @__PURE__ */ new WeakMap();
10
+ /**
11
+ * A constructor that builds the schema with its own class and then wraps its
12
+ * `_zod.run`. Zod's `clone()` calls `new inst._zod.constr(def)`, so pointing
13
+ * `constr` at this wrapper keeps the behavior through `.describe()`,
14
+ * `.meta()`, `.check()`, and the clones frameworks make. The schema keeps
15
+ * its class: a guarded object is still a `ZodObject` with a `shape`.
16
+ *
17
+ * The wrapper reads its configuration from the definition on every run:
18
+ * `wholeSchemaGuard` checks the source value before the base parse, and an
19
+ * intersection turns the exception zod throws for values its branches
20
+ * cannot merge into an issue, as v3 reports it.
21
+ */
22
+ const instrumentedClass = (Base) => {
23
+ const cached = instrumentedClasses.get(Base);
24
+ if (cached) return cached;
25
+ function Instrumented(def) {
26
+ const inst = new Base(def);
27
+ const zod = internals(inst);
28
+ zod.constr = Instrumented;
29
+ const runAsBase = zod.run;
30
+ zod.run = (payload, ctx) => {
31
+ const fail = (message) => {
32
+ payload.issues.push({
33
+ code: "custom",
34
+ message,
35
+ input: payload.value,
36
+ inst,
37
+ path: []
38
+ });
39
+ return payload;
40
+ };
41
+ const guard = zod.def.wholeSchemaGuard;
42
+ if (guard !== void 0 && ctx.direction !== "backward") {
43
+ const failure = guard(payload.value);
44
+ if (failure !== void 0) return fail(failure);
45
+ }
46
+ if (zod.def.type !== "intersection") return runAsBase(payload, ctx);
47
+ try {
48
+ return runAsBase(payload, ctx);
49
+ } catch (error) {
50
+ if (!isUnmergeable(error)) throw error;
51
+ return fail(error.message);
52
+ }
53
+ };
54
+ return inst;
55
+ }
56
+ const constructor = Instrumented;
57
+ instrumentedClasses.set(Base, constructor);
58
+ instrumentedClasses.set(constructor, constructor);
59
+ baseClasses.set(constructor, Base);
60
+ return constructor;
61
+ };
62
+ /** `schema` rebuilt through the instrumented constructor with `def`, keeping its registry metadata. */
63
+ const rebuild = (schema, def) => {
64
+ const zod = internals(schema);
65
+ const Base = baseClasses.get(zod.constr) ?? zod.constr;
66
+ const rebuilt = new (instrumentedClass(Base))(def);
67
+ const meta = z.globalRegistry.get(schema);
68
+ if (meta) z.globalRegistry.add(rebuilt, meta);
69
+ return rebuilt;
70
+ };
71
+ const attachGuard = (schema, guard) => {
72
+ const zod = internals(schema);
73
+ const wholeSchemaGuard = composeGuards(guard, zod.def.wholeSchemaGuard);
74
+ return rebuild(schema, z.core.util.mergeDefs(zod.def, { wholeSchemaGuard }));
75
+ };
76
+ const intersection = (left, right) => {
77
+ const schema = z.intersection(left, right);
78
+ return rebuild(schema, internals(schema).def);
79
+ };
80
+ /** Wrappers carry the inner description, as every v3 wrapper does through its `_def`. */
81
+ const carryDescription = (inner, wrapper) => {
82
+ const description = z.globalRegistry.get(inner)?.description;
83
+ if (description !== void 0) z.globalRegistry.add(wrapper, { description });
84
+ return wrapper;
85
+ };
86
+ const rewrap = {
87
+ optional: (inner) => z.optional(inner),
88
+ nullable: (inner) => z.nullable(inner),
89
+ readonly: (inner) => z.readonly(inner),
90
+ prefault: (inner, def) => z.prefault(inner, def.defaultValue)
91
+ };
92
+ const isWrapper = (type) => typeof type === "string" && Object.hasOwn(rewrap, type);
93
+ /**
94
+ * Registers `annotations` on the innermost non-wrapper node, rebuilding the
95
+ * wrappers above it since `.meta()` clones. Validation-shaped keys such as
96
+ * `type: "integer"` must not sit on a wrapper: a nullable renders as
97
+ * `anyOf: [inner, null]`, and a `type` beside that `anyOf` would reject null.
98
+ */
99
+ const annotateInnermost = (schema, annotations) => {
100
+ const def = internals(schema).def;
101
+ if (!isWrapper(def.type)) return schema.meta(annotations);
102
+ const inner = annotateInnermost(def.innerType, annotations);
103
+ const wrapper = rewrap[def.type](inner, def);
104
+ const ownMeta = z.globalRegistry.get(schema);
105
+ if (ownMeta) z.globalRegistry.add(wrapper, ownMeta);
106
+ return wrapper;
107
+ };
108
+ const decorate = (schema, decorations) => {
109
+ const { description, annotations } = decorations;
110
+ if (annotations === void 0) return description === void 0 ? schema : schema.describe(description);
111
+ if (!isWrapper(internals(schema).def.type)) return schema.meta(description === void 0 ? annotations : {
112
+ description,
113
+ ...annotations
114
+ });
115
+ const annotated = annotateInnermost(schema, annotations);
116
+ if (description !== void 0) z.globalRegistry.add(annotated, {
117
+ ...z.globalRegistry.get(annotated),
118
+ description
119
+ });
120
+ return annotated;
121
+ };
122
+ /** Issues pushed onto a check payload; the enclosing schemas prefix the path. */
123
+ const sinkFor = (push) => ({
124
+ custom(message, options) {
125
+ push({
126
+ code: "custom",
127
+ message,
128
+ ...withPath(options?.path),
129
+ ...options?.params === void 0 ? {} : { params: options.params }
130
+ });
131
+ },
132
+ unrecognizedKeys(keys, message, options) {
133
+ push({
134
+ code: "unrecognized_keys",
135
+ keys: [...keys],
136
+ message,
137
+ ...withPath(options?.path)
138
+ });
139
+ },
140
+ invalidUnion(message, failures, options) {
141
+ push({
142
+ code: "invalid_union",
143
+ errors: failures.map((failure) => [...failure.issues]),
144
+ message,
145
+ ...withPath(options?.path)
146
+ });
147
+ },
148
+ forward(failure) {
149
+ for (const issue of failure.issues) push({ ...issue });
150
+ }
151
+ });
152
+ let ipProbes;
153
+ let urlProbe;
154
+ const isIp = (value) => {
155
+ ipProbes ??= [z.ipv4(), z.ipv6()];
156
+ return ipProbes.some((probe) => probe.safeParse(value).success);
157
+ };
158
+ const isUrl = (value) => {
159
+ urlProbe ??= z.url();
160
+ return urlProbe.safeParse(value).success;
161
+ };
162
+ const stringFormat = (schema, format, message) => {
163
+ const string = schema;
164
+ switch (format) {
165
+ case "email": return string.email(message);
166
+ case "ip": return string.refine(isIp, message);
167
+ case "ipv4": return string.ipv4(message);
168
+ case "ipv6": return string.ipv6(message);
169
+ case "uri": return string.refine(isUrl, message);
170
+ case "uuid": return string.guid(message);
171
+ case "date-time": return string.datetime({
172
+ offset: true,
173
+ error: message
174
+ });
175
+ case "time": return string.time(message);
176
+ case "date": return string.date(message);
177
+ case "duration": return string.duration(message);
178
+ }
179
+ };
180
+ /** Zod v4 output: metadata in the global registry, refinements as checks, the guard as a run wrapper. */
181
+ const zodV4Backend = {
182
+ isSchema: (value) => value instanceof z.ZodType,
183
+ isNever: (schema) => schema instanceof z.ZodNever,
184
+ any: () => z.any(),
185
+ never: () => z.never(),
186
+ boolean: () => z.boolean(),
187
+ null: () => z.null(),
188
+ string: () => z.string(),
189
+ number: () => z.number(),
190
+ literal: (value) => z.literal(value),
191
+ enum: (values) => z.enum(values),
192
+ predicate: (test) => z.any().refine(test),
193
+ stringFormat,
194
+ base64: (schema, message) => schema.base64(message),
195
+ regex: (schema, pattern, message) => schema.regex(pattern, message),
196
+ integer: (schema, message) => schema.refine((value) => Number.isInteger(value), message),
197
+ bound: (schema, kind, value, message) => schema[kind](value, message),
198
+ array: (item) => z.array(item),
199
+ minItems: (schema, count, message) => schema.min(count, message),
200
+ maxItems: (schema, count, message) => schema.max(count, message),
201
+ tuple: (items, rest) => buildTuple(z.tuple(items), rest),
202
+ object: (shape, policy) => applyObjectPolicy(z.object(shape), policy),
203
+ record: (value) => z.record(z.string(), value),
204
+ union: (options) => z.union(options),
205
+ intersection,
206
+ optional: (schema) => carryDescription(schema, schema.optional()),
207
+ nullable: (schema) => carryDescription(schema, schema.nullable()),
208
+ withDefault: (schema, value) => carryDescription(schema, schema.prefault(value)),
209
+ readonly: (schema) => carryDescription(schema, schema.readonly()),
210
+ decorate,
211
+ refine: (schema, test, message) => schema.refine((value) => test(value), message),
212
+ superRefine: (schema, check) => schema.superRefine((value, ctx) => check(value, sinkFor((issue) => ctx.addIssue(issue)))),
213
+ rewrite: (schema, fn) => schema.check((payload) => {
214
+ const sink = sinkFor((issue) => payload.issues.push({
215
+ input: payload.value,
216
+ continue: true,
217
+ ...issue
218
+ }));
219
+ payload.value = fn(payload.value, sink);
220
+ }),
221
+ run,
222
+ attachGuard
223
+ };
224
+
225
+ // src/backend/zod-v4-floor.ts
226
+ /**
227
+ * The first zod release whose `zod/v4` shares its metadata registry through
228
+ * `globalThis.__zod_globalRegistry`. Below it, two copies of zod in one
229
+ * process keep separate registries, and the descriptions and annotations the
230
+ * v4 builder writes are invisible to a serializer loaded from the other copy.
231
+ */
232
+ const ZOD_V4_FLOOR = {
233
+ major: 4,
234
+ minor: 1,
235
+ patch: 13
236
+ };
237
+ const formatZodVersion = (version) => `${version.major}.${version.minor}.${version.patch}`;
238
+ const meetsZodV4Floor = (version) => version.major !== ZOD_V4_FLOOR.major ? version.major > ZOD_V4_FLOOR.major : version.minor !== ZOD_V4_FLOOR.minor ? version.minor > ZOD_V4_FLOOR.minor : version.patch >= ZOD_V4_FLOOR.patch;
239
+
240
+ // src/v4.ts
241
+ if (!meetsZodV4Floor(version)) throw new Error(`@composio/json-schema-to-zod/v4 requires zod >= ${formatZodVersion(ZOD_V4_FLOOR)}; found ${formatZodVersion(version)}`);
242
+ const converter = createConverter(zodV4Backend);
243
+ const jsonSchemaToZod = (schema, options = {}) => converter.jsonSchemaToZod(schema, options);
244
+ const jsonSchemaToZodShape = (schema, options = {}) => converter.jsonSchemaToZodShape(schema, options);
245
+
246
+ export { InvalidPatternError, jsonSchemaToZod, jsonSchemaToZodShape };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@composio/json-schema-to-zod",
3
- "version": "0.3.4",
3
+ "version": "0.4.1",
4
4
  "description": "",
5
5
  "main": "dist/index.mjs",
6
6
  "type": "module",
@@ -23,6 +23,10 @@
23
23
  ".": {
24
24
  "types": "./dist/index.d.mts",
25
25
  "default": "./dist/index.mjs"
26
+ },
27
+ "./v4": {
28
+ "types": "./dist/v4.d.mts",
29
+ "default": "./dist/v4.mjs"
26
30
  }
27
31
  },
28
32
  "files": [
@@ -36,22 +40,27 @@
36
40
  ],
37
41
  "license": "ISC",
38
42
  "devDependencies": {
43
+ "@ai-sdk/provider-utils": "^5.0.76",
44
+ "@langchain/core": "^1.3.6",
39
45
  "@types/json-schema": "^7.0.15",
40
- "@types/node": "^26.6.2",
46
+ "@types/node": "^26.6.6",
41
47
  "ajv": "^8.20.0",
42
48
  "fast-check": "^4.10.2",
43
- "tsdown": "^0.23.0",
49
+ "tsdown": "^0.23.7",
44
50
  "typescript": "^7.0.2",
45
- "vitest": "^5.0.1",
46
- "zod": "^4.5.4"
51
+ "vitest": "^5.1.0",
52
+ "zod": "^4.6.7",
53
+ "zod-3-25": "npm:zod@3.25.76",
54
+ "zod-floor": "npm:zod@4.1.13",
55
+ "zod-to-json-schema": "^3.25.2"
47
56
  },
48
57
  "peerDependencies": {
49
58
  "zod": ">=3.25.76 <5"
50
59
  },
51
60
  "dependencies": {
52
- "@cfworker/json-schema": "^4.1.1",
61
+ "@cfworker/json-schema": "^4.1.6",
53
62
  "dequal": "^2.0.3",
54
- "re2js": "^2.8.6"
63
+ "re2js": "^2.9.1"
55
64
  },
56
65
  "scripts": {
57
66
  "clean": "git clean -xdf node_modules",