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
@@ -1,45 +1,6 @@
1
- import { T as resolveBaseType, a as WRAPPER_TYPES, c as isBinarySchema, m as readDef, t as ProblemDetailsSchema, w as readObjectShape } from "./error-response-C839d8By.mjs";
1
+ import { g as ROUTES_GROUP, n as PLUGIN_SERVERS_META_KEY, t as PLUGIN_ROUTES_META_KEY } from "./plugin-xxCxibmu.mjs";
2
+ import { E as resolveBaseType, T as readObjectShape, a as WRAPPER_TYPES, c as isBinarySchema, m as readDef, t as ProblemDetailsSchema } from "./error-response-CNQaKVYd.mjs";
2
3
  import { z } from "zod";
3
- //#region src/types.ts
4
- const METHODS = [
5
- "GET",
6
- "HEAD",
7
- "POST",
8
- "PUT",
9
- "PATCH",
10
- "DELETE",
11
- "OPTIONS"
12
- ];
13
- /**
14
- * Key under which every declaration says what it is, so `kizuna generate` can
15
- * tell a route from a job from any other export. A symbol, so nothing that
16
- * walks a declaration's own entries sees it.
17
- */
18
- const DECLARATION = Symbol.for("kizuna.declaration");
19
- /**
20
- * Where a declaration stores what answers it. Off the string keys, so a builder
21
- * can carry both the declaration and the `handler` that attaches one.
22
- */
23
- const HANDLER = Symbol.for("kizuna.handler");
24
- /**
25
- * Key under which a routes group carries its group tag key, the source
26
- * `flattenRoutes` and the generator use to apply the group's tag to every route
27
- * in it. Stamped by `k.routes`.
28
- */
29
- const ROUTES_TAG = Symbol.for("kizuna.routes.tag");
30
- /**
31
- * Type-only key under which `defineConfig` brands each route with its resolved
32
- * handler context. Never written at runtime.
33
- */
34
- const HANDLER_CONTEXT_BRAND = Symbol.for("kizuna.route.handlerContext");
35
- /**
36
- * Type-only key under which `defineConfig` brands a guarded route with the
37
- * statuses its guard answers for it. Never written at runtime.
38
- */
39
- const AUTO_RESPONSES_BRAND = Symbol.for("kizuna.route.autoResponses");
40
- const AUTO_GUARD_BRAND = Symbol.for("kizuna.route.guardBody");
41
- const AUTO_GUARD_WRITTEN_BRAND = Symbol.for("kizuna.route.guardBodyWritten");
42
- //#endregion
43
4
  //#region src/coercion.ts
44
5
  /**
45
6
  * The schema kinds a path/query/header string is coerced into. A field of any
@@ -158,18 +119,21 @@ const isRouteDefinition = (value) => {
158
119
  const candidate = value;
159
120
  return typeof candidate.method === "string" && typeof candidate.path === "string" && !!candidate.responses;
160
121
  };
161
- const flattenRoutes = (routes, prefix, inheritedTags = []) => {
162
- const ownTag = routes[ROUTES_TAG];
163
- const activeTags = ownTag ? [...inheritedTags, ownTag] : inheritedTags;
122
+ /**
123
+ * Flatten a tree of routes, each with its groups.
124
+ */
125
+ const flattenRoutes = (routes, prefix, inheritedGroup) => {
126
+ const declared = routes[ROUTES_GROUP];
127
+ const group = declared === void 0 || declared === "" ? inheritedGroup : declared;
164
128
  const collected = [];
165
129
  for (const [key, value] of Object.entries(routes)) {
166
130
  const fullKey = prefix ? `${prefix}.${key}` : key;
167
131
  if (isRouteDefinition(value)) collected.push({
168
132
  routeKey: fullKey,
169
133
  route: value,
170
- routeTags: activeTags
134
+ routeGroups: [...new Set([...group === void 0 ? [] : [group], ...value.groups ?? []])]
171
135
  });
172
- else if (value && typeof value === "object") collected.push(...flattenRoutes(value, fullKey, activeTags));
136
+ else if (value && typeof value === "object") collected.push(...flattenRoutes(value, fullKey, group));
173
137
  }
174
138
  return collected;
175
139
  };
@@ -544,6 +508,47 @@ const encodeStreamBody = (source, options) => {
544
508
  });
545
509
  };
546
510
  //#endregion
