@mastra/deployer 0.0.0-commonjs-20250227130920

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 (86) hide show
  1. package/.turbo/turbo-build.log +41 -0
  2. package/CHANGELOG.md +897 -0
  3. package/LICENSE +44 -0
  4. package/README.md +159 -0
  5. package/dist/_tsup-dts-rollup.d.cts +360 -0
  6. package/dist/_tsup-dts-rollup.d.ts +360 -0
  7. package/dist/build/analyze.cjs +367 -0
  8. package/dist/build/analyze.d.cts +1 -0
  9. package/dist/build/analyze.d.ts +1 -0
  10. package/dist/build/analyze.js +2 -0
  11. package/dist/build/bundler.cjs +353 -0
  12. package/dist/build/bundler.d.cts +2 -0
  13. package/dist/build/bundler.d.ts +2 -0
  14. package/dist/build/bundler.js +2 -0
  15. package/dist/build/index.cjs +1146 -0
  16. package/dist/build/index.d.cts +10 -0
  17. package/dist/build/index.d.ts +10 -0
  18. package/dist/build/index.js +5 -0
  19. package/dist/bundler/index.cjs +999 -0
  20. package/dist/bundler/index.d.cts +1 -0
  21. package/dist/bundler/index.d.ts +1 -0
  22. package/dist/bundler/index.js +5 -0
  23. package/dist/chunk-3ONBKVC4.js +113 -0
  24. package/dist/chunk-AXS5WSIK.js +290 -0
  25. package/dist/chunk-DTSFVNIF.js +260 -0
  26. package/dist/chunk-JMH7HCD6.js +274 -0
  27. package/dist/chunk-SGK37ZWD.js +254 -0
  28. package/dist/chunk-YNXJO2XU.js +69 -0
  29. package/dist/index.cjs +1229 -0
  30. package/dist/index.d.cts +6 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +131 -0
  33. package/dist/server/index.cjs +4930 -0
  34. package/dist/server/index.d.cts +2 -0
  35. package/dist/server/index.d.ts +2 -0
  36. package/dist/server/index.js +4923 -0
  37. package/dist/templates/instrumentation-template.js +86 -0
  38. package/eslint.config.js +6 -0
  39. package/global.d.ts +0 -0
  40. package/package.json +112 -0
  41. package/public/templates/instrumentation-template.js +86 -0
  42. package/src/build/analyze.ts +279 -0
  43. package/src/build/babel/fix-libsql.ts +41 -0
  44. package/src/build/babel/get-deployer.ts +54 -0
  45. package/src/build/babel/get-telemetry-config.ts +62 -0
  46. package/src/build/babel/remove-deployer.ts +43 -0
  47. package/src/build/bundle.ts +139 -0
  48. package/src/build/bundler.ts +135 -0
  49. package/src/build/deployer.ts +67 -0
  50. package/src/build/deps.ts +149 -0
  51. package/src/build/env.ts +76 -0
  52. package/src/build/fs.ts +66 -0
  53. package/src/build/index.ts +7 -0
  54. package/src/build/isNodeBuiltin.ts +7 -0
  55. package/src/build/plugins/fix-libsql.ts +69 -0
  56. package/src/build/plugins/hono-alias.ts +17 -0
  57. package/src/build/plugins/pino.ts +93 -0
  58. package/src/build/plugins/remove-deployer.ts +37 -0
  59. package/src/build/plugins/telemetry-fix.ts +54 -0
  60. package/src/build/telemetry.ts +76 -0
  61. package/src/build/utils.ts +12 -0
  62. package/src/build/watcher.ts +43 -0
  63. package/src/bundler/index.ts +144 -0
  64. package/src/deploy/base.ts +30 -0
  65. package/src/deploy/index.ts +2 -0
  66. package/src/deploy/log.ts +61 -0
  67. package/src/index.ts +3 -0
  68. package/src/server/handlers/agents.ts +209 -0
  69. package/src/server/handlers/client.ts +36 -0
  70. package/src/server/handlers/error.ts +29 -0
  71. package/src/server/handlers/logs.ts +53 -0
  72. package/src/server/handlers/memory.ts +196 -0
  73. package/src/server/handlers/prompt.ts +128 -0
  74. package/src/server/handlers/root.ts +6 -0
  75. package/src/server/handlers/telemetry.ts +48 -0
  76. package/src/server/handlers/tools.ts +114 -0
  77. package/src/server/handlers/utils.ts +15 -0
  78. package/src/server/handlers/vector.ts +149 -0
  79. package/src/server/handlers/workflows.ts +119 -0
  80. package/src/server/index.ts +1355 -0
  81. package/src/server/openapi.json +434 -0
  82. package/src/server/openapi.script.js +22 -0
  83. package/src/server/types.ts +4 -0
  84. package/src/server/welcome.ts +105 -0
  85. package/tsconfig.json +5 -0
  86. package/vitest.config.ts +8 -0
