-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalk-schema-structure.ts
More file actions
294 lines (263 loc) · 8.38 KB
/
walk-schema-structure.ts
File metadata and controls
294 lines (263 loc) · 8.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import type { z, ZodDiscriminatedUnion } from 'zod';
import { getSchemaChildren } from './schema-structure.js';
// ---------------------------------------------------------------------------
// Path types
// ---------------------------------------------------------------------------
/**
* Represents a single step in navigating through a schema structure.
*
* - `object-key`: navigate into an object property
* - `tuple-index`: navigate into a specific tuple position
* - `discriminated-union-array`: enter an array and pick the unique element
* matching a discriminator value
* - `array`: descend into a plain array's element schema (non-deterministic)
* - `record`: descend into a record's value schema (non-deterministic)
*/
export type SchemaPathElement =
| { type: 'object-key'; key: string }
| { type: 'tuple-index'; index: number }
| {
type: 'discriminated-union-array';
discriminatorKey: string;
value: string;
}
| { type: 'array' }
| { type: 'record' };
// ---------------------------------------------------------------------------
// Visitor types
// ---------------------------------------------------------------------------
/**
* The context passed to visitors during a schema structure walk.
* Carries the current path as `SchemaPathElement[]`.
*/
export interface SchemaStructureWalkContext {
/** The absolute path to the current node in the schema. */
readonly path: SchemaPathElement[];
}
/**
* A visitor that plugs into `walkSchemaStructure`.
*
* Called for every node in the schema tree. If the visitor returns a
* cleanup function, it will be called after all children have been visited —
* similar to the React `useEffect` cleanup pattern.
*/
export interface SchemaStructureVisitor {
visit(
schema: z.ZodType,
ctx: SchemaStructureWalkContext,
): (() => void) | undefined;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Walks a Zod schema structure (without data) invoking registered visitors
* at every schema node.
*
* Unlike `walkDataWithSchema`, this operates on the schema alone.
* Every structural descent produces a path element:
* - Object keys → `object-key`
* - Tuple indices → `tuple-index`
* - Arrays of discriminated unions → `discriminated-union-array` (one per branch)
* - Plain arrays → `array`
* - Records → `record`
* - Discriminated unions on objects are transparent (no path element)
*
* Uses a `Set<z.ZodType>` circular-reference guard with delete-on-backtrack
* so the same schema can appear at different paths.
*/
export function walkSchemaStructure(
schema: z.ZodType,
visitors: readonly SchemaStructureVisitor[],
): void {
walkNode(schema, [], visitors, new Set());
}
// ---------------------------------------------------------------------------
// Internal walker
// ---------------------------------------------------------------------------
function walkNode(
schema: z.ZodType,
path: SchemaPathElement[],
visitors: readonly SchemaStructureVisitor[],
visited: Set<z.ZodType>,
): void {
// Circular reference guard
if (visited.has(schema)) {
return;
}
visited.add(schema);
const ctx: SchemaStructureWalkContext = { path };
// Step 1: Call all visitors, collect any cleanup functions returned.
const cleanups: (() => void)[] = [];
for (const visitor of visitors) {
const cleanup = visitor.visit(schema, ctx);
if (cleanup) cleanups.push(cleanup);
}
// Step 2: Structural descent based on schema children (no data).
const children = getSchemaChildren(schema, undefined, []);
switch (children.kind) {
case 'leaf':
case 'leaf-union': {
break;
}
case 'wrapper': {
walkNode(children.innerSchema, path, visitors, visited);
break;
}
case 'object': {
for (const [key, fieldSchema] of children.entries) {
walkNode(
fieldSchema,
[...path, { type: 'object-key', key }],
visitors,
visited,
);
}
break;
}
case 'array': {
// Check if the element schema is a discriminated union.
// If so, walk each branch with a discriminated-union-array path element.
// Otherwise, walk the element schema with no path element (non-deterministic).
const unwrappedElement = unwrapSchema(children.elementSchema);
const elementChildren = getSchemaChildren(
unwrappedElement,
undefined,
[],
);
if (elementChildren.kind === 'discriminated-union') {
walkDiscriminatedUnionArrayBranches(
unwrappedElement as ZodDiscriminatedUnion,
path,
visitors,
visited,
);
} else {
// Plain array — descend with an array path element
walkNode(
children.elementSchema,
[...path, { type: 'array' }],
visitors,
visited,
);
}
break;
}
case 'discriminated-union': {
// Transparent on objects — walk all branches with the same path.
const unwrapped = unwrapSchema(schema) as ZodDiscriminatedUnion;
for (const option of unwrapped.options as z.ZodType[]) {
walkNode(option, path, visitors, visited);
}
break;
}
case 'tuple': {
for (const [i, itemSchema] of children.items.entries()) {
walkNode(
itemSchema,
[...path, { type: 'tuple-index', index: i }],
visitors,
visited,
);
}
if (children.rest) {
// Rest elements don't have a fixed index; walk without path element
walkNode(children.rest, path, visitors, visited);
}
break;
}
case 'record': {
// Record — descend with a record path element
walkNode(
children.valueSchema,
[...path, { type: 'record' }],
visitors,
visited,
);
break;
}
case 'intersection': {
walkNode(children.left, path, visitors, visited);
walkNode(children.right, path, visitors, visited);
break;
}
}
// Step 3: Run cleanup functions in reverse order (innermost first).
for (let i = cleanups.length - 1; i >= 0; i--) {
cleanups[i]();
}
visited.delete(schema);
}
/**
* Walks each branch of a discriminated union that is an array element,
* pushing a `discriminated-union-array` path element for each branch.
*/
function walkDiscriminatedUnionArrayBranches(
unionSchema: ZodDiscriminatedUnion,
path: SchemaPathElement[],
visitors: readonly SchemaStructureVisitor[],
visited: Set<z.ZodType>,
): void {
const discriminatorKey = unionSchema._zod.def.discriminator;
for (const option of unionSchema.options as z.ZodType[]) {
const literalValue = extractDiscriminatorValue(option, discriminatorKey);
if (literalValue == null) {
// Fallback: walk without path element
walkNode(option, path, visitors, visited);
continue;
}
walkNode(
option,
[
...path,
{
type: 'discriminated-union-array',
discriminatorKey,
value: literalValue,
},
],
visitors,
visited,
);
}
}
/**
* Extracts the literal discriminator value from a union branch schema.
*/
function extractDiscriminatorValue(
branchSchema: z.ZodType,
discriminatorKey: string,
): string | undefined {
const branchChildren = getSchemaChildren(branchSchema, undefined, []);
if (branchChildren.kind !== 'object') {
return undefined;
}
const discEntry = branchChildren.entries.find(
([key]) => key === discriminatorKey,
);
if (!discEntry) {
return undefined;
}
const discSchema = unwrapSchema(discEntry[1]);
const discChildren = getSchemaChildren(discSchema, undefined, []);
if (discChildren.kind !== 'leaf') {
return undefined;
}
const { values } = discSchema._zod.def as unknown as {
values: unknown[];
};
return values[0] as string | undefined;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Unwraps wrapper schemas (optional, nullable, default, etc.) to the underlying schema.
*/
function unwrapSchema(schema: z.ZodType): z.ZodType {
const children = getSchemaChildren(schema, undefined, []);
if (children.kind === 'wrapper') {
return unwrapSchema(children.innerSchema);
}
return schema;
}