511
+ //#region src/tool-name.ts
512
+ /**
513
+ * Set by the MCP specification.
514
+ *
515
+ * @see https://modelcontextprotocol.io/specification/latest/server/tools
516
+ */
517
+ const MAX_TOOL_NAME_LENGTH = 128;
518
+ /**
519
+ * The specification allows a dot too, and kizuna's own route and tool keys are
520
+ * dotted. Claude and GitHub Copilot validate against this narrower set and
521
+ * reject the whole tool list over one name outside it, so the dot does not
522
+ * survive here.
523
+ */
524
+ const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
525
+ const toSnakeCase = (segment) => segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
526
+ /**
527
+ * `users.listUsers` becomes `users_list_users`, the shape MCP servers publish
528
+ * and models are trained on.
529
+ */
530
+ const toToolName = (key) => key.split(".").map(toSnakeCase).join("_");
531
+ const sentenceLabel = (origin) => origin === "route" ? "Route" : "Tool";
532
+ /**
533
+ * Every key mapped to its published tool name, throwing on a name MCP clients
534
+ * reject and on two keys that converge on one name.
535
+ */
536
+ const deriveToolNames = (entries) => {
537
+ const names = /* @__PURE__ */ new Map();
538
+ const claimedBy = /* @__PURE__ */ new Map();
539
+ for (const entry of entries) {
540
+ const { key, origin } = entry;
541
+ const name = toToolName(key);
542
+ if (!TOOL_NAME_PATTERN.test(name)) throw new Error(`${sentenceLabel(origin)} "${key}" becomes the tool name "${name}", which contains characters outside the letters, digits, underscore, and dash that MCP clients accept. Rename the ${origin}.`);
543
+ if (name.length > MAX_TOOL_NAME_LENGTH) throw new Error(`${sentenceLabel(origin)} "${key}" becomes the tool name "${name}", which is ${name.length} characters, exceeding the MCP maximum of ${MAX_TOOL_NAME_LENGTH}. Use a shorter key.`);
544
+ const claimant = claimedBy.get(name);
545
+ if (claimant !== void 0) throw new Error(`${sentenceLabel(claimant.origin)} "${claimant.key}" and ${origin} "${key}" both become the tool name "${name}". Rename one of them.`);
546
+ claimedBy.set(name, entry);
547
+ names.set(key, name);
548
+ }
549
+ return names;
550
+ };
551
+ //#endregion
547
552
  //#region src/schedule.ts
548
553
  /**
549
554
  * The cron expression of a {@link JobSchedule}, whichever form it was written in.
@@ -925,7 +930,7 @@ const cron = {
925
930
  //#endregion
926
931
  //#region src/jobs.ts
927
932
  /**
928
- * The namespace the job endpoints are mounted under when `jobs.path` says
933
+ * The namespace the job endpoints are mounted under when `jobRunner.path` says
929
934
  * nothing.
930
935
  */
931
936
  const DEFAULT_JOBS_PATH = "/jobs";
