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
package/src/adapter.ts CHANGED
@@ -27,8 +27,7 @@ import { problemDetails, problemFromBody, type ProblemDetails } from './problem-
27
27
  import { isVoidSchema, isBinarySchema } from './zod-internals.js';
28
28
  import { resolveCoercionPlans } from './coercion.js';
29
29
  import { isRawResponse, type RawResponse } from './raw-response.js';
30
- import { pluginRouteTree, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, type ApiPlugins } from './plugin.js';
31
- import { resolvePluginServers } from './plugin-server.js';
30
+ import { pluginRouteTree, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, type ResolvedPlugin } from './plugin.js';
32
31
  import {
33
32
  resolveResponseBody,
34
33
  resolveResponseContentType,
@@ -39,6 +38,8 @@ import {
39
38
  isSuccessStatus,
40
39
  } from './generator-utils.js';
41
40
  import { encodeStreamBody, EVENT_STREAM_MEDIA_TYPE, streamContentType, type EncodeStreamOptions } from './stream.js';
41
+ import { streamToolsOf } from './tool-events.js';
42
+ import { createStreamTools, type StreamTools } from './tool-runner.js';
42
43
  import { DEFAULT_JOBS_PATH, flattenJobs, type Jobs, type JobsConfig } from './jobs.js';
43
44
  import { createJobRunner, jobFnAt, JobInputError, type JobRunner, type JobRunnerOptions, type JobErrorHandler } from './job-runner.js';
44
45
  import {
@@ -58,7 +59,7 @@ export { rawResponse, isRawResponse, type RawResponse } from './raw-response.js'
58
59
  export { encodeStreamBody, type EncodeStreamOptions, type StreamContext } from './stream.js';
59
60
  export { isStreamResponse } from './generator-utils.js';
60
61
  export {
61
- createPlugin,
62
+ definePlugin,
62
63
  pluginRouteTree,
63
64
  type PluginDeclaration,
64
65
  type PluginDefinition,
@@ -67,8 +68,8 @@ export {
67
68
  type PluginExportValues,
68
69
  type PluginArgs,
69
70
  type PluginRoutesOf,
70
- type PluginPropsOf,
71
71
  type PluginExportsOf,
72
+ type ResolvedPlugin,
72
73
  } from './plugin.js';
73
74
  export type { CompiledJob, Jobs, JobHandler, JobHandlers, FlattenedJob } from './jobs.js';
74
75
  export { flattenJobs, isCompiledJob, jobAt } from './jobs.js';
@@ -82,7 +83,7 @@ export {
82
83
  type JobFnByKey,
83
84
  } from './job-runner.js';
84
85
  export {
85
- createJobTransport,
86
+ defineJobTransport,
86
87
  JobDispatchError,
87
88
  type JobTransport,
88
89
  type JobMessage,
@@ -91,8 +92,7 @@ export {
91
92
  type JobWorker,
92
93
  type JobWorkerContext,
93
94
  } from './job-transport.js';
94
- export { pluginRoutesOf, pluginRouterOf, pluginExportsOf, resolvePluginServers } from './plugin-server.js';
95
- export { type PluginRouter } from './plugin.js';
95
+ export { pluginRoutesOf, pluginRouterOf, pluginExportsOf, resolvePlugins, createApiReference } from './plugin-server.js';
96
96
 
97
97
  export class ResponseValidationError extends Error {
98
98
  readonly routeKey: string;
@@ -257,7 +257,19 @@ export const contractOf = <C = unknown>(api: unknown): C => (api as Record<symbo
257
257
  /**
258
258
  * What kizuna puts in handler args. Must agree with the spread in `runPipeline`.
259
259
  */
260
- export const HANDLER_ARG_KEYS = ['params', 'query', 'body', 'headers', 'throwError', 'auth', 'requestContext', 'plugins'] as const;
260
+ export const HANDLER_ARG_KEYS = [
261
+ 'params',
262
+ 'query',
263
+ 'body',
264
+ 'headers',
265
+ 'throwError',
266
+ 'auth',
267
+ 'requestContext',
268
+ 'plugins',
269
+ 'tools',
270
+ 'rawBody',
271
+ 'lastEventId',
272
+ ] as const;
261
273
 
262
274
  /**
263
275
  * The adapter's own context, with kizuna's arguments removed.
@@ -283,6 +295,30 @@ export interface ApiParts {
283
295
  */
284
296
  }
285
297
 
298
+ /**
299
+ * Each plugin's router, built from the handlers its routes carry, and its
300
+ * exports. A plugin route without a handler throws, since nothing would answer
301
+ * it.
302
+ */
303
+ const pluginServers = (
304
+ plugins: Record<string, ResolvedPlugin> | undefined
305
+ ): Record<string, { router: Record<string, unknown>; exports?: unknown }> => {
306
+ const servers: Record<string, { router: Record<string, unknown>; exports?: unknown }> = {};
307
+ for (const [slug, plugin] of Object.entries(plugins ?? {})) {
308
+ for (const [routeKey, route] of Object.entries(plugin.routes)) {
309
+ if (route[HANDLER] !== undefined) continue;
310
+ throw new Error(
311
+ `Plugin '${slug}' declares the route '${routeKey}' without a handler. Declare it with \`route(...).handler(...)\`.`
312
+ );
313
+ }
314
+ servers[slug] = {
315
+ router: routerFromRoutes(plugin.routes),
316
+ exports: plugin.exports,
317
+ };
318
+ }
319
+ return servers;
320
+ };
321
+
286
322
  /**
287
323
  * Brand an api's routes with the parts that serve them, for the adapter to read back when mounting.
288
324
  */
@@ -291,7 +327,7 @@ export const assembleApi = <const R extends Routes>(
291
327
  routes: R;
292
328
  securitySchemes?: Record<string, SecurityScheme>;
293
329
  guardSchema?: z.ZodType;
294
- plugins?: ApiPlugins;
330
+ plugins?: Record<string, ResolvedPlugin>;
295
331
  },
296
332
  parts: ApiParts
297
333
  ): ApiWithRouter<R> => {
@@ -312,20 +348,22 @@ export const assembleApi = <const R extends Routes>(
312
348
  [CONTRACT_META]: contract,
313
349
  } as Record<string | symbol, unknown>;
314
350
 
315
- // Resolved after the api exists, because a plugin's server half receives it.
316
- api[PLUGIN_SERVERS_META_KEY] = resolvePluginServers(contract.plugins, api);
351
+ api[PLUGIN_SERVERS_META_KEY] = pluginServers(contract.plugins);
317
352
 
318
353
  return api as unknown as ApiWithRouter<R>;
319
354
  };
320
355
 
321
356
  /**
322
357
  * The endpoints jobs are served on, in the {@link Routes} shape the request
323
- * pipeline takes.
358
+ * pipeline takes. None when the jobs run in process.
324
359
  */
325
- export const jobRoutes = (meta: JobsMeta): Routes => ({
326
- [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
327
- [RUN_ROUTE_KEY]: runRoute(meta),
328
- });
360
+ export const jobRoutes = (meta: JobsMeta): Routes =>
361
+ meta.config?.mode === 'in-process'
362
+ ? {}
363
+ : {
364
+ [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
365
+ [RUN_ROUTE_KEY]: runRoute(meta),
366
+ };
329
367
 
330
368
  /**
331
369
  * Their handlers, in the {@link Router} shape the request pipeline takes.
@@ -587,9 +625,19 @@ export type {
587
625
  ContextFromAuth,
588
626
  } from './handler-pipeline.js';
589
627
  export { buildPath, parsePath, type PathSegment } from './path-params.js';
628
+ export {
629
+ buildToolDefinitions,
630
+ buildToolInputSchema,
631
+ describeTool,
632
+ selectToolRoutes,
633
+ toolOptionsOf,
634
+ toolRefusal,
635
+ type ToolDefinition,
636
+ type ToolInputSchema,
637
+ } from './tool-definitions.js';
590
638
  export { sortFlattenedRoutes } from './route-matcher.js';
591
639
  export {
592
- ROUTES_TAG,
640
+ ROUTES_GROUP,
593
641
  HANDLER_CONTEXT_BRAND,
594
642
  type HandlerContextBrand,
595
643
  AUTO_RESPONSES_BRAND,
@@ -597,8 +645,8 @@ export {
597
645
  type AutoResponsesBrand,
598
646
  } from './types.js';
599
647
  export { authenticationChallenge, resolveSecurityRequirements } from './security-scheme.js';
600
- export { tagRoutes } from './routes.js';
601
- export { isTagSet, type NormalizeTags } from './tags.js';
648
+ export { groupRoutes } from './routes.js';
649
+ export { isGroupSet } from './groups.js';
602
650
  export { ResponseError } from './response-error.js';
603
651
  export { problemDetails, type ProblemDetails } from './problem-details.js';
604
652
  export type { MatchResult, RouteMatch } from './route-matcher.js';
@@ -628,6 +676,11 @@ export interface AdapterRequest<NativeRequest> {
628
676
  query: unknown;
629
677
  headers: unknown;
630
678
  readBody: (route: RouteDefinition) => Promise<unknown> | unknown;
679
+ /**
680
+ * The body as it was sent, for a route with `rawBody: true`, or `undefined`
681
+ * when it was already consumed.
682
+ */
683
+ readRawBody?: (route: RouteDefinition) => Promise<string | undefined> | string | undefined;
631
684
  }
632
685
 
633
686
  /**
@@ -751,6 +804,11 @@ export interface HandleArgs<NativeRequest, HandlerContext, ResponseContext, TRou
751
804
  * header, `undefined` when absent. For guards and request context resolvers on
752
805
  * adapters that expose raw header records.
753
806
  */
807
+ const streamsEvents = (route: RouteDefinition): boolean =>
808
+ Object.values(route.responses).some(
809
+ (response) => isStreamResponse(response) && streamContentType(response) === EVENT_STREAM_MEDIA_TYPE
810
+ );
811
+
754
812
  export const getHeaderValue = (value: unknown): string | undefined => {
755
813
  if (typeof value === 'string') return value;
756
814
  if (Array.isArray(value) && typeof value[0] === 'string') return value[0];
@@ -841,7 +899,7 @@ export const extractCredential = (scheme: SecurityScheme, request: AdapterReques
841
899
  };
842
900
 
843
901
  /**
844
- * The request pipeline `createAdapter` builds: what matches a request to a
902
+ * The request pipeline `defineAdapter` builds: what matches a request to a
845
903
  * route, runs the guards and the handler, and hands the result back to the
846
904
  * framework.
847
905
  */
@@ -1158,6 +1216,23 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1158
1216
  body: undefined,
1159
1217
  };
1160
1218
 
1219
+ let rawBody: string | undefined;
1220
+ if (route.rawBody === true) {
1221
+ rawBody = request.readRawBody === undefined ? undefined : await request.readRawBody(route);
1222
+ if (rawBody === undefined) {
1223
+ const error = new Error(
1224
+ `[kizuna] ${routeKey} needs the raw body, but it was parsed before kizuna saw it. On Express, mount kizuna before express.json(), or pass \`verify: keepRawBody\` to it.`
1225
+ );
1226
+ console.error(error.message);
1227
+ return {
1228
+ kind: 'handler-error',
1229
+ routeKey,
1230
+ route,
1231
+ error,
1232
+ };
1233
+ }
1234
+ }
1235
+
1161
1236
  const acceptHeader = (raw.headers as Record<string, string | undefined>)['accept'];
1162
1237
  if (!isAcceptable(acceptHeader, route)) {
1163
1238
  return {
@@ -1181,7 +1256,7 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1181
1256
  };
1182
1257
  }
1183
1258
  try {
1184
- raw.body = await request.readBody(route);
1259
+ raw.body = rawBody !== undefined ? parseBodyText(rawBody, route) : await request.readBody(route);
1185
1260
  } catch {
1186
1261
  return {
1187
1262
  kind: 'invalid-body',
@@ -1202,7 +1277,123 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1202
1277
  };
1203
1278
  }
1204
1279
 
1205
- const handler = resolveHandler(router, routeKey);
1280
+ return invokeRoute({
1281
+ resolved,
1282
+ parsed: validation.parsed,
1283
+ handler: resolveHandler(router, routeKey),
1284
+ request,
1285
+ routes,
1286
+ definition,
1287
+ handlerContext: () => definition.buildHandlerContext(request, responseContext),
1288
+ guards,
1289
+ schemes,
1290
+ contextResolvers,
1291
+ pluginExports,
1292
+ jobRunner,
1293
+ responseValidation,
1294
+ rawBody,
1295
+ });
1296
+ };
1297
+
1298
+ interface Invocation<NativeRequest, HandlerContext, ResponseContext> {
1299
+ resolved: ResolvedRoute;
1300
+ parsed: RawInputs;
1301
+ /**
1302
+ * The body as sent, for a route with `rawBody: true`.
1303
+ */
1304
+ rawBody?: string;
1305
+ handler: unknown;
1306
+ request: AdapterRequest<NativeRequest>;
1307
+ routes: Routes;
1308
+ definition: AdapterDefinition<NativeRequest, unknown, HandlerContext, ResponseContext>;
1309
+ handlerContext: () => HandlerContext | Promise<HandlerContext>;
1310
+ guards: GuardMap<HandlerContext> | undefined;
1311
+ schemes: Record<string, SecurityScheme> | undefined;
1312
+ contextResolvers: RequestContextMap<HandlerContext> | undefined;
1313
+ pluginExports: Record<string, unknown> | undefined;
1314
+ jobRunner: JobRunner<Jobs> | undefined;
1315
+ responseValidation: boolean | undefined;
1316
+ }
1317
+
1318
+ const streamToolsOfRoute = (route: RouteDefinition): Routes | undefined => {
1319
+ for (const response of Object.values(route.responses)) {
1320
+ const tools = streamToolsOf(response);
1321
+ if (tools !== undefined) return tools;
1322
+ }
1323
+ return undefined;
1324
+ };
1325
+
1326
+ /**
1327
+ * What a tool call reports: the status and body HTTP would have sent.
1328
+ */
1329
+ const toolAnswer = (result: AdapterResult): { status: number; body: unknown } => {
1330
+ if (result.kind === 'raw-response') {
1331
+ return {
1332
+ status: 500,
1333
+ body: problemDetails(500, 'This route answers with a raw response, and a tool answers with a JSON body.'),
1334
+ };
1335
+ }
1336
+ if (result.kind === 'handler-error') console.error(`[kizuna] tool "${result.routeKey}" threw:`, result.error);
1337
+ const rendered = renderJsonResult(result);
1338
+ return {
1339
+ status: rendered.status,
1340
+ body: rendered.body,
1341
+ };
1342
+ };
1343
+
1344
+ /**
1345
+ * Each call runs its route as a request of its own, from the same caller.
1346
+ */
1347
+ const streamToolsFor = <NativeRequest, HandlerContext, ResponseContext>(
1348
+ tools: Routes,
1349
+ invocation: Invocation<NativeRequest, HandlerContext, ResponseContext>,
1350
+ handlerContext: HandlerContext
1351
+ ): StreamTools =>
1352
+ createStreamTools(tools, {
1353
+ headers: invocation.request.headers,
1354
+ invoke: async (entry, parsed, params) =>
1355
+ toolAnswer(
1356
+ await invokeRoute({
1357
+ ...invocation,
1358
+ resolved: {
1359
+ routeKey: entry.routeKey,
1360
+ route: entry.route,
1361
+ params,
1362
+ },
1363
+ parsed,
1364
+ handler: entry.route[HANDLER],
1365
+ handlerContext: () => handlerContext,
1366
+ })
1367
+ ),
1368
+ render: (failure) => {
1369
+ const formatted = formatValidationError(failure);
1370
+ return toolAnswer({
1371
+ kind: 'validation-failed',
1372
+ stage: failure.stage,
1373
+ detail: formatted.detail,
1374
+ issues: formatted.issues,
1375
+ });
1376
+ },
1377
+ });
1378
+
1379
+ const invokeRoute = async <NativeRequest, HandlerContext, ResponseContext>(
1380
+ invocation: Invocation<NativeRequest, HandlerContext, ResponseContext>
1381
+ ): Promise<AdapterResult> => {
1382
+ const {
1383
+ resolved,
1384
+ parsed,
1385
+ request,
1386
+ routes,
1387
+ definition,
1388
+ guards,
1389
+ schemes,
1390
+ contextResolvers,
1391
+ pluginExports,
1392
+ jobRunner,
1393
+ responseValidation,
1394
+ } = invocation;
1395
+ const { routeKey, route, params } = resolved;
1396
+ const handler = invocation.handler;
1206
1397
  if (typeof handler !== 'function') {
1207
1398
  return {
1208
1399
  kind: 'no-handler',
@@ -1211,7 +1402,7 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1211
1402
  }
1212
1403
 
1213
1404
  try {
1214
- const handlerContext = await definition.buildHandlerContext(request, responseContext);
1405
+ const handlerContext = await invocation.handlerContext();
1215
1406
 
1216
1407
  const requestContext: Record<string, unknown> = {};
1217
1408
  if (contextResolvers) {
@@ -1219,7 +1410,7 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1219
1410
  requestContext[name] = await resolver({
1220
1411
  ...(handlerContext as Record<string, unknown>),
1221
1412
  params,
1222
- headers: raw.headers as Record<string, string | string[] | undefined>,
1413
+ headers: request.headers as Record<string, string | string[] | undefined>,
1223
1414
  } as Parameters<typeof resolver>[0]);
1224
1415
  }
1225
1416
  }
@@ -1288,15 +1479,31 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1288
1479
  const throwError = (response: { status: number; body: unknown; headers?: ResponseHeaders }): never => {
1289
1480
  throw new ResponseError(response);
1290
1481
  };
1482
+ const tools = streamToolsOfRoute(route);
1291
1483
  const handlerResult = await (
1292
1484
  handler as (args: unknown) => Promise<{ status: number; body: unknown; headers?: ResponseHeaders } | RawResponse>
1293
1485
  )({
1294
- params: validation.parsed.params,
1295
- query: validation.parsed.query,
1296
- body: validation.parsed.body,
1297
- headers: validation.parsed.headers,
1486
+ params: parsed.params,
1487
+ query: parsed.query,
1488
+ body: parsed.body,
1489
+ headers: parsed.headers,
1490
+ ...(route.rawBody === true
1491
+ ? {
1492
+ rawBody: invocation.rawBody,
1493
+ }
1494
+ : {}),
1495
+ ...(streamsEvents(route)
1496
+ ? {
1497
+ lastEventId: getHeaderValue((invocation.request.headers as Record<string, unknown>)['last-event-id']),
1498
+ }
1499
+ : {}),
1298
1500
  throwError,
1299
1501
  ...handlerContext,
1502
+ ...(tools
1503
+ ? {
1504
+ tools: streamToolsFor(tools, invocation, handlerContext),
1505
+ }
1506
+ : {}),
1300
1507
  ...(jobRunner ? { jobs: jobRunner } : {}),
1301
1508
  ...(hasRequestContext ? { requestContext } : {}),
1302
1509
  ...(Object.keys(securityContext).length > 0 ? { auth: securityContext } : {}),
@@ -1352,7 +1559,7 @@ const routedPipeline = async <NativeRequest, HandlerContext, ResponseContext>(
1352
1559
  }
1353
1560
  };
1354
1561
 
1355
- export const createAdapter = <NativeRequest, NativeResponse, HandlerContext, ResponseContext = Record<string, never>>(
1562
+ export const defineAdapter = <NativeRequest, NativeResponse, HandlerContext, ResponseContext = Record<string, never>>(
1356
1563
  definition: AdapterDefinition<NativeRequest, NativeResponse, HandlerContext, ResponseContext>
1357
1564
  ): RequestPipeline<NativeRequest, NativeResponse, HandlerContext, ResponseContext> => ({
1358
1565
  handle: async ({
@@ -1640,6 +1847,15 @@ const formDataToObject = (form: FormData): Record<string, unknown> => {
1640
1847
  return result;
1641
1848
  };
1642
1849
 
1850
+ /**
1851
+ * Parse a body from its text, the way {@link parseFetchBody} would, for a route
1852
+ * whose text core already read.
1853
+ */
1854
+ export const parseBodyText = (text: string, route: RouteDefinition): unknown => {
1855
+ if (route.contentType === 'application/x-www-form-urlencoded') return Object.fromEntries(new URLSearchParams(text));
1856
+ return text.length > 0 ? JSON.parse(text) : undefined;
1857
+ };
1858
+
1643
1859
  /**
1644
1860
  * Content-type-aware body parser for Web Fetch `Request`.
1645
1861
  *
@@ -1,19 +1,19 @@
1
1
  import type { z } from 'zod';
2
2
  import type { Routes } from './types.js';
3
- import type { TagSet, TagOptions } from './tags.js';
3
+ import type { GroupSet, GroupOptions, GroupPaths } from './groups.js';
4
4
  import type { SecurityScheme } from './security-scheme.js';
5
5
  import type { RequestContextSchema } from './request-context.js';
6
6
  import type { Jobs, JobsConfig } from './jobs.js';
7
7
  import type { ApiPlugins } from './plugin.js';
8
8
 
9
9
  /**
10
- * A kizuna API definition: its routes plus tags, identities, and validation
10
+ * A kizuna API definition: its routes plus groups, identities, and validation
11
11
  * settings. Produced by `defineConfig` and consumed by the server adapters,
12
12
  * fetch client, OpenAPI generator, and SDK generators.
13
13
  */
14
14
  export interface ApiDefinition<
15
15
  Routes_ extends Routes = Routes,
16
- Tags extends Record<string, TagOptions> = Record<string, TagOptions>,
16
+ Groups extends Record<string, GroupOptions | string> = Record<string, GroupOptions | string>,
17
17
  Codes extends string = string,
18
18
  Schemes extends Record<string, SecurityScheme> = Record<string, SecurityScheme>,
19
19
  RequestContext extends Record<string, RequestContextSchema> = Record<string, RequestContextSchema>,
@@ -42,14 +42,13 @@ export interface ApiDefinition<
42
42
  */
43
43
  jobs?: Jobs_;
44
44
  /**
45
- * The job settings named in `defineConfig` under `jobsConfig`.
45
+ * The job settings named in `defineConfig` under `jobRunner`.
46
46
  */
47
47
  jobsConfig?: JobsConfig;
48
48
  /**
49
- * The tag set declared with `k.tags`. Routes reference its keys; the
50
- * OpenAPI generator resolves each key to its title and description.
49
+ * The groups declared with `k.groups`.
51
50
  */
52
- tags?: TagSet<Tags>;
51
+ groups?: GroupSet<Groups>;
53
52
  /**
54
53
  * The identities named in `defineConfig`. A route's `auth` names them,
55
54
  * `defineConfig` writes each route's `security` from it, and the
@@ -74,18 +73,15 @@ export interface ApiDefinition<
74
73
  }
75
74
 
76
75
  /**
77
- * Internal helper that builds a {@link ApiDefinition} from routes, tags, identities,
76
+ * Internal helper that builds a {@link ApiDefinition} from routes, groups, identities,
78
77
  * and issue codes. Called by `defineConfig`. Not part of the public surface;
79
78
  * author contracts through `k`.
80
79
  */
81
80
  export function buildApiDefinition<
82
- const Tags extends Record<string, TagOptions> = Record<string, never>,
81
+ const Groups extends Record<string, GroupOptions | string> = {},
83
82
  const Codes extends string = never,
84
83
  const Schemes extends Record<string, SecurityScheme> = Record<string, never>,
85
- const R extends Routes<Extract<keyof Tags, string>, Extract<keyof Schemes, string>> = Routes<
86
- Extract<keyof Tags, string>,
87
- Extract<keyof Schemes, string>
88
- >,
84
+ const R extends Routes<GroupPaths<Groups>, Extract<keyof Schemes, string>> = Routes<GroupPaths<Groups>, Extract<keyof Schemes, string>>,
89
85
  const RequestContext extends Record<string, RequestContextSchema> = Record<string, never>,
90
86
  const Plugins extends ApiPlugins = Record<string, never>,
91
87
  const Jobs_ extends Jobs = Record<string, never>,
@@ -95,21 +91,21 @@ export function buildApiDefinition<
95
91
  guardSchema?: GuardSchema;
96
92
  jobs?: Jobs_;
97
93
  jobsConfig?: JobsConfig;
98
- tags?: TagSet<Tags>;
94
+ groups?: GroupSet<Groups>;
99
95
  securitySchemes?: Schemes;
100
96
  requestContext?: RequestContext;
101
97
  validation?: {
102
98
  issueCodes?: readonly Codes[];
103
99
  };
104
100
  plugins?: Plugins;
105
- }): ApiDefinition<R, Tags, Codes, Schemes, RequestContext, Plugins, Jobs_, GuardSchema> {
101
+ }): ApiDefinition<R, Groups, Codes, Schemes, RequestContext, Plugins, Jobs_, GuardSchema> {
106
102
  return {
107
103
  routes: config.routes,
108
104
  guardSchema: config.guardSchema,
109
105
  plugins: config.plugins,
110
106
  jobs: config.jobs,
111
107
  jobsConfig: config.jobsConfig,
112
- tags: config.tags,
108
+ groups: config.groups,
113
109
  securitySchemes: config.securitySchemes,
114
110
  requestContext: config.requestContext,
115
111
  validation: config.validation,
package/src/api.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { HANDLER } from './types.js';
2
+ import { pluginExportsOf } from './plugin-server.js';
2
3
  import type { z } from 'zod';
3
4
  import type { ApiDefinition } from './api-definition.js';
4
5
  import { assembleApi, routerFromRoutes, warnUnsupportedJobOptions, JOBS_META, type ApiParts, type ApiWithRouter } from './adapter.js';
@@ -9,7 +10,7 @@ import type { JobErrorHandler } from './job-runner.js';
9
10
  import type { ApiPlugins } from './plugin.js';
10
11
  import type { Routes } from './types.js';
11
12
  import type { SecurityScheme } from './security-scheme.js';
12
- import type { TagSet, TagOptions } from './tags.js';
13
+ import type { GroupSet } from './groups.js';
13
14
  import type { RequestContextSchema } from './request-context.js';
14
15
 
15
16
  /**
@@ -43,7 +44,7 @@ export interface ApiImplementations {
43
44
  }
44
45
 
45
46
  export interface BuildApiConfig {
46
- tags?: TagSet<Record<string, TagOptions>>;
47
+ groups?: GroupSet;
47
48
  securitySchemes?: Record<string, SecurityScheme>;
48
49
  guardSchema?: z.ZodType;
49
50
  requestContext?: Record<string, RequestContextSchema>;
@@ -89,7 +90,9 @@ export const buildApi = (
89
90
  plugins: implementations.plugins,
90
91
  } as ApiParts;
91
92
 
92
- const api = Object.assign(assembleApi(contract, parts) as Record<string | symbol, unknown>, contract, {
93
+ // At runtime the contract holds each plugin resolved, its options validated and `setup` run.
94
+ const assembled = assembleApi(contract as unknown as Parameters<typeof assembleApi>[0], parts) as Record<string | symbol, unknown>;
95
+ const api = Object.assign(assembled, contract, {
93
96
  [JOBS_META]: contract.jobs
94
97
  ? {
95
98
  jobs: contract.jobs,
@@ -97,6 +100,7 @@ export const buildApi = (
97
100
  config: contract.jobsConfig,
98
101
  transport: implementations.jobTransport,
99
102
  onError: implementations.onJobError,
103
+ plugins: pluginExportsOf(assembled),
100
104
  }
101
105
  : undefined,
102
106
  }) as Record<string, unknown>;
package/src/brand.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { z } from 'zod';
2
+ import { readDef } from './zod-internals.js';
3
+
4
+ /**
5
+ * What a brand wraps. Every client can give a scalar a type of its own.
6
+ */
7
+ export type BrandableSchema = z.ZodType<string | number | bigint | boolean | Date>;
8
+
9
+ const BRANDABLE_TYPES = new Set(['string', 'number', 'bigint', 'boolean', 'date']);
10
+
11
+ /**
12
+ * Brand a Zod schema, so the server and every generated client type its values
13
+ * as that brand. The schema is a string, number, bigint, boolean or date.
14
+ *
15
+ * ```ts
16
+ * const UserId = Kizuna.brand('UserId', z.string());
17
+ * ```
18
+ */
19
+ export const createBrand = <Brand extends string, T extends BrandableSchema>(brand: Brand, schema: T): z.core.$ZodBranded<T, Brand> => {
20
+ const type = readDef(schema).type;
21
+ if (type === undefined || !BRANDABLE_TYPES.has(type)) {
22
+ throw new Error(
23
+ `Kizuna.brand('${brand}') takes a string, number, bigint, boolean or date schema, not \`${type ?? 'unknown'}\`. Put .optional() or .nullable() on the brand instead.`
24
+ );
25
+ }
26
+ return schema.meta({
27
+ brand,
28
+ }) as z.core.$ZodBranded<T, Brand>;
29
+ };