kizunajs 2.0.0-beta.2 → 2.0.0-beta.21

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.
Files changed (81) hide show
  1. package/README.md +3 -2
  2. package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
  3. package/dist/adapter-C3WYdSfx.d.cts +2754 -0
  4. package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
  5. package/dist/adapter-D4bTPElA.d.mts +2754 -0
  6. package/dist/adapter.cjs +37 -29
  7. package/dist/adapter.d.cts +3 -5
  8. package/dist/adapter.d.mts +3 -5
  9. package/dist/adapter.mjs +5 -5
  10. package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
  11. package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
  12. package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
  13. package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
  14. package/dist/generator.cjs +190 -95
  15. package/dist/generator.d.cts +189 -28
  16. package/dist/generator.d.mts +189 -28
  17. package/dist/generator.mjs +151 -60
  18. package/dist/index.cjs +159 -84
  19. package/dist/index.d.cts +193 -253
  20. package/dist/index.d.mts +193 -253
  21. package/dist/index.mjs +112 -38
  22. package/dist/jobs-entry.cjs +12 -11
  23. package/dist/jobs-entry.d.cts +1 -1
  24. package/dist/jobs-entry.d.mts +1 -1
  25. package/dist/jobs-entry.mjs +3 -2
  26. package/dist/plugin-Dw-yCjTY.cjs +233 -0
  27. package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
  28. package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
  29. package/dist/plugin-xxCxibmu.mjs +138 -0
  30. package/dist/plugin.cjs +8 -72
  31. package/dist/plugin.d.cts +3 -3
  32. package/dist/plugin.d.mts +3 -3
  33. package/dist/plugin.mjs +2 -68
  34. package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
  35. package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
  36. package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
  37. package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
  38. package/dist/schemas.cjs +3 -2
  39. package/dist/schemas.d.cts +24 -3
  40. package/dist/schemas.d.mts +24 -3
  41. package/dist/schemas.mjs +3 -3
  42. package/package.json +1 -1
  43. package/src/adapter.ts +245 -29
  44. package/src/api-definition.ts +12 -16
  45. package/src/api.ts +7 -3
  46. package/src/brand.ts +29 -0
  47. package/src/config.ts +51 -10
  48. package/src/configured.ts +13 -6
  49. package/src/define-config.ts +118 -39
  50. package/src/generator.ts +363 -46
  51. package/src/group-routes.ts +106 -0
  52. package/src/groups.ts +140 -0
  53. package/src/handler-pipeline.ts +78 -19
  54. package/src/index.ts +15 -6
  55. package/src/job-runner.ts +5 -0
  56. package/src/job-transport.ts +3 -3
  57. package/src/job.ts +8 -6
  58. package/src/jobs-dev-runner.ts +6 -0
  59. package/src/jobs.ts +61 -8
  60. package/src/kizuna.ts +56 -33
  61. package/src/plugin-server.ts +129 -19
  62. package/src/plugin.ts +269 -127
  63. package/src/routes.ts +80 -32
  64. package/src/schemas.ts +1 -0
  65. package/src/tool-answer.ts +21 -0
  66. package/src/tool-definitions.ts +166 -0
  67. package/src/tool-events.ts +90 -18
  68. package/src/tool-records.ts +11 -3
  69. package/src/tool-runner.ts +298 -0
  70. package/src/types.ts +90 -24
  71. package/src/zod-internals.ts +22 -5
  72. package/src/zod-meta.ts +7 -2
  73. package/dist/adapter-BGfMqEkM.d.cts +0 -563
  74. package/dist/adapter-Ci3cfcoT.d.mts +0 -563
  75. package/dist/api-definition-BHnh15zD.d.mts +0 -803
  76. package/dist/api-definition-DQj-ewHy.d.cts +0 -803
  77. package/dist/error-response-BBGSdgYw.d.mts +0 -67
  78. package/dist/error-response-Do38sr-9.d.cts +0 -67
  79. package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
  80. package/dist/plugin-DhKvx_T0.d.cts +0 -830
  81. package/src/tags.ts +0 -67