@@ -1051,8 +1056,20 @@ const isCompiledJob = (value) => {
1051
1056
  * Throws when either job endpoint lands on a path an API route already serves.
1052
1057
  * Called by `defineConfig`, the one place that sees both.
1053
1058
  */
1059
+ /**
1060
+ * Throw when declared jobs do not say how they run, or when the job endpoints
1061
+ * would be served with no identity guarding them.
1062
+ */
1063
+ const assertJobRunner = (jobs, config) => {
1064
+ const flattened = jobs ? flattenJobs(jobs) : [];
1065
+ if (flattened.length === 0) return;
1066
+ if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process.");
1067
+ if (config.mode === "in-process" || flattened.some(({ job }) => job.identity !== void 0)) return;
1068
+ const base = config.path ?? "/jobs";
1069
+ throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'in-process' }\` when the jobs run in this process with \`startJobs\`.`);
1070
+ };
1054
1071
  const jobClaims = (jobs, config) => {
1055
- if (!jobs || flattenJobs(jobs).length === 0) return [];
1072
+ if (!jobs || config?.mode === "in-process" || flattenJobs(jobs).length === 0) return [];
1056
1073
  const base = config?.path ?? "/jobs";
1057
1074
  return [{
1058
1075
  method: config?.method ?? "POST",
@@ -1169,4 +1186,126 @@ const assertValidCache = (routes) => {
1169
1186
  }
1170
1187
  };
1171
1188
  //#endregion
1172
- export { allowedMethodsForPath as $, streamSchemas as A, resolveResponseCache as B, assertValidStreams as C, soleStreamResponse as D, routeStreams as E, isSuccessStatus as F, sanitizeFieldName as G, resolveResponseEtag as H, isZodSchema as I, statusToCamelCase as J, sanitizeIdentifier as K, localTypeName as L, isHintPrefix as M, isJsonMediaType as N, streamContentType as O, isStreamResponse as P, parsePath as Q, mergeHeaderFields as R, EVENT_STREAM_MEDIA_TYPE as S, isNamedStream as T, resolveResponseHeaders as U, resolveResponseContentType as V, resolveResponseStream as W, toPascalCase as X, toCamelCase as Y, buildPath as Z, nextRun as _, DEFAULT_JOBS_PATH as a, AUTO_GUARD_BRAND as at, scheduleExpression as b, isCompiledJob as c, DECLARATION as ct, jobClaims as d, METHODS as dt, flattenRoutes as et, toJobResponse as f, ROUTES_TAG as ft, firesBetween as g, dueSchedules as h, deprecationHeaders as i, resolveCoercionPlans as it, streamStatuses as j, streamMode as k, isJobDefinition as l, HANDLER as lt, cron as m, cacheHeaders as n, isRouteDefinition as nt, buildJobs as o, AUTO_GUARD_WRITTEN_BRAND as ot, assertValidSchedule as p, shortTypeName as q, assertValidDeprecationDates as r, validateRequest as rt, flattenJobs as s, AUTO_RESPONSES_BRAND as st, assertValidCache as t, formatValidationError as tt, jobAt as u, HANDLER_CONTEXT_BRAND as ut, nextRuns as v, encodeStreamBody as w, scheduleTimezone as x, parseCron as y, resolveResponseBody as z };
1189
+ //#region src/plugin-server.ts
1190
+ /**
1191
+ * The plugin routes `assembleApi` stashed on the api. Empty without plugins, so
1192
+ * an adapter can mount it unconditionally.
1193
+ */
1194
+ const pluginRoutesOf = (api) => api[PLUGIN_ROUTES_META_KEY] ?? {};
1195
+ /**
1196
+ * Their handlers, keyed to match {@link pluginRoutesOf}.
1197
+ */
1198
+ const pluginRouterOf = (api) => {
1199
+ const servers = api[PLUGIN_SERVERS_META_KEY];
1200
+ const router = {};
1201
+ for (const [pluginKey, served] of Object.entries(servers ?? {})) router[pluginKey] = served.router;
1202
+ return router;
1203
+ };
1204
+ /**
1205
+ * What each plugin exports, for the adapter to pass into the pipeline as the
1206
+ * handler args' `plugins`.
1207
+ */
1208
+ const pluginExportsOf = (api) => {
1209
+ const servers = api[PLUGIN_SERVERS_META_KEY];
1210
+ const exported = {};
1211
+ for (const [pluginKey, served] of Object.entries(servers ?? {})) if (served.exports !== void 0) exported[pluginKey] = served.exports;
1212
+ return exported;
1213
+ };
1214
+ /**
1215
+ * One issue as the app should read it: the field, and what's wrong with it.
1216
+ */
1217
+ const describeIssue = (issue) => {
1218
+ const field = issue.path.map(String).join(".");
1219
+ if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) return `${field} is required`;
1220
+ return field === "" ? issue.message : `${field}: ${issue.message}`;
1221
+ };
1222
+ /**
1223
+ * A route's path under its plugin's base path. A route at `/` serves the base
1224
+ * path itself, since `/webhooks` and `/webhooks/` are different paths.
1225
+ */
1226
+ const underBasePath = (basePath, path) => path === "/" ? basePath : `${basePath}${path}`;
1227
+ /**
1228
+ * The base path a plugin's routes are served under: the app's, else the
1229
+ * plugin's own. An app can only move a plugin that declares one.
1230
+ */
1231
+ const basePathOf = (declaration) => {
1232
+ const { definition, slug } = declaration;
1233
+ if (declaration.basePath !== void 0 && definition.basePath === void 0) throw new Error(`[kizuna] Plugin '${slug}' declares no \`basePath\`, so its routes can't be moved. Remove \`basePath\`.`);
1234
+ const basePath = declaration.basePath ?? definition.basePath;
1235
+ if (basePath !== void 0 && (!basePath.startsWith("/") || basePath.endsWith("/"))) throw new Error(`[kizuna] Plugin '${slug}' has the base path '${basePath}'. A base path starts with \`/\` and doesn't end with one.`);
1236
+ return basePath;
1237
+ };
1238
+ /**
1239
+ * Validate one installed plugin's options and run its `setup`.
1240
+ */
1241
+ const resolvePlugin = (declaration, api) => {
1242
+ const { definition, slug } = declaration;
1243
+ let options = void 0;
1244
+ if (definition.options !== void 0) {
1245
+ const parsed = definition.options.safeParse(declaration.input);
1246
+ if (!parsed.success) throw new Error(`[kizuna] Plugin '${slug}' has invalid options: ${parsed.error.issues.map(describeIssue).join("; ")}`);
1247
+ options = parsed.data;
1248
+ }
1249
+ const setup = definition.setup({
1250
+ options,
1251
+ api
1252
+ });
1253
+ const basePath = basePathOf(declaration);
1254
+ const routes = setup.routes ?? {};
1255
+ return {
1256
+ slug,
1257
+ definedSlug: definition.slug,
1258
+ options,
1259
+ routes: basePath === void 0 ? routes : Object.fromEntries(Object.entries(routes).map(([routeKey, route]) => [routeKey, {
1260
+ ...route,
1261
+ path: underBasePath(basePath, route.path)
1262
+ }])),
1263
+ exports: setup.exports,
1264
+ generators: setup.generators ?? [],
1265
+ validate: setup.validate
1266
+ };
1267
+ };
1268
+ /**
1269
+ * Resolve every installed plugin, keyed by slug. Two plugins on one slug throw,
1270
+ * naming both, since handlers could only reach one of them.
1271
+ */
1272
+ const resolvePlugins = (declarations, api) => {
1273
+ const resolved = {};
1274
+ for (const declaration of declarations ?? []) {
1275
+ const existing = resolved[declaration.slug];
1276
+ if (existing !== void 0) throw new Error(`[kizuna] Two plugins are installed under the slug '${declaration.slug}': '${existing.definedSlug}' and '${declaration.definition.slug}'. Pass one of them a \`slug\` of its own.`);
1277
+ resolved[declaration.slug] = resolvePlugin(declaration, api);
1278
+ }
1279
+ return resolved;
1280
+ };
1281
+ /**
1282
+ * A stand-in for the api that plugins receive in `setup`, before it exists.
1283
+ * Reading it inside a handler works once `bind` has run; reading it during
1284
+ * `setup` throws, since the api is still being assembled.
1285
+ */
1286
+ const createApiReference = () => {
1287
+ let current;
1288
+ const assembled = () => {
1289
+ if (current === void 0) throw new Error("[kizuna] A plugin read the api during `setup`. Read it inside a handler, once the config has assembled.");
1290
+ return current;
1291
+ };
1292
+ return {
1293
+ api: new Proxy({}, {
1294
+ get: (_target, key) => Reflect.get(assembled(), key),
1295
+ has: (_target, key) => Reflect.has(assembled(), key),
1296
+ ownKeys: () => Reflect.ownKeys(assembled()),
1297
+ getOwnPropertyDescriptor: (_target, key) => {
1298
+ const descriptor = Reflect.getOwnPropertyDescriptor(assembled(), key);
1299
+ return descriptor === void 0 ? void 0 : {
1300
+ ...descriptor,
1301
+ configurable: true
1302
+ };
1303
+ }
1304
+ }),
1305
+ bind: (target) => {
1306
+ current = target;
1307
+ }
1308
+ };
1309
+ };
1310
+ //#endregion
1311
+ export { resolveResponseStream as $, toToolName as A, streamStatuses as B, firesBetween as C, scheduleExpression as D, parseCron as E, routeStreams as F, isZodSchema as G, isJsonMediaType as H, soleStreamResponse as I, resolveResponseBody as J, localTypeName as K, streamContentType as L, assertValidStreams as M, encodeStreamBody as N, scheduleTimezone as O, isNamedStream as P, resolveResponseHeaders as Q, streamMode as R, dueSchedules as S, nextRuns as T, isStreamResponse as U, isHintPrefix as V, isSuccessStatus as W, resolveResponseContentType as X, resolveResponseCache as Y, resolveResponseEtag as Z, jobAt as _, pluginRoutesOf as a, toPascalCase as at, assertValidSchedule as b, cacheHeaders as c, allowedMethodsForPath as ct, DEFAULT_JOBS_PATH as d, isRouteDefinition as dt, sanitizeFieldName as et, assertJobRunner as f, validateRequest as ft, isJobDefinition as g, isCompiledJob as h, pluginRouterOf as i, toCamelCase as it, EVENT_STREAM_MEDIA_TYPE as j, deriveToolNames as k, assertValidDeprecationDates as l, flattenRoutes as lt, flattenJobs as m, describeIssue as n, shortTypeName as nt, resolvePlugins as o, buildPath as ot, buildJobs as p, resolveCoercionPlans as pt, mergeHeaderFields as q, pluginExportsOf as r, statusToCamelCase as rt, assertValidCache as s, parsePath as st, createApiReference as t, sanitizeIdentifier as tt, deprecationHeaders as u, formatValidationError as ut, jobClaims as v, nextRun as w, cron as x, toJobResponse as y, streamSchemas as z };