@adecore/agent-contracts 0.65.1 → 0.66.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/dist/agent.js +2 -1
- package/dist/chat.d.ts +29 -3
- package/dist/chat.js +24 -13
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/model.js +2 -1
- package/dist/task.js +5 -4
- package/dist/tolerance.d.ts +67 -0
- package/dist/tolerance.js +11 -0
- package/dist/usage.js +4 -1
- package/dist/wire-stamps.d.ts +52 -0
- package/dist/wire-stamps.js +308 -0
- package/package.json +8 -3
- package/src/agent.ts +2 -1
- package/src/chat.ts +87 -39
- package/src/index.ts +21 -0
- package/src/model.ts +2 -1
- package/src/task.ts +5 -4
- package/src/tolerance.ts +104 -0
- package/src/usage.ts +4 -1
- package/src/wire-stamps.ts +472 -0
package/src/tolerance.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { AgentStatus } from './agent.ts';
|
|
3
|
+
import type {
|
|
4
|
+
ChatApprovalItem,
|
|
5
|
+
ChatBackgroundTask,
|
|
6
|
+
ChatEvent,
|
|
7
|
+
ChatGoalStatus,
|
|
8
|
+
ChatItem,
|
|
9
|
+
ChatQuestionItem,
|
|
10
|
+
ChatRequestKind,
|
|
11
|
+
ChatTurnLimit,
|
|
12
|
+
ChatUnknownEvent,
|
|
13
|
+
ChatUnknownItem
|
|
14
|
+
} from './chat.ts';
|
|
15
|
+
import type { RuntimeMode } from './model.ts';
|
|
16
|
+
import type { Task, TaskResult, TaskStatus } from './task.ts';
|
|
17
|
+
import type { UsageProvider } from './usage.ts';
|
|
18
|
+
import { readStamped, type WireDegradation } from './wire-stamps.ts';
|
|
19
|
+
|
|
20
|
+
export { lossyItems, openUnion, openValues, wireStampOf, wireStampsIn, type WireDegradation, type WireStamp, type WireStampAt } from './wire-stamps.ts';
|
|
21
|
+
|
|
22
|
+
declare const unknownWord: unique symbol;
|
|
23
|
+
|
|
24
|
+
/* A word of a newer host in an open vocabulary: a string, but none of the words this version can switch on. */
|
|
25
|
+
export type UnknownWord = string & { readonly [unknownWord]: true };
|
|
26
|
+
|
|
27
|
+
/* Each open union by the name it is stamped with: the type a strict parse gives and what a member this version cannot read becomes. */
|
|
28
|
+
export type OpenUnionTable = Record<string, { readonly known: unknown; readonly unknown: unknown }>;
|
|
29
|
+
|
|
30
|
+
/* Each open vocabulary by the name it is stamped with, as a strict parse types it. */
|
|
31
|
+
export type OpenWordTable = Record<string, unknown>;
|
|
32
|
+
|
|
33
|
+
export type OpenUnions = {
|
|
34
|
+
ChatItem: { known: ChatItem; unknown: ChatUnknownItem };
|
|
35
|
+
ChatEvent: { known: ChatEvent; unknown: ChatUnknownEvent };
|
|
36
|
+
ChatPendingRequest: { known: ChatApprovalItem | ChatQuestionItem; unknown: ChatUnknownItem };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type OpenWords = {
|
|
40
|
+
AgentStatus: AgentStatus;
|
|
41
|
+
ChatBackgroundTaskKind: ChatBackgroundTask['kind'];
|
|
42
|
+
ChatGoalStatus: ChatGoalStatus;
|
|
43
|
+
ChatRequestKind: ChatRequestKind;
|
|
44
|
+
ChatTurnLimitKind: ChatTurnLimit['kind'];
|
|
45
|
+
RuntimeMode: RuntimeMode;
|
|
46
|
+
TaskPauseKind: NonNullable<Task['paused']>['kind'];
|
|
47
|
+
TaskResultSource: TaskResult['source'];
|
|
48
|
+
TaskStatus: TaskStatus;
|
|
49
|
+
TaskWake: Task['wake'];
|
|
50
|
+
UsageProvider: UsageProvider;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
54
|
+
|
|
55
|
+
type UnknownMemberOf<T, Unions extends OpenUnionTable> = {
|
|
56
|
+
[K in keyof Unions]: Same<T, Unions[K]['known']> extends true ? Unions[K]['unknown'] : never;
|
|
57
|
+
}[keyof Unions];
|
|
58
|
+
|
|
59
|
+
type IsOpenWord<T, Words extends OpenWordTable> = true extends { [K in keyof Words]: Same<T, Words[K]> }[keyof Words] ? true : false;
|
|
60
|
+
|
|
61
|
+
// A mapped type over a type parameter keeps an array an array and a tuple a tuple.
|
|
62
|
+
type TolerantShape<T, Unions extends OpenUnionTable, Words extends OpenWordTable, Depth extends unknown[]> = T extends object
|
|
63
|
+
? { [K in keyof T]: TolerantAt<T[K], Unions, Words, [...Depth, unknown]> }
|
|
64
|
+
: T;
|
|
65
|
+
|
|
66
|
+
/*
|
|
67
|
+
* Stops this deep, which no stamped path reaches, so a recursive type such as a tree of UI blocks ends instead of
|
|
68
|
+
* unfolding without end.
|
|
69
|
+
*/
|
|
70
|
+
type MaxDepth = 12;
|
|
71
|
+
|
|
72
|
+
type TolerantAt<T, Unions extends OpenUnionTable, Words extends OpenWordTable, Depth extends unknown[]> = Depth['length'] extends MaxDepth
|
|
73
|
+
? T
|
|
74
|
+
: [UnknownMemberOf<NonNullable<T>, Unions>] extends [never]
|
|
75
|
+
? IsOpenWord<NonNullable<T>, Words> extends true
|
|
76
|
+
? T | UnknownWord
|
|
77
|
+
: TolerantShape<T, Unions, Words, Depth>
|
|
78
|
+
: TolerantShape<NonNullable<T>, Unions, Words, Depth> | UnknownMemberOf<NonNullable<T>, Unions> | Extract<T, null | undefined>;
|
|
79
|
+
|
|
80
|
+
/*
|
|
81
|
+
* `T` as `readTolerant` may hand it over with these tables: an open union also holds its unknown member, and an open
|
|
82
|
+
* vocabulary also an `UnknownWord`. Types match a table by being the same type, never by one being part of the other.
|
|
83
|
+
*/
|
|
84
|
+
export type TolerantWith<T, Unions extends OpenUnionTable, Words extends OpenWordTable> = TolerantAt<T, Unions, Words, []>;
|
|
85
|
+
|
|
86
|
+
/* `T` as `readTolerant` may hand it over with the open unions and vocabularies of these contracts. */
|
|
87
|
+
export type Tolerant<T> = TolerantWith<T, OpenUnions, OpenWords>;
|
|
88
|
+
|
|
89
|
+
export type ToleratedRead<T> =
|
|
90
|
+
| { readonly success: true; readonly data: T; readonly degraded: readonly WireDegradation[] }
|
|
91
|
+
| { readonly success: false; readonly error: z.ZodError };
|
|
92
|
+
|
|
93
|
+
/*
|
|
94
|
+
* Reads what a host sent the way a client of an older version should: the strict parse when it holds, otherwise
|
|
95
|
+
* every open union, lossy list and open vocabulary stamped below `schema` degrades in place, and `degraded` says
|
|
96
|
+
* where. A host reading what a client sent keeps parsing strictly. An app that stamps schemas of its own passes its
|
|
97
|
+
* tables joined with these (`OpenUnions & AppUnions`) to type what it reads.
|
|
98
|
+
*/
|
|
99
|
+
export function readTolerant<S extends z.core.$ZodType, Unions extends OpenUnionTable = OpenUnions, Words extends OpenWordTable = OpenWords>(
|
|
100
|
+
schema: S,
|
|
101
|
+
input: unknown
|
|
102
|
+
): ToleratedRead<TolerantWith<z.output<S>, Unions, Words>> {
|
|
103
|
+
return readStamped(schema, input) as ToleratedRead<TolerantWith<z.output<S>, Unions, Words>>;
|
|
104
|
+
}
|
package/src/usage.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { ProviderAccountIdSchema } from './provider-accounts.ts';
|
|
3
|
+
import { openValues } from './wire-stamps.ts';
|
|
3
4
|
|
|
4
5
|
/* The providers whose usage the daemon reads: the CLIs' own records, and the log a host keeps of what it calls itself. A subset of `AgentKindSchema`: it grows with the readers. */
|
|
5
|
-
export const UsageProviderSchema = z.enum(['claude', 'codex', 'nanogpt', 'grok', 'copilot', 'anthropic-claude-api'])
|
|
6
|
+
export const UsageProviderSchema = openValues(z.enum(['claude', 'codex', 'nanogpt', 'grok', 'copilot', 'anthropic-claude-api']), 'UsageProvider', {
|
|
7
|
+
words: 'strings'
|
|
8
|
+
});
|
|
6
9
|
export type UsageProvider = z.infer<typeof UsageProviderSchema>;
|
|
7
10
|
|
|
8
11
|
export const USAGE_PROVIDERS = UsageProviderSchema.options;
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* What a newer host may add to a schema without an older client refusing the whole reply or event. A stamp is only
|
|
5
|
+
* metadata: a strict parse ignores it, so a host keeps refusing what it receives. Only a client reading what a host
|
|
6
|
+
* sent applies it, through `readTolerant`, and a generator for another language can read the same stamps.
|
|
7
|
+
*/
|
|
8
|
+
export type WireStamp =
|
|
9
|
+
| {
|
|
10
|
+
readonly open: 'union';
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly tag: string;
|
|
13
|
+
readonly base: readonly string[];
|
|
14
|
+
}
|
|
15
|
+
| { readonly open: 'items' }
|
|
16
|
+
| {
|
|
17
|
+
readonly open: 'values';
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly words: 'cases' | 'strings';
|
|
20
|
+
readonly known: readonly string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface WireStampAt {
|
|
24
|
+
readonly path: readonly (string | number)[];
|
|
25
|
+
readonly stamp: WireStamp;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/* What `readTolerant` gave up on to read the rest, at the path of the input it happened at. */
|
|
29
|
+
export type WireDegradation =
|
|
30
|
+
| { readonly kind: 'unknown-member'; readonly path: readonly (string | number)[]; readonly name: string; readonly tag: string }
|
|
31
|
+
| { readonly kind: 'dropped-element'; readonly path: readonly (string | number)[] }
|
|
32
|
+
| { readonly kind: 'unknown-word'; readonly path: readonly (string | number)[]; readonly name: string; readonly word: string };
|
|
33
|
+
|
|
34
|
+
// Keyed by the schema object, so the stamps hold whichever copy of zod built the schema.
|
|
35
|
+
const stamps = new WeakMap<object, WireStamp>();
|
|
36
|
+
// Whether a schema has a stamp at or below it; a host may stamp its own schemas after these, so a new stamp starts it over.
|
|
37
|
+
let stampedBelow = new WeakMap<object, boolean>();
|
|
38
|
+
|
|
39
|
+
function stamp(schema: object, value: WireStamp): void {
|
|
40
|
+
stamps.set(schema, value);
|
|
41
|
+
stampedBelow = new WeakMap();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/*
|
|
45
|
+
* A union a newer host may add a member to, or a value inside a member. A member that does not read keeps its place as
|
|
46
|
+
* `{ [tag]: 'unknown', ...base, raw }` once its tag is a string and every field in `base` reads with the first member's schema.
|
|
47
|
+
*/
|
|
48
|
+
export function openUnion<S extends z.core.$ZodType>(schema: S, name: string, options: { readonly tag: string; readonly base: readonly string[] }): S {
|
|
49
|
+
const members = optionsOf(schema);
|
|
50
|
+
|
|
51
|
+
if (members === null || members.some((member) => propValues(member, options.tag) === null)) {
|
|
52
|
+
throw new Error(`${name} cannot be an open union: every member needs a ${options.tag} literal`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (members.some((member) => propValues(member, options.tag)?.has('unknown'))) {
|
|
56
|
+
throw new Error(`${name} cannot be an open union: no member may be tagged unknown`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
stamp(schema, { open: 'union', name, tag: options.tag, base: [...options.base] });
|
|
60
|
+
|
|
61
|
+
return schema;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/* A list that leaves out an element it cannot read, so one newer entry does not empty the page it is on. */
|
|
65
|
+
export function lossyItems<S extends z.core.$ZodType>(schema: S): S {
|
|
66
|
+
if (defOf(schema).type !== 'array') {
|
|
67
|
+
throw new Error('Only an array can leave out an element');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
stamp(schema, { open: 'items' });
|
|
71
|
+
|
|
72
|
+
return schema;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/*
|
|
76
|
+
* A vocabulary a newer host may add a word to. A word this version does not know is kept as it came. `words` says how a
|
|
77
|
+
* typed client models the known ones: as `cases` beside an unknown one, or as plain `strings`. A string schema is already
|
|
78
|
+
* open, so it takes the stamp only to name its `known` words for such a client, which reads them as `strings`.
|
|
79
|
+
*/
|
|
80
|
+
export function openValues<S extends z.core.$ZodType>(
|
|
81
|
+
schema: S,
|
|
82
|
+
name: string,
|
|
83
|
+
options: { readonly words?: 'cases' | 'strings'; readonly known?: readonly string[] } = {}
|
|
84
|
+
): S {
|
|
85
|
+
const def = defOf(schema);
|
|
86
|
+
|
|
87
|
+
if (def.type === 'string' && options.known !== undefined) {
|
|
88
|
+
stamp(schema, { open: 'values', name, words: 'strings', known: [...options.known] });
|
|
89
|
+
|
|
90
|
+
return schema;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (def.type !== 'enum' || def.entries === undefined) {
|
|
94
|
+
throw new Error(`${name} cannot take open values: only an enum can, or a string that names its known words`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
stamp(schema, { open: 'values', name, words: options.words ?? 'cases', known: [...(options.known ?? Object.values(def.entries).map(String))] });
|
|
98
|
+
|
|
99
|
+
return schema;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/* The stamp on this very schema object, for a generator that walks a schema itself. */
|
|
103
|
+
export function wireStampOf(schema: object): WireStamp | undefined {
|
|
104
|
+
return stamps.get(schema);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/* Every stamp reachable from `schema`, with the path of the input it applies at (`[]` for an array element, `{}` for a record value). */
|
|
108
|
+
export function wireStampsIn(schema: z.core.$ZodType): WireStampAt[] {
|
|
109
|
+
const found: WireStampAt[] = [];
|
|
110
|
+
const seen = new Set<object>();
|
|
111
|
+
|
|
112
|
+
const visit = (node: z.core.$ZodType, path: (string | number)[]): void => {
|
|
113
|
+
if (seen.has(node)) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
seen.add(node);
|
|
118
|
+
|
|
119
|
+
const stamp = stamps.get(node);
|
|
120
|
+
|
|
121
|
+
if (stamp !== undefined) {
|
|
122
|
+
found.push({ path, stamp });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
for (const [key, child] of childrenOf(node)) {
|
|
126
|
+
visit(child, key === null ? path : [...path, key]);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
seen.delete(node);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
visit(schema, []);
|
|
133
|
+
|
|
134
|
+
return found;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export type StampedRead =
|
|
138
|
+
| { readonly success: true; readonly data: unknown; readonly degraded: readonly WireDegradation[] }
|
|
139
|
+
| { readonly success: false; readonly error: z.ZodError };
|
|
140
|
+
|
|
141
|
+
/*
|
|
142
|
+
* Reads what a host sent: strictly when that works, so a reply this version fully knows comes out exactly as a strict
|
|
143
|
+
* parse makes it. Otherwise each stamp degrades the nearest open container around what failed and the rest is read as
|
|
144
|
+
* strictly as before; what has no open container around it refuses the whole input, as a strict parse does.
|
|
145
|
+
*/
|
|
146
|
+
export function readStamped(schema: z.core.$ZodType, input: unknown): StampedRead {
|
|
147
|
+
const strict = z.safeParse(schema, input);
|
|
148
|
+
|
|
149
|
+
if (strict.success) {
|
|
150
|
+
return { success: true, data: strict.data, degraded: [] };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const degraded: WireDegradation[] = [];
|
|
154
|
+
const read = walk(schema, input, [], degraded);
|
|
155
|
+
|
|
156
|
+
return read === FAILED ? { success: false, error: strict.error } : { success: true, data: read.value, degraded };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface Def {
|
|
160
|
+
readonly type: string;
|
|
161
|
+
readonly shape?: Record<string, z.core.$ZodType>;
|
|
162
|
+
readonly catchall?: z.core.$ZodType;
|
|
163
|
+
readonly element?: z.core.$ZodType;
|
|
164
|
+
readonly innerType?: z.core.$ZodType;
|
|
165
|
+
readonly options?: readonly z.core.$ZodType[];
|
|
166
|
+
readonly discriminator?: string;
|
|
167
|
+
readonly keyType?: z.core.$ZodType;
|
|
168
|
+
readonly valueType?: z.core.$ZodType;
|
|
169
|
+
readonly entries?: Record<string, string | number>;
|
|
170
|
+
readonly checks?: readonly unknown[];
|
|
171
|
+
readonly getter?: () => z.core.$ZodType;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const FAILED = Symbol('failed');
|
|
175
|
+
|
|
176
|
+
type Walked = { readonly value: unknown } | typeof FAILED;
|
|
177
|
+
|
|
178
|
+
function defOf(schema: z.core.$ZodType): Def {
|
|
179
|
+
return schema._zod.def as unknown as Def;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function optionsOf(schema: z.core.$ZodType): readonly z.core.$ZodType[] | null {
|
|
183
|
+
const def = defOf(schema);
|
|
184
|
+
|
|
185
|
+
return def.type === 'union' && def.options !== undefined ? def.options : null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function propValues(member: z.core.$ZodType, tag: string): ReadonlySet<unknown> | null {
|
|
189
|
+
return (member._zod as { propValues?: Record<string, Set<unknown>> }).propValues?.[tag] ?? null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// The schemas a value of `schema` is read with, by the key of the input they read (`null` for a wrapper of the same value).
|
|
193
|
+
function childrenOf(schema: z.core.$ZodType): [string | number | null, z.core.$ZodType][] {
|
|
194
|
+
const def = defOf(schema);
|
|
195
|
+
|
|
196
|
+
switch (def.type) {
|
|
197
|
+
case 'object':
|
|
198
|
+
return [...Object.entries(def.shape ?? {}), ...(def.catchall === undefined ? [] : [['{}', def.catchall] as [string, z.core.$ZodType]])];
|
|
199
|
+
case 'array':
|
|
200
|
+
return def.element === undefined ? [] : [['[]', def.element]];
|
|
201
|
+
case 'record':
|
|
202
|
+
return def.valueType === undefined ? [] : [['{}', def.valueType]];
|
|
203
|
+
case 'union':
|
|
204
|
+
return (def.options ?? []).map((option) => [null, option]);
|
|
205
|
+
case 'optional':
|
|
206
|
+
case 'nullable':
|
|
207
|
+
case 'default':
|
|
208
|
+
case 'prefault':
|
|
209
|
+
case 'readonly':
|
|
210
|
+
case 'nonoptional':
|
|
211
|
+
case 'catch':
|
|
212
|
+
return def.innerType === undefined ? [] : [[null, def.innerType]];
|
|
213
|
+
case 'lazy':
|
|
214
|
+
return def.getter === undefined ? [] : [[null, def.getter()]];
|
|
215
|
+
default:
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function hasStamp(schema: z.core.$ZodType): boolean {
|
|
221
|
+
const known = stampedBelow.get(schema);
|
|
222
|
+
|
|
223
|
+
if (known !== undefined) {
|
|
224
|
+
return known;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const result = wireStampsIn(schema).length > 0;
|
|
228
|
+
|
|
229
|
+
stampedBelow.set(schema, result);
|
|
230
|
+
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function strictly(schema: z.core.$ZodType, input: unknown): Walked {
|
|
235
|
+
const parsed = z.safeParse(schema, input);
|
|
236
|
+
|
|
237
|
+
return parsed.success ? { value: parsed.data } : FAILED;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
241
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function walk(schema: z.core.$ZodType, input: unknown, path: (string | number)[], degraded: WireDegradation[]): Walked {
|
|
245
|
+
if (!hasStamp(schema)) {
|
|
246
|
+
return strictly(schema, input);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const stamp = stamps.get(schema);
|
|
250
|
+
|
|
251
|
+
if (stamp?.open === 'values') {
|
|
252
|
+
const read = strictly(schema, input);
|
|
253
|
+
|
|
254
|
+
// A string schema takes any word itself, so only an enum has a word to keep that a strict parse refused.
|
|
255
|
+
if (read !== FAILED || typeof input !== 'string' || defOf(schema).type !== 'enum') {
|
|
256
|
+
return read;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
degraded.push({ kind: 'unknown-word', path, name: stamp.name, word: input });
|
|
260
|
+
|
|
261
|
+
return { value: input };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (stamp?.open === 'union') {
|
|
265
|
+
return walkOpenUnion(schema, stamp, input, path, degraded);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const def = defOf(schema);
|
|
269
|
+
|
|
270
|
+
// A check over a whole container cannot run on a value with a degraded part, so such a container stays strict.
|
|
271
|
+
if ((def.checks?.length ?? 0) > 0) {
|
|
272
|
+
return strictly(schema, input);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
switch (def.type) {
|
|
276
|
+
case 'object':
|
|
277
|
+
return walkObject(def, input, path, degraded);
|
|
278
|
+
case 'array':
|
|
279
|
+
// A list of an open union leaves out a member without the fields every member shares, which has no place to keep.
|
|
280
|
+
return walkArray(def, stamp?.open === 'items' || (def.element !== undefined && stamps.get(def.element)?.open === 'union'), input, path, degraded);
|
|
281
|
+
case 'record':
|
|
282
|
+
return walkRecord(def, input, path, degraded);
|
|
283
|
+
case 'union':
|
|
284
|
+
return walkUnion(def, input, path, degraded);
|
|
285
|
+
case 'optional':
|
|
286
|
+
return input === undefined ? { value: undefined } : walk(def.innerType!, input, path, degraded);
|
|
287
|
+
case 'nullable':
|
|
288
|
+
return input === null ? { value: null } : walk(def.innerType!, input, path, degraded);
|
|
289
|
+
case 'default':
|
|
290
|
+
case 'prefault':
|
|
291
|
+
return input === undefined ? strictly(schema, input) : walk(def.innerType!, input, path, degraded);
|
|
292
|
+
case 'readonly':
|
|
293
|
+
case 'nonoptional':
|
|
294
|
+
return walk(def.innerType!, input, path, degraded);
|
|
295
|
+
case 'lazy':
|
|
296
|
+
return walk(def.getter!(), input, path, degraded);
|
|
297
|
+
default:
|
|
298
|
+
return strictly(schema, input);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function walkOpenUnion(
|
|
303
|
+
schema: z.core.$ZodType,
|
|
304
|
+
stamp: Extract<WireStamp, { open: 'union' }>,
|
|
305
|
+
input: unknown,
|
|
306
|
+
path: (string | number)[],
|
|
307
|
+
degraded: WireDegradation[]
|
|
308
|
+
): Walked {
|
|
309
|
+
const word = isRecord(input) ? input[stamp.tag] : undefined;
|
|
310
|
+
|
|
311
|
+
if (!isRecord(input) || typeof word !== 'string') {
|
|
312
|
+
return FAILED;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const members = optionsOf(schema) ?? [];
|
|
316
|
+
const member = members.find((candidate) => propValues(candidate, stamp.tag)?.has(word));
|
|
317
|
+
|
|
318
|
+
if (member !== undefined) {
|
|
319
|
+
const mark = degraded.length;
|
|
320
|
+
const read = walk(member, input, path, degraded);
|
|
321
|
+
|
|
322
|
+
if (read !== FAILED) {
|
|
323
|
+
return read;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
degraded.length = mark;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const shape = defOf(members[0]!).shape ?? {};
|
|
330
|
+
const base: Record<string, unknown> = {};
|
|
331
|
+
|
|
332
|
+
for (const key of stamp.base) {
|
|
333
|
+
const field = shape[key];
|
|
334
|
+
const read = field === undefined || !(key in input) ? FAILED : strictly(field, input[key]);
|
|
335
|
+
|
|
336
|
+
if (read === FAILED) {
|
|
337
|
+
return FAILED;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
base[key] = read.value;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
degraded.push({ kind: 'unknown-member', path, name: stamp.name, tag: word });
|
|
344
|
+
|
|
345
|
+
return { value: { ...base, [stamp.tag]: 'unknown', raw: input } };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function walkObject(def: Def, input: unknown, path: (string | number)[], degraded: WireDegradation[]): Walked {
|
|
349
|
+
if (!isRecord(input)) {
|
|
350
|
+
return FAILED;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const shape = def.shape ?? {};
|
|
354
|
+
const output: Record<string, unknown> = {};
|
|
355
|
+
|
|
356
|
+
for (const [key, field] of Object.entries(shape)) {
|
|
357
|
+
const present = key in input;
|
|
358
|
+
|
|
359
|
+
// As zod does: an absent optional key adds nothing, not even an `undefined`.
|
|
360
|
+
if (!present && field._zod.optin === 'optional' && field._zod.optout === 'optional') {
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const read = walk(field, input[key], [...path, key], degraded);
|
|
365
|
+
|
|
366
|
+
if (read === FAILED) {
|
|
367
|
+
return FAILED;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (read.value !== undefined || present || field._zod.optin === 'defaulted') {
|
|
371
|
+
output[key] = read.value;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (def.catchall === undefined) {
|
|
376
|
+
return { value: output };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const catchall = defOf(def.catchall).type;
|
|
380
|
+
|
|
381
|
+
for (const [key, value] of Object.entries(input)) {
|
|
382
|
+
if (Object.hasOwn(shape, key) || key === '__proto__') {
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (catchall === 'never') {
|
|
387
|
+
return FAILED;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const read = walk(def.catchall, value, [...path, key], degraded);
|
|
391
|
+
|
|
392
|
+
if (read === FAILED) {
|
|
393
|
+
return FAILED;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
output[key] = read.value;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return { value: output };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function walkArray(def: Def, lossy: boolean, input: unknown, path: (string | number)[], degraded: WireDegradation[]): Walked {
|
|
403
|
+
if (!Array.isArray(input) || def.element === undefined) {
|
|
404
|
+
return FAILED;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const output: unknown[] = [];
|
|
408
|
+
|
|
409
|
+
for (const [i, element] of input.entries()) {
|
|
410
|
+
// An element left out takes back what it degraded, so the list only names the element itself.
|
|
411
|
+
const mark = degraded.length;
|
|
412
|
+
const read = walk(def.element, element, [...path, i], degraded);
|
|
413
|
+
|
|
414
|
+
if (read !== FAILED) {
|
|
415
|
+
output.push(read.value);
|
|
416
|
+
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (!lossy) {
|
|
421
|
+
return FAILED;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
degraded.length = mark;
|
|
425
|
+
degraded.push({ kind: 'dropped-element', path: [...path, i] });
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return { value: output };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function walkRecord(def: Def, input: unknown, path: (string | number)[], degraded: WireDegradation[]): Walked {
|
|
432
|
+
if (!isRecord(input) || def.keyType === undefined || def.valueType === undefined) {
|
|
433
|
+
return FAILED;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const output: Record<string, unknown> = {};
|
|
437
|
+
|
|
438
|
+
for (const [key, value] of Object.entries(input)) {
|
|
439
|
+
const name = strictly(def.keyType, key);
|
|
440
|
+
const read = name === FAILED ? FAILED : walk(def.valueType, value, [...path, key], degraded);
|
|
441
|
+
|
|
442
|
+
if (name === FAILED || read === FAILED) {
|
|
443
|
+
return FAILED;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
output[String(name.value)] = read.value;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return { value: output };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function walkUnion(def: Def, input: unknown, path: (string | number)[], degraded: WireDegradation[]): Walked {
|
|
453
|
+
const tag = def.discriminator;
|
|
454
|
+
const word = tag !== undefined && isRecord(input) ? input[tag] : undefined;
|
|
455
|
+
|
|
456
|
+
for (const option of def.options ?? []) {
|
|
457
|
+
if (tag !== undefined && !propValues(option, tag)?.has(word)) {
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const mark = degraded.length;
|
|
462
|
+
const read = walk(option, input, path, degraded);
|
|
463
|
+
|
|
464
|
+
if (read !== FAILED) {
|
|
465
|
+
return read;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
degraded.length = mark;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return FAILED;
|
|
472
|
+
}
|