@@ -0,0 +1,298 @@
1
+ import { flattenRoutes, validateRequest, type FlattenedRoute, type RawInputs, type ValidationFailure } from './handler-pipeline.js';
2
+ import { parsePath } from './path-params.js';
3
+ import { problemDetails } from './problem-details.js';
4
+ import { buildToolDefinitions, toolOptionsOf, type ToolDefinition } from './tool-definitions.js';
5
+ import type { ToolCall, ToolError, ToolResult } from './tool-events.js';
6
+ import type { RouteDefinition, Routes } from './types.js';
7
+ import { isVoidSchema } from './zod-internals.js';
8
+
9
+ /**
10
+ * A call as the model sent it. `name` is the tool name or its dotted key.
11
+ */
12
+ export interface ToolRunCall {
13
+ id: string;
14
+ name: string;
15
+ input?: unknown;
16
+ }
17
+
18
+ export interface ToolRunOptions {
19
+ /**
20
+ * The person's answer to a call that needs approval. Unset, the call waits.
21
+ * `false` declines it.
22
+ */
23
+ approved?: boolean;
24
+ }
25
+
26
+ /**
27
+ * The call as the model knows it, to put back in the conversation.
28
+ */
29
+ export interface ModelToolCall {
30
+ id: string;
31
+ name: string;
32
+ input: unknown;
33
+ }
34
+
35
+ /**
36
+ * How a call went. `content` is what the model reads.
37
+ */
38
+ export type ToolRunResult = {
39
+ call: ModelToolCall;
40
+ } & (
41
+ | {
42
+ state: 'done';
43
+ status: number;
44
+ body: unknown;
45
+ content: string;
46
+ isError: false;
47
+ }
48
+ | {
49
+ state: 'failed';
50
+ status: number;
51
+ body: unknown;
52
+ content: string;
53
+ isError: true;
54
+ }
55
+ | {
56
+ state: 'declined';
57
+ content: string;
58
+ isError: true;
59
+ }
60
+ | {
61
+ /**
62
+ * Nothing ran. The client asks the person and sends a {@link ToolAnswer} back.
63
+ */
64
+ state: 'needs-approval';
65
+ }
66
+ );
67
+
68
+ /**
69
+ * The person's answer to a call that needs approval.
70
+ */
71
+ export interface ToolAnswer {
72
+ call: ToolRunCall;
73
+ approved: boolean;
74
+ }
75
+
76
+ /**
77
+ * The tool events `run` yields.
78
+ */
79
+ export type ToolEventYield<R extends Routes> =
80
+ | {
81
+ event: 'tool_call';
82
+ data: ToolCall<R, 'input'>;
83
+ }
84
+ | {
85
+ event: 'tool_result';
86
+ data: ToolResult<R, 'input'>;
87
+ }
88
+ | {
89
+ event: 'tool_error';
90
+ data: ToolError<R>;
91
+ };
92
+
93
+ /**
94
+ * The routes a streamed response names under `tools`, bound to the caller.
95
+ */
96
+ export interface StreamTools<R extends Routes = Routes> {
97
+ /**
98
+ * What to hand the model.
99
+ */
100
+ readonly definitions: ToolDefinition[];
101
+
102
+ /**
103
+ * Run one call as the caller, through the route's validation, guards and
104
+ * handler. An answered call runs with `run(answer.call, answer)`.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const result = yield* tools.run({
109
+ * id: block.id,
110
+ * name: block.name,
111
+ * input: block.input,
112
+ * });
113
+ * ```
114
+ */
115
+ run: (call: ToolRunCall, options?: ToolRunOptions) => AsyncGenerator<ToolEventYield<R>, ToolRunResult, undefined>;
116
+ }
117
+
118
+ /**
119
+ * What the request pipeline lends a tool call.
120
+ */
121
+ export interface ToolPipeline {
122
+ headers: unknown;
123
+ invoke: (entry: FlattenedRoute, parsed: RawInputs, params: Record<string, string>) => Promise<{ status: number; body: unknown }>;
124
+ render: (failure: ValidationFailure) => { status: number; body: unknown };
125
+ }
126
+
127
+ const DECLINED = 'Declined, so nothing ran.';
128
+
129
+ const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
130
+
131
+ const detailOf = (status: number, body: unknown): string =>
132
+ isRecord(body) && typeof body['detail'] === 'string' ? body['detail'] : `The route answered ${status}.`;
133
+
134
+ const callInput = (route: RouteDefinition, parsed: RawInputs): Record<string, unknown> | undefined => {
135
+ const input: Record<string, unknown> = {};
136
+ if (parsePath(route.path).paramNames.length > 0) input['params'] = parsed.params;
137
+ if (route.query) input['query'] = parsed.query;
138
+ if (route.body && !isVoidSchema(route.body)) input['body'] = parsed.body;
139
+ return Object.keys(input).length > 0 ? input : undefined;
140
+ };
141
+
142
+ const definitionsCache = new WeakMap<Routes, ToolDefinition[]>();
143
+
144
+ const definitionsFor = (tools: Routes): ToolDefinition[] => {
145
+ const cached = definitionsCache.get(tools);
146
+ if (cached) return cached;
147
+ const built = buildToolDefinitions(tools);
148
+ definitionsCache.set(tools, built);
149
+ return built;
150
+ };
151
+
152
+ /**
153
+ * Bind a response's tools to the request streaming it.
154
+ */
155
+ export const createStreamTools = <R extends Routes>(tools: R, pipeline: ToolPipeline): StreamTools<R> => {
156
+ const definitions = definitionsFor(tools);
157
+ const entries = new Map(flattenRoutes(tools).map((entry) => [entry.routeKey, entry]));
158
+ const keysByName = new Map(definitions.map((definition) => [definition.name, definition.key]));
159
+
160
+ const namesByKey = new Map(definitions.map((definition) => [definition.key, definition.name]));
161
+
162
+ const answered = (call: ModelToolCall, status: number, body: unknown): ToolRunResult => {
163
+ const content = JSON.stringify({
164
+ status,
165
+ body,
166
+ });
167
+ return status < 400
168
+ ? {
169
+ call,
170
+ state: 'done',
171
+ status,
172
+ body,
173
+ content,
174
+ isError: false,
175
+ }
176
+ : {
177
+ call,
178
+ state: 'failed',
179
+ status,
180
+ body,
181
+ content,
182
+ isError: true,
183
+ };
184
+ };
185
+
186
+ async function* run(call: ToolRunCall, options: ToolRunOptions = {}): AsyncGenerator<ToolEventYield<R>, ToolRunResult, undefined> {
187
+ const key = keysByName.get(call.name) ?? call.name;
188
+ const entry = entries.get(key);
189
+ const modelCall = {
190
+ id: call.id,
191
+ name: namesByKey.get(key) ?? call.name,
192
+ input: call.input ?? {},
193
+ };
194
+ // An unknown name has no event to go in.
195
+ if (entry === undefined) {
196
+ return answered(
197
+ modelCall,
198
+ 404,
199
+ problemDetails(404, `No tool named "${call.name}". Call one of: ${[...keysByName.keys()].join(', ')}.`)
200
+ );
201
+ }
202
+
203
+ const failed = (status: number, body: unknown) =>
204
+ ({
205
+ event: 'tool_error',
206
+ data: {
207
+ id: call.id,
208
+ name: key,
209
+ message: detailOf(status, body),
210
+ },
211
+ }) as ToolEventYield<R>;
212
+
213
+ const input = isRecord(call.input) ? call.input : {};
214
+ // Guards read params as strings, as from a URL.
215
+ const params = Object.fromEntries(
216
+ Object.entries(isRecord(input['params']) ? input['params'] : {}).map(([name, value]) => [name, String(value)])
217
+ );
218
+ const validation = validateRequest(entry.route, {
219
+ params,
220
+ query: input['query'] ?? {},
221
+ body: input['body'],
222
+ headers: pipeline.headers,
223
+ });
224
+ if (!validation.ok) {
225
+ const rendered = pipeline.render(validation.error);
226
+ yield failed(rendered.status, rendered.body);
227
+ return answered(modelCall, rendered.status, rendered.body);
228
+ }
229
+
230
+ const validated = callInput(entry.route, validation.parsed);
231
+ const needsApproval = toolOptionsOf(entry.route)?.needsApproval === true;
232
+ const waiting = needsApproval && options.approved === undefined;
233
+ yield {
234
+ event: 'tool_call',
235
+ data: {
236
+ id: call.id,
237
+ name: key,
238
+ ...(waiting
239
+ ? {
240
+ needsApproval: true,
241
+ }
242
+ : {}),
243
+ ...(validated === undefined
244
+ ? {}
245
+ : {
246
+ input: validated,
247
+ }),
248
+ },
249
+ } as ToolEventYield<R>;
250
+
251
+ if (waiting) {
252
+ return {
253
+ call: modelCall,
254
+ state: 'needs-approval',
255
+ };
256
+ }
257
+ if (needsApproval && options.approved === false) {
258
+ yield {
259
+ event: 'tool_error',
260
+ data: {
261
+ id: call.id,
262
+ name: key,
263
+ message: DECLINED,
264
+ },
265
+ } as ToolEventYield<R>;
266
+ return {
267
+ call: modelCall,
268
+ state: 'declined',
269
+ content: DECLINED,
270
+ isError: true,
271
+ };
272
+ }
273
+
274
+ const { status, body } = await pipeline.invoke(entry, validation.parsed, params);
275
+ if (status >= 400) {
276
+ yield failed(status, body);
277
+ } else {
278
+ yield {
279
+ event: 'tool_result',
280
+ data: {
281
+ id: call.id,
282
+ name: key,
283
+ ...(body === undefined
284
+ ? {}
285
+ : {
286
+ output: body,
287
+ }),
288
+ },
289
+ } as ToolEventYield<R>;
290
+ }
291
+ return answered(modelCall, status, body);
292
+ }
293
+
294
+ return {
295
+ definitions,
296
+ run,
297
+ };
298
+ };
package/src/types.ts CHANGED
@@ -235,6 +235,21 @@ export type RouteAuth<Names extends string = string> =
235
235
  requires?: RequiredPermissions;
