Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

transforms.ts

124 lines5.3 KB

1/**
2 * Recursively strip `null` values from a JSON-shaped value so optional fields
3 * present as `null` in OpenAI-compatible structured output round-trip cleanly
4 * through Zod schemas that expect `undefined` (or absence) instead of `null`.
5 *
6 * Behaviour:
7 * - Top-level `null` becomes `undefined`.
8 * - Object properties whose value is `null` are removed entirely (so
9 * `'key' in result` is `false`). Zod's `.optional()` treats absent keys
10 * the same as `undefined`, which is the round-trip we want; setting the
11 * key to `undefined` would still register the property in `Object.keys`
12 * and break some `.strict()`/`Object.keys`-based callers.
13 * - Array elements recurse via this same function; a `null` element therefore
14 * becomes `undefined` (top-level rule), preserving array length so
15 * positional indices stay stable. Don't rely on element-`null` round-trip.
16 *
17 * Scope: designed for `JSON.parse` output (plain objects, arrays, strings,
18 * numbers, booleans, null). Class instances, `Date`, `Map`, `Set`, etc. are
19 * NOT preserved — they're walked via `Object.entries`, which sees only own
20 * enumerable string-keyed properties. Native built-ins like `Date`/`Map`/`Set`
21 * therefore become `{}`; arbitrary class instances become a plain-object
22 * snapshot of just their own enumerable string properties. Don't pass
23 * non-JSON values.
24 *
25 * Schema-blind: strips EVERY null, including ones a `.nullable()` field
26 * legitimately allows. When the original schema is available, prefer
27 * {@link undoNullWidening}, which only strips the nulls strict-mode widening
28 * synthesized.
29 */
30export function transformNullsToUndefined<T>(obj: T): T {
31 if (obj === null) {
32 return undefined as T
33 }
34​
35 if (typeof obj !== 'object') {
36 return obj
37 }
38​
39 if (Array.isArray(obj)) {
40 return obj.map((item) => transformNullsToUndefined(item)) as T
41 }
42​
43 // `Object.fromEntries` keeps an own key named `__proto__`. An assignment
44 // `result['__proto__'] = x` would set the prototype instead.
45 return Object.fromEntries(
46 Object.entries(obj as Record<string, unknown>)
47 .filter(([, value]) => value !== null)
48 .map(([key, value]) => [key, transformNullsToUndefined(value)]),
49 ) as T
51​
52/**
53 * Records exactly where strict-mode null-widening synthesized a `null`, so
54 * {@link undoNullWidening} can strip those nulls and leave every other one
55 * untouched. Built by the widening pass itself as it walks the schema (see
56 * `convertSchemaForStructuredOutput` in `@tanstack/ai`), so it can never drift
57 * from what was actually widened — no value-shape guessing required.
58 *
59 * - `widened`: the widening pass added `null` to THIS position's type (an
60 * optional field promoted to `required` + nullable). A `null` here is
61 * synthetic → strip it. Positions a `.nullable()`/`.nullish()` field already
62 * allowed carry no `widened` mark, so their nulls survive.
63 * - `properties` / `items`: descend into a nested object / array to reach
64 * widened positions deeper in the tree. Only objects and arrays the widener
65 * actually recursed into appear here.
66 */
67export type NullWideningMap = {
68 widened?: boolean
69 properties?: Record<string, NullWideningMap>
70 items?: NullWideningMap | Array<NullWideningMap>
72​
73function walk(value: unknown, map: NullWideningMap | undefined): unknown {
74 if (value === null) {
75 // Strip only nulls the widening pass synthesized (marked `widened`); keep
76 // every genuine `.nullable()`/`.nullish()` null and every null the map
77 // doesn't describe.
78 return map?.widened ? undefined : null
79 }
80 if (typeof value !== 'object' || !map) return value
81​
82 if (Array.isArray(value)) {
83 const { items } = map
84 if (!items) return value
85 // Tuple maps (`items: [a, b, …]`) describe each position separately;
86 // a single `items` map applies to every element.
87 return Array.isArray(items)
88 ? value.map((item, index) => walk(item, items[index]))
89 : value.map((item) => walk(item, items))
90 }
91​
92 const { properties } = map
93 if (!properties) return value
94 const result: Array<[string, unknown]> = []
95 for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
96 const next = walk(child, properties[key])
97 // A synthesized null collapsed to undefined → omit the key so the field
98 // reads as absent (`key in result === false`), matching how `.optional()`
99 // treats absence.
100 if (next === undefined) continue
101 result.push([key, next])
102 }
103 // `Object.fromEntries` keeps an own key named `__proto__`.
104 return Object.fromEntries(result)
106​
107/**
108 * Inverse of strict-mode null-widening for structured output.
109 *
110 * To satisfy OpenAI-style strict schemas, optional fields are widened to
111 * `required` with `null` added to their type, so the provider returns `null`
112 * for an absent optional. Validating that `null` against the ORIGINAL schema
113 * fails, because `.optional()` means `T | undefined`, not `T | null`.
114 *
115 * Unlike {@link transformNullsToUndefined}, this consults a {@link
116 * NullWideningMap} recorded by the widening pass and drops ONLY the nulls that
117 * pass actually synthesized. Nulls a `.nullable()`/`.nullish()` field genuinely
118 * allows are preserved, so both `optional` and `nullable` fields round-trip
119 * correctly. With no map, the value is returned untouched.
120 */
121export function undoNullWidening<T>(value: T, map?: NullWideningMap): T {
122 if (!map) return value
123 return walk(value, map) as T