@@ -0,0 +1,4930 @@
1
+ 'use strict';
2
+
3
+ var promises = require('fs/promises');
4
+ var path = require('path');
5
+ var url = require('url');
6
+ var http = require('http');
7
+ var http2 = require('http2');
8
+ var stream = require('stream');
9
+ var crypto = require('crypto');
10
+ var filepath = require('hono/utils/filepath');
11
+ var mime = require('hono/utils/mime');
12
+ var fs = require('fs');
13
+ var html = require('hono/html');
14
+ var hono = require('hono');
15
+ var bodyLimit = require('hono/body-limit');
16
+ var cors = require('hono/cors');
17
+ var logger = require('hono/logger');
18
+ var httpException = require('hono/http-exception');
19
+ var zod = require('zod');
20
+ var agent = require('@mastra/core/agent');
21
+ var streaming = require('hono/streaming');
22
+
23
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
24
+
25
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
26
+
27
+ // src/server/index.ts
28
+ var RequestError = class extends Error {
29
+ static name = "RequestError";
30
+ constructor(message, options) {
31
+ super(message, options);
32
+ }
33
+ };
34
+ var toRequestError = (e2) => {
35
+ if (e2 instanceof RequestError) {
36
+ return e2;
37
+ }
38
+ return new RequestError(e2.message, { cause: e2 });
39
+ };
40
+ var GlobalRequest = global.Request;
41
+ var Request = class extends GlobalRequest {
42
+ constructor(input, options) {
43
+ if (typeof input === "object" && getRequestCache in input) {
44
+ input = input[getRequestCache]();
45
+ }
46
+ if (typeof options?.body?.getReader !== "undefined") {
47
+ options.duplex ??= "half";
48
+ }
49
+ super(input, options);
50
+ }
51
+ };
52
+ var newRequestFromIncoming = (method, url, incoming, abortController) => {
53
+ const headerRecord = [];
54
+ const rawHeaders = incoming.rawHeaders;
55
+ for (let i2 = 0; i2 < rawHeaders.length; i2 += 2) {
56
+ const { [i2]: key, [i2 + 1]: value } = rawHeaders;
57
+ if (key.charCodeAt(0) !== /*:*/
58
+ 58) {
59
+ headerRecord.push([key, value]);
60
+ }
61
+ }
62
+ const init = {
63
+ method,
64
+ headers: headerRecord,
65
+ signal: abortController.signal
66
+ };
67
+ if (method === "TRACE") {
68
+ init.method = "GET";
69
+ const req = new Request(url, init);
70
+ Object.defineProperty(req, "method", {
71
+ get() {
72
+ return "TRACE";
73
+ }
74
+ });
75
+ return req;
76
+ }
77
+ if (!(method === "GET" || method === "HEAD")) {
78
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
79
+ init.body = new ReadableStream({
80
+ start(controller) {
81
+ controller.enqueue(incoming.rawBody);
82
+ controller.close();
83
+ }
84
+ });
85
+ } else {
86
+ init.body = stream.Readable.toWeb(incoming);
87
+ }
88
+ }
89
+ return new Request(url, init);
90
+ };
91
+ var getRequestCache = Symbol("getRequestCache");
92
+ var requestCache = Symbol("requestCache");
93
+ var incomingKey = Symbol("incomingKey");
94
+ var urlKey = Symbol("urlKey");
95
+ var abortControllerKey = Symbol("abortControllerKey");
96
+ var getAbortController = Symbol("getAbortController");
97
+ var requestPrototype = {
98
+ get method() {
99
+ return this[incomingKey].method || "GET";
100
+ },
101
+ get url() {
102
+ return this[urlKey];
103
+ },
104
+ [getAbortController]() {
105
+ this[getRequestCache]();
106
+ return this[abortControllerKey];
107
+ },
108
+ [getRequestCache]() {
109
+ this[abortControllerKey] ||= new AbortController();
110
+ return this[requestCache] ||= newRequestFromIncoming(
111
+ this.method,
112
+ this[urlKey],
113
+ this[incomingKey],
114
+ this[abortControllerKey]
115
+ );
116
+ }
117
+ };
118
+ [
119
+ "body",
120
+ "bodyUsed",
121
+ "cache",
122
+ "credentials",
123
+ "destination",
124
+ "headers",
125
+ "integrity",
126
+ "mode",
127
+ "redirect",
128
+ "referrer",
129
+ "referrerPolicy",
130
+ "signal",
131
+ "keepalive"
132
+ ].forEach((k) => {
133
+ Object.defineProperty(requestPrototype, k, {
134
+ get() {
135
+ return this[getRequestCache]()[k];
136
+ }
137
+ });
138
+ });
139
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
140
+ Object.defineProperty(requestPrototype, k, {
141
+ value: function() {
142
+ return this[getRequestCache]()[k]();
143
+ }
144
+ });
145
+ });
146
+ Object.setPrototypeOf(requestPrototype, Request.prototype);
147
+ var newRequest = (incoming, defaultHostname) => {
148
+ const req = Object.create(requestPrototype);
149
+ req[incomingKey] = incoming;
150
+ const host = (incoming instanceof http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
151
+ if (!host) {
152
+ throw new RequestError("Missing host header");
153
+ }
154
+ const url = new URL(
155
+ `${incoming instanceof http2.Http2ServerRequest || incoming.socket && incoming.socket.encrypted ? "https" : "http"}://${host}${incoming.url}`
156
+ );
157
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
158
+ throw new RequestError("Invalid host header");
159
+ }
160
+ req[urlKey] = url.href;
161
+ return req;
162
+ };
163
+ function writeFromReadableStream(stream, writable) {
164
+ if (stream.locked) {
165
+ throw new TypeError("ReadableStream is locked.");
166
+ } else if (writable.destroyed) {
167
+ stream.cancel();
168
+ return;
169
+ }
170
+ const reader = stream.getReader();
171
+ writable.on("close", cancel);
172
+ writable.on("error", cancel);
173
+ reader.read().then(flow, cancel);
174
+ return reader.closed.finally(() => {
175
+ writable.off("close", cancel);
176
+ writable.off("error", cancel);
177
+ });
178
+ function cancel(error) {
179
+ reader.cancel(error).catch(() => {
180
+ });
181
+ if (error) {
182
+ writable.destroy(error);
183
+ }
184
+ }
185
+ function onDrain() {
186
+ reader.read().then(flow, cancel);
187
+ }
188
+ function flow({ done, value }) {
189
+ try {
190
+ if (done) {
191
+ writable.end();
192
+ } else if (!writable.write(value)) {
193
+ writable.once("drain", onDrain);
194
+ } else {
195
+ return reader.read().then(flow, cancel);
196
+ }
197
+ } catch (e2) {
198
+ cancel(e2);
199
+ }
200
+ }
201
+ }
202
+ var buildOutgoingHttpHeaders = (headers) => {
203
+ const res = {};
204
+ if (!(headers instanceof Headers)) {
205
+ headers = new Headers(headers ?? void 0);
206
+ }
207
+ const cookies = [];
208
+ for (const [k, v] of headers) {
209
+ if (k === "set-cookie") {
210
+ cookies.push(v);
211
+ } else {
212
+ res[k] = v;
213
+ }
214
+ }
215
+ if (cookies.length > 0) {
216
+ res["set-cookie"] = cookies;
217
+ }
218
+ res["content-type"] ??= "text/plain; charset=UTF-8";
219
+ return res;
220
+ };
221
+ var responseCache = Symbol("responseCache");
222
+ var getResponseCache = Symbol("getResponseCache");
223
+ var cacheKey = Symbol("cache");
224
+ var GlobalResponse = global.Response;
225
+ var Response2 = class _Response {
226
+ #body;
227
+ #init;
228
+ [getResponseCache]() {
229
+ delete this[cacheKey];
230
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
231
+ }
232
+ constructor(body, init) {
233
+ this.#body = body;
234
+ if (init instanceof _Response) {
235
+ const cachedGlobalResponse = init[responseCache];
236
+ if (cachedGlobalResponse) {
237
+ this.#init = cachedGlobalResponse;
238
+ this[getResponseCache]();
239
+ return;
240
+ } else {
241
+ this.#init = init.#init;
242
+ }
243
+ } else {
244
+ this.#init = init;
245
+ }
246
+ if (typeof body === "string" || typeof body?.getReader !== "undefined") {
247
+ let headers = init?.headers || { "content-type": "text/plain; charset=UTF-8" };
248
+ if (headers instanceof Headers) {
249
+ headers = buildOutgoingHttpHeaders(headers);
250
+ }
251
+ this[cacheKey] = [init?.status || 200, body, headers];
252
+ }
253
+ }
254
+ };
255
+ [
256
+ "body",
257
+ "bodyUsed",
258
+ "headers",
259
+ "ok",
260
+ "redirected",
261
+ "status",
262
+ "statusText",
263
+ "trailers",
264
+ "type",
265
+ "url"
266
+ ].forEach((k) => {
267
+ Object.defineProperty(Response2.prototype, k, {
268
+ get() {
269
+ return this[getResponseCache]()[k];
270
+ }
271
+ });
272
+ });
273
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
274
+ Object.defineProperty(Response2.prototype, k, {
275
+ value: function() {
276
+ return this[getResponseCache]()[k]();
277
+ }
278
+ });
279
+ });
280
+ Object.setPrototypeOf(Response2, GlobalResponse);
281
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
282
+ var stateKey = Reflect.ownKeys(new GlobalResponse()).find(
283
+ (k) => typeof k === "symbol" && k.toString() === "Symbol(state)"
284
+ );
285
+ if (!stateKey) {
286
+ console.warn("Failed to find Response internal state key");
287
+ }
288
+ function getInternalBody(response) {
289
+ if (!stateKey) {
290
+ return;
291
+ }
292
+ if (response instanceof Response2) {
293
+ response = response[getResponseCache]();
294
+ }
295
+ const state = response[stateKey];
296
+ return state && state.body || void 0;
297
+ }
298
+ var X_ALREADY_SENT = "x-hono-already-sent";
299
+ var webFetch = global.fetch;
300
+ if (typeof global.crypto === "undefined") {
301
+ global.crypto = crypto__default.default;
302
+ }
303
+ global.fetch = (info, init) => {
304
+ init = {
305
+ // Disable compression handling so people can return the result of a fetch
306
+ // directly in the loader without messing with the Content-Encoding header.
307
+ compress: false,
308
+ ...init
309
+ };
310
+ return webFetch(info, init);
311
+ };
312
+ var regBuffer = /^no$/i;
313
+ var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
314
+ var handleRequestError = () => new Response(null, {
315
+ status: 400
316
+ });
317
+ var handleFetchError = (e2) => new Response(null, {
318
+ status: e2 instanceof Error && (e2.name === "TimeoutError" || e2.constructor.name === "TimeoutError") ? 504 : 500
319
+ });
320
+ var handleResponseError = (e2, outgoing) => {
321
+ const err = e2 instanceof Error ? e2 : new Error("unknown error", { cause: e2 });
322
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
323
+ console.info("The user aborted a request.");
324
+ } else {
325
+ console.error(e2);
326
+ if (!outgoing.headersSent) {
327
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
328
+ }
329
+ outgoing.end(`Error: ${err.message}`);
330
+ outgoing.destroy(err);
331
+ }
332
+ };
333
+ var responseViaCache = (res, outgoing) => {
334
+ const [status, body, header] = res[cacheKey];
335
+ if (typeof body === "string") {
336
+ header["Content-Length"] = Buffer.byteLength(body);
337
+ outgoing.writeHead(status, header);
338
+ outgoing.end(body);
339
+ } else {
340
+ outgoing.writeHead(status, header);
341
+ return writeFromReadableStream(body, outgoing)?.catch(
342
+ (e2) => handleResponseError(e2, outgoing)
343
+ );
344
+ }
345
+ };
346
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
347
+ if (res instanceof Promise) {
348
+ if (options.errorHandler) {
349
+ try {
350
+ res = await res;
351
+ } catch (err) {
352
+ const errRes = await options.errorHandler(err);
353
+ if (!errRes) {
354
+ return;
355
+ }
356
+ res = errRes;
357
+ }
358
+ } else {
359
+ res = await res.catch(handleFetchError);
360
+ }
361
+ }
362
+ if (cacheKey in res) {
363
+ return responseViaCache(res, outgoing);
364
+ }
365
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
366
+ const internalBody = getInternalBody(res);
367
+ if (internalBody) {
368
+ const { length, source, stream } = internalBody;
369
+ if (source instanceof Uint8Array && source.byteLength !== length) ; else {
370
+ if (length) {
371
+ resHeaderRecord["content-length"] = length;
372
+ }
373
+ outgoing.writeHead(res.status, resHeaderRecord);
374
+ if (typeof source === "string" || source instanceof Uint8Array) {
375
+ outgoing.end(source);
376
+ } else if (source instanceof Blob) {
377
+ outgoing.end(new Uint8Array(await source.arrayBuffer()));
378
+ } else {
379
+ await writeFromReadableStream(stream, outgoing);
380
+ }
381
+ return;
382
+ }
383
+ }
384
+ if (res.body) {
385
+ const {
386
+ "transfer-encoding": transferEncoding,
387
+ "content-encoding": contentEncoding,
388
+ "content-length": contentLength,
389
+ "x-accel-buffering": accelBuffering,
390
+ "content-type": contentType
391
+ } = resHeaderRecord;
392
+ if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
393
+ accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
394
+ outgoing.writeHead(res.status, resHeaderRecord);
395
+ await writeFromReadableStream(res.body, outgoing);
396
+ } else {
397
+ const buffer = await res.arrayBuffer();
398
+ resHeaderRecord["content-length"] = buffer.byteLength;
399
+ outgoing.writeHead(res.status, resHeaderRecord);
400
+ outgoing.end(new Uint8Array(buffer));
401
+ }
402
+ } else if (resHeaderRecord[X_ALREADY_SENT]) ; else {
403
+ outgoing.writeHead(res.status, resHeaderRecord);
404
+ outgoing.end();
405
+ }
406
+ };
407
+ var getRequestListener = (fetchCallback, options = {}) => {
408
+ if (options.overrideGlobalObjects !== false && global.Request !== Request) {
409
+ Object.defineProperty(global, "Request", {
410
+ value: Request
411
+ });
412
+ Object.defineProperty(global, "Response", {
413
+ value: Response2
414
+ });
415
+ }
416
+ return async (incoming, outgoing) => {
417
+ let res, req;
418
+ try {
419
+ req = newRequest(incoming, options.hostname);
420
+ outgoing.on("close", () => {
421
+ const abortController = req[abortControllerKey];
422
+ if (!abortController) {
423
+ return;
424
+ }
425
+ if (incoming.errored) {
426
+ req[abortControllerKey].abort(incoming.errored.toString());
427
+ } else if (!outgoing.writableFinished) {
428
+ req[abortControllerKey].abort("Client connection prematurely closed.");
429
+ }
430
+ });
431
+ res = fetchCallback(req, { incoming, outgoing });
432
+ if (cacheKey in res) {
433
+ return responseViaCache(res, outgoing);
434
+ }
435
+ } catch (e2) {
436
+ if (!res) {
437
+ if (options.errorHandler) {
438
+ res = await options.errorHandler(req ? e2 : toRequestError(e2));
439
+ if (!res) {
440
+ return;
441
+ }
442
+ } else if (!req) {
443
+ res = handleRequestError();
444
+ } else {
445
+ res = handleFetchError(e2);
446
+ }
447
+ } else {
448
+ return handleResponseError(e2, outgoing);
449
+ }
450
+ }
451
+ try {
452
+ return responseViaResponseObject(res, outgoing, options);
453
+ } catch (e2) {
454
+ return handleResponseError(e2, outgoing);
455
+ }
456
+ };
457
+ };
458
+ var createAdaptorServer = (options) => {
459
+ const fetchCallback = options.fetch;
460
+ const requestListener = getRequestListener(fetchCallback, {
461
+ hostname: options.hostname,
462
+ overrideGlobalObjects: options.overrideGlobalObjects
463
+ });
464
+ const createServer = options.createServer || http.createServer;
465
+ const server = createServer(options.serverOptions || {}, requestListener);
466
+ return server;
467
+ };
468
+ var serve = (options, listeningListener) => {
469
+ const server = createAdaptorServer(options);
470
+ server.listen(options?.port, options.hostname, () => {
471
+ const serverInfo = server.address();
472
+ listeningListener && listeningListener(serverInfo);
473
+ });
474
+ return server;
475
+ };
476
+ var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
477
+ var ENCODINGS = {
478
+ br: ".br",
479
+ zstd: ".zst",
480
+ gzip: ".gz"
481
+ };
482
+ var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
483
+ var createStreamBody = (stream) => {
484
+ const body = new ReadableStream({
485
+ start(controller) {
486
+ stream.on("data", (chunk) => {
487
+ controller.enqueue(chunk);
488
+ });
489
+ stream.on("end", () => {
490
+ controller.close();
491
+ });
492
+ },
493
+ cancel() {
494
+ stream.destroy();
495
+ }
496
+ });
497
+ return body;
498
+ };
499
+ var addCurrentDirPrefix = (path) => {
500
+ return `./${path}`;
501
+ };
502
+ var getStats = (path) => {
503
+ let stats;
504
+ try {
505
+ stats = fs.lstatSync(path);
506
+ } catch {
507
+ }
508
+ return stats;
509
+ };
510
+ var serveStatic = (options = { root: "" }) => {
511
+ return async (c2, next) => {
512
+ if (c2.finalized) {
513
+ return next();
514
+ }
515
+ let filename;
516
+ try {
517
+ filename = options.path ?? decodeURIComponent(c2.req.path);
518
+ } catch {
519
+ await options.onNotFound?.(c2.req.path, c2);
520
+ return next();
521
+ }
522
+ let path = filepath.getFilePathWithoutDefaultDocument({
523
+ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
524
+ root: options.root
525
+ });
526
+ if (path) {
527
+ path = addCurrentDirPrefix(path);
528
+ } else {
529
+ return next();
530
+ }
531
+ let stats = getStats(path);
532
+ if (stats && stats.isDirectory()) {
533
+ path = filepath.getFilePath({
534
+ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
535
+ root: options.root,
536
+ defaultDocument: options.index ?? "index.html"
537
+ });
538
+ if (path) {
539
+ path = addCurrentDirPrefix(path);
540
+ } else {
541
+ return next();
542
+ }
543
+ stats = getStats(path);
544
+ }
545
+ if (!stats) {
546
+ await options.onNotFound?.(path, c2);
547
+ return next();
548
+ }
549
+ await options.onFound?.(path, c2);
550
+ const mimeType = mime.getMimeType(path);
551
+ c2.header("Content-Type", mimeType || "application/octet-stream");
552
+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
553
+ const acceptEncodingSet = new Set(
554
+ c2.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
555
+ );
556
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
557
+ if (!acceptEncodingSet.has(encoding)) {
558
+ continue;
559
+ }
560
+ const precompressedStats = getStats(path + ENCODINGS[encoding]);
561
+ if (precompressedStats) {
562
+ c2.header("Content-Encoding", encoding);
563
+ c2.header("Vary", "Accept-Encoding", { append: true });
564
+ stats = precompressedStats;
565
+ path = path + ENCODINGS[encoding];
566
+ break;
567
+ }
568
+ }
569
+ }
570
+ const size = stats.size;
571
+ if (c2.req.method == "HEAD" || c2.req.method == "OPTIONS") {
572
+ c2.header("Content-Length", size.toString());
573
+ c2.status(200);
574
+ return c2.body(null);
575
+ }
576
+ const range = c2.req.header("range") || "";
577
+ if (!range) {
578
+ c2.header("Content-Length", size.toString());
579
+ return c2.body(createStreamBody(fs.createReadStream(path)), 200);
580
+ }
581
+ c2.header("Accept-Ranges", "bytes");
582
+ c2.header("Date", stats.birthtime.toUTCString());
583
+ const parts = range.replace(/bytes=/, "").split("-", 2);
584
+ const start = parts[0] ? parseInt(parts[0], 10) : 0;
585
+ let end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1;
586
+ if (size < end - start + 1) {
587
+ end = size - 1;
588
+ }
589
+ const chunksize = end - start + 1;
590
+ const stream = fs.createReadStream(path, { start, end });
591
+ c2.header("Content-Length", chunksize.toString());
592
+ c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
593
+ return c2.body(createStreamBody(stream), 206);
594
+ };
595
+ };
596
+ var RENDER_TYPE = {
597
+ STRING_ARRAY: "string_array",
598
+ STRING: "string",
599
+ JSON_STRING: "json_string",
600
+ RAW: "raw"
601
+ };
602
+ var RENDER_TYPE_MAP = {
603
+ configUrl: RENDER_TYPE.STRING,
604
+ deepLinking: RENDER_TYPE.RAW,
605
+ presets: RENDER_TYPE.STRING_ARRAY,
606
+ plugins: RENDER_TYPE.STRING_ARRAY,
607
+ spec: RENDER_TYPE.JSON_STRING,
608
+ url: RENDER_TYPE.STRING,
609
+ urls: RENDER_TYPE.JSON_STRING,
610
+ layout: RENDER_TYPE.STRING,
611
+ docExpansion: RENDER_TYPE.STRING,
612
+ maxDisplayedTags: RENDER_TYPE.RAW,
613
+ operationsSorter: RENDER_TYPE.RAW,
614
+ requestInterceptor: RENDER_TYPE.RAW,
615
+ responseInterceptor: RENDER_TYPE.RAW,
616
+ persistAuthorization: RENDER_TYPE.RAW,
617
+ defaultModelsExpandDepth: RENDER_TYPE.RAW,
618
+ defaultModelExpandDepth: RENDER_TYPE.RAW,
619
+ defaultModelRendering: RENDER_TYPE.STRING,
620
+ displayRequestDuration: RENDER_TYPE.RAW,
621
+ filter: RENDER_TYPE.RAW,
622
+ showExtensions: RENDER_TYPE.RAW,
623
+ showCommonExtensions: RENDER_TYPE.RAW,
624
+ queryConfigEnabled: RENDER_TYPE.RAW,
625
+ displayOperationId: RENDER_TYPE.RAW,
626
+ tagsSorter: RENDER_TYPE.RAW,
627
+ onComplete: RENDER_TYPE.RAW,
628
+ syntaxHighlight: RENDER_TYPE.JSON_STRING,
629
+ tryItOutEnabled: RENDER_TYPE.RAW,
630
+ requestSnippetsEnabled: RENDER_TYPE.RAW,
631
+ requestSnippets: RENDER_TYPE.JSON_STRING,
632
+ oauth2RedirectUrl: RENDER_TYPE.STRING,
633
+ showMutabledRequest: RENDER_TYPE.RAW,
634
+ request: RENDER_TYPE.JSON_STRING,
635
+ supportedSubmitMethods: RENDER_TYPE.JSON_STRING,
636
+ validatorUrl: RENDER_TYPE.STRING,
637
+ withCredentials: RENDER_TYPE.RAW,
638
+ modelPropertyMacro: RENDER_TYPE.RAW,
639
+ parameterMacro: RENDER_TYPE.RAW
640
+ };
641
+ var renderSwaggerUIOptions = (options) => {
642
+ const optionsStrings = Object.entries(options).map(([k, v]) => {
643
+ const key = k;
644
+ if (RENDER_TYPE_MAP[key] === RENDER_TYPE.STRING) {
645
+ return `${key}: '${v}'`;
646
+ }
647
+ if (RENDER_TYPE_MAP[key] === RENDER_TYPE.STRING_ARRAY) {
648
+ if (!Array.isArray(v)) {
649
+ return "";
650
+ }
651
+ return `${key}: [${v.map((ve) => `${ve}`).join(",")}]`;
652
+ }
653
+ if (RENDER_TYPE_MAP[key] === RENDER_TYPE.JSON_STRING) {
654
+ return `${key}: ${JSON.stringify(v)}`;
655
+ }
656
+ if (RENDER_TYPE_MAP[key] === RENDER_TYPE.RAW) {
657
+ return `${key}: ${v}`;
658
+ }
659
+ return "";
660
+ }).join(",");
661
+ return optionsStrings;
662
+ };
663
+ var remoteAssets = ({ version }) => {
664
+ const url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : ""}`;
665
+ return {
666
+ css: [`${url}/swagger-ui.css`],
667
+ js: [`${url}/swagger-ui-bundle.js`]
668
+ };
669
+ };
670
+ var SwaggerUI = (options) => {
671
+ const asset = remoteAssets({ version: options?.version });
672
+ delete options.version;
673
+ if (options.manuallySwaggerUIHtml) {
674
+ return options.manuallySwaggerUIHtml(asset);
675
+ }
676
+ const optionsStrings = renderSwaggerUIOptions(options);
677
+ return `
678
+ <div>
679
+ <div id="swagger-ui"></div>
680
+ ${asset.css.map((url) => html.html`<link rel="stylesheet" href="${url}" />`)}
681
+ ${asset.js.map((url) => html.html`<script src="${url}" crossorigin="anonymous"></script>`)}
682
+ <script>
683
+ window.onload = () => {
684
+ window.ui = SwaggerUIBundle({
685
+ dom_id: '#swagger-ui',${optionsStrings},
686
+ })
687
+ }
688
+ </script>
689
+ </div>
690
+ `;
691
+ };
692
+ var middleware = (options) => async (c2) => {
693
+ const title = options?.title ?? "SwaggerUI";
694
+ return c2.html(
695
+ /* html */
696
+ `
697
+ <html lang="en">
698
+ <head>
699
+ <meta charset="utf-8" />
700
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
701
+ <meta name="description" content="SwaggerUI" />
702
+ <title>${title}</title>
703
+ </head>
704
+ <body>
705
+ ${SwaggerUI(options)}
706
+ </body>
707
+ </html>
708
+ `
709
+ );
710
+ };
711
+
712
+ // ../../node_modules/.pnpm/hono-openapi@0.4.4_hono@4.7_c963f431f476ec58780e56f6b21cedc5/node_modules/hono-openapi/utils.js
713
+ var e = Symbol("openapi");
714
+ var s2 = ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
715
+ var n = (e2) => e2.charAt(0).toUpperCase() + e2.slice(1);
716
+ var o = (e2, t2) => {
717
+ let s3 = e2;
718
+ if ("/" === t2) return `${s3}Index`;
719
+ for (const e3 of t2.split("/")) 123 === e3.charCodeAt(0) ? s3 += `By${n(e3.slice(1, -1))}` : s3 += n(e3);
720
+ return s3;
721
+ };
722
+ function a({ path: e2, method: t2, data: s3, schema: n2 }) {
723
+ e2 = ((e3) => e3.split("/").map((e4) => {
724
+ let t3 = e4;
725
+ return t3.startsWith(":") && (t3 = t3.slice(1, t3.length), t3.endsWith("?") && (t3 = t3.slice(0, -1)), t3 = `{${t3}}`), t3;
726
+ }).join("/"))(e2);
727
+ const a2 = t2.toLowerCase();
728
+ n2[e2] = { ...n2[e2] ? n2[e2] : {}, [a2]: { responses: {}, ...n2[e2]?.[a2] ?? {}, operationId: o(a2, e2), ...s3 } };
729
+ }
730
+ function c(e2, { excludeStaticFile: t2 = true, exclude: s3 = [] }) {
731
+ const n2 = {}, o2 = Array.isArray(s3) ? s3 : [s3];
732
+ for (const [s4, a2] of Object.entries(e2)) if (!(o2.some((e3) => "string" == typeof e3 ? s4 === e3 : e3.test(s4)) || s4.includes("*") || t2 && s4.includes("."))) {
733
+ for (const e3 of Object.keys(a2)) {
734
+ const t3 = a2[e3];
735
+ if (s4.includes("{")) {
736
+ t3.parameters || (t3.parameters = []);
737
+ const e4 = s4.split("/").filter((e5) => e5.startsWith("{") && !t3.parameters.find((t4) => "path" === t4.in && t4.name === e5.slice(1, e5.length - 1)));
738
+ for (const s5 of e4) {
739
+ const e5 = s5.slice(1, s5.length - 1), n3 = t3.parameters.findIndex((t4) => "param" === t4.in && t4.name === e5);
740
+ -1 !== n3 ? t3.parameters[n3].in = "path" : t3.parameters.push({ schema: { type: "string" }, in: "path", name: e5, required: true });
741
+ }
742
+ }
743
+ t3.responses || (t3.responses = { 200: {} });
744
+ }
745
+ n2[s4] = a2;
746
+ }
747
+ return n2;
748
+ }
749
+ function i(e2, t2) {
750
+ const s3 = { version: "3.1.0", components: {} };
751
+ let n2 = null;
752
+ return async (o2) => (n2 || (n2 = await r(e2, t2, s3, o2)), o2.json(n2));
753
+ }
754
+ async function r(t2, { documentation: n2 = {}, excludeStaticFile: o2 = true, exclude: i2 = [], excludeMethods: r2 = ["OPTIONS"], excludeTags: p2 = [], defaultOptions: l } = { documentation: {}, excludeStaticFile: true, exclude: [], excludeMethods: ["OPTIONS"], excludeTags: [] }, { version: m = "3.1.0", components: d = {} } = { version: "3.1.0", components: {} }, h) {
755
+ const u = { version: m, components: d }, f = {};
756
+ for (const n3 of t2.routes) {
757
+ if (!(e in n3.handler)) continue;
758
+ if (r2.includes(n3.method)) continue;
759
+ if (false === s2.includes(n3.method) && "ALL" !== n3.method) continue;
760
+ const { resolver: t3, metadata: o3 = {} } = n3.handler[e], c2 = l?.[n3.method], { docs: i3, components: p3 } = await t3({ ...u, ...o3 }, c2);
761
+ if (u.components = { ...u.components, ...p3 ?? {} }, "ALL" === n3.method) for (const e2 of s2) a({ path: n3.path, data: i3, method: e2, schema: f });
762
+ else a({ method: n3.method, path: n3.path, data: i3, schema: f });
763
+ }
764
+ for (const e2 in f) for (const t3 in f[e2]) {
765
+ const s3 = f[e2][t3]?.hide;
766
+ s3 && ("boolean" == typeof s3 ? s3 : h && s3(h)) && delete f[e2][t3];
767
+ }
768
+ return { openapi: u.version, ...{ ...n2, tags: n2.tags?.filter((e2) => !p2?.includes(e2?.name)), info: { title: "Hono Documentation", description: "Development documentation", version: "0.0.0", ...n2.info }, paths: { ...c(f, { excludeStaticFile: o2, exclude: i2 }), ...n2.paths }, components: { ...n2.components, schemas: { ...u.components, ...n2.components?.schemas } } } };
769
+ }
770
+ function p(s3) {
771
+ const { validateResponse: n2, ...o2 } = s3;
772
+ return Object.assign(async (e2, o3) => {
773
+ if (await o3(), n2 && s3.responses) {
774
+ const o4 = e2.res.status, a2 = e2.res.headers.get("content-type");
775
+ if (o4 && a2) {
776
+ const c2 = s3.responses[o4];
777
+ if (c2 && "content" in c2 && c2.content) {
778
+ const s4 = a2.split(";")[0], o5 = c2.content[s4];
779
+ if (o5?.schema && "validator" in o5.schema) try {
780
+ let t2;
781
+ const n3 = e2.res.clone();
782
+ if ("application/json" === s4 ? t2 = await n3.json() : "text/plain" === s4 && (t2 = await n3.text()), !t2) throw new Error("No data to validate!");
783
+ await o5.schema.validator(t2);
784
+ } catch (e3) {
785
+ let s5 = { status: 500, message: "Response validation failed!" };
786
+ throw "object" == typeof n2 && (s5 = { ...s5, ...n2 }), new httpException.HTTPException(s5.status, { message: s5.message, cause: e3 });
787
+ }
788
+ }
789
+ }
790
+ }
791
+ }, { [e]: { resolver: (e2, t2) => async function(e3, t3, s4 = {}) {
792
+ let n3 = {};
793
+ const o3 = { ...s4, ...t3, responses: { ...s4?.responses, ...t3.responses } };
794
+ for (const t4 of Object.keys(o3.responses)) {
795
+ const s5 = o3.responses[t4];
796
+ if (s5 && "content" in s5) for (const t5 of Object.keys(s5.content ?? {})) {
797
+ const o4 = s5.content?.[t5];
798
+ if (o4 && (o4.schema && "builder" in o4.schema)) {
799
+ const t6 = await o4.schema.builder(e3);
800
+ o4.schema = t6.schema, t6.components && (n3 = { ...n3, ...t6.components });
801
+ }
802
+ }
803
+ }
804
+ return { docs: o3, components: n3 };
805
+ }(e2, o2, t2) } });
806
+ }
807
+
808
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/double-indexed-kv.js
809
+ var DoubleIndexedKV = class {
810
+ constructor() {
811
+ this.keyToValue = /* @__PURE__ */ new Map();
812
+ this.valueToKey = /* @__PURE__ */ new Map();
813
+ }
814
+ set(key, value) {
815
+ this.keyToValue.set(key, value);
816
+ this.valueToKey.set(value, key);
817
+ }
818
+ getByKey(key) {
819
+ return this.keyToValue.get(key);
820
+ }
821
+ getByValue(value) {
822
+ return this.valueToKey.get(value);
823
+ }
824
+ clear() {
825
+ this.keyToValue.clear();
826
+ this.valueToKey.clear();
827
+ }
828
+ };
829
+
830
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/registry.js
831
+ var Registry = class {
832
+ constructor(generateIdentifier) {
833
+ this.generateIdentifier = generateIdentifier;
834
+ this.kv = new DoubleIndexedKV();
835
+ }
836
+ register(value, identifier) {
837
+ if (this.kv.getByValue(value)) {
838
+ return;
839
+ }
840
+ if (!identifier) {
841
+ identifier = this.generateIdentifier(value);
842
+ }
843
+ this.kv.set(identifier, value);
844
+ }
845
+ clear() {
846
+ this.kv.clear();
847
+ }
848
+ getIdentifier(value) {
849
+ return this.kv.getByValue(value);
850
+ }
851
+ getValue(identifier) {
852
+ return this.kv.getByKey(identifier);
853
+ }
854
+ };
855
+
856
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/class-registry.js
857
+ var ClassRegistry = class extends Registry {
858
+ constructor() {
859
+ super((c2) => c2.name);
860
+ this.classToAllowedProps = /* @__PURE__ */ new Map();
861
+ }
862
+ register(value, options) {
863
+ if (typeof options === "object") {
864
+ if (options.allowProps) {
865
+ this.classToAllowedProps.set(value, options.allowProps);
866
+ }
867
+ super.register(value, options.identifier);
868
+ } else {
869
+ super.register(value, options);
870
+ }
871
+ }
872
+ getAllowedProps(value) {
873
+ return this.classToAllowedProps.get(value);
874
+ }
875
+ };
876
+
877
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/util.js
878
+ function valuesOfObj(record) {
879
+ if ("values" in Object) {
880
+ return Object.values(record);
881
+ }
882
+ const values = [];
883
+ for (const key in record) {
884
+ if (record.hasOwnProperty(key)) {
885
+ values.push(record[key]);
886
+ }
887
+ }
888
+ return values;
889
+ }
890
+ function find(record, predicate) {
891
+ const values = valuesOfObj(record);
892
+ if ("find" in values) {
893
+ return values.find(predicate);
894
+ }
895
+ const valuesNotNever = values;
896
+ for (let i2 = 0; i2 < valuesNotNever.length; i2++) {
897
+ const value = valuesNotNever[i2];
898
+ if (predicate(value)) {
899
+ return value;
900
+ }
901
+ }
902
+ return void 0;
903
+ }
904
+ function forEach(record, run) {
905
+ Object.entries(record).forEach(([key, value]) => run(value, key));
906
+ }
907
+ function includes(arr, value) {
908
+ return arr.indexOf(value) !== -1;
909
+ }
910
+ function findArr(record, predicate) {
911
+ for (let i2 = 0; i2 < record.length; i2++) {
912
+ const value = record[i2];
913
+ if (predicate(value)) {
914
+ return value;
915
+ }
916
+ }
917
+ return void 0;
918
+ }
919
+
920
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/custom-transformer-registry.js
921
+ var CustomTransformerRegistry = class {
922
+ constructor() {
923
+ this.transfomers = {};
924
+ }
925
+ register(transformer) {
926
+ this.transfomers[transformer.name] = transformer;
927
+ }
928
+ findApplicable(v) {
929
+ return find(this.transfomers, (transformer) => transformer.isApplicable(v));
930
+ }
931
+ findByName(name) {
932
+ return this.transfomers[name];
933
+ }
934
+ };
935
+
936
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/is.js
937
+ var getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
938
+ var isUndefined = (payload) => typeof payload === "undefined";
939
+ var isNull = (payload) => payload === null;
940
+ var isPlainObject = (payload) => {
941
+ if (typeof payload !== "object" || payload === null)
942
+ return false;
943
+ if (payload === Object.prototype)
944
+ return false;
945
+ if (Object.getPrototypeOf(payload) === null)
946
+ return true;
947
+ return Object.getPrototypeOf(payload) === Object.prototype;
948
+ };
949
+ var isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
950
+ var isArray = (payload) => Array.isArray(payload);
951
+ var isString = (payload) => typeof payload === "string";
952
+ var isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
953
+ var isBoolean = (payload) => typeof payload === "boolean";
954
+ var isRegExp = (payload) => payload instanceof RegExp;
955
+ var isMap = (payload) => payload instanceof Map;
956
+ var isSet = (payload) => payload instanceof Set;
957
+ var isSymbol = (payload) => getType(payload) === "Symbol";
958
+ var isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
959
+ var isError = (payload) => payload instanceof Error;
960
+ var isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
961
+ var isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
962
+ var isBigint = (payload) => typeof payload === "bigint";
963
+ var isInfinite = (payload) => payload === Infinity || payload === -Infinity;
964
+ var isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
965
+ var isURL = (payload) => payload instanceof URL;
966
+
967
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/pathstringifier.js
968
+ var escapeKey = (key) => key.replace(/\./g, "\\.");
969
+ var stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
970
+ var parsePath = (string) => {
971
+ const result = [];
972
+ let segment = "";
973
+ for (let i2 = 0; i2 < string.length; i2++) {
974
+ let char = string.charAt(i2);
975
+ const isEscapedDot = char === "\\" && string.charAt(i2 + 1) === ".";
976
+ if (isEscapedDot) {
977
+ segment += ".";
978
+ i2++;
979
+ continue;
980
+ }
981
+ const isEndOfSegment = char === ".";
982
+ if (isEndOfSegment) {
983
+ result.push(segment);
984
+ segment = "";
985
+ continue;
986
+ }
987
+ segment += char;
988
+ }
989
+ const lastSegment = segment;
990
+ result.push(lastSegment);
991
+ return result;
992
+ };
993
+
994
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/transformer.js
995
+ function simpleTransformation(isApplicable, annotation, transform, untransform) {
996
+ return {
997
+ isApplicable,
998
+ annotation,
999
+ transform,
1000
+ untransform
1001
+ };
1002
+ }
1003
+ var simpleRules = [
1004
+ simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
1005
+ simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
1006
+ if (typeof BigInt !== "undefined") {
1007
+ return BigInt(v);
1008
+ }
1009
+ console.error("Please add a BigInt polyfill.");
1010
+ return v;
1011
+ }),
1012
+ simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
1013
+ simpleTransformation(isError, "Error", (v, superJson) => {
1014
+ const baseError = {
1015
+ name: v.name,
1016
+ message: v.message
1017
+ };
1018
+ superJson.allowedErrorProps.forEach((prop) => {
1019
+ baseError[prop] = v[prop];
1020
+ });
1021
+ return baseError;
1022
+ }, (v, superJson) => {
1023
+ const e2 = new Error(v.message);
1024
+ e2.name = v.name;
1025
+ e2.stack = v.stack;
1026
+ superJson.allowedErrorProps.forEach((prop) => {
1027
+ e2[prop] = v[prop];
1028
+ });
1029
+ return e2;
1030
+ }),
1031
+ simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
1032
+ const body = regex.slice(1, regex.lastIndexOf("/"));
1033
+ const flags = regex.slice(regex.lastIndexOf("/") + 1);
1034
+ return new RegExp(body, flags);
1035
+ }),
1036
+ simpleTransformation(
1037
+ isSet,
1038
+ "set",
1039
+ // (sets only exist in es6+)
1040
+ // eslint-disable-next-line es5/no-es6-methods
1041
+ (v) => [...v.values()],
1042
+ (v) => new Set(v)
1043
+ ),
1044
+ simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
1045
+ simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
1046
+ if (isNaNValue(v)) {
1047
+ return "NaN";
1048
+ }
1049
+ if (v > 0) {
1050
+ return "Infinity";
1051
+ } else {
1052
+ return "-Infinity";
1053
+ }
1054
+ }, Number),
1055
+ simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
1056
+ return "-0";
1057
+ }, Number),
1058
+ simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
1059
+ ];
1060
+ function compositeTransformation(isApplicable, annotation, transform, untransform) {
1061
+ return {
1062
+ isApplicable,
1063
+ annotation,
1064
+ transform,
1065
+ untransform
1066
+ };
1067
+ }
1068
+ var symbolRule = compositeTransformation((s3, superJson) => {
1069
+ if (isSymbol(s3)) {
1070
+ const isRegistered = !!superJson.symbolRegistry.getIdentifier(s3);
1071
+ return isRegistered;
1072
+ }
1073
+ return false;
1074
+ }, (s3, superJson) => {
1075
+ const identifier = superJson.symbolRegistry.getIdentifier(s3);
1076
+ return ["symbol", identifier];
1077
+ }, (v) => v.description, (_, a2, superJson) => {
1078
+ const value = superJson.symbolRegistry.getValue(a2[1]);
1079
+ if (!value) {
1080
+ throw new Error("Trying to deserialize unknown symbol");
1081
+ }
1082
+ return value;
1083
+ });
1084
+ var constructorToName = [
1085
+ Int8Array,
1086
+ Uint8Array,
1087
+ Int16Array,
1088
+ Uint16Array,
1089
+ Int32Array,
1090
+ Uint32Array,
1091
+ Float32Array,
1092
+ Float64Array,
1093
+ Uint8ClampedArray
1094
+ ].reduce((obj, ctor) => {
1095
+ obj[ctor.name] = ctor;
1096
+ return obj;
1097
+ }, {});
1098
+ var typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a2) => {
1099
+ const ctor = constructorToName[a2[1]];
1100
+ if (!ctor) {
1101
+ throw new Error("Trying to deserialize unknown typed array");
1102
+ }
1103
+ return new ctor(v);
1104
+ });
1105
+ function isInstanceOfRegisteredClass(potentialClass, superJson) {
1106
+ if (potentialClass?.constructor) {
1107
+ const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
1108
+ return isRegistered;
1109
+ }
1110
+ return false;
1111
+ }
1112
+ var classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
1113
+ const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
1114
+ return ["class", identifier];
1115
+ }, (clazz, superJson) => {
1116
+ const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
1117
+ if (!allowedProps) {
1118
+ return { ...clazz };
1119
+ }
1120
+ const result = {};
1121
+ allowedProps.forEach((prop) => {
1122
+ result[prop] = clazz[prop];
1123
+ });
1124
+ return result;
1125
+ }, (v, a2, superJson) => {
1126
+ const clazz = superJson.classRegistry.getValue(a2[1]);
1127
+ if (!clazz) {
1128
+ throw new Error(`Trying to deserialize unknown class '${a2[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
1129
+ }
1130
+ return Object.assign(Object.create(clazz.prototype), v);
1131
+ });
1132
+ var customRule = compositeTransformation((value, superJson) => {
1133
+ return !!superJson.customTransformerRegistry.findApplicable(value);
1134
+ }, (value, superJson) => {
1135
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
1136
+ return ["custom", transformer.name];
1137
+ }, (value, superJson) => {
1138
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
1139
+ return transformer.serialize(value);
1140
+ }, (v, a2, superJson) => {
1141
+ const transformer = superJson.customTransformerRegistry.findByName(a2[1]);
1142
+ if (!transformer) {
1143
+ throw new Error("Trying to deserialize unknown custom value");
1144
+ }
1145
+ return transformer.deserialize(v);
1146
+ });
1147
+ var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
1148
+ var transformValue = (value, superJson) => {
1149
+ const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
1150
+ if (applicableCompositeRule) {
1151
+ return {
1152
+ value: applicableCompositeRule.transform(value, superJson),
1153
+ type: applicableCompositeRule.annotation(value, superJson)
1154
+ };
1155
+ }
1156
+ const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
1157
+ if (applicableSimpleRule) {
1158
+ return {
1159
+ value: applicableSimpleRule.transform(value, superJson),
1160
+ type: applicableSimpleRule.annotation
1161
+ };
1162
+ }
1163
+ return void 0;
1164
+ };
1165
+ var simpleRulesByAnnotation = {};
1166
+ simpleRules.forEach((rule) => {
1167
+ simpleRulesByAnnotation[rule.annotation] = rule;
1168
+ });
1169
+ var untransformValue = (json, type, superJson) => {
1170
+ if (isArray(type)) {
1171
+ switch (type[0]) {
1172
+ case "symbol":
1173
+ return symbolRule.untransform(json, type, superJson);
1174
+ case "class":
1175
+ return classRule.untransform(json, type, superJson);
1176
+ case "custom":
1177
+ return customRule.untransform(json, type, superJson);
1178
+ case "typed-array":
1179
+ return typedArrayRule.untransform(json, type, superJson);
1180
+ default:
1181
+ throw new Error("Unknown transformation: " + type);
1182
+ }
1183
+ } else {
1184
+ const transformation = simpleRulesByAnnotation[type];
1185
+ if (!transformation) {
1186
+ throw new Error("Unknown transformation: " + type);
1187
+ }
1188
+ return transformation.untransform(json, superJson);
1189
+ }
1190
+ };
1191
+
1192
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/accessDeep.js
1193
+ var getNthKey = (value, n2) => {
1194
+ if (n2 > value.size)
1195
+ throw new Error("index out of bounds");
1196
+ const keys = value.keys();
1197
+ while (n2 > 0) {
1198
+ keys.next();
1199
+ n2--;
1200
+ }
1201
+ return keys.next().value;
1202
+ };
1203
+ function validatePath(path) {
1204
+ if (includes(path, "__proto__")) {
1205
+ throw new Error("__proto__ is not allowed as a property");
1206
+ }
1207
+ if (includes(path, "prototype")) {
1208
+ throw new Error("prototype is not allowed as a property");
1209
+ }
1210
+ if (includes(path, "constructor")) {
1211
+ throw new Error("constructor is not allowed as a property");
1212
+ }
1213
+ }
1214
+ var getDeep = (object, path) => {
1215
+ validatePath(path);
1216
+ for (let i2 = 0; i2 < path.length; i2++) {
1217
+ const key = path[i2];
1218
+ if (isSet(object)) {
1219
+ object = getNthKey(object, +key);
1220
+ } else if (isMap(object)) {
1221
+ const row = +key;
1222
+ const type = +path[++i2] === 0 ? "key" : "value";
1223
+ const keyOfRow = getNthKey(object, row);
1224
+ switch (type) {
1225
+ case "key":
1226
+ object = keyOfRow;
1227
+ break;
1228
+ case "value":
1229
+ object = object.get(keyOfRow);
1230
+ break;
1231
+ }
1232
+ } else {
1233
+ object = object[key];
1234
+ }
1235
+ }
1236
+ return object;
1237
+ };
1238
+ var setDeep = (object, path, mapper) => {
1239
+ validatePath(path);
1240
+ if (path.length === 0) {
1241
+ return mapper(object);
1242
+ }
1243
+ let parent = object;
1244
+ for (let i2 = 0; i2 < path.length - 1; i2++) {
1245
+ const key = path[i2];
1246
+ if (isArray(parent)) {
1247
+ const index = +key;
1248
+ parent = parent[index];
1249
+ } else if (isPlainObject(parent)) {
1250
+ parent = parent[key];
1251
+ } else if (isSet(parent)) {
1252
+ const row = +key;
1253
+ parent = getNthKey(parent, row);
1254
+ } else if (isMap(parent)) {
1255
+ const isEnd = i2 === path.length - 2;
1256
+ if (isEnd) {
1257
+ break;
1258
+ }
1259
+ const row = +key;
1260
+ const type = +path[++i2] === 0 ? "key" : "value";
1261
+ const keyOfRow = getNthKey(parent, row);
1262
+ switch (type) {
1263
+ case "key":
1264
+ parent = keyOfRow;
1265
+ break;
1266
+ case "value":
1267
+ parent = parent.get(keyOfRow);
1268
+ break;
1269
+ }
1270
+ }
1271
+ }
1272
+ const lastKey = path[path.length - 1];
1273
+ if (isArray(parent)) {
1274
+ parent[+lastKey] = mapper(parent[+lastKey]);
1275
+ } else if (isPlainObject(parent)) {
1276
+ parent[lastKey] = mapper(parent[lastKey]);
1277
+ }
1278
+ if (isSet(parent)) {
1279
+ const oldValue = getNthKey(parent, +lastKey);
1280
+ const newValue = mapper(oldValue);
1281
+ if (oldValue !== newValue) {
1282
+ parent.delete(oldValue);
1283
+ parent.add(newValue);
1284
+ }
1285
+ }
1286
+ if (isMap(parent)) {
1287
+ const row = +path[path.length - 2];
1288
+ const keyToRow = getNthKey(parent, row);
1289
+ const type = +lastKey === 0 ? "key" : "value";
1290
+ switch (type) {
1291
+ case "key": {
1292
+ const newKey = mapper(keyToRow);
1293
+ parent.set(newKey, parent.get(keyToRow));
1294
+ if (newKey !== keyToRow) {
1295
+ parent.delete(keyToRow);
1296
+ }
1297
+ break;
1298
+ }
1299
+ case "value": {
1300
+ parent.set(keyToRow, mapper(parent.get(keyToRow)));
1301
+ break;
1302
+ }
1303
+ }
1304
+ }
1305
+ return object;
1306
+ };
1307
+
1308
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/plainer.js
1309
+ function traverse(tree, walker2, origin = []) {
1310
+ if (!tree) {
1311
+ return;
1312
+ }
1313
+ if (!isArray(tree)) {
1314
+ forEach(tree, (subtree, key) => traverse(subtree, walker2, [...origin, ...parsePath(key)]));
1315
+ return;
1316
+ }
1317
+ const [nodeValue, children] = tree;
1318
+ if (children) {
1319
+ forEach(children, (child, key) => {
1320
+ traverse(child, walker2, [...origin, ...parsePath(key)]);
1321
+ });
1322
+ }
1323
+ walker2(nodeValue, origin);
1324
+ }
1325
+ function applyValueAnnotations(plain, annotations, superJson) {
1326
+ traverse(annotations, (type, path) => {
1327
+ plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
1328
+ });
1329
+ return plain;
1330
+ }
1331
+ function applyReferentialEqualityAnnotations(plain, annotations) {
1332
+ function apply(identicalPaths, path) {
1333
+ const object = getDeep(plain, parsePath(path));
1334
+ identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
1335
+ plain = setDeep(plain, identicalObjectPath, () => object);
1336
+ });
1337
+ }
1338
+ if (isArray(annotations)) {
1339
+ const [root, other] = annotations;
1340
+ root.forEach((identicalPath) => {
1341
+ plain = setDeep(plain, parsePath(identicalPath), () => plain);
1342
+ });
1343
+ if (other) {
1344
+ forEach(other, apply);
1345
+ }
1346
+ } else {
1347
+ forEach(annotations, apply);
1348
+ }
1349
+ return plain;
1350
+ }
1351
+ var isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
1352
+ function addIdentity(object, path, identities) {
1353
+ const existingSet = identities.get(object);
1354
+ if (existingSet) {
1355
+ existingSet.push(path);
1356
+ } else {
1357
+ identities.set(object, [path]);
1358
+ }
1359
+ }
1360
+ function generateReferentialEqualityAnnotations(identitites, dedupe) {
1361
+ const result = {};
1362
+ let rootEqualityPaths = void 0;
1363
+ identitites.forEach((paths) => {
1364
+ if (paths.length <= 1) {
1365
+ return;
1366
+ }
1367
+ if (!dedupe) {
1368
+ paths = paths.map((path) => path.map(String)).sort((a2, b) => a2.length - b.length);
1369
+ }
1370
+ const [representativePath, ...identicalPaths] = paths;
1371
+ if (representativePath.length === 0) {
1372
+ rootEqualityPaths = identicalPaths.map(stringifyPath);
1373
+ } else {
1374
+ result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
1375
+ }
1376
+ });
1377
+ if (rootEqualityPaths) {
1378
+ if (isEmptyObject(result)) {
1379
+ return [rootEqualityPaths];
1380
+ } else {
1381
+ return [rootEqualityPaths, result];
1382
+ }
1383
+ } else {
1384
+ return isEmptyObject(result) ? void 0 : result;
1385
+ }
1386
+ }
1387
+ var walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
1388
+ const primitive = isPrimitive(object);
1389
+ if (!primitive) {
1390
+ addIdentity(object, path, identities);
1391
+ const seen = seenObjects.get(object);
1392
+ if (seen) {
1393
+ return dedupe ? {
1394
+ transformedValue: null
1395
+ } : seen;
1396
+ }
1397
+ }
1398
+ if (!isDeep(object, superJson)) {
1399
+ const transformed2 = transformValue(object, superJson);
1400
+ const result2 = transformed2 ? {
1401
+ transformedValue: transformed2.value,
1402
+ annotations: [transformed2.type]
1403
+ } : {
1404
+ transformedValue: object
1405
+ };
1406
+ if (!primitive) {
1407
+ seenObjects.set(object, result2);
1408
+ }
1409
+ return result2;
1410
+ }
1411
+ if (includes(objectsInThisPath, object)) {
1412
+ return {
1413
+ transformedValue: null
1414
+ };
1415
+ }
1416
+ const transformationResult = transformValue(object, superJson);
1417
+ const transformed = transformationResult?.value ?? object;
1418
+ const transformedValue = isArray(transformed) ? [] : {};
1419
+ const innerAnnotations = {};
1420
+ forEach(transformed, (value, index) => {
1421
+ if (index === "__proto__" || index === "constructor" || index === "prototype") {
1422
+ throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
1423
+ }
1424
+ const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
1425
+ transformedValue[index] = recursiveResult.transformedValue;
1426
+ if (isArray(recursiveResult.annotations)) {
1427
+ innerAnnotations[index] = recursiveResult.annotations;
1428
+ } else if (isPlainObject(recursiveResult.annotations)) {
1429
+ forEach(recursiveResult.annotations, (tree, key) => {
1430
+ innerAnnotations[escapeKey(index) + "." + key] = tree;
1431
+ });
1432
+ }
1433
+ });
1434
+ const result = isEmptyObject(innerAnnotations) ? {
1435
+ transformedValue,
1436
+ annotations: !!transformationResult ? [transformationResult.type] : void 0
1437
+ } : {
1438
+ transformedValue,
1439
+ annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
1440
+ };
1441
+ if (!primitive) {
1442
+ seenObjects.set(object, result);
1443
+ }
1444
+ return result;
1445
+ };
1446
+
1447
+ // ../../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
1448
+ function getType2(payload) {
1449
+ return Object.prototype.toString.call(payload).slice(8, -1);
1450
+ }
1451
+ function isArray2(payload) {
1452
+ return getType2(payload) === "Array";
1453
+ }
1454
+ function isPlainObject2(payload) {
1455
+ if (getType2(payload) !== "Object")
1456
+ return false;
1457
+ const prototype = Object.getPrototypeOf(payload);
1458
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
1459
+ }
1460
+
1461
+ // ../../node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js
1462
+ function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
1463
+ const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
1464
+ if (propType === "enumerable")
1465
+ carry[key] = newVal;
1466
+ if (includeNonenumerable && propType === "nonenumerable") {
1467
+ Object.defineProperty(carry, key, {
1468
+ value: newVal,
1469
+ enumerable: false,
1470
+ writable: true,
1471
+ configurable: true
1472
+ });
1473
+ }
1474
+ }
1475
+ function copy(target, options = {}) {
1476
+ if (isArray2(target)) {
1477
+ return target.map((item) => copy(item, options));
1478
+ }
1479
+ if (!isPlainObject2(target)) {
1480
+ return target;
1481
+ }
1482
+ const props = Object.getOwnPropertyNames(target);
1483
+ const symbols = Object.getOwnPropertySymbols(target);
1484
+ return [...props, ...symbols].reduce((carry, key) => {
1485
+ if (isArray2(options.props) && !options.props.includes(key)) {
1486
+ return carry;
1487
+ }
1488
+ const val = target[key];
1489
+ const newVal = copy(val, options);
1490
+ assignProp(carry, key, newVal, target, options.nonenumerable);
1491
+ return carry;
1492
+ }, {});
1493
+ }
1494
+
1495
+ // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/index.js
1496
+ var SuperJSON = class {
1497
+ /**
1498
+ * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
1499
+ */
1500
+ constructor({ dedupe = false } = {}) {
1501
+ this.classRegistry = new ClassRegistry();
1502
+ this.symbolRegistry = new Registry((s3) => s3.description ?? "");
1503
+ this.customTransformerRegistry = new CustomTransformerRegistry();
1504
+ this.allowedErrorProps = [];
1505
+ this.dedupe = dedupe;
1506
+ }
1507
+ serialize(object) {
1508
+ const identities = /* @__PURE__ */ new Map();
1509
+ const output = walker(object, identities, this, this.dedupe);
1510
+ const res = {
1511
+ json: output.transformedValue
1512
+ };
1513
+ if (output.annotations) {
1514
+ res.meta = {
1515
+ ...res.meta,
1516
+ values: output.annotations
1517
+ };
1518
+ }
1519
+ const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
1520
+ if (equalityAnnotations) {
1521
+ res.meta = {
1522
+ ...res.meta,
1523
+ referentialEqualities: equalityAnnotations
1524
+ };
1525
+ }
1526
+ return res;
1527
+ }
1528
+ deserialize(payload) {
1529
+ const { json, meta } = payload;
1530
+ let result = copy(json);
1531
+ if (meta?.values) {
1532
+ result = applyValueAnnotations(result, meta.values, this);
1533
+ }
1534
+ if (meta?.referentialEqualities) {
1535
+ result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
1536
+ }
1537
+ return result;
1538
+ }
1539
+ stringify(object) {
1540
+ return JSON.stringify(this.serialize(object));
1541
+ }
1542
+ parse(string) {
1543
+ return this.deserialize(JSON.parse(string));
1544
+ }
1545
+ registerClass(v, options) {
1546
+ this.classRegistry.register(v, options);
1547
+ }
1548
+ registerSymbol(v, identifier) {
1549
+ this.symbolRegistry.register(v, identifier);
1550
+ }
1551
+ registerCustom(transformer, name) {
1552
+ this.customTransformerRegistry.register({
1553
+ name,
1554
+ ...transformer
1555
+ });
1556
+ }
1557
+ allowErrorProps(...props) {
1558
+ this.allowedErrorProps.push(...props);
1559
+ }
1560
+ };
1561
+ SuperJSON.defaultInstance = new SuperJSON();
1562
+ SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
1563
+ SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
1564
+ SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
1565
+ SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
1566
+ SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
1567
+ SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
1568
+ SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
1569
+ SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
1570
+ var stringify = SuperJSON.stringify;
1571
+
1572
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Options.js
1573
+ var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
1574
+ var defaultOptions = {
1575
+ name: void 0,
1576
+ $refStrategy: "root",
1577
+ basePath: ["#"],
1578
+ effectStrategy: "input",
1579
+ pipeStrategy: "all",
1580
+ dateStrategy: "format:date-time",
1581
+ mapStrategy: "entries",
1582
+ removeAdditionalStrategy: "passthrough",
1583
+ definitionPath: "definitions",
1584
+ target: "jsonSchema7",
1585
+ strictUnions: false,
1586
+ definitions: {},
1587
+ errorMessages: false,
1588
+ markdownDescription: false,
1589
+ patternStrategy: "escape",
1590
+ applyRegexFlags: false,
1591
+ emailStrategy: "format:email",
1592
+ base64Strategy: "contentEncoding:base64",
1593
+ nameStrategy: "ref"
1594
+ };
1595
+ var getDefaultOptions = (options) => typeof options === "string" ? {
1596
+ ...defaultOptions,
1597
+ name: options
1598
+ } : {
1599
+ ...defaultOptions,
1600
+ ...options
1601
+ };
1602
+
1603
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Refs.js
1604
+ var getRefs = (options) => {
1605
+ const _options = getDefaultOptions(options);
1606
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1607
+ return {
1608
+ ..._options,
1609
+ currentPath,
1610
+ propertyPath: void 0,
1611
+ seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
1612
+ def._def,
1613
+ {
1614
+ def: def._def,
1615
+ path: [..._options.basePath, _options.definitionPath, name],
1616
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1617
+ jsonSchema: void 0
1618
+ }
1619
+ ]))
1620
+ };
1621
+ };
1622
+
1623
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
1624
+ function addErrorMessage(res, key, errorMessage, refs) {
1625
+ if (!refs?.errorMessages)
1626
+ return;
1627
+ if (errorMessage) {
1628
+ res.errorMessage = {
1629
+ ...res.errorMessage,
1630
+ [key]: errorMessage
1631
+ };
1632
+ }
1633
+ }
1634
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
1635
+ res[key] = value;
1636
+ addErrorMessage(res, key, errorMessage, refs);
1637
+ }
1638
+
1639
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
1640
+ function parseAnyDef() {
1641
+ return {};
1642
+ }
1643
+ function parseArrayDef(def, refs) {
1644
+ const res = {
1645
+ type: "array"
1646
+ };
1647
+ if (def.type?._def && def.type?._def?.typeName !== zod.ZodFirstPartyTypeKind.ZodAny) {
1648
+ res.items = parseDef(def.type._def, {
1649
+ ...refs,
1650
+ currentPath: [...refs.currentPath, "items"]
1651
+ });
1652
+ }
1653
+ if (def.minLength) {
1654
+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
1655
+ }
1656
+ if (def.maxLength) {
1657
+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
1658
+ }
1659
+ if (def.exactLength) {
1660
+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
1661
+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
1662
+ }
1663
+ return res;
1664
+ }
1665
+
1666
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
1667
+ function parseBigintDef(def, refs) {
1668
+ const res = {
1669
+ type: "integer",
1670
+ format: "int64"
1671
+ };
1672
+ if (!def.checks)
1673
+ return res;
1674
+ for (const check of def.checks) {
1675
+ switch (check.kind) {
1676
+ case "min":
1677
+ if (refs.target === "jsonSchema7") {
1678
+ if (check.inclusive) {
1679
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1680
+ } else {
1681
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1682
+ }
1683
+ } else {
1684
+ if (!check.inclusive) {
1685
+ res.exclusiveMinimum = true;
1686
+ }
1687
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1688
+ }
1689
+ break;
1690
+ case "max":
1691
+ if (refs.target === "jsonSchema7") {
1692
+ if (check.inclusive) {
1693
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1694
+ } else {
1695
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1696
+ }
1697
+ } else {
1698
+ if (!check.inclusive) {
1699
+ res.exclusiveMaximum = true;
1700
+ }
1701
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1702
+ }
1703
+ break;
1704
+ case "multipleOf":
1705
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1706
+ break;
1707
+ }
1708
+ }
1709
+ return res;
1710
+ }
1711
+
1712
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
1713
+ function parseBooleanDef() {
1714
+ return {
1715
+ type: "boolean"
1716
+ };
1717
+ }
1718
+
1719
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
1720
+ function parseBrandedDef(_def, refs) {
1721
+ return parseDef(_def.type._def, refs);
1722
+ }
1723
+
1724
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
1725
+ var parseCatchDef = (def, refs) => {
1726
+ return parseDef(def.innerType._def, refs);
1727
+ };
1728
+
1729
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
1730
+ function parseDateDef(def, refs, overrideDateStrategy) {
1731
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
1732
+ if (Array.isArray(strategy)) {
1733
+ return {
1734
+ anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item))
1735
+ };
1736
+ }
1737
+ switch (strategy) {
1738
+ case "string":
1739
+ case "format:date-time":
1740
+ return {
1741
+ type: "string",
1742
+ format: "date-time"
1743
+ };
1744
+ case "format:date":
1745
+ return {
1746
+ type: "string",
1747
+ format: "date"
1748
+ };
1749
+ case "integer":
1750
+ return integerDateParser(def, refs);
1751
+ }
1752
+ }
1753
+ var integerDateParser = (def, refs) => {
1754
+ const res = {
1755
+ type: "integer",
1756
+ format: "unix-time"
1757
+ };
1758
+ if (refs.target === "openApi3") {
1759
+ return res;
1760
+ }
1761
+ for (const check of def.checks) {
1762
+ switch (check.kind) {
1763
+ case "min":
1764
+ setResponseValueAndErrors(
1765
+ res,
1766
+ "minimum",
1767
+ check.value,
1768
+ // This is in milliseconds
1769
+ check.message,
1770
+ refs
1771
+ );
1772
+ break;
1773
+ case "max":
1774
+ setResponseValueAndErrors(
1775
+ res,
1776
+ "maximum",
1777
+ check.value,
1778
+ // This is in milliseconds
1779
+ check.message,
1780
+ refs
1781
+ );
1782
+ break;
1783
+ }
1784
+ }
1785
+ return res;
1786
+ };
1787
+
1788
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
1789
+ function parseDefaultDef(_def, refs) {
1790
+ return {
1791
+ ...parseDef(_def.innerType._def, refs),
1792
+ default: _def.defaultValue()
1793
+ };
1794
+ }
1795
+
1796
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
1797
+ function parseEffectsDef(_def, refs) {
1798
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
1799
+ }
1800
+
1801
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
1802
+ function parseEnumDef(def) {
1803
+ return {
1804
+ type: "string",
1805
+ enum: Array.from(def.values)
1806
+ };
1807
+ }
1808
+
1809
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
1810
+ var isJsonSchema7AllOfType = (type) => {
1811
+ if ("type" in type && type.type === "string")
1812
+ return false;
1813
+ return "allOf" in type;
1814
+ };
1815
+ function parseIntersectionDef(def, refs) {
1816
+ const allOf = [
1817
+ parseDef(def.left._def, {
1818
+ ...refs,
1819
+ currentPath: [...refs.currentPath, "allOf", "0"]
1820
+ }),
1821
+ parseDef(def.right._def, {
1822
+ ...refs,
1823
+ currentPath: [...refs.currentPath, "allOf", "1"]
1824
+ })
1825
+ ].filter((x) => !!x);
1826
+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
1827
+ const mergedAllOf = [];
1828
+ allOf.forEach((schema) => {
1829
+ if (isJsonSchema7AllOfType(schema)) {
1830
+ mergedAllOf.push(...schema.allOf);
1831
+ if (schema.unevaluatedProperties === void 0) {
1832
+ unevaluatedProperties = void 0;
1833
+ }
1834
+ } else {
1835
+ let nestedSchema = schema;
1836
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1837
+ const { additionalProperties, ...rest } = schema;
1838
+ nestedSchema = rest;
1839
+ } else {
1840
+ unevaluatedProperties = void 0;
1841
+ }
1842
+ mergedAllOf.push(nestedSchema);
1843
+ }
1844
+ });
1845
+ return mergedAllOf.length ? {
1846
+ allOf: mergedAllOf,
1847
+ ...unevaluatedProperties
1848
+ } : void 0;
1849
+ }
1850
+
1851
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
1852
+ function parseLiteralDef(def, refs) {
1853
+ const parsedType = typeof def.value;
1854
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1855
+ return {
1856
+ type: Array.isArray(def.value) ? "array" : "object"
1857
+ };
1858
+ }
1859
+ if (refs.target === "openApi3") {
1860
+ return {
1861
+ type: parsedType === "bigint" ? "integer" : parsedType,
1862
+ enum: [def.value]
1863
+ };
1864
+ }
1865
+ return {
1866
+ type: parsedType === "bigint" ? "integer" : parsedType,
1867
+ const: def.value
1868
+ };
1869
+ }
1870
+
1871
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
1872
+ var emojiRegex = void 0;
1873
+ var zodPatterns = {
1874
+ /**
1875
+ * `c` was changed to `[cC]` to replicate /i flag
1876
+ */
1877
+ cuid: /^[cC][^\s-]{8,}$/,
1878
+ cuid2: /^[0-9a-z]+$/,
1879
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1880
+ /**
1881
+ * `a-z` was added to replicate /i flag
1882
+ */
1883
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1884
+ /**
1885
+ * Constructed a valid Unicode RegExp
1886
+ *
1887
+ * Lazily instantiate since this type of regex isn't supported
1888
+ * in all envs (e.g. React Native).
1889
+ *
1890
+ * See:
1891
+ * https://github.com/colinhacks/zod/issues/2433
1892
+ * Fix in Zod:
1893
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1894
+ */
1895
+ emoji: () => {
1896
+ if (emojiRegex === void 0) {
1897
+ emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
1898
+ }
1899
+ return emojiRegex;
1900
+ },
1901
+ /**
1902
+ * Unused
1903
+ */
1904
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1905
+ /**
1906
+ * Unused
1907
+ */
1908
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1909
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1910
+ /**
1911
+ * Unused
1912
+ */
1913
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1914
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1915
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1916
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1917
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1918
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1919
+ };
1920
+ function parseStringDef(def, refs) {
1921
+ const res = {
1922
+ type: "string"
1923
+ };
1924
+ if (def.checks) {
1925
+ for (const check of def.checks) {
1926
+ switch (check.kind) {
1927
+ case "min":
1928
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
1929
+ break;
1930
+ case "max":
1931
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
1932
+ break;
1933
+ case "email":
1934
+ switch (refs.emailStrategy) {
1935
+ case "format:email":
1936
+ addFormat(res, "email", check.message, refs);
1937
+ break;
1938
+ case "format:idn-email":
1939
+ addFormat(res, "idn-email", check.message, refs);
1940
+ break;
1941
+ case "pattern:zod":
1942
+ addPattern(res, zodPatterns.email, check.message, refs);
1943
+ break;
1944
+ }
1945
+ break;
1946
+ case "url":
1947
+ addFormat(res, "uri", check.message, refs);
1948
+ break;
1949
+ case "uuid":
1950
+ addFormat(res, "uuid", check.message, refs);
1951
+ break;
1952
+ case "regex":
1953
+ addPattern(res, check.regex, check.message, refs);
1954
+ break;
1955
+ case "cuid":
1956
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1957
+ break;
1958
+ case "cuid2":
1959
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1960
+ break;
1961
+ case "startsWith":
1962
+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
1963
+ break;
1964
+ case "endsWith":
1965
+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
1966
+ break;
1967
+ case "datetime":
1968
+ addFormat(res, "date-time", check.message, refs);
1969
+ break;
1970
+ case "date":
1971
+ addFormat(res, "date", check.message, refs);
1972
+ break;
1973
+ case "time":
1974
+ addFormat(res, "time", check.message, refs);
1975
+ break;
1976
+ case "duration":
1977
+ addFormat(res, "duration", check.message, refs);
1978
+ break;
1979
+ case "length":
1980
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
1981
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
1982
+ break;
1983
+ case "includes": {
1984
+ addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
1985
+ break;
1986
+ }
1987
+ case "ip": {
1988
+ if (check.version !== "v6") {
1989
+ addFormat(res, "ipv4", check.message, refs);
1990
+ }
1991
+ if (check.version !== "v4") {
1992
+ addFormat(res, "ipv6", check.message, refs);
1993
+ }
1994
+ break;
1995
+ }
1996
+ case "base64url":
1997
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1998
+ break;
1999
+ case "jwt":
2000
+ addPattern(res, zodPatterns.jwt, check.message, refs);
2001
+ break;
2002
+ case "cidr": {
2003
+ if (check.version !== "v6") {
2004
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
2005
+ }
2006
+ if (check.version !== "v4") {
2007
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
2008
+ }
2009
+ break;
2010
+ }
2011
+ case "emoji":
2012
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
2013
+ break;
2014
+ case "ulid": {
2015
+ addPattern(res, zodPatterns.ulid, check.message, refs);
2016
+ break;
2017
+ }
2018
+ case "base64": {
2019
+ switch (refs.base64Strategy) {
2020
+ case "format:binary": {
2021
+ addFormat(res, "binary", check.message, refs);
2022
+ break;
2023
+ }
2024
+ case "contentEncoding:base64": {
2025
+ setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
2026
+ break;
2027
+ }
2028
+ case "pattern:zod": {
2029
+ addPattern(res, zodPatterns.base64, check.message, refs);
2030
+ break;
2031
+ }
2032
+ }
2033
+ break;
2034
+ }
2035
+ case "nanoid": {
2036
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
2037
+ }
2038
+ }
2039
+ }
2040
+ }
2041
+ return res;
2042
+ }
2043
+ function escapeLiteralCheckValue(literal, refs) {
2044
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
2045
+ }
2046
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
2047
+ function escapeNonAlphaNumeric(source) {
2048
+ let result = "";
2049
+ for (let i2 = 0; i2 < source.length; i2++) {
2050
+ if (!ALPHA_NUMERIC.has(source[i2])) {
2051
+ result += "\\";
2052
+ }
2053
+ result += source[i2];
2054
+ }
2055
+ return result;
2056
+ }
2057
+ function addFormat(schema, value, message, refs) {
2058
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
2059
+ if (!schema.anyOf) {
2060
+ schema.anyOf = [];
2061
+ }
2062
+ if (schema.format) {
2063
+ schema.anyOf.push({
2064
+ format: schema.format,
2065
+ ...schema.errorMessage && refs.errorMessages && {
2066
+ errorMessage: { format: schema.errorMessage.format }
2067
+ }
2068
+ });
2069
+ delete schema.format;
2070
+ if (schema.errorMessage) {
2071
+ delete schema.errorMessage.format;
2072
+ if (Object.keys(schema.errorMessage).length === 0) {
2073
+ delete schema.errorMessage;
2074
+ }
2075
+ }
2076
+ }
2077
+ schema.anyOf.push({
2078
+ format: value,
2079
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
2080
+ });
2081
+ } else {
2082
+ setResponseValueAndErrors(schema, "format", value, message, refs);
2083
+ }
2084
+ }
2085
+ function addPattern(schema, regex, message, refs) {
2086
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
2087
+ if (!schema.allOf) {
2088
+ schema.allOf = [];
2089
+ }
2090
+ if (schema.pattern) {
2091
+ schema.allOf.push({
2092
+ pattern: schema.pattern,
2093
+ ...schema.errorMessage && refs.errorMessages && {
2094
+ errorMessage: { pattern: schema.errorMessage.pattern }
2095
+ }
2096
+ });
2097
+ delete schema.pattern;
2098
+ if (schema.errorMessage) {
2099
+ delete schema.errorMessage.pattern;
2100
+ if (Object.keys(schema.errorMessage).length === 0) {
2101
+ delete schema.errorMessage;
2102
+ }
2103
+ }
2104
+ }
2105
+ schema.allOf.push({
2106
+ pattern: stringifyRegExpWithFlags(regex, refs),
2107
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
2108
+ });
2109
+ } else {
2110
+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
2111
+ }
2112
+ }
2113
+ function stringifyRegExpWithFlags(regex, refs) {
2114
+ if (!refs.applyRegexFlags || !regex.flags) {
2115
+ return regex.source;
2116
+ }
2117
+ const flags = {
2118
+ i: regex.flags.includes("i"),
2119
+ m: regex.flags.includes("m"),
2120
+ s: regex.flags.includes("s")
2121
+ // `.` matches newlines
2122
+ };
2123
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
2124
+ let pattern = "";
2125
+ let isEscaped = false;
2126
+ let inCharGroup = false;
2127
+ let inCharRange = false;
2128
+ for (let i2 = 0; i2 < source.length; i2++) {
2129
+ if (isEscaped) {
2130
+ pattern += source[i2];
2131
+ isEscaped = false;
2132
+ continue;
2133
+ }
2134
+ if (flags.i) {
2135
+ if (inCharGroup) {
2136
+ if (source[i2].match(/[a-z]/)) {
2137
+ if (inCharRange) {
2138
+ pattern += source[i2];
2139
+ pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase();
2140
+ inCharRange = false;
2141
+ } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) {
2142
+ pattern += source[i2];
2143
+ inCharRange = true;
2144
+ } else {
2145
+ pattern += `${source[i2]}${source[i2].toUpperCase()}`;
2146
+ }
2147
+ continue;
2148
+ }
2149
+ } else if (source[i2].match(/[a-z]/)) {
2150
+ pattern += `[${source[i2]}${source[i2].toUpperCase()}]`;
2151
+ continue;
2152
+ }
2153
+ }
2154
+ if (flags.m) {
2155
+ if (source[i2] === "^") {
2156
+ pattern += `(^|(?<=[\r
2157
+ ]))`;
2158
+ continue;
2159
+ } else if (source[i2] === "$") {
2160
+ pattern += `($|(?=[\r
2161
+ ]))`;
2162
+ continue;
2163
+ }
2164
+ }
2165
+ if (flags.s && source[i2] === ".") {
2166
+ pattern += inCharGroup ? `${source[i2]}\r
2167
+ ` : `[${source[i2]}\r
2168
+ ]`;
2169
+ continue;
2170
+ }
2171
+ pattern += source[i2];
2172
+ if (source[i2] === "\\") {
2173
+ isEscaped = true;
2174
+ } else if (inCharGroup && source[i2] === "]") {
2175
+ inCharGroup = false;
2176
+ } else if (!inCharGroup && source[i2] === "[") {
2177
+ inCharGroup = true;
2178
+ }
2179
+ }
2180
+ try {
2181
+ new RegExp(pattern);
2182
+ } catch {
2183
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
2184
+ return regex.source;
2185
+ }
2186
+ return pattern;
2187
+ }
2188
+
2189
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
2190
+ function parseRecordDef(def, refs) {
2191
+ if (refs.target === "openAi") {
2192
+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
2193
+ }
2194
+ if (refs.target === "openApi3" && def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
2195
+ return {
2196
+ type: "object",
2197
+ required: def.keyType._def.values,
2198
+ properties: def.keyType._def.values.reduce((acc, key) => ({
2199
+ ...acc,
2200
+ [key]: parseDef(def.valueType._def, {
2201
+ ...refs,
2202
+ currentPath: [...refs.currentPath, "properties", key]
2203
+ }) ?? {}
2204
+ }), {}),
2205
+ additionalProperties: false
2206
+ };
2207
+ }
2208
+ const schema = {
2209
+ type: "object",
2210
+ additionalProperties: parseDef(def.valueType._def, {
2211
+ ...refs,
2212
+ currentPath: [...refs.currentPath, "additionalProperties"]
2213
+ }) ?? {}
2214
+ };
2215
+ if (refs.target === "openApi3") {
2216
+ return schema;
2217
+ }
2218
+ if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
2219
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
2220
+ return {
2221
+ ...schema,
2222
+ propertyNames: keyType
2223
+ };
2224
+ } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
2225
+ return {
2226
+ ...schema,
2227
+ propertyNames: {
2228
+ enum: def.keyType._def.values
2229
+ }
2230
+ };
2231
+ } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
2232
+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
2233
+ return {
2234
+ ...schema,
2235
+ propertyNames: keyType
2236
+ };
2237
+ }
2238
+ return schema;
2239
+ }
2240
+
2241
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
2242
+ function parseMapDef(def, refs) {
2243
+ if (refs.mapStrategy === "record") {
2244
+ return parseRecordDef(def, refs);
2245
+ }
2246
+ const keys = parseDef(def.keyType._def, {
2247
+ ...refs,
2248
+ currentPath: [...refs.currentPath, "items", "items", "0"]
2249
+ }) || {};
2250
+ const values = parseDef(def.valueType._def, {
2251
+ ...refs,
2252
+ currentPath: [...refs.currentPath, "items", "items", "1"]
2253
+ }) || {};
2254
+ return {
2255
+ type: "array",
2256
+ maxItems: 125,
2257
+ items: {
2258
+ type: "array",
2259
+ items: [keys, values],
2260
+ minItems: 2,
2261
+ maxItems: 2
2262
+ }
2263
+ };
2264
+ }
2265
+
2266
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
2267
+ function parseNativeEnumDef(def) {
2268
+ const object = def.values;
2269
+ const actualKeys = Object.keys(def.values).filter((key) => {
2270
+ return typeof object[object[key]] !== "number";
2271
+ });
2272
+ const actualValues = actualKeys.map((key) => object[key]);
2273
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
2274
+ return {
2275
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
2276
+ enum: actualValues
2277
+ };
2278
+ }
2279
+
2280
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
2281
+ function parseNeverDef() {
2282
+ return {
2283
+ not: {}
2284
+ };
2285
+ }
2286
+
2287
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
2288
+ function parseNullDef(refs) {
2289
+ return refs.target === "openApi3" ? {
2290
+ enum: ["null"],
2291
+ nullable: true
2292
+ } : {
2293
+ type: "null"
2294
+ };
2295
+ }
2296
+
2297
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
2298
+ var primitiveMappings = {
2299
+ ZodString: "string",
2300
+ ZodNumber: "number",
2301
+ ZodBigInt: "integer",
2302
+ ZodBoolean: "boolean",
2303
+ ZodNull: "null"
2304
+ };
2305
+ function parseUnionDef(def, refs) {
2306
+ if (refs.target === "openApi3")
2307
+ return asAnyOf(def, refs);
2308
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
2309
+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
2310
+ const types = options.reduce((types2, x) => {
2311
+ const type = primitiveMappings[x._def.typeName];
2312
+ return type && !types2.includes(type) ? [...types2, type] : types2;
2313
+ }, []);
2314
+ return {
2315
+ type: types.length > 1 ? types : types[0]
2316
+ };
2317
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
2318
+ const types = options.reduce((acc, x) => {
2319
+ const type = typeof x._def.value;
2320
+ switch (type) {
2321
+ case "string":
2322
+ case "number":
2323
+ case "boolean":
2324
+ return [...acc, type];
2325
+ case "bigint":
2326
+ return [...acc, "integer"];
2327
+ case "object":
2328
+ if (x._def.value === null)
2329
+ return [...acc, "null"];
2330
+ case "symbol":
2331
+ case "undefined":
2332
+ case "function":
2333
+ default:
2334
+ return acc;
2335
+ }
2336
+ }, []);
2337
+ if (types.length === options.length) {
2338
+ const uniqueTypes = types.filter((x, i2, a2) => a2.indexOf(x) === i2);
2339
+ return {
2340
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
2341
+ enum: options.reduce((acc, x) => {
2342
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
2343
+ }, [])
2344
+ };
2345
+ }
2346
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
2347
+ return {
2348
+ type: "string",
2349
+ enum: options.reduce((acc, x) => [
2350
+ ...acc,
2351
+ ...x._def.values.filter((x2) => !acc.includes(x2))
2352
+ ], [])
2353
+ };
2354
+ }
2355
+ return asAnyOf(def, refs);
2356
+ }
2357
+ var asAnyOf = (def, refs) => {
2358
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i2) => parseDef(x._def, {
2359
+ ...refs,
2360
+ currentPath: [...refs.currentPath, "anyOf", `${i2}`]
2361
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
2362
+ return anyOf.length ? { anyOf } : void 0;
2363
+ };
2364
+
2365
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
2366
+ function parseNullableDef(def, refs) {
2367
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
2368
+ if (refs.target === "openApi3") {
2369
+ return {
2370
+ type: primitiveMappings[def.innerType._def.typeName],
2371
+ nullable: true
2372
+ };
2373
+ }
2374
+ return {
2375
+ type: [
2376
+ primitiveMappings[def.innerType._def.typeName],
2377
+ "null"
2378
+ ]
2379
+ };
2380
+ }
2381
+ if (refs.target === "openApi3") {
2382
+ const base2 = parseDef(def.innerType._def, {
2383
+ ...refs,
2384
+ currentPath: [...refs.currentPath]
2385
+ });
2386
+ if (base2 && "$ref" in base2)
2387
+ return { allOf: [base2], nullable: true };
2388
+ return base2 && { ...base2, nullable: true };
2389
+ }
2390
+ const base = parseDef(def.innerType._def, {
2391
+ ...refs,
2392
+ currentPath: [...refs.currentPath, "anyOf", "0"]
2393
+ });
2394
+ return base && { anyOf: [base, { type: "null" }] };
2395
+ }
2396
+
2397
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
2398
+ function parseNumberDef(def, refs) {
2399
+ const res = {
2400
+ type: "number"
2401
+ };
2402
+ if (!def.checks)
2403
+ return res;
2404
+ for (const check of def.checks) {
2405
+ switch (check.kind) {
2406
+ case "int":
2407
+ res.type = "integer";
2408
+ addErrorMessage(res, "type", check.message, refs);
2409
+ break;
2410
+ case "min":
2411
+ if (refs.target === "jsonSchema7") {
2412
+ if (check.inclusive) {
2413
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2414
+ } else {
2415
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
2416
+ }
2417
+ } else {
2418
+ if (!check.inclusive) {
2419
+ res.exclusiveMinimum = true;
2420
+ }
2421
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2422
+ }
2423
+ break;
2424
+ case "max":
2425
+ if (refs.target === "jsonSchema7") {
2426
+ if (check.inclusive) {
2427
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2428
+ } else {
2429
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
2430
+ }
2431
+ } else {
2432
+ if (!check.inclusive) {
2433
+ res.exclusiveMaximum = true;
2434
+ }
2435
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2436
+ }
2437
+ break;
2438
+ case "multipleOf":
2439
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
2440
+ break;
2441
+ }
2442
+ }
2443
+ return res;
2444
+ }
2445
+ function decideAdditionalProperties(def, refs) {
2446
+ if (refs.removeAdditionalStrategy === "strict") {
2447
+ return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, {
2448
+ ...refs,
2449
+ currentPath: [...refs.currentPath, "additionalProperties"]
2450
+ }) ?? true;
2451
+ } else {
2452
+ return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, {
2453
+ ...refs,
2454
+ currentPath: [...refs.currentPath, "additionalProperties"]
2455
+ }) ?? true;
2456
+ }
2457
+ }
2458
+ function parseObjectDef(def, refs) {
2459
+ const forceOptionalIntoNullable = refs.target === "openAi";
2460
+ const result = {
2461
+ type: "object",
2462
+ ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
2463
+ if (propDef === void 0 || propDef._def === void 0)
2464
+ return acc;
2465
+ let propOptional = propDef.isOptional();
2466
+ if (propOptional && forceOptionalIntoNullable) {
2467
+ if (propDef instanceof zod.ZodOptional) {
2468
+ propDef = propDef._def.innerType;
2469
+ }
2470
+ if (!propDef.isNullable()) {
2471
+ propDef = propDef.nullable();
2472
+ }
2473
+ propOptional = false;
2474
+ }
2475
+ const parsedDef = parseDef(propDef._def, {
2476
+ ...refs,
2477
+ currentPath: [...refs.currentPath, "properties", propName],
2478
+ propertyPath: [...refs.currentPath, "properties", propName]
2479
+ });
2480
+ if (parsedDef === void 0)
2481
+ return acc;
2482
+ return {
2483
+ properties: { ...acc.properties, [propName]: parsedDef },
2484
+ required: propOptional ? acc.required : [...acc.required, propName]
2485
+ };
2486
+ }, { properties: {}, required: [] }),
2487
+ additionalProperties: decideAdditionalProperties(def, refs)
2488
+ };
2489
+ if (!result.required.length)
2490
+ delete result.required;
2491
+ return result;
2492
+ }
2493
+
2494
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
2495
+ var parseOptionalDef = (def, refs) => {
2496
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
2497
+ return parseDef(def.innerType._def, refs);
2498
+ }
2499
+ const innerSchema = parseDef(def.innerType._def, {
2500
+ ...refs,
2501
+ currentPath: [...refs.currentPath, "anyOf", "1"]
2502
+ });
2503
+ return innerSchema ? {
2504
+ anyOf: [
2505
+ {
2506
+ not: {}
2507
+ },
2508
+ innerSchema
2509
+ ]
2510
+ } : {};
2511
+ };
2512
+
2513
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
2514
+ var parsePipelineDef = (def, refs) => {
2515
+ if (refs.pipeStrategy === "input") {
2516
+ return parseDef(def.in._def, refs);
2517
+ } else if (refs.pipeStrategy === "output") {
2518
+ return parseDef(def.out._def, refs);
2519
+ }
2520
+ const a2 = parseDef(def.in._def, {
2521
+ ...refs,
2522
+ currentPath: [...refs.currentPath, "allOf", "0"]
2523
+ });
2524
+ const b = parseDef(def.out._def, {
2525
+ ...refs,
2526
+ currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"]
2527
+ });
2528
+ return {
2529
+ allOf: [a2, b].filter((x) => x !== void 0)
2530
+ };
2531
+ };
2532
+
2533
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
2534
+ function parsePromiseDef(def, refs) {
2535
+ return parseDef(def.type._def, refs);
2536
+ }
2537
+
2538
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
2539
+ function parseSetDef(def, refs) {
2540
+ const items = parseDef(def.valueType._def, {
2541
+ ...refs,
2542
+ currentPath: [...refs.currentPath, "items"]
2543
+ });
2544
+ const schema = {
2545
+ type: "array",
2546
+ uniqueItems: true,
2547
+ items
2548
+ };
2549
+ if (def.minSize) {
2550
+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
2551
+ }
2552
+ if (def.maxSize) {
2553
+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
2554
+ }
2555
+ return schema;
2556
+ }
2557
+
2558
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
2559
+ function parseTupleDef(def, refs) {
2560
+ if (def.rest) {
2561
+ return {
2562
+ type: "array",
2563
+ minItems: def.items.length,
2564
+ items: def.items.map((x, i2) => parseDef(x._def, {
2565
+ ...refs,
2566
+ currentPath: [...refs.currentPath, "items", `${i2}`]
2567
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
2568
+ additionalItems: parseDef(def.rest._def, {
2569
+ ...refs,
2570
+ currentPath: [...refs.currentPath, "additionalItems"]
2571
+ })
2572
+ };
2573
+ } else {
2574
+ return {
2575
+ type: "array",
2576
+ minItems: def.items.length,
2577
+ maxItems: def.items.length,
2578
+ items: def.items.map((x, i2) => parseDef(x._def, {
2579
+ ...refs,
2580
+ currentPath: [...refs.currentPath, "items", `${i2}`]
2581
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
2582
+ };
2583
+ }
2584
+ }
2585
+
2586
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
2587
+ function parseUndefinedDef() {
2588
+ return {
2589
+ not: {}
2590
+ };
2591
+ }
2592
+
2593
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
2594
+ function parseUnknownDef() {
2595
+ return {};
2596
+ }
2597
+
2598
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
2599
+ var parseReadonlyDef = (def, refs) => {
2600
+ return parseDef(def.innerType._def, refs);
2601
+ };
2602
+
2603
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parseDef.js
2604
+ function parseDef(def, refs, forceResolution = false) {
2605
+ const seenItem = refs.seen.get(def);
2606
+ if (refs.override) {
2607
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
2608
+ if (overrideResult !== ignoreOverride) {
2609
+ return overrideResult;
2610
+ }
2611
+ }
2612
+ if (seenItem && !forceResolution) {
2613
+ const seenSchema = get$ref(seenItem, refs);
2614
+ if (seenSchema !== void 0) {
2615
+ return seenSchema;
2616
+ }
2617
+ }
2618
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2619
+ refs.seen.set(def, newItem);
2620
+ const jsonSchema = selectParser(def, def.typeName, refs);
2621
+ if (jsonSchema) {
2622
+ addMeta(def, refs, jsonSchema);
2623
+ }
2624
+ newItem.jsonSchema = jsonSchema;
2625
+ return jsonSchema;
2626
+ }
2627
+ var get$ref = (item, refs) => {
2628
+ switch (refs.$refStrategy) {
2629
+ case "root":
2630
+ return { $ref: item.path.join("/") };
2631
+ case "relative":
2632
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
2633
+ case "none":
2634
+ case "seen": {
2635
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2636
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
2637
+ return {};
2638
+ }
2639
+ return refs.$refStrategy === "seen" ? {} : void 0;
2640
+ }
2641
+ }
2642
+ };
2643
+ var getRelativePath = (pathA, pathB) => {
2644
+ let i2 = 0;
2645
+ for (; i2 < pathA.length && i2 < pathB.length; i2++) {
2646
+ if (pathA[i2] !== pathB[i2])
2647
+ break;
2648
+ }
2649
+ return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/");
2650
+ };
2651
+ var selectParser = (def, typeName, refs) => {
2652
+ switch (typeName) {
2653
+ case zod.ZodFirstPartyTypeKind.ZodString:
2654
+ return parseStringDef(def, refs);
2655
+ case zod.ZodFirstPartyTypeKind.ZodNumber:
2656
+ return parseNumberDef(def, refs);
2657
+ case zod.ZodFirstPartyTypeKind.ZodObject:
2658
+ return parseObjectDef(def, refs);
2659
+ case zod.ZodFirstPartyTypeKind.ZodBigInt:
2660
+ return parseBigintDef(def, refs);
2661
+ case zod.ZodFirstPartyTypeKind.ZodBoolean:
2662
+ return parseBooleanDef();
2663
+ case zod.ZodFirstPartyTypeKind.ZodDate:
2664
+ return parseDateDef(def, refs);
2665
+ case zod.ZodFirstPartyTypeKind.ZodUndefined:
2666
+ return parseUndefinedDef();
2667
+ case zod.ZodFirstPartyTypeKind.ZodNull:
2668
+ return parseNullDef(refs);
2669
+ case zod.ZodFirstPartyTypeKind.ZodArray:
2670
+ return parseArrayDef(def, refs);
2671
+ case zod.ZodFirstPartyTypeKind.ZodUnion:
2672
+ case zod.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
2673
+ return parseUnionDef(def, refs);
2674
+ case zod.ZodFirstPartyTypeKind.ZodIntersection:
2675
+ return parseIntersectionDef(def, refs);
2676
+ case zod.ZodFirstPartyTypeKind.ZodTuple:
2677
+ return parseTupleDef(def, refs);
2678
+ case zod.ZodFirstPartyTypeKind.ZodRecord:
2679
+ return parseRecordDef(def, refs);
2680
+ case zod.ZodFirstPartyTypeKind.ZodLiteral:
2681
+ return parseLiteralDef(def, refs);
2682
+ case zod.ZodFirstPartyTypeKind.ZodEnum:
2683
+ return parseEnumDef(def);
2684
+ case zod.ZodFirstPartyTypeKind.ZodNativeEnum:
2685
+ return parseNativeEnumDef(def);
2686
+ case zod.ZodFirstPartyTypeKind.ZodNullable:
2687
+ return parseNullableDef(def, refs);
2688
+ case zod.ZodFirstPartyTypeKind.ZodOptional:
2689
+ return parseOptionalDef(def, refs);
2690
+ case zod.ZodFirstPartyTypeKind.ZodMap:
2691
+ return parseMapDef(def, refs);
2692
+ case zod.ZodFirstPartyTypeKind.ZodSet:
2693
+ return parseSetDef(def, refs);
2694
+ case zod.ZodFirstPartyTypeKind.ZodLazy:
2695
+ return parseDef(def.getter()._def, refs);
2696
+ case zod.ZodFirstPartyTypeKind.ZodPromise:
2697
+ return parsePromiseDef(def, refs);
2698
+ case zod.ZodFirstPartyTypeKind.ZodNaN:
2699
+ case zod.ZodFirstPartyTypeKind.ZodNever:
2700
+ return parseNeverDef();
2701
+ case zod.ZodFirstPartyTypeKind.ZodEffects:
2702
+ return parseEffectsDef(def, refs);
2703
+ case zod.ZodFirstPartyTypeKind.ZodAny:
2704
+ return parseAnyDef();
2705
+ case zod.ZodFirstPartyTypeKind.ZodUnknown:
2706
+ return parseUnknownDef();
2707
+ case zod.ZodFirstPartyTypeKind.ZodDefault:
2708
+ return parseDefaultDef(def, refs);
2709
+ case zod.ZodFirstPartyTypeKind.ZodBranded:
2710
+ return parseBrandedDef(def, refs);
2711
+ case zod.ZodFirstPartyTypeKind.ZodReadonly:
2712
+ return parseReadonlyDef(def, refs);
2713
+ case zod.ZodFirstPartyTypeKind.ZodCatch:
2714
+ return parseCatchDef(def, refs);
2715
+ case zod.ZodFirstPartyTypeKind.ZodPipeline:
2716
+ return parsePipelineDef(def, refs);
2717
+ case zod.ZodFirstPartyTypeKind.ZodFunction:
2718
+ case zod.ZodFirstPartyTypeKind.ZodVoid:
2719
+ case zod.ZodFirstPartyTypeKind.ZodSymbol:
2720
+ return void 0;
2721
+ default:
2722
+ return /* @__PURE__ */ ((_) => void 0)();
2723
+ }
2724
+ };
2725
+ var addMeta = (def, refs, jsonSchema) => {
2726
+ if (def.description) {
2727
+ jsonSchema.description = def.description;
2728
+ if (refs.markdownDescription) {
2729
+ jsonSchema.markdownDescription = def.description;
2730
+ }
2731
+ }
2732
+ return jsonSchema;
2733
+ };
2734
+
2735
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
2736
+ var zodToJsonSchema = (schema, options) => {
2737
+ const refs = getRefs(options);
2738
+ const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
2739
+ ...acc,
2740
+ [name2]: parseDef(schema2._def, {
2741
+ ...refs,
2742
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
2743
+ }, true) ?? {}
2744
+ }), {}) : void 0;
2745
+ const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
2746
+ const main = parseDef(schema._def, name === void 0 ? refs : {
2747
+ ...refs,
2748
+ currentPath: [...refs.basePath, refs.definitionPath, name]
2749
+ }, false) ?? {};
2750
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2751
+ if (title !== void 0) {
2752
+ main.title = title;
2753
+ }
2754
+ const combined = name === void 0 ? definitions ? {
2755
+ ...main,
2756
+ [refs.definitionPath]: definitions
2757
+ } : main : {
2758
+ $ref: [
2759
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2760
+ refs.definitionPath,
2761
+ name
2762
+ ].join("/"),
2763
+ [refs.definitionPath]: {
2764
+ ...definitions,
2765
+ [name]: main
2766
+ }
2767
+ };
2768
+ if (refs.target === "jsonSchema7") {
2769
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
2770
+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
2771
+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
2772
+ }
2773
+ if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
2774
+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
2775
+ }
2776
+ return combined;
2777
+ };
2778
+
2779
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.24.1_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/index.js
2780
+ var esm_default = zodToJsonSchema;
2781
+ function handleError(error, defaultMessage) {
2782
+ console.error(defaultMessage, error);
2783
+ const apiError = error;
2784
+ throw new httpException.HTTPException(apiError.status || 500, {
2785
+ message: apiError.message || defaultMessage
2786
+ });
2787
+ }
2788
+ function errorHandler(err, c2) {
2789
+ if (err instanceof httpException.HTTPException) {
2790
+ return c2.json({ error: err.message }, err.status);
2791
+ }
2792
+ console.error(err);
2793
+ return c2.json({ error: "Internal Server Error" }, 500);
2794
+ }
2795
+ function validateBody(body) {
2796
+ const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
2797
+ if (!value) {
2798
+ acc[key] = `${key} is required`;
2799
+ }
2800
+ return acc;
2801
+ }, {});
2802
+ if (Object.keys(errorResponse).length > 0) {
2803
+ throw new httpException.HTTPException(400, { message: JSON.stringify(errorResponse) });
2804
+ }
2805
+ }
2806
+
2807
+ // src/server/handlers/agents.ts
2808
+ async function getAgentsHandler(c2) {
2809
+ try {
2810
+ const mastra = c2.get("mastra");
2811
+ const agents = mastra.getAgents();
2812
+ const serializedAgents = Object.entries(agents).reduce((acc, [_id, _agent]) => {
2813
+ const agent = _agent;
2814
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc2, [key, tool]) => {
2815
+ const _tool = tool;
2816
+ acc2[key] = {
2817
+ ..._tool,
2818
+ inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2819
+ outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2820
+ };
2821
+ return acc2;
2822
+ }, {});
2823
+ acc[_id] = {
2824
+ name: agent.name,
2825
+ instructions: agent.instructions,
2826
+ tools: serializedAgentTools,
2827
+ provider: agent.llm?.getProvider(),
2828
+ modelId: agent.llm?.getModelId()
2829
+ };
2830
+ return acc;
2831
+ }, {});
2832
+ return c2.json(serializedAgents);
2833
+ } catch (error) {
2834
+ return handleError(error, "Error getting agents");
2835
+ }
2836
+ }
2837
+ async function getAgentByIdHandler(c2) {
2838
+ try {
2839
+ const mastra = c2.get("mastra");
2840
+ const agentId = c2.req.param("agentId");
2841
+ const agent = mastra.getAgent(agentId);
2842
+ if (!agent) {
2843
+ throw new httpException.HTTPException(404, { message: "Agent not found" });
2844
+ }
2845
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc, [key, tool]) => {
2846
+ const _tool = tool;
2847
+ acc[key] = {
2848
+ ..._tool,
2849
+ inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2850
+ outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2851
+ };
2852
+ return acc;
2853
+ }, {});
2854
+ return c2.json({
2855
+ name: agent.name,
2856
+ instructions: agent.instructions,
2857
+ tools: serializedAgentTools,
2858
+ provider: agent.llm?.getProvider(),
2859
+ modelId: agent.llm?.getModelId()
2860
+ });
2861
+ } catch (error) {
2862
+ return handleError(error, "Error getting agent");
2863
+ }
2864
+ }
2865
+ async function getEvalsByAgentIdHandler(c2) {
2866
+ try {
2867
+ const mastra = c2.get("mastra");
2868
+ const agentId = c2.req.param("agentId");
2869
+ const agent = mastra.getAgent(agentId);
2870
+ const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "test") || [];
2871
+ return c2.json({
2872
+ id: agentId,
2873
+ name: agent.name,
2874
+ instructions: agent.instructions,
2875
+ evals
2876
+ });
2877
+ } catch (error) {
2878
+ return handleError(error, "Error getting test evals");
2879
+ }
2880
+ }
2881
+ async function getLiveEvalsByAgentIdHandler(c2) {
2882
+ try {
2883
+ const mastra = c2.get("mastra");
2884
+ const agentId = c2.req.param("agentId");
2885
+ const agent = mastra.getAgent(agentId);
2886
+ const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "live") || [];
2887
+ return c2.json({
2888
+ id: agentId,
2889
+ name: agent.name,
2890
+ instructions: agent.instructions,
2891
+ evals
2892
+ });
2893
+ } catch (error) {
2894
+ return handleError(error, "Error getting live evals");
2895
+ }
2896
+ }
2897
+ async function generateHandler(c2) {
2898
+ try {
2899
+ const mastra = c2.get("mastra");
2900
+ const agentId = c2.req.param("agentId");
2901
+ const agent = mastra.getAgent(agentId);
2902
+ if (!agent) {
2903
+ throw new httpException.HTTPException(404, { message: "Agent not found" });
2904
+ }
2905
+ const { messages, threadId, resourceid, resourceId, output, runId } = await c2.req.json();
2906
+ validateBody({ messages });
2907
+ if (!Array.isArray(messages)) {
2908
+ throw new httpException.HTTPException(400, { message: "Messages should be an array" });
2909
+ }
2910
+ const finalResourceId = resourceId ?? resourceid;
2911
+ const result = await agent.generate(messages, { threadId, resourceId: finalResourceId, output, runId });
2912
+ return c2.json(result);
2913
+ } catch (error) {
2914
+ return handleError(error, "Error generating from agent");
2915
+ }
2916
+ }
2917
+ async function streamGenerateHandler(c2) {
2918
+ try {
2919
+ const mastra = c2.get("mastra");
2920
+ const agentId = c2.req.param("agentId");
2921
+ const agent = mastra.getAgent(agentId);
2922
+ if (!agent) {
2923
+ throw new httpException.HTTPException(404, { message: "Agent not found" });
2924
+ }
2925
+ const { messages, threadId, resourceid, resourceId, output, runId } = await c2.req.json();
2926
+ validateBody({ messages });
2927
+ if (!Array.isArray(messages)) {
2928
+ throw new httpException.HTTPException(400, { message: "Messages should be an array" });
2929
+ }
2930
+ const finalResourceId = resourceId ?? resourceid;
2931
+ const streamResult = await agent.stream(messages, { threadId, resourceId: finalResourceId, output, runId });
2932
+ const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
2933
+ sendUsage: true,
2934
+ sendReasoning: true,
2935
+ getErrorMessage: (error) => {
2936
+ return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
2937
+ }
2938
+ });
2939
+ return streamResponse;
2940
+ } catch (error) {
2941
+ return handleError(error, "Error streaming from agent");
2942
+ }
2943
+ }
2944
+ async function setAgentInstructionsHandler(c2) {
2945
+ try {
2946
+ const isPlayground = c2.get("playground") === true;
2947
+ if (!isPlayground) {
2948
+ return c2.json({ error: "This API is only available in the playground environment" }, 403);
2949
+ }
2950
+ const agentId = c2.req.param("agentId");
2951
+ const { instructions } = await c2.req.json();
2952
+ if (!agentId || !instructions) {
2953
+ return c2.json({ error: "Missing required fields" }, 400);
2954
+ }
2955
+ const mastra = c2.get("mastra");
2956
+ const agent = mastra.getAgent(agentId);
2957
+ if (!agent) {
2958
+ return c2.json({ error: "Agent not found" }, 404);
2959
+ }
2960
+ agent.__updateInstructions(instructions);
2961
+ return c2.json(
2962
+ {
2963
+ instructions
2964
+ },
2965
+ 200
2966
+ );
2967
+ } catch (error) {
2968
+ return handleError(error, "Error setting agent instructions");
2969
+ }
2970
+ }
2971
+
2972
+ // src/server/handlers/client.ts
2973
+ var clients = /* @__PURE__ */ new Set();
2974
+ function handleClientsRefresh(c2) {
2975
+ const stream = new ReadableStream({
2976
+ start(controller) {
2977
+ clients.add(controller);
2978
+ controller.enqueue("data: connected\n\n");
2979
+ c2.req.raw.signal.addEventListener("abort", () => {
2980
+ clients.delete(controller);
2981
+ });
2982
+ }
2983
+ });
2984
+ return new Response(stream, {
2985
+ headers: {
2986
+ "Content-Type": "text/event-stream",
2987
+ "Cache-Control": "no-cache",
2988
+ Connection: "keep-alive",
2989
+ "Access-Control-Allow-Origin": "*"
2990
+ }
2991
+ });
2992
+ }
2993
+ function handleTriggerClientsRefresh(c2) {
2994
+ clients.forEach((controller) => {
2995
+ try {
2996
+ controller.enqueue("data: refresh\n\n");
2997
+ } catch {
2998
+ clients.delete(controller);
2999
+ }
3000
+ });
3001
+ return c2.json({ success: true, clients: clients.size });
3002
+ }
3003
+ async function getLogsHandler(c2) {
3004
+ try {
3005
+ const mastra = c2.get("mastra");
3006
+ const transportId = c2.req.query("transportId");
3007
+ if (!transportId) {
3008
+ throw new httpException.HTTPException(400, { message: "transportId is required" });
3009
+ }
3010
+ const logs = await mastra.getLogs(transportId);
3011
+ return c2.json(logs);
3012
+ } catch (error) {
3013
+ return handleError(error, "Error getting logs");
3014
+ }
3015
+ }
3016
+ async function getLogsByRunIdHandler(c2) {
3017
+ try {
3018
+ const mastra = c2.get("mastra");
3019
+ const runId = c2.req.param("runId");
3020
+ const transportId = c2.req.query("transportId");
3021
+ if (!transportId) {
3022
+ throw new httpException.HTTPException(400, { message: "transportId is required" });
3023
+ }
3024
+ const logs = await mastra.getLogsByRunId({ runId, transportId });
3025
+ return c2.json(logs);
3026
+ } catch (error) {
3027
+ return handleError(error, "Error getting logs by run ID");
3028
+ }
3029
+ }
3030
+ async function getLogTransports(c2) {
3031
+ console.log("here");
3032
+ try {
3033
+ const mastra = c2.get("mastra");
3034
+ const logger2 = mastra.getLogger();
3035
+ const transports = logger2.transports;
3036
+ return c2.json({
3037
+ transports: Object.keys(transports)
3038
+ });
3039
+ } catch (e2) {
3040
+ return handleError(e2, "Error getting log Transports ");
3041
+ }
3042
+ }
3043
+ function getMemoryFromContext(c2) {
3044
+ const mastra = c2.get("mastra");
3045
+ const agentId = c2.req.query("agentId");
3046
+ const agent = agentId ? mastra.getAgent(agentId) : null;
3047
+ if (agentId && !agent) {
3048
+ throw new httpException.HTTPException(404, { message: "Agent not found" });
3049
+ }
3050
+ const memory = agent?.getMemory?.() || mastra.memory;
3051
+ return memory;
3052
+ }
3053
+ async function getMemoryStatusHandler(c2) {
3054
+ try {
3055
+ const memory = getMemoryFromContext(c2);
3056
+ if (!memory) {
3057
+ return c2.json({ result: false });
3058
+ }
3059
+ return c2.json({ result: true });
3060
+ } catch (error) {
3061
+ return handleError(error, "Error getting memory status");
3062
+ }
3063
+ }
3064
+ async function getThreadsHandler(c2) {
3065
+ try {
3066
+ const { resourceid } = c2.req.query();
3067
+ const memory = getMemoryFromContext(c2);
3068
+ if (!memory) {
3069
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3070
+ }
3071
+ if (!resourceid) {
3072
+ throw new httpException.HTTPException(400, { message: "Resource ID is required" });
3073
+ }
3074
+ const threads = await memory.getThreadsByResourceId({ resourceId: resourceid });
3075
+ return c2.json(threads);
3076
+ } catch (error) {
3077
+ return handleError(error, "Error getting threads");
3078
+ }
3079
+ }
3080
+ async function getThreadByIdHandler(c2) {
3081
+ try {
3082
+ const memory = getMemoryFromContext(c2);
3083
+ const threadId = c2.req.param("threadId");
3084
+ if (!memory) {
3085
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3086
+ }
3087
+ const thread = await memory.getThreadById({ threadId });
3088
+ if (!thread) {
3089
+ throw new httpException.HTTPException(404, { message: "Thread not found" });
3090
+ }
3091
+ return c2.json(thread);
3092
+ } catch (error) {
3093
+ return handleError(error, "Error getting thread");
3094
+ }
3095
+ }
3096
+ async function saveMessagesHandler(c2) {
3097
+ try {
3098
+ const memory = getMemoryFromContext(c2);
3099
+ const { messages } = await c2.req.json();
3100
+ if (!memory) {
3101
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3102
+ }
3103
+ validateBody({ messages });
3104
+ if (!Array.isArray(messages)) {
3105
+ throw new httpException.HTTPException(400, { message: "Messages should be an array" });
3106
+ }
3107
+ const processedMessages = messages.map((message) => ({
3108
+ ...message,
3109
+ id: memory.generateId(),
3110
+ createdAt: message.createdAt ? new Date(message.createdAt) : /* @__PURE__ */ new Date()
3111
+ }));
3112
+ const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
3113
+ return c2.json(result);
3114
+ } catch (error) {
3115
+ return handleError(error, "Error saving messages");
3116
+ }
3117
+ }
3118
+ async function createThreadHandler(c2) {
3119
+ try {
3120
+ const memory = getMemoryFromContext(c2);
3121
+ const { title, metadata, resourceid, threadId } = await c2.req.json();
3122
+ if (!memory) {
3123
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3124
+ }
3125
+ validateBody({ resourceid });
3126
+ const result = await memory.createThread({ resourceId: resourceid, title, metadata, threadId });
3127
+ return c2.json(result);
3128
+ } catch (error) {
3129
+ return handleError(error, "Error saving thread to memory");
3130
+ }
3131
+ }
3132
+ async function updateThreadHandler(c2) {
3133
+ try {
3134
+ const memory = getMemoryFromContext(c2);
3135
+ const threadId = c2.req.param("threadId");
3136
+ const { title, metadata, resourceid } = await c2.req.json();
3137
+ const updatedAt = /* @__PURE__ */ new Date();
3138
+ if (!memory) {
3139
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3140
+ }
3141
+ const thread = await memory.getThreadById({ threadId });
3142
+ if (!thread) {
3143
+ throw new httpException.HTTPException(404, { message: "Thread not found" });
3144
+ }
3145
+ const updatedThread = {
3146
+ ...thread,
3147
+ title: title || thread.title,
3148
+ metadata: metadata || thread.metadata,
3149
+ resourceId: resourceid || thread.resourceId,
3150
+ createdAt: thread.createdAt,
3151
+ updatedAt
3152
+ };
3153
+ const result = await memory.saveThread({ thread: updatedThread });
3154
+ return c2.json(result);
3155
+ } catch (error) {
3156
+ return handleError(error, "Error updating thread");
3157
+ }
3158
+ }
3159
+ async function deleteThreadHandler(c2) {
3160
+ try {
3161
+ const memory = getMemoryFromContext(c2);
3162
+ const threadId = c2.req.param("threadId");
3163
+ if (!memory) {
3164
+ throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3165
+ }
3166
+ const thread = await memory.getThreadById({ threadId });
3167
+ if (!thread) {
3168
+ throw new httpException.HTTPException(404, { message: "Thread not found" });
3169
+ }
3170
+ await memory.deleteThread(threadId);
3171
+ return c2.json({ result: "Thread deleted" });
3172
+ } catch (error) {
3173
+ return handleError(error, "Error deleting thread");
3174
+ }
3175
+ }
3176
+ async function getMessagesHandler(c2) {
3177
+ try {
3178
+ const memory = getMemoryFromContext(c2);
3179
+ const threadId = c2.req.param("threadId");
3180
+ if (!memory) {
3181
+ return c2.json({ error: "Memory is not initialized" }, 400);
3182
+ }
3183
+ const thread = await memory.getThreadById({ threadId });
3184
+ if (!thread) {
3185
+ return c2.json({ error: "Thread not found" }, 404);
3186
+ }
3187
+ const result = await memory.query({ threadId });
3188
+ return c2.json(result);
3189
+ } catch (error) {
3190
+ return handleError(error, "Error getting messages");
3191
+ }
3192
+ }
3193
+ async function generateSystemPromptHandler(c2) {
3194
+ try {
3195
+ const agentId = c2.req.param("agentId");
3196
+ const isPlayground = c2.get("playground") === true;
3197
+ if (!isPlayground) {
3198
+ return c2.json({ error: "This API is only available in the playground environment" }, 403);
3199
+ }
3200
+ const { instructions, comment } = await c2.req.json();
3201
+ if (!instructions) {
3202
+ return c2.json({ error: "Missing instructions in request body" }, 400);
3203
+ }
3204
+ const mastra = c2.get("mastra");
3205
+ const agent$1 = mastra.getAgent(agentId);
3206
+ if (!agent$1) {
3207
+ return c2.json({ error: "Agent not found" }, 404);
3208
+ }
3209
+ let evalSummary = "";
3210
+ try {
3211
+ const testEvals = await mastra.storage?.getEvalsByAgentName?.(agent$1.name, "test") || [];
3212
+ const liveEvals = await mastra.storage?.getEvalsByAgentName?.(agent$1.name, "live") || [];
3213
+ const evalsMapped = [...testEvals, ...liveEvals].filter(
3214
+ ({ instructions: evalInstructions }) => evalInstructions === instructions
3215
+ );
3216
+ evalSummary = evalsMapped.map(
3217
+ ({ input, output, result: result2 }) => `
3218
+ Input: ${input}
3219
+
3220
+ Output: ${output}
3221
+
3222
+ Result: ${JSON.stringify(result2)}
3223
+
3224
+ `
3225
+ ).join("");
3226
+ } catch (error) {
3227
+ mastra.getLogger().error(`Error fetching evals`, { error });
3228
+ }
3229
+ const ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `
3230
+ You are an expert system prompt engineer, specialized in analyzing and enhancing instructions to create clear, effective, and comprehensive system prompts. Your goal is to help users transform their basic instructions into well-structured system prompts that will guide AI behavior effectively.
3231
+ Follow these steps to analyze and enhance the instructions:
3232
+ 1. ANALYSIS PHASE
3233
+ - Identify the core purpose and goals
3234
+ - Extract key constraints and requirements
3235
+ - Recognize domain-specific terminology and concepts
3236
+ - Note any implicit assumptions that should be made explicit
3237
+ 2. PROMPT STRUCTURE
3238
+ Create a system prompt with these components:
3239
+ a) ROLE DEFINITION
3240
+ - Clear statement of the AI's role and purpose
3241
+ - Key responsibilities and scope
3242
+ - Primary stakeholders and users
3243
+ b) CORE CAPABILITIES
3244
+ - Main functions and abilities
3245
+ - Specific domain knowledge required
3246
+ - Tools and resources available
3247
+ c) BEHAVIORAL GUIDELINES
3248
+ - Communication style and tone
3249
+ - Decision-making framework
3250
+ - Error handling approach
3251
+ - Ethical considerations
3252
+ d) CONSTRAINTS & BOUNDARIES
3253
+ - Explicit limitations
3254
+ - Out-of-scope activities
3255
+ - Security and privacy considerations
3256
+ e) SUCCESS CRITERIA
3257
+ - Quality standards
3258
+ - Expected outcomes
3259
+ - Performance metrics
3260
+ 3. QUALITY CHECKS
3261
+ Ensure the prompt is:
3262
+ - Clear and unambiguous
3263
+ - Comprehensive yet concise
3264
+ - Properly scoped
3265
+ - Technically accurate
3266
+ - Ethically sound
3267
+ 4. OUTPUT FORMAT
3268
+ Return a structured response with:
3269
+ - Enhanced system prompt
3270
+ - Analysis of key components
3271
+ - Identified goals and constraints
3272
+ - Core domain concepts
3273
+ Remember: A good system prompt should be specific enough to guide behavior but flexible enough to handle edge cases.
3274
+ Focus on creating prompts that are clear, actionable, and aligned with the intended use case.
3275
+ `;
3276
+ const systemPromptAgent = new agent.Agent({
3277
+ name: "system-prompt-enhancer",
3278
+ instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS,
3279
+ model: agent$1.llm?.getModel()
3280
+ });
3281
+ const result = await systemPromptAgent.generate(
3282
+ `
3283
+ We need to improve the system prompt.
3284
+ Current: ${instructions}
3285
+ ${comment ? `User feedback: ${comment}` : ""}
3286
+ ${evalSummary ? `
3287
+ Evaluation Results:
3288
+ ${evalSummary}` : ""}
3289
+ `,
3290
+ {
3291
+ output: zod.z.object({
3292
+ new_prompt: zod.z.string(),
3293
+ explanation: zod.z.string()
3294
+ })
3295
+ }
3296
+ );
3297
+ return c2.json(result?.object || {});
3298
+ } catch (error) {
3299
+ return handleError(error, "Error generating system prompt");
3300
+ }
3301
+ }
3302
+
3303
+ // src/server/handlers/root.ts
3304
+ async function rootHandler(c2) {
3305
+ return c2.text("Hello to the Mastra API!");
3306
+ }
3307
+ async function getTelemetryHandler(c2) {
3308
+ try {
3309
+ const mastra = c2.get("mastra");
3310
+ const telemetry = mastra.telemetry;
3311
+ const storage = mastra.storage;
3312
+ const { name, scope, page, perPage } = c2.req.query();
3313
+ const attribute = c2.req.queries("attribute");
3314
+ if (!telemetry) {
3315
+ throw new httpException.HTTPException(400, { message: "Telemetry is not initialized" });
3316
+ }
3317
+ if (!storage) {
3318
+ throw new httpException.HTTPException(400, { message: "Storage is not initialized" });
3319
+ }
3320
+ const attributes = attribute ? Object.fromEntries(
3321
+ (Array.isArray(attribute) ? attribute : [attribute]).map((attr) => {
3322
+ const [key, value] = attr.split(":");
3323
+ return [key, value];
3324
+ })
3325
+ ) : void 0;
3326
+ const traces = await storage.getTraces({
3327
+ name,
3328
+ scope,
3329
+ page: Number(page ?? 0),
3330
+ perPage: Number(perPage ?? 100),
3331
+ attributes
3332
+ });
3333
+ return c2.json({ traces });
3334
+ } catch (error) {
3335
+ return handleError(error, "Error saving messages");
3336
+ }
3337
+ }
3338
+ async function getToolsHandler(c2) {
3339
+ try {
3340
+ const tools = c2.get("tools");
3341
+ if (!tools) {
3342
+ return c2.json({});
3343
+ }
3344
+ const serializedTools = Object.entries(tools).reduce(
3345
+ (acc, [id, _tool]) => {
3346
+ const tool = _tool;
3347
+ acc[id] = {
3348
+ ...tool,
3349
+ inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3350
+ outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3351
+ };
3352
+ return acc;
3353
+ },
3354
+ {}
3355
+ );
3356
+ return c2.json(serializedTools);
3357
+ } catch (error) {
3358
+ return handleError(error, "Error getting tools");
3359
+ }
3360
+ }
3361
+ async function getToolByIdHandler(c2) {
3362
+ try {
3363
+ const tools = c2.get("tools");
3364
+ const toolId = c2.req.param("toolId");
3365
+ const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3366
+ if (!tool) {
3367
+ throw new httpException.HTTPException(404, { message: "Tool not found" });
3368
+ }
3369
+ const serializedTool = {
3370
+ ...tool,
3371
+ inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3372
+ outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3373
+ };
3374
+ return c2.json(serializedTool);
3375
+ } catch (error) {
3376
+ return handleError(error, "Error getting tool");
3377
+ }
3378
+ }
3379
+ function executeToolHandler(tools) {
3380
+ return async (c2) => {
3381
+ try {
3382
+ const toolId = decodeURIComponent(c2.req.param("toolId"));
3383
+ const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3384
+ if (!tool) {
3385
+ return c2.json({ error: "Tool not found" }, 404);
3386
+ }
3387
+ if (!tool?.execute) {
3388
+ return c2.json({ error: "Tool is not executable" }, 400);
3389
+ }
3390
+ const { data } = await c2.req.json();
3391
+ const mastra = c2.get("mastra");
3392
+ const result = await tool.execute({
3393
+ context: data,
3394
+ mastra,
3395
+ runId: mastra.runId
3396
+ });
3397
+ return c2.json(result);
3398
+ } catch (error) {
3399
+ return handleError(error, "Error executing tool");
3400
+ }
3401
+ };
3402
+ }
3403
+ async function executeAgentToolHandler(c2) {
3404
+ try {
3405
+ const mastra = c2.get("mastra");
3406
+ const agentId = c2.req.param("agentId");
3407
+ const toolId = c2.req.param("toolId");
3408
+ const agent = mastra.getAgent(agentId);
3409
+ const tool = Object.values(agent?.tools || {}).find((tool2) => tool2.id === toolId);
3410
+ if (!tool) {
3411
+ throw new httpException.HTTPException(404, { message: "Tool not found" });
3412
+ }
3413
+ if (!tool?.execute) {
3414
+ return c2.json({ error: "Tool is not executable" }, 400);
3415
+ }
3416
+ const { data } = await c2.req.json();
3417
+ const result = await tool.execute({
3418
+ context: data,
3419
+ mastra,
3420
+ runId: agentId
3421
+ });
3422
+ return c2.json(result);
3423
+ } catch (error) {
3424
+ return handleError(error, "Error executing tool");
3425
+ }
3426
+ }
3427
+ var getVector = (c2, vectorName) => {
3428
+ const vector = c2.get("mastra").getVector(vectorName);
3429
+ if (!vector) {
3430
+ throw new httpException.HTTPException(404, { message: `Vector store ${vectorName} not found` });
3431
+ }
3432
+ return vector;
3433
+ };
3434
+ async function upsertVectors(c2) {
3435
+ try {
3436
+ const vectorName = c2.req.param("vectorName");
3437
+ const { indexName, vectors, metadata, ids } = await c2.req.json();
3438
+ if (!indexName || !vectors || !Array.isArray(vectors)) {
3439
+ throw new httpException.HTTPException(400, { message: "Invalid request body. indexName and vectors array are required." });
3440
+ }
3441
+ const vector = getVector(c2, vectorName);
3442
+ const result = await vector.upsert(indexName, vectors, metadata, ids);
3443
+ return c2.json({ ids: result });
3444
+ } catch (error) {
3445
+ return handleError(error, "Error upserting vectors");
3446
+ }
3447
+ }
3448
+ async function createIndex(c2) {
3449
+ try {
3450
+ const vectorName = c2.req.param("vectorName");
3451
+ const { indexName, dimension, metric } = await c2.req.json();
3452
+ if (!indexName || typeof dimension !== "number" || dimension <= 0) {
3453
+ throw new httpException.HTTPException(400, {
3454
+ message: "Invalid request body. indexName and positive dimension number are required."
3455
+ });
3456
+ }
3457
+ if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
3458
+ throw new httpException.HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
3459
+ }
3460
+ const vector = getVector(c2, vectorName);
3461
+ await vector.createIndex(indexName, dimension, metric);
3462
+ return c2.json({ success: true });
3463
+ } catch (error) {
3464
+ return handleError(error, "Error creating index");
3465
+ }
3466
+ }
3467
+ async function queryVectors(c2) {
3468
+ try {
3469
+ const vectorName = c2.req.param("vectorName");
3470
+ const { indexName, queryVector, topK = 10, filter, includeVector = false } = await c2.req.json();
3471
+ if (!indexName || !queryVector || !Array.isArray(queryVector)) {
3472
+ throw new httpException.HTTPException(400, { message: "Invalid request body. indexName and queryVector array are required." });
3473
+ }
3474
+ const vector = getVector(c2, vectorName);
3475
+ const results = await vector.query(indexName, queryVector, topK, filter, includeVector);
3476
+ return c2.json({ results });
3477
+ } catch (error) {
3478
+ return handleError(error, "Error querying vectors");
3479
+ }
3480
+ }
3481
+ async function listIndexes(c2) {
3482
+ try {
3483
+ const vectorName = c2.req.param("vectorName");
3484
+ const vector = getVector(c2, vectorName);
3485
+ const indexes = await vector.listIndexes();
3486
+ return c2.json({ indexes: indexes.filter(Boolean) });
3487
+ } catch (error) {
3488
+ return handleError(error, "Error listing indexes");
3489
+ }
3490
+ }
3491
+ async function describeIndex(c2) {
3492
+ try {
3493
+ const vectorName = c2.req.param("vectorName");
3494
+ const indexName = c2.req.param("indexName");
3495
+ if (!indexName) {
3496
+ throw new httpException.HTTPException(400, { message: "Index name is required" });
3497
+ }
3498
+ const vector = getVector(c2, vectorName);
3499
+ const stats = await vector.describeIndex(indexName);
3500
+ return c2.json({
3501
+ dimension: stats.dimension,
3502
+ count: stats.count,
3503
+ metric: stats.metric?.toLowerCase()
3504
+ });
3505
+ } catch (error) {
3506
+ return handleError(error, "Error describing index");
3507
+ }
3508
+ }
3509
+ async function deleteIndex(c2) {
3510
+ try {
3511
+ const vectorName = c2.req.param("vectorName");
3512
+ const indexName = c2.req.param("indexName");
3513
+ if (!indexName) {
3514
+ throw new httpException.HTTPException(400, { message: "Index name is required" });
3515
+ }
3516
+ const vector = getVector(c2, vectorName);
3517
+ await vector.deleteIndex(indexName);
3518
+ return c2.json({ success: true });
3519
+ } catch (error) {
3520
+ return handleError(error, "Error deleting index");
3521
+ }
3522
+ }
3523
+ async function getWorkflowsHandler(c2) {
3524
+ try {
3525
+ const mastra = c2.get("mastra");
3526
+ const workflows = mastra.getWorkflows({ serialized: true });
3527
+ return c2.json(workflows);
3528
+ } catch (error) {
3529
+ return handleError(error, "Error getting workflows");
3530
+ }
3531
+ }
3532
+ async function getWorkflowByIdHandler(c2) {
3533
+ try {
3534
+ const mastra = c2.get("mastra");
3535
+ const workflowId = c2.req.param("workflowId");
3536
+ const workflow = mastra.getWorkflow(workflowId);
3537
+ const triggerSchema = workflow?.triggerSchema;
3538
+ const stepGraph = workflow.stepGraph;
3539
+ const stepSubscriberGraph = workflow.stepSubscriberGraph;
3540
+ const serializedSteps = Object.entries(workflow.steps).reduce((acc, [key, step]) => {
3541
+ const _step = step;
3542
+ acc[key] = {
3543
+ ..._step,
3544
+ inputSchema: _step.inputSchema ? stringify(esm_default(_step.inputSchema)) : void 0,
3545
+ outputSchema: _step.outputSchema ? stringify(esm_default(_step.outputSchema)) : void 0
3546
+ };
3547
+ return acc;
3548
+ }, {});
3549
+ return c2.json({
3550
+ name: workflow.name,
3551
+ triggerSchema: triggerSchema ? stringify(esm_default(triggerSchema)) : void 0,
3552
+ steps: serializedSteps,
3553
+ stepGraph,
3554
+ stepSubscriberGraph
3555
+ });
3556
+ } catch (error) {
3557
+ return handleError(error, "Error getting workflow");
3558
+ }
3559
+ }
3560
+ async function executeWorkflowHandler(c2) {
3561
+ try {
3562
+ const mastra = c2.get("mastra");
3563
+ const workflowId = c2.req.param("workflowId");
3564
+ const workflow = mastra.getWorkflow(workflowId);
3565
+ const body = await c2.req.json();
3566
+ const { start } = workflow.createRun();
3567
+ const result = await start({
3568
+ triggerData: body
3569
+ });
3570
+ return c2.json(result);
3571
+ } catch (error) {
3572
+ return handleError(error, "Error executing workflow");
3573
+ }
3574
+ }
3575
+ async function watchWorkflowHandler(c2) {
3576
+ try {
3577
+ const mastra = c2.get("mastra");
3578
+ const logger2 = mastra.getLogger();
3579
+ const workflowId = c2.req.param("workflowId");
3580
+ const workflow = mastra.getWorkflow(workflowId);
3581
+ return streaming.streamText(
3582
+ c2,
3583
+ async (stream) => {
3584
+ return new Promise((_resolve, _reject) => {
3585
+ let unwatch = workflow.watch(({ activePaths, context }) => {
3586
+ void stream.write(JSON.stringify({ activePaths, context }) + "");
3587
+ });
3588
+ stream.onAbort(() => {
3589
+ unwatch?.();
3590
+ });
3591
+ });
3592
+ },
3593
+ async (err, stream) => {
3594
+ logger2.error("Error in watch stream: " + err?.message);
3595
+ stream.abort();
3596
+ await stream.close();
3597
+ }
3598
+ );
3599
+ } catch (error) {
3600
+ return handleError(error, "Error watching workflow");
3601
+ }
3602
+ }
3603
+ async function resumeWorkflowHandler(c2) {
3604
+ try {
3605
+ const mastra = c2.get("mastra");
3606
+ const workflowId = c2.req.param("workflowId");
3607
+ const workflow = mastra.getWorkflow(workflowId);
3608
+ const { stepId, runId, context } = await c2.req.json();
3609
+ const result = await workflow.resume({
3610
+ stepId,
3611
+ runId,
3612
+ context
3613
+ });
3614
+ return c2.json(result);
3615
+ } catch (error) {
3616
+ return handleError(error, "Error resuming workflow step");
3617
+ }
3618
+ }
3619
+
3620
+ // src/server/welcome.ts
3621
+ var html2 = `
3622
+ <!doctype html>
3623
+ <html lang="en">
3624
+ <head>
3625
+ <meta charset="UTF-8" />
3626
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
3627
+ <title>Welcome to Mastra</title>
3628
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/inter-ui/3.19.3/inter.min.css" />
3629
+ <style>
3630
+ body {
3631
+ margin: 0;
3632
+ padding: 0;
3633
+ background-color: #0d0d0d;
3634
+ color: #ffffff;
3635
+ font-family:
3636
+ 'Inter',
3637
+ -apple-system,
3638
+ BlinkMacSystemFont,
3639
+ system-ui,
3640
+ sans-serif;
3641
+ min-height: 100vh;
3642
+ display: flex;
3643
+ flex-direction: column;
3644
+ }
3645
+
3646
+ main {
3647
+ flex: 1;
3648
+ display: flex;
3649
+ flex-direction: column;
3650
+ align-items: center;
3651
+ justify-content: center;
3652
+ padding: 2rem;
3653
+ text-align: center;
3654
+ }
3655
+
3656
+ h1 {
3657
+ font-size: 4rem;
3658
+ font-weight: 600;
3659
+ margin: 0 0 1rem 0;
3660
+ background: linear-gradient(to right, #fff, #ccc);
3661
+ -webkit-background-clip: text;
3662
+ -webkit-text-fill-color: transparent;
3663
+ line-height: 1.2;
3664
+ }
3665
+
3666
+ .subtitle {
3667
+ color: #9ca3af;
3668
+ font-size: 1.25rem;
3669
+ max-width: 600px;
3670
+ margin: 0 auto 3rem auto;
3671
+ line-height: 1.6;
3672
+ }
3673
+
3674
+ .docs-link {
3675
+ background-color: #1a1a1a;
3676
+ padding: 1rem 2rem;
3677
+ border-radius: 0.5rem;
3678
+ display: flex;
3679
+ align-items: center;
3680
+ gap: 1rem;
3681
+ font-family: monospace;
3682
+ font-size: 1rem;
3683
+ color: #ffffff;
3684
+ text-decoration: none;
3685
+ transition: background-color 0.2s;
3686
+ }
3687
+
3688
+ .docs-link:hover {
3689
+ background-color: #252525;
3690
+ }
3691
+
3692
+ .arrow-icon {
3693
+ transition: transform 0.2s;
3694
+ }
3695
+
3696
+ .docs-link:hover .arrow-icon {
3697
+ transform: translateX(4px);
3698
+ }
3699
+ </style>
3700
+ </head>
3701
+ <body>
3702
+ <main>
3703
+ <h1>Welcome to Mastra</h1>
3704
+ <p class="subtitle">
3705
+ From the team that brought you Gatsby: prototype and productionize AI features with a modern JS/TS stack.
3706
+ </p>
3707
+
3708
+ <a href="https://mastra.ai/docs" class="docs-link">
3709
+ Browse the docs
3710
+ <svg
3711
+ class="arrow-icon"
3712
+ width="20"
3713
+ height="20"
3714
+ viewBox="0 0 24 24"
3715
+ fill="none"
3716
+ stroke="currentColor"
3717
+ stroke-width="2"
3718
+ >
3719
+ <path d="M5 12h14M12 5l7 7-7 7" />
3720
+ </svg>
3721
+ </a>
3722
+ </main>
3723
+ </body>
3724
+ </html>
3725
+ `;
3726
+
3727
+ // src/server/index.ts
3728
+ async function createHonoServer(mastra, options = {}) {
3729
+ const app = new hono.Hono();
3730
+ const mastraToolsPaths = process.env.MASTRA_TOOLS_PATH;
3731
+ const toolImports = mastraToolsPaths ? await Promise.all(
3732
+ mastraToolsPaths.split(",").map(async (toolPath) => {
3733
+ return import(url.pathToFileURL(toolPath).href);
3734
+ })
3735
+ ) : [];
3736
+ const tools = toolImports.reduce((acc, toolModule) => {
3737
+ Object.entries(toolModule).forEach(([key, tool]) => {
3738
+ acc[key] = tool;
3739
+ });
3740
+ return acc;
3741
+ }, {});
3742
+ app.use(
3743
+ "*",
3744
+ cors.cors({
3745
+ origin: "*",
3746
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
3747
+ allowHeaders: ["Content-Type", "Authorization"],
3748
+ exposeHeaders: ["Content-Length", "X-Requested-With"],
3749
+ credentials: false,
3750
+ maxAge: 3600
3751
+ })
3752
+ );
3753
+ if (options.apiReqLogs) {
3754
+ app.use(logger.logger());
3755
+ }
3756
+ app.onError(errorHandler);
3757
+ app.use("*", async (c2, next) => {
3758
+ c2.set("mastra", mastra);
3759
+ c2.set("tools", tools);
3760
+ c2.set("playground", options.playground === true);
3761
+ await next();
3762
+ });
3763
+ const bodyLimitOptions = {
3764
+ maxSize: 4.5 * 1024 * 1024,
3765
+ // 4.5 MB,
3766
+ onError: (c2) => c2.json({ error: "Request body too large" }, 413)
3767
+ };
3768
+ app.get(
3769
+ "/api",
3770
+ p({
3771
+ description: "Get API status",
3772
+ tags: ["system"],
3773
+ responses: {
3774
+ 200: {
3775
+ description: "Success"
3776
+ }
3777
+ }
3778
+ }),
3779
+ rootHandler
3780
+ );
3781
+ app.get(
3782
+ "/api/agents",
3783
+ p({
3784
+ description: "Get all available agents",
3785
+ tags: ["agents"],
3786
+ responses: {
3787
+ 200: {
3788
+ description: "List of all agents"
3789
+ }
3790
+ }
3791
+ }),
3792
+ getAgentsHandler
3793
+ );
3794
+ app.get(
3795
+ "/api/agents/:agentId",
3796
+ p({
3797
+ description: "Get agent by ID",
3798
+ tags: ["agents"],
3799
+ parameters: [
3800
+ {
3801
+ name: "agentId",
3802
+ in: "path",
3803
+ required: true,
3804
+ schema: { type: "string" }
3805
+ }
3806
+ ],
3807
+ responses: {
3808
+ 200: {
3809
+ description: "Agent details"
3810
+ },
3811
+ 404: {
3812
+ description: "Agent not found"
3813
+ }
3814
+ }
3815
+ }),
3816
+ getAgentByIdHandler
3817
+ );
3818
+ app.get(
3819
+ "/api/agents/:agentId/evals/ci",
3820
+ p({
3821
+ description: "Get CI evals by agent ID",
3822
+ tags: ["agents"],
3823
+ parameters: [
3824
+ {
3825
+ name: "agentId",
3826
+ in: "path",
3827
+ required: true,
3828
+ schema: { type: "string" }
3829
+ }
3830
+ ],
3831
+ responses: {
3832
+ 200: {
3833
+ description: "List of evals"
3834
+ }
3835
+ }
3836
+ }),
3837
+ getEvalsByAgentIdHandler
3838
+ );
3839
+ app.get(
3840
+ "/api/agents/:agentId/evals/live",
3841
+ p({
3842
+ description: "Get live evals by agent ID",
3843
+ tags: ["agents"],
3844
+ parameters: [
3845
+ {
3846
+ name: "agentId",
3847
+ in: "path",
3848
+ required: true,
3849
+ schema: { type: "string" }
3850
+ }
3851
+ ],
3852
+ responses: {
3853
+ 200: {
3854
+ description: "List of evals"
3855
+ }
3856
+ }
3857
+ }),
3858
+ getLiveEvalsByAgentIdHandler
3859
+ );
3860
+ app.post(
3861
+ "/api/agents/:agentId/generate",
3862
+ bodyLimit.bodyLimit(bodyLimitOptions),
3863
+ p({
3864
+ description: "Generate a response from an agent",
3865
+ tags: ["agents"],
3866
+ parameters: [
3867
+ {
3868
+ name: "agentId",
3869
+ in: "path",
3870
+ required: true,
3871
+ schema: { type: "string" }
3872
+ }
3873
+ ],
3874
+ requestBody: {
3875
+ required: true,
3876
+ content: {
3877
+ "application/json": {
3878
+ schema: {
3879
+ type: "object",
3880
+ properties: {
3881
+ messages: {
3882
+ type: "array",
3883
+ items: { type: "object" }
3884
+ },
3885
+ threadId: { type: "string" },
3886
+ resourceId: { type: "string", description: "The resource ID for the conversation" },
3887
+ resourceid: {
3888
+ type: "string",
3889
+ description: "The resource ID for the conversation (deprecated, use resourceId instead)",
3890
+ deprecated: true
3891
+ },
3892
+ runId: { type: "string" },
3893
+ output: { type: "object" }
3894
+ },
3895
+ required: ["messages"]
3896
+ }
3897
+ }
3898
+ }
3899
+ },
3900
+ responses: {
3901
+ 200: {
3902
+ description: "Generated response"
3903
+ },
3904
+ 404: {
3905
+ description: "Agent not found"
3906
+ }
3907
+ }
3908
+ }),
3909
+ generateHandler
3910
+ );
3911
+ app.post(
3912
+ "/api/agents/:agentId/stream",
3913
+ bodyLimit.bodyLimit(bodyLimitOptions),
3914
+ p({
3915
+ description: "Stream a response from an agent",
3916
+ tags: ["agents"],
3917
+ parameters: [
3918
+ {
3919
+ name: "agentId",
3920
+ in: "path",
3921
+ required: true,
3922
+ schema: { type: "string" }
3923
+ }
3924
+ ],
3925
+ requestBody: {
3926
+ required: true,
3927
+ content: {
3928
+ "application/json": {
3929
+ schema: {
3930
+ type: "object",
3931
+ properties: {
3932
+ messages: {
3933
+ type: "array",
3934
+ items: { type: "object" }
3935
+ },
3936
+ threadId: { type: "string" },
3937
+ resourceId: { type: "string", description: "The resource ID for the conversation" },
3938
+ resourceid: {
3939
+ type: "string",
3940
+ description: "The resource ID for the conversation (deprecated, use resourceId instead)",
3941
+ deprecated: true
3942
+ },
3943
+ runId: { type: "string" },
3944
+ output: { type: "object" }
3945
+ },
3946
+ required: ["messages"]
3947
+ }
3948
+ }
3949
+ }
3950
+ },
3951
+ responses: {
3952
+ 200: {
3953
+ description: "Streamed response"
3954
+ },
3955
+ 404: {
3956
+ description: "Agent not found"
3957
+ }
3958
+ }
3959
+ }),
3960
+ streamGenerateHandler
3961
+ );
3962
+ app.post(
3963
+ "/api/agents/:agentId/instructions",
3964
+ bodyLimit.bodyLimit(bodyLimitOptions),
3965
+ p({
3966
+ description: "Update an agent's instructions",
3967
+ tags: ["agents"],
3968
+ parameters: [
3969
+ {
3970
+ name: "agentId",
3971
+ in: "path",
3972
+ required: true,
3973
+ schema: { type: "string" }
3974
+ }
3975
+ ],
3976
+ requestBody: {
3977
+ required: true,
3978
+ content: {
3979
+ "application/json": {
3980
+ schema: {
3981
+ type: "object",
3982
+ properties: {
3983
+ instructions: {
3984
+ type: "string",
3985
+ description: "New instructions for the agent"
3986
+ }
3987
+ },
3988
+ required: ["instructions"]
3989
+ }
3990
+ }
3991
+ }
3992
+ },
3993
+ responses: {
3994
+ 200: {
3995
+ description: "Instructions updated successfully"
3996
+ },
3997
+ 403: {
3998
+ description: "Not allowed in non-playground environment"
3999
+ },
4000
+ 404: {
4001
+ description: "Agent not found"
4002
+ }
4003
+ }
4004
+ }),
4005
+ setAgentInstructionsHandler
4006
+ );
4007
+ app.post(
4008
+ "/api/agents/:agentId/instructions/enhance",
4009
+ bodyLimit.bodyLimit(bodyLimitOptions),
4010
+ p({
4011
+ description: "Generate an improved system prompt from instructions",
4012
+ tags: ["agents"],
4013
+ parameters: [
4014
+ {
4015
+ name: "agentId",
4016
+ in: "path",
4017
+ required: true,
4018
+ schema: { type: "string" },
4019
+ description: "ID of the agent whose model will be used for prompt generation"
4020
+ }
4021
+ ],
4022
+ requestBody: {
4023
+ required: true,
4024
+ content: {
4025
+ "application/json": {
4026
+ schema: {
4027
+ type: "object",
4028
+ properties: {
4029
+ instructions: {
4030
+ type: "string",
4031
+ description: "Instructions to generate a system prompt from"
4032
+ },
4033
+ comment: {
4034
+ type: "string",
4035
+ description: "Optional comment for the enhanced prompt"
4036
+ }
4037
+ },
4038
+ required: ["instructions"]
4039
+ }
4040
+ }
4041
+ }
4042
+ },
4043
+ responses: {
4044
+ 200: {
4045
+ description: "Generated system prompt and analysis",
4046
+ content: {
4047
+ "application/json": {
4048
+ schema: {
4049
+ type: "object",
4050
+ properties: {
4051
+ explanation: {
4052
+ type: "string",
4053
+ description: "Detailed analysis of the instructions"
4054
+ },
4055
+ new_prompt: {
4056
+ type: "string",
4057
+ description: "The enhanced system prompt"
4058
+ }
4059
+ }
4060
+ }
4061
+ }
4062
+ }
4063
+ },
4064
+ 400: {
4065
+ description: "Missing or invalid request parameters"
4066
+ },
4067
+ 404: {
4068
+ description: "Agent not found"
4069
+ },
4070
+ 500: {
4071
+ description: "Internal server error or model response parsing error"
4072
+ }
4073
+ }
4074
+ }),
4075
+ generateSystemPromptHandler
4076
+ );
4077
+ app.post(
4078
+ "/api/agents/:agentId/tools/:toolId/execute",
4079
+ bodyLimit.bodyLimit(bodyLimitOptions),
4080
+ p({
4081
+ description: "Execute a tool through an agent",
4082
+ tags: ["agents"],
4083
+ parameters: [
4084
+ {
4085
+ name: "agentId",
4086
+ in: "path",
4087
+ required: true,
4088
+ schema: { type: "string" }
4089
+ },
4090
+ {
4091
+ name: "toolId",
4092
+ in: "path",
4093
+ required: true,
4094
+ schema: { type: "string" }
4095
+ }
4096
+ ],
4097
+ requestBody: {
4098
+ required: true,
4099
+ content: {
4100
+ "application/json": {
4101
+ schema: {
4102
+ type: "object",
4103
+ properties: {
4104
+ data: { type: "object" }
4105
+ },
4106
+ required: ["data"]
4107
+ }
4108
+ }
4109
+ }
4110
+ },
4111
+ responses: {
4112
+ 200: {
4113
+ description: "Tool execution result"
4114
+ },
4115
+ 404: {
4116
+ description: "Tool or agent not found"
4117
+ }
4118
+ }
4119
+ }),
4120
+ executeAgentToolHandler
4121
+ );
4122
+ app.get(
4123
+ "/api/memory/status",
4124
+ p({
4125
+ description: "Get memory status",
4126
+ tags: ["memory"],
4127
+ parameters: [
4128
+ {
4129
+ name: "agentId",
4130
+ in: "query",
4131
+ required: true,
4132
+ schema: { type: "string" }
4133
+ }
4134
+ ],
4135
+ responses: {
4136
+ 200: {
4137
+ description: "Memory status"
4138
+ }
4139
+ }
4140
+ }),
4141
+ getMemoryStatusHandler
4142
+ );
4143
+ app.get(
4144
+ "/api/memory/threads",
4145
+ p({
4146
+ description: "Get all threads",
4147
+ tags: ["memory"],
4148
+ parameters: [
4149
+ {
4150
+ name: "resourceid",
4151
+ in: "query",
4152
+ required: true,
4153
+ schema: { type: "string" }
4154
+ },
4155
+ {
4156
+ name: "agentId",
4157
+ in: "query",
4158
+ required: true,
4159
+ schema: { type: "string" }
4160
+ }
4161
+ ],
4162
+ responses: {
4163
+ 200: {
4164
+ description: "List of all threads"
4165
+ }
4166
+ }
4167
+ }),
4168
+ getThreadsHandler
4169
+ );
4170
+ app.get(
4171
+ "/api/memory/threads/:threadId",
4172
+ p({
4173
+ description: "Get thread by ID",
4174
+ tags: ["memory"],
4175
+ parameters: [
4176
+ {
4177
+ name: "threadId",
4178
+ in: "path",
4179
+ required: true,
4180
+ schema: { type: "string" }
4181
+ },
4182
+ {
4183
+ name: "agentId",
4184
+ in: "query",
4185
+ required: true,
4186
+ schema: { type: "string" }
4187
+ }
4188
+ ],
4189
+ responses: {
4190
+ 200: {
4191
+ description: "Thread details"
4192
+ },
4193
+ 404: {
4194
+ description: "Thread not found"
4195
+ }
4196
+ }
4197
+ }),
4198
+ getThreadByIdHandler
4199
+ );
4200
+ app.get(
4201
+ "/api/memory/threads/:threadId/messages",
4202
+ p({
4203
+ description: "Get messages for a thread",
4204
+ tags: ["memory"],
4205
+ parameters: [
4206
+ {
4207
+ name: "threadId",
4208
+ in: "path",
4209
+ required: true,
4210
+ schema: { type: "string" }
4211
+ },
4212
+ {
4213
+ name: "agentId",
4214
+ in: "query",
4215
+ required: true,
4216
+ schema: { type: "string" }
4217
+ }
4218
+ ],
4219
+ responses: {
4220
+ 200: {
4221
+ description: "List of messages"
4222
+ }
4223
+ }
4224
+ }),
4225
+ getMessagesHandler
4226
+ );
4227
+ app.post(
4228
+ "/api/memory/threads",
4229
+ bodyLimit.bodyLimit(bodyLimitOptions),
4230
+ p({
4231
+ description: "Create a new thread",
4232
+ tags: ["memory"],
4233
+ parameters: [
4234
+ {
4235
+ name: "agentId",
4236
+ in: "query",
4237
+ required: true,
4238
+ schema: { type: "string" }
4239
+ }
4240
+ ],
4241
+ requestBody: {
4242
+ required: true,
4243
+ content: {
4244
+ "application/json": {
4245
+ schema: {
4246
+ type: "object",
4247
+ properties: {
4248
+ title: { type: "string" },
4249
+ metadata: { type: "object" },
4250
+ resourceid: { type: "string" },
4251
+ threadId: { type: "string" }
4252
+ }
4253
+ }
4254
+ }
4255
+ }
4256
+ },
4257
+ responses: {
4258
+ 200: {
4259
+ description: "Created thread"
4260
+ }
4261
+ }
4262
+ }),
4263
+ createThreadHandler
4264
+ );
4265
+ app.patch(
4266
+ "/api/memory/threads/:threadId",
4267
+ p({
4268
+ description: "Update a thread",
4269
+ tags: ["memory"],
4270
+ parameters: [
4271
+ {
4272
+ name: "threadId",
4273
+ in: "path",
4274
+ required: true,
4275
+ schema: { type: "string" }
4276
+ },
4277
+ {
4278
+ name: "agentId",
4279
+ in: "query",
4280
+ required: true,
4281
+ schema: { type: "string" }
4282
+ }
4283
+ ],
4284
+ requestBody: {
4285
+ required: true,
4286
+ content: {
4287
+ "application/json": {
4288
+ schema: { type: "object" }
4289
+ }
4290
+ }
4291
+ },
4292
+ responses: {
4293
+ 200: {
4294
+ description: "Updated thread"
4295
+ },
4296
+ 404: {
4297
+ description: "Thread not found"
4298
+ }
4299
+ }
4300
+ }),
4301
+ updateThreadHandler
4302
+ );
4303
+ app.delete(
4304
+ "/api/memory/threads/:threadId",
4305
+ p({
4306
+ description: "Delete a thread",
4307
+ tags: ["memory"],
4308
+ parameters: [
4309
+ {
4310
+ name: "threadId",
4311
+ in: "path",
4312
+ required: true,
4313
+ schema: { type: "string" }
4314
+ },
4315
+ {
4316
+ name: "agentId",
4317
+ in: "query",
4318
+ required: true,
4319
+ schema: { type: "string" }
4320
+ }
4321
+ ],
4322
+ responses: {
4323
+ 200: {
4324
+ description: "Thread deleted"
4325
+ },
4326
+ 404: {
4327
+ description: "Thread not found"
4328
+ }
4329
+ }
4330
+ }),
4331
+ deleteThreadHandler
4332
+ );
4333
+ app.post(
4334
+ "/api/memory/save-messages",
4335
+ bodyLimit.bodyLimit(bodyLimitOptions),
4336
+ p({
4337
+ description: "Save messages",
4338
+ tags: ["memory"],
4339
+ parameters: [
4340
+ {
4341
+ name: "agentId",
4342
+ in: "query",
4343
+ required: true,
4344
+ schema: { type: "string" }
4345
+ }
4346
+ ],
4347
+ requestBody: {
4348
+ required: true,
4349
+ content: {
4350
+ "application/json": {
4351
+ schema: {
4352
+ type: "object",
4353
+ properties: {
4354
+ messages: {
4355
+ type: "array",
4356
+ items: { type: "object" }
4357
+ }
4358
+ },
4359
+ required: ["messages"]
4360
+ }
4361
+ }
4362
+ }
4363
+ },
4364
+ responses: {
4365
+ 200: {
4366
+ description: "Messages saved"
4367
+ }
4368
+ }
4369
+ }),
4370
+ saveMessagesHandler
4371
+ );
4372
+ app.get(
4373
+ "/api/telemetry",
4374
+ p({
4375
+ description: "Get all traces",
4376
+ tags: ["telemetry"],
4377
+ responses: {
4378
+ 200: {
4379
+ description: "List of all traces (paged)"
4380
+ }
4381
+ }
4382
+ }),
4383
+ getTelemetryHandler
4384
+ );
4385
+ app.get(
4386
+ "/api/workflows",
4387
+ p({
4388
+ description: "Get all workflows",
4389
+ tags: ["workflows"],
4390
+ responses: {
4391
+ 200: {
4392
+ description: "List of all workflows"
4393
+ }
4394
+ }
4395
+ }),
4396
+ getWorkflowsHandler
4397
+ );
4398
+ app.get(
4399
+ "/api/workflows/:workflowId",
4400
+ p({
4401
+ description: "Get workflow by ID",
4402
+ tags: ["workflows"],
4403
+ parameters: [
4404
+ {
4405
+ name: "workflowId",
4406
+ in: "path",
4407
+ required: true,
4408
+ schema: { type: "string" }
4409
+ }
4410
+ ],
4411
+ responses: {
4412
+ 200: {
4413
+ description: "Workflow details"
4414
+ },
4415
+ 404: {
4416
+ description: "Workflow not found"
4417
+ }
4418
+ }
4419
+ }),
4420
+ getWorkflowByIdHandler
4421
+ );
4422
+ app.post(
4423
+ "/api/workflows/:workflowId/execute",
4424
+ bodyLimit.bodyLimit(bodyLimitOptions),
4425
+ p({
4426
+ description: "Execute/Start a workflow",
4427
+ tags: ["workflows"],
4428
+ parameters: [
4429
+ {
4430
+ name: "workflowId",
4431
+ in: "path",
4432
+ required: true,
4433
+ schema: { type: "string" }
4434
+ }
4435
+ ],
4436
+ requestBody: {
4437
+ required: true,
4438
+ content: {
4439
+ "application/json": {
4440
+ schema: {
4441
+ type: "object",
4442
+ properties: {
4443
+ input: { type: "object" }
4444
+ }
4445
+ }
4446
+ }
4447
+ }
4448
+ },
4449
+ responses: {
4450
+ 200: {
4451
+ description: "Workflow execution result"
4452
+ },
4453
+ 404: {
4454
+ description: "Workflow not found"
4455
+ }
4456
+ }
4457
+ }),
4458
+ executeWorkflowHandler
4459
+ );
4460
+ app.post(
4461
+ "/api/workflows/:workflowId/resume",
4462
+ p({
4463
+ description: "Resume a suspended workflow step",
4464
+ tags: ["workflows"],
4465
+ parameters: [
4466
+ {
4467
+ name: "workflowId",
4468
+ in: "path",
4469
+ required: true,
4470
+ schema: { type: "string" }
4471
+ }
4472
+ ],
4473
+ requestBody: {
4474
+ required: true,
4475
+ content: {
4476
+ "application/json": {
4477
+ schema: {
4478
+ type: "object",
4479
+ properties: {
4480
+ stepId: { type: "string" },
4481
+ runId: { type: "string" },
4482
+ context: { type: "object" }
4483
+ }
4484
+ }
4485
+ }
4486
+ }
4487
+ }
4488
+ }),
4489
+ resumeWorkflowHandler
4490
+ );
4491
+ app.get(
4492
+ "/api/workflows/:workflowId/watch",
4493
+ p({
4494
+ description: "Watch workflow transitions in real-time",
4495
+ parameters: [
4496
+ {
4497
+ name: "workflowId",
4498
+ in: "path",
4499
+ required: true,
4500
+ schema: { type: "string" }
4501
+ }
4502
+ ],
4503
+ tags: ["workflows"],
4504
+ responses: {
4505
+ 200: {
4506
+ description: "Workflow transitions in real-time"
4507
+ }
4508
+ }
4509
+ }),
4510
+ watchWorkflowHandler
4511
+ );
4512
+ app.get(
4513
+ "/api/logs",
4514
+ p({
4515
+ description: "Get all logs",
4516
+ tags: ["logs"],
4517
+ parameters: [
4518
+ {
4519
+ name: "transportId",
4520
+ in: "query",
4521
+ required: true,
4522
+ schema: { type: "string" }
4523
+ }
4524
+ ],
4525
+ responses: {
4526
+ 200: {
4527
+ description: "List of all logs"
4528
+ }
4529
+ }
4530
+ }),
4531
+ getLogsHandler
4532
+ );
4533
+ app.get(
4534
+ "/api/logs/transports",
4535
+ p({
4536
+ description: "List of all log transports",
4537
+ tags: ["logs"],
4538
+ responses: {
4539
+ 200: {
4540
+ description: "List of all log transports"
4541
+ }
4542
+ }
4543
+ }),
4544
+ getLogTransports
4545
+ );
4546
+ app.get(
4547
+ "/api/logs/:runId",
4548
+ p({
4549
+ description: "Get logs by run ID",
4550
+ tags: ["logs"],
4551
+ parameters: [
4552
+ {
4553
+ name: "runId",
4554
+ in: "path",
4555
+ required: true,
4556
+ schema: { type: "string" }
4557
+ },
4558
+ {
4559
+ name: "transportId",
4560
+ in: "query",
4561
+ required: true,
4562
+ schema: { type: "string" }
4563
+ }
4564
+ ],
4565
+ responses: {
4566
+ 200: {
4567
+ description: "List of logs for run ID"
4568
+ }
4569
+ }
4570
+ }),
4571
+ getLogsByRunIdHandler
4572
+ );
4573
+ app.get(
4574
+ "/api/tools",
4575
+ p({
4576
+ description: "Get all tools",
4577
+ tags: ["tools"],
4578
+ responses: {
4579
+ 200: {
4580
+ description: "List of all tools"
4581
+ }
4582
+ }
4583
+ }),
4584
+ getToolsHandler
4585
+ );
4586
+ app.get(
4587
+ "/api/tools/:toolId",
4588
+ p({
4589
+ description: "Get tool by ID",
4590
+ tags: ["tools"],
4591
+ parameters: [
4592
+ {
4593
+ name: "toolId",
4594
+ in: "path",
4595
+ required: true,
4596
+ schema: { type: "string" }
4597
+ }
4598
+ ],
4599
+ responses: {
4600
+ 200: {
4601
+ description: "Tool details"
4602
+ },
4603
+ 404: {
4604
+ description: "Tool not found"
4605
+ }
4606
+ }
4607
+ }),
4608
+ getToolByIdHandler
4609
+ );
4610
+ app.post(
4611
+ "/api/tools/:toolId/execute",
4612
+ bodyLimit.bodyLimit(bodyLimitOptions),
4613
+ p({
4614
+ description: "Execute a tool",
4615
+ tags: ["tools"],
4616
+ parameters: [
4617
+ {
4618
+ name: "toolId",
4619
+ in: "path",
4620
+ required: true,
4621
+ schema: { type: "string" }
4622
+ }
4623
+ ],
4624
+ requestBody: {
4625
+ required: true,
4626
+ content: {
4627
+ "application/json": {
4628
+ schema: {
4629
+ type: "object",
4630
+ properties: {
4631
+ data: { type: "object" }
4632
+ },
4633
+ required: ["data"]
4634
+ }
4635
+ }
4636
+ }
4637
+ },
4638
+ responses: {
4639
+ 200: {
4640
+ description: "Tool execution result"
4641
+ },
4642
+ 404: {
4643
+ description: "Tool not found"
4644
+ }
4645
+ }
4646
+ }),
4647
+ executeToolHandler(tools)
4648
+ );
4649
+ app.post(
4650
+ "/api/vector/:vectorName/upsert",
4651
+ bodyLimit.bodyLimit(bodyLimitOptions),
4652
+ p({
4653
+ description: "Upsert vectors into an index",
4654
+ tags: ["vector"],
4655
+ parameters: [
4656
+ {
4657
+ name: "vectorName",
4658
+ in: "path",
4659
+ required: true,
4660
+ schema: { type: "string" }
4661
+ }
4662
+ ],
4663
+ requestBody: {
4664
+ required: true,
4665
+ content: {
4666
+ "application/json": {
4667
+ schema: {
4668
+ type: "object",
4669
+ properties: {
4670
+ indexName: { type: "string" },
4671
+ vectors: {
4672
+ type: "array",
4673
+ items: {
4674
+ type: "array",
4675
+ items: { type: "number" }
4676
+ }
4677
+ },
4678
+ metadata: {
4679
+ type: "array",
4680
+ items: { type: "object" }
4681
+ },
4682
+ ids: {
4683
+ type: "array",
4684
+ items: { type: "string" }
4685
+ }
4686
+ },
4687
+ required: ["indexName", "vectors"]
4688
+ }
4689
+ }
4690
+ }
4691
+ },
4692
+ responses: {
4693
+ 200: {
4694
+ description: "Vectors upserted successfully"
4695
+ }
4696
+ }
4697
+ }),
4698
+ upsertVectors
4699
+ );
4700
+ app.post(
4701
+ "/api/vector/:vectorName/create-index",
4702
+ bodyLimit.bodyLimit(bodyLimitOptions),
4703
+ p({
4704
+ description: "Create a new vector index",
4705
+ tags: ["vector"],
4706
+ parameters: [
4707
+ {
4708
+ name: "vectorName",
4709
+ in: "path",
4710
+ required: true,
4711
+ schema: { type: "string" }
4712
+ }
4713
+ ],
4714
+ requestBody: {
4715
+ required: true,
4716
+ content: {
4717
+ "application/json": {
4718
+ schema: {
4719
+ type: "object",
4720
+ properties: {
4721
+ indexName: { type: "string" },
4722
+ dimension: { type: "number" },
4723
+ metric: {
4724
+ type: "string",
4725
+ enum: ["cosine", "euclidean", "dotproduct"]
4726
+ }
4727
+ },
4728
+ required: ["indexName", "dimension"]
4729
+ }
4730
+ }
4731
+ }
4732
+ },
4733
+ responses: {
4734
+ 200: {
4735
+ description: "Index created successfully"
4736
+ }
4737
+ }
4738
+ }),
4739
+ createIndex
4740
+ );
4741
+ app.post(
4742
+ "/api/vector/:vectorName/query",
4743
+ bodyLimit.bodyLimit(bodyLimitOptions),
4744
+ p({
4745
+ description: "Query vectors from an index",
4746
+ tags: ["vector"],
4747
+ parameters: [
4748
+ {
4749
+ name: "vectorName",
4750
+ in: "path",
4751
+ required: true,
4752
+ schema: { type: "string" }
4753
+ }
4754
+ ],
4755
+ requestBody: {
4756
+ required: true,
4757
+ content: {
4758
+ "application/json": {
4759
+ schema: {
4760
+ type: "object",
4761
+ properties: {
4762
+ indexName: { type: "string" },
4763
+ queryVector: {
4764
+ type: "array",
4765
+ items: { type: "number" }
4766
+ },
4767
+ topK: { type: "number" },
4768
+ filter: { type: "object" },
4769
+ includeVector: { type: "boolean" }
4770
+ },
4771
+ required: ["indexName", "queryVector"]
4772
+ }
4773
+ }
4774
+ }
4775
+ },
4776
+ responses: {
4777
+ 200: {
4778
+ description: "Query results"
4779
+ }
4780
+ }
4781
+ }),
4782
+ queryVectors
4783
+ );
4784
+ app.get(
4785
+ "/api/vector/:vectorName/indexes",
4786
+ p({
4787
+ description: "List all indexes for a vector store",
4788
+ tags: ["vector"],
4789
+ parameters: [
4790
+ {
4791
+ name: "vectorName",
4792
+ in: "path",
4793
+ required: true,
4794
+ schema: { type: "string" }
4795
+ }
4796
+ ],
4797
+ responses: {
4798
+ 200: {
4799
+ description: "List of indexes"
4800
+ }
4801
+ }
4802
+ }),
4803
+ listIndexes
4804
+ );
4805
+ app.get(
4806
+ "/api/vector/:vectorName/indexes/:indexName",
4807
+ p({
4808
+ description: "Get details about a specific index",
4809
+ tags: ["vector"],
4810
+ parameters: [
4811
+ {
4812
+ name: "vectorName",
4813
+ in: "path",
4814
+ required: true,
4815
+ schema: { type: "string" }
4816
+ },
4817
+ {
4818
+ name: "indexName",
4819
+ in: "path",
4820
+ required: true,
4821
+ schema: { type: "string" }
4822
+ }
4823
+ ],
4824
+ responses: {
4825
+ 200: {
4826
+ description: "Index details"
4827
+ }
4828
+ }
4829
+ }),
4830
+ describeIndex
4831
+ );
4832
+ app.delete(
4833
+ "/api/vector/:vectorName/indexes/:indexName",
4834
+ p({
4835
+ description: "Delete a specific index",
4836
+ tags: ["vector"],
4837
+ parameters: [
4838
+ {
4839
+ name: "vectorName",
4840
+ in: "path",
4841
+ required: true,
4842
+ schema: { type: "string" }
4843
+ },
4844
+ {
4845
+ name: "indexName",
4846
+ in: "path",
4847
+ required: true,
4848
+ schema: { type: "string" }
4849
+ }
4850
+ ],
4851
+ responses: {
4852
+ 200: {
4853
+ description: "Index deleted successfully"
4854
+ }
4855
+ }
4856
+ }),
4857
+ deleteIndex
4858
+ );
4859
+ app.get(
4860
+ "/openapi.json",
4861
+ i(app, {
4862
+ documentation: {
4863
+ info: { title: "Mastra API", version: "1.0.0", description: "Mastra API" }
4864
+ }
4865
+ })
4866
+ );
4867
+ app.get("/swagger-ui", middleware({ url: "/openapi.json" }));
4868
+ if (options?.swaggerUI) {
4869
+ app.get("/swagger-ui", middleware({ url: "/openapi.json" }));
4870
+ }
4871
+ if (options?.playground) {
4872
+ app.get("/refresh-events", handleClientsRefresh);
4873
+ app.post("/__refresh", handleTriggerClientsRefresh);
4874
+ app.use("/assets/*", async (c2, next) => {
4875
+ const path = c2.req.path;
4876
+ if (path.endsWith(".js")) {
4877
+ c2.header("Content-Type", "application/javascript");
4878
+ } else if (path.endsWith(".css")) {
4879
+ c2.header("Content-Type", "text/css");
4880
+ }
4881
+ await next();
4882
+ });
4883
+ app.use(
4884
+ "/assets/*",
4885
+ serveStatic({
4886
+ root: "./playground/assets"
4887
+ })
4888
+ );
4889
+ app.use(
4890
+ "*",
4891
+ serveStatic({
4892
+ root: "./playground"
4893
+ })
4894
+ );
4895
+ }
4896
+ app.get("*", async (c2, next) => {
4897
+ if (c2.req.path.startsWith("/api/") || c2.req.path.startsWith("/swagger-ui") || c2.req.path.startsWith("/openapi.json")) {
4898
+ return await next();
4899
+ }
4900
+ if (options?.playground) {
4901
+ const indexHtml = await promises.readFile(path.join(process.cwd(), "./playground/index.html"), "utf-8");
4902
+ return c2.newResponse(indexHtml, 200, { "Content-Type": "text/html" });
4903
+ }
4904
+ return c2.newResponse(html2, 200, { "Content-Type": "text/html" });
4905
+ });
4906
+ return app;
4907
+ }
4908
+ async function createNodeServer(mastra, options = {}) {
4909
+ const app = await createHonoServer(mastra, options);
4910
+ return serve(
4911
+ {
4912
+ fetch: app.fetch,
4913
+ port: Number(process.env.PORT) || 4111
4914
+ },
4915
+ () => {
4916
+ const logger2 = mastra.getLogger();
4917
+ logger2.info(`\u{1F984} Mastra API running on port ${process.env.PORT || 4111}/api`);
4918
+ logger2.info(`\u{1F4DA} Open API documentation available at http://localhost:${process.env.PORT || 4111}/openapi.json`);
4919
+ if (options?.swaggerUI) {
4920
+ logger2.info(`\u{1F9EA} Swagger UI available at http://localhost:${process.env.PORT || 4111}/swagger-ui`);
4921
+ }
4922
+ if (options?.playground) {
4923
+ logger2.info(`\u{1F468}\u200D\u{1F4BB} Playground available at http://localhost:${process.env.PORT || 4111}/`);
4924
+ }
4925
+ }
4926
+ );
4927
+ }
4928
+
4929
+ exports.createHonoServer = createHonoServer;
4930
+ exports.createNodeServer = createNodeServer;