236
236
  };
237
237
 
238
+ /**
239
+ * Rejects a route that is both `hidden` and a `tool`: a hidden route is left out
240
+ * of everything that publishes routes, MCP included.
241
+ */
242
+ export type RouteHiddenToolCheck<Route> = Route extends {
243
+ hidden: true;
244
+ tool: true | RouteToolOptions;
245
+ }
246
+ ? {
247
+ tool: {
248
+ 'kizuna: a hidden route cannot publish as a tool. Remove `tool`, or `hidden`': true;
249
+ };
250
+ }
251
+ : unknown;
252
+
238
253
  /**
239
254
  * Response headers keyed by name.
240
255
  */
@@ -264,7 +279,7 @@ export type RouteHandlerFunction = (args: never) => unknown;
264
279
 
265
280
  /**
266
281
  * What a route publishes as, over MCP. `description`, `title` and the four
267
- * hints are MCP's own, field for field; `confirm` is kizuna's.
282
+ * hints are MCP's own, field for field; `needsApproval` is kizuna's.
268
283
  *
269
284
  * Each hint defaults from the route's method, so a `GET` is already marked read
270
285
  * only and a `DELETE` already destructive. Set one to say what the method
@@ -302,17 +317,19 @@ export interface RouteToolOptions {
302
317
  */
303
318
  openWorldHint?: boolean;
304
319
  /**
305
- * What the person reads before this route runs as a tool. They agree or
306
- * decline, and declining leaves the handler uncalled.
320
+ * The person approves each call before it runs as a tool.
307
321
  *
308
- * Kizuna's own, sent over MCP's elicitation. The four hints above say what
309
- * the route does, and leave a client to decide whether that warrants
310
- * asking; this asks.
322
+ * @example
323
+ * ```ts
324
+ * tool: {
325
+ * needsApproval: true,
326
+ * },
327
+ * ```
311
328
  */
312
- confirm?: string;
329
+ needsApproval?: boolean;
313
330
  }
314
331
 
315
- export interface RouteDefinition<TagKeys extends string = string, SchemeNames extends string = string> {
332
+ export interface RouteDefinition<GroupPaths extends string = string, SchemeNames extends string = string> {
316
333
  method: Method;
317
334
  /**
318
335
  * What this route requires of its caller. See {@link RouteAuth}.
@@ -341,6 +358,59 @@ export interface RouteDefinition<TagKeys extends string = string, SchemeNames ex
341
358
  * },
342
359
  */
343
360
  tool?: boolean | RouteToolOptions;
361
+ /**
362
+ * Keep this route out of the generated clients, the OpenAPI document and
363
+ * MCP. It is still served.
364
+ *
365
+ * @example
366
+ * ```ts
367
+ * check: k
368
+ * .route({
369
+ * method: 'GET',
370
+ * path: '/health',
371
+ * hidden: true,
372
+ * responses: {
373
+ * 200: HealthSchema,
374
+ * },
375
+ * })
376
+ * .handler(() => ({
377
+ * status: 200,
378
+ * body: {
379
+ * status: 'ok',
380
+ * },
381
+ * })),
382
+ * ```
383
+ */
384
+ hidden?: boolean;
385
+ /**
386
+ * Receive the body exactly as it was sent, as `rawBody`, beside the
387
+ * validated `body`. Check a sender's signature against `rawBody`, since
388
+ * re-serialising the JSON can change a byte and break it.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * resendEvents: k
393
+ * .route({
394
+ * method: 'POST',
395
+ * path: '/webhooks/resend',
396
+ * auth: false,
397
+ * hidden: true,
398
+ * rawBody: true,
399
+ * body: ResendEventSchema,
400
+ * responses: {
401
+ * 204: z.void(),
402
+ * },
403
+ * })
404
+ * .handler(({ rawBody, headers }) => {
405
+ * verifySignature(rawBody, headers);
406
+ *
407
+ * return {
408
+ * status: 204,
409
+ * };
410
+ * }),
411
+ * ```
412
+ */
413
+ rawBody?: true;
344
414
  /**
345
415
  * Deprecates the route. Pass a message to tell callers what to use instead,
346
416
  * or the object form to announce the deprecation in response headers.
@@ -399,11 +469,9 @@ export interface RouteDefinition<TagKeys extends string = string, SchemeNames ex
399
469
  link?: string;
400
470
  };
401
471
  /**
402
- * Tag keys grouping this route in the OpenAPI spec. Keys come from the tag set
403
- * declared with `k.tags`; `k.routes` stamps the group's tag onto every
404
- * route, and the generator resolves each key to its `title` for the spec.
472
+ * More groups to list this route under, as dotted paths.
405
473
  */
406
- tags?: readonly TagKeys[];
474
+ groups?: readonly GroupPaths[];
407
475
  /**
408
476
  * The security schemes this route requires, referencing identities named
409
477
  * under `identities` on `defineConfig`. Each entry is a scheme name or a
@@ -468,11 +536,9 @@ export interface RouteDefinition<TagKeys extends string = string, SchemeNames ex
468
536
  }
469
537
 
470
538
  /**
471
- * Key under which a routes group carries its group tag key, the source
472
- * `flattenRoutes` and the generator use to apply the group's tag to every route
473
- * in it. Stamped by `k.routes`.
539
+ * Where a tree from `k.routes` carries its group's dotted path.
474
540
  */
475
- export const ROUTES_TAG: unique symbol = Symbol.for('kizuna.routes.tag') as symbol as typeof ROUTES_TAG;
541
+ export const ROUTES_GROUP: unique symbol = Symbol.for('kizuna.routes.group') as symbol as typeof ROUTES_GROUP;
476
542
 
477
543
  /**
478
544
  * Type-only key under which `defineConfig` brands each route with its resolved
@@ -509,9 +575,9 @@ export interface AutoResponsesBrand<Statuses extends number, Body = ProblemDetai
509
575
  */
510
576
  export type GuardStatus = Extract<KnownStatus, 401 | 403>;
511
577
 
512
- export interface Routes<TagKeys extends string = string, SchemeNames extends string = string> {
513
- [ROUTES_TAG]?: string;
514
- [key: string]: RouteDefinition<TagKeys, SchemeNames> | Routes<TagKeys, SchemeNames>;
578
+ export interface Routes<GroupPaths extends string = string, SchemeNames extends string = string> {
579
+ [ROUTES_GROUP]?: string;
580
+ [key: string]: RouteDefinition<GroupPaths, SchemeNames> | Routes<GroupPaths, SchemeNames>;
515
581
  }
516
582
 
517
583
  /**
@@ -519,8 +585,8 @@ export interface Routes<TagKeys extends string = string, SchemeNames extends str
519
585
  * `security`, `roles` and `requires`, which `defineConfig` resolves from its
520
586
  * `auth`. Writing any of them on a route is a type error.
521
587
  */
522
- export type AuthoredRouteDefinition<TagKeys extends string = string, Names extends string = string> = Omit<
523
- RouteDefinition<TagKeys>,
588
+ export type AuthoredRouteDefinition<GroupPaths extends string = string, Names extends string = string> = Omit<
589
+ RouteDefinition<GroupPaths>,
524
590
  'security' | 'roles' | 'requires' | 'auth'
525
591
  > & {
526
592
  security?: never;
@@ -535,7 +601,7 @@ export type AuthoredRouteDefinition<TagKeys extends string = string, Names exten
535
601
  /**
536
602
  * A tree of {@link AuthoredRouteDefinition}s, the shape `k.routes` accepts.
537
603
  */
538
- export interface AuthoredRoutes<TagKeys extends string = string, Names extends string = string> {
539
- [ROUTES_TAG]?: string;
540
- [key: string]: AuthoredRouteDefinition<TagKeys, Names> | AuthoredRoutes<TagKeys, Names>;
604
+ export interface AuthoredRoutes<GroupPaths extends string = string, Names extends string = string> {
605
+ [ROUTES_GROUP]?: string;
606
+ [key: string]: AuthoredRouteDefinition<GroupPaths, Names> | AuthoredRoutes<GroupPaths, Names>;
541
607
  }
@@ -8,6 +8,8 @@ export interface ZodDef {
8
8
  coerce?: boolean;
9
9
  innerType?: z.core.$ZodType;
10
10
  element?: z.core.$ZodType;
11
+ items?: z.core.$ZodType[];
12
+ rest?: z.core.$ZodType | null;
11
13
  in?: z.core.$ZodType;
12
14
  out?: z.core.$ZodType;
13
15
  shape?: Record<string, z.core.$ZodType>;
@@ -94,16 +96,22 @@ export const resolveBaseType = (schema: z.core.$ZodType): string => {
94
96
  };
95
97
 
96
98
  /**
97
- * Removes optional/nullable/default wrappers, returning the inner schema and
98
- * whether any were present.
99
+ * Removes optional/nullable/default wrappers, returning the inner schema,
100
+ * whether the key may be absent, and whether the value may be null. A
101
+ * `z.string().nullable()` field is required, so it reports `optional: false`.
99
102
  */
100
- export const unwrapOptionalWrappers = (schema: z.core.$ZodType): { inner: z.core.$ZodType; optional: boolean } => {
103
+ export const unwrapOptionalWrappers = (schema: z.core.$ZodType): { inner: z.core.$ZodType; optional: boolean; nullable: boolean } => {
101
104
  let current = schema;
102
105
  let optional = false;
106
+ let nullable = false;
103
107
  while (true) {
104
108
  const def = readDef(current);
105
- if (def.type !== 'optional' && def.type !== 'nullable' && def.type !== 'default' && def.type !== 'nullish') break;
106
- optional = true;
109
+ if (def.type === 'optional' || def.type === 'default') optional = true;
110
+ else if (def.type === 'nullable') nullable = true;
111
+ else if (def.type === 'nullish') {
112
+ optional = true;
113
+ nullable = true;
114
+ } else break;
107
115
  const next = def.innerType;
108
116
  if (!next) break;
109
117
  current = next;
@@ -111,6 +119,7 @@ export const unwrapOptionalWrappers = (schema: z.core.$ZodType): { inner: z.core
111
119
  return {
112
120
  inner: current,
113
121
  optional,
122
+ nullable,
114
123
  };
115
124
  };
116
125
 
@@ -296,6 +305,14 @@ export const readMetaDescription = (schema: z.core.$ZodType): string | undefined
296
305
  return typeof description === 'string' ? description : undefined;
297
306
  };
298
307
 
308
+ /**
309
+ * Returns a schema's `brand` metadata, set by `Kizuna.brand`, or undefined.
310
+ */
311
+ export const readMetaBrand = (schema: z.core.$ZodType): string | undefined => {
312
+ const brand = readMeta(schema)?.brand;
313
+ return typeof brand === 'string' ? brand : undefined;
314
+ };
315
+
299
316
  /**
300
317
  * The `Kizuna.model` schemas in the global registry, keyed by their `id`.
301
318
  */
package/src/zod-meta.ts CHANGED
@@ -1,7 +1,12 @@
1
- import type { $output } from 'zod/v4/core';
1
+ import type { $input, $output } from 'zod/v4/core';
2
2
 
3
3
  declare module 'zod/v4/core' {
4
4
  interface GlobalMeta {
5
+ /**
6
+ * The brand generated clients give this schema's values. Set by
7
+ * `Kizuna.brand`.
8
+ */
9
+ brand?: string;
5
10
  /**
6
11
  * Deprecates the schema. Pass a message to tell callers what to use
7
12
  * instead.
@@ -16,7 +21,7 @@ declare module 'zod/v4/core' {
16
21
  * example: 'ada@example.com',
17
22
  * });
18
23
  */
19
- example?: $output | $output[];
24
+ example?: $input | $output | Array<$input | $output>;
20
25
  }
21
26
  }
22
27