@mastra/deployer 0.2.6-alpha.1 → 0.2.6-alpha.2

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.
@@ -1,24 +1,32 @@
1
+ import crypto, { randomUUID } from 'crypto';
1
2
  import { readFile } from 'fs/promises';
2
3
  import { join } from 'path';
3
4
  import { pathToFileURL } from 'url';
4
5
  import { createServer } from 'http';
5
6
  import { Http2ServerRequest } from 'http2';
6
7
  import { Readable } from 'stream';
7
- import crypto from 'crypto';
8
8
  import { getFilePathWithoutDefaultDocument, getFilePath } from 'hono/utils/filepath';
9
9
  import { getMimeType } from 'hono/utils/mime';
10
10
  import { createReadStream, lstatSync } from 'fs';
11
11
  import { html } from 'hono/html';
12
+ import { Telemetry } from '@mastra/core';
12
13
  import { Hono } from 'hono';
13
14
  import { bodyLimit } from 'hono/body-limit';
14
15
  import { cors } from 'hono/cors';
15
16
  import { logger } from 'hono/logger';
16
17
  import { HTTPException } from 'hono/http-exception';
17
- import { z, ZodFirstPartyTypeKind, ZodOptional } from 'zod';
18
+ import { getAgentsHandler as getAgentsHandler$1, getAgentByIdHandler as getAgentByIdHandler$1, getEvalsByAgentIdHandler as getEvalsByAgentIdHandler$1, getLiveEvalsByAgentIdHandler as getLiveEvalsByAgentIdHandler$1, generateHandler as generateHandler$2, streamGenerateHandler as streamGenerateHandler$2 } from '@mastra/server/handlers/agents';
19
+ import { getLogsHandler as getLogsHandler$1, getLogTransports as getLogTransports$1, getLogsByRunIdHandler as getLogsByRunIdHandler$1 } from '@mastra/server/handlers/logs';
20
+ import { getMemoryStatusHandler as getMemoryStatusHandler$1, getThreadsHandler as getThreadsHandler$1, getThreadByIdHandler as getThreadByIdHandler$1, getMessagesHandler as getMessagesHandler$1, createThreadHandler as createThreadHandler$1, updateThreadHandler as updateThreadHandler$1, deleteThreadHandler as deleteThreadHandler$1, saveMessagesHandler as saveMessagesHandler$1 } from '@mastra/server/handlers/memory';
21
+ import { getNetworksHandler as getNetworksHandler$1, getNetworkByIdHandler as getNetworkByIdHandler$1, generateHandler as generateHandler$1, streamGenerateHandler as streamGenerateHandler$1 } from '@mastra/server/handlers/network';
18
22
  import { Agent } from '@mastra/core/agent';
19
- import { TABLE_TRACES } from '@mastra/core/storage';
20
- import { isVercelTool } from '@mastra/core';
21
- import { streamText } from 'hono/streaming';
23
+ import { z } from 'zod';
24
+ import { getTelemetryHandler as getTelemetryHandler$1, storeTelemetryHandler as storeTelemetryHandler$1 } from '@mastra/server/handlers/telemetry';
25
+ import { executeAgentToolHandler as executeAgentToolHandler$1, getToolsHandler as getToolsHandler$1, getToolByIdHandler as getToolByIdHandler$1, executeToolHandler as executeToolHandler$1 } from '@mastra/server/handlers/tools';
26
+ import { upsertVectors as upsertVectors$1, createIndex as createIndex$1, queryVectors as queryVectors$1, listIndexes as listIndexes$1, describeIndex as describeIndex$1, deleteIndex as deleteIndex$1 } from '@mastra/server/handlers/vector';
27
+ import { getSpeakersHandler as getSpeakersHandler$1, generateSpeechHandler, transcribeSpeechHandler } from '@mastra/server/handlers/voice';
28
+ import { getWorkflowsHandler as getWorkflowsHandler$1, getWorkflowByIdHandler as getWorkflowByIdHandler$1, resumeWorkflowHandler as resumeWorkflowHandler$1, resumeAsyncWorkflowHandler as resumeAsyncWorkflowHandler$1, createRunHandler as createRunHandler$1, startAsyncWorkflowHandler as startAsyncWorkflowHandler$1, startWorkflowRunHandler as startWorkflowRunHandler$1, watchWorkflowHandler as watchWorkflowHandler$1 } from '@mastra/server/handlers/workflows';
29
+ import { stream } from 'hono/streaming';
22
30
 
23
31
  // src/server/index.ts
24
32
  var RequestError = class extends Error {
@@ -156,14 +164,14 @@ var newRequest = (incoming, defaultHostname) => {
156
164
  req[urlKey] = url.href;
157
165
  return req;
158
166
  };
159
- function writeFromReadableStream(stream, writable) {
160
- if (stream.locked) {
167
+ function writeFromReadableStream(stream2, writable) {
168
+ if (stream2.locked) {
161
169
  throw new TypeError("ReadableStream is locked.");
162
170
  } else if (writable.destroyed) {
163
- stream.cancel();
171
+ stream2.cancel();
164
172
  return;
165
173
  }
166
- const reader = stream.getReader();
174
+ const reader = stream2.getReader();
167
175
  writable.on("close", cancel);
168
176
  writable.on("error", cancel);
169
177
  reader.read().then(flow, cancel);
@@ -171,11 +179,11 @@ function writeFromReadableStream(stream, writable) {
171
179
  writable.off("close", cancel);
172
180
  writable.off("error", cancel);
173
181
  });
174
- function cancel(error2) {
175
- reader.cancel(error2).catch(() => {
182
+ function cancel(error) {
183
+ reader.cancel(error).catch(() => {
176
184
  });
177
- if (error2) {
178
- writable.destroy(error2);
185
+ if (error) {
186
+ writable.destroy(error);
179
187
  }
180
188
  }
181
189
  function onDrain() {
@@ -361,7 +369,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
361
369
  const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
362
370
  const internalBody = getInternalBody(res);
363
371
  if (internalBody) {
364
- const { length, source, stream } = internalBody;
372
+ const { length, source, stream: stream2 } = internalBody;
365
373
  if (source instanceof Uint8Array && source.byteLength !== length) ; else {
366
374
  if (length) {
367
375
  resHeaderRecord["content-length"] = length;
@@ -372,7 +380,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
372
380
  } else if (source instanceof Blob) {
373
381
  outgoing.end(new Uint8Array(await source.arrayBuffer()));
374
382
  } else {
375
- await writeFromReadableStream(stream, outgoing);
383
+ await writeFromReadableStream(stream2, outgoing);
376
384
  }
377
385
  return;
378
386
  }
@@ -476,18 +484,18 @@ var ENCODINGS = {
476
484
  gzip: ".gz"
477
485
  };
478
486
  var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
479
- var createStreamBody = (stream) => {
487
+ var createStreamBody = (stream2) => {
480
488
  const body = new ReadableStream({
481
489
  start(controller) {
482
- stream.on("data", (chunk) => {
490
+ stream2.on("data", (chunk) => {
483
491
  controller.enqueue(chunk);
484
492
  });
485
- stream.on("end", () => {
493
+ stream2.on("end", () => {
486
494
  controller.close();
487
495
  });
488
496
  },
489
497
  cancel() {
490
- stream.destroy();
498
+ stream2.destroy();
491
499
  }
492
500
  });
493
501
  return body;
@@ -583,10 +591,10 @@ var serveStatic = (options = { root: "" }) => {
583
591
  end = size - 1;
584
592
  }
585
593
  const chunksize = end - start + 1;
586
- const stream = createReadStream(path, { start, end });
594
+ const stream2 = createReadStream(path, { start, end });
587
595
  c2.header("Content-Length", chunksize.toString());
588
596
  c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
589
- return c2.body(createStreamBody(stream), 206);
597
+ return c2.body(createStreamBody(stream2), 206);
590
598
  };
591
599
  };
592
600
  var RENDER_TYPE = {
@@ -833,2007 +841,8 @@ async function x(e2, t2, s3 = {}) {
833
841
  }
834
842
  return { docs: o2, components: n2 };
835
843
  }
836
-
837
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/double-indexed-kv.js
838
- var DoubleIndexedKV = class {
839
- constructor() {
840
- this.keyToValue = /* @__PURE__ */ new Map();
841
- this.valueToKey = /* @__PURE__ */ new Map();
842
- }
843
- set(key, value) {
844
- this.keyToValue.set(key, value);
845
- this.valueToKey.set(value, key);
846
- }
847
- getByKey(key) {
848
- return this.keyToValue.get(key);
849
- }
850
- getByValue(value) {
851
- return this.valueToKey.get(value);
852
- }
853
- clear() {
854
- this.keyToValue.clear();
855
- this.valueToKey.clear();
856
- }
857
- };
858
-
859
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/registry.js
860
- var Registry = class {
861
- constructor(generateIdentifier) {
862
- this.generateIdentifier = generateIdentifier;
863
- this.kv = new DoubleIndexedKV();
864
- }
865
- register(value, identifier) {
866
- if (this.kv.getByValue(value)) {
867
- return;
868
- }
869
- if (!identifier) {
870
- identifier = this.generateIdentifier(value);
871
- }
872
- this.kv.set(identifier, value);
873
- }
874
- clear() {
875
- this.kv.clear();
876
- }
877
- getIdentifier(value) {
878
- return this.kv.getByValue(value);
879
- }
880
- getValue(identifier) {
881
- return this.kv.getByKey(identifier);
882
- }
883
- };
884
-
885
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/class-registry.js
886
- var ClassRegistry = class extends Registry {
887
- constructor() {
888
- super((c2) => c2.name);
889
- this.classToAllowedProps = /* @__PURE__ */ new Map();
890
- }
891
- register(value, options) {
892
- if (typeof options === "object") {
893
- if (options.allowProps) {
894
- this.classToAllowedProps.set(value, options.allowProps);
895
- }
896
- super.register(value, options.identifier);
897
- } else {
898
- super.register(value, options);
899
- }
900
- }
901
- getAllowedProps(value) {
902
- return this.classToAllowedProps.get(value);
903
- }
904
- };
905
-
906
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/util.js
907
- function valuesOfObj(record) {
908
- if ("values" in Object) {
909
- return Object.values(record);
910
- }
911
- const values = [];
912
- for (const key in record) {
913
- if (record.hasOwnProperty(key)) {
914
- values.push(record[key]);
915
- }
916
- }
917
- return values;
918
- }
919
- function find(record, predicate) {
920
- const values = valuesOfObj(record);
921
- if ("find" in values) {
922
- return values.find(predicate);
923
- }
924
- const valuesNotNever = values;
925
- for (let i2 = 0; i2 < valuesNotNever.length; i2++) {
926
- const value = valuesNotNever[i2];
927
- if (predicate(value)) {
928
- return value;
929
- }
930
- }
931
- return void 0;
932
- }
933
- function forEach(record, run) {
934
- Object.entries(record).forEach(([key, value]) => run(value, key));
935
- }
936
- function includes(arr, value) {
937
- return arr.indexOf(value) !== -1;
938
- }
939
- function findArr(record, predicate) {
940
- for (let i2 = 0; i2 < record.length; i2++) {
941
- const value = record[i2];
942
- if (predicate(value)) {
943
- return value;
944
- }
945
- }
946
- return void 0;
947
- }
948
-
949
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/custom-transformer-registry.js
950
- var CustomTransformerRegistry = class {
951
- constructor() {
952
- this.transfomers = {};
953
- }
954
- register(transformer) {
955
- this.transfomers[transformer.name] = transformer;
956
- }
957
- findApplicable(v) {
958
- return find(this.transfomers, (transformer) => transformer.isApplicable(v));
959
- }
960
- findByName(name) {
961
- return this.transfomers[name];
962
- }
963
- };
964
-
965
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/is.js
966
- var getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
967
- var isUndefined = (payload) => typeof payload === "undefined";
968
- var isNull = (payload) => payload === null;
969
- var isPlainObject = (payload) => {
970
- if (typeof payload !== "object" || payload === null)
971
- return false;
972
- if (payload === Object.prototype)
973
- return false;
974
- if (Object.getPrototypeOf(payload) === null)
975
- return true;
976
- return Object.getPrototypeOf(payload) === Object.prototype;
977
- };
978
- var isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
979
- var isArray = (payload) => Array.isArray(payload);
980
- var isString = (payload) => typeof payload === "string";
981
- var isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
982
- var isBoolean = (payload) => typeof payload === "boolean";
983
- var isRegExp = (payload) => payload instanceof RegExp;
984
- var isMap = (payload) => payload instanceof Map;
985
- var isSet = (payload) => payload instanceof Set;
986
- var isSymbol = (payload) => getType(payload) === "Symbol";
987
- var isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
988
- var isError = (payload) => payload instanceof Error;
989
- var isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
990
- var isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
991
- var isBigint = (payload) => typeof payload === "bigint";
992
- var isInfinite = (payload) => payload === Infinity || payload === -Infinity;
993
- var isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
994
- var isURL = (payload) => payload instanceof URL;
995
-
996
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/pathstringifier.js
997
- var escapeKey = (key) => key.replace(/\./g, "\\.");
998
- var stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
999
- var parsePath = (string) => {
1000
- const result = [];
1001
- let segment = "";
1002
- for (let i2 = 0; i2 < string.length; i2++) {
1003
- let char = string.charAt(i2);
1004
- const isEscapedDot = char === "\\" && string.charAt(i2 + 1) === ".";
1005
- if (isEscapedDot) {
1006
- segment += ".";
1007
- i2++;
1008
- continue;
1009
- }
1010
- const isEndOfSegment = char === ".";
1011
- if (isEndOfSegment) {
1012
- result.push(segment);
1013
- segment = "";
1014
- continue;
1015
- }
1016
- segment += char;
1017
- }
1018
- const lastSegment = segment;
1019
- result.push(lastSegment);
1020
- return result;
1021
- };
1022
-
1023
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/transformer.js
1024
- function simpleTransformation(isApplicable, annotation, transform, untransform) {
1025
- return {
1026
- isApplicable,
1027
- annotation,
1028
- transform,
1029
- untransform
1030
- };
1031
- }
1032
- var simpleRules = [
1033
- simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
1034
- simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
1035
- if (typeof BigInt !== "undefined") {
1036
- return BigInt(v);
1037
- }
1038
- console.error("Please add a BigInt polyfill.");
1039
- return v;
1040
- }),
1041
- simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
1042
- simpleTransformation(isError, "Error", (v, superJson) => {
1043
- const baseError = {
1044
- name: v.name,
1045
- message: v.message
1046
- };
1047
- superJson.allowedErrorProps.forEach((prop) => {
1048
- baseError[prop] = v[prop];
1049
- });
1050
- return baseError;
1051
- }, (v, superJson) => {
1052
- const e2 = new Error(v.message);
1053
- e2.name = v.name;
1054
- e2.stack = v.stack;
1055
- superJson.allowedErrorProps.forEach((prop) => {
1056
- e2[prop] = v[prop];
1057
- });
1058
- return e2;
1059
- }),
1060
- simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
1061
- const body = regex.slice(1, regex.lastIndexOf("/"));
1062
- const flags = regex.slice(regex.lastIndexOf("/") + 1);
1063
- return new RegExp(body, flags);
1064
- }),
1065
- simpleTransformation(
1066
- isSet,
1067
- "set",
1068
- // (sets only exist in es6+)
1069
- // eslint-disable-next-line es5/no-es6-methods
1070
- (v) => [...v.values()],
1071
- (v) => new Set(v)
1072
- ),
1073
- simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
1074
- simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
1075
- if (isNaNValue(v)) {
1076
- return "NaN";
1077
- }
1078
- if (v > 0) {
1079
- return "Infinity";
1080
- } else {
1081
- return "-Infinity";
1082
- }
1083
- }, Number),
1084
- simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
1085
- return "-0";
1086
- }, Number),
1087
- simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
1088
- ];
1089
- function compositeTransformation(isApplicable, annotation, transform, untransform) {
1090
- return {
1091
- isApplicable,
1092
- annotation,
1093
- transform,
1094
- untransform
1095
- };
1096
- }
1097
- var symbolRule = compositeTransformation((s3, superJson) => {
1098
- if (isSymbol(s3)) {
1099
- const isRegistered = !!superJson.symbolRegistry.getIdentifier(s3);
1100
- return isRegistered;
1101
- }
1102
- return false;
1103
- }, (s3, superJson) => {
1104
- const identifier = superJson.symbolRegistry.getIdentifier(s3);
1105
- return ["symbol", identifier];
1106
- }, (v) => v.description, (_, a2, superJson) => {
1107
- const value = superJson.symbolRegistry.getValue(a2[1]);
1108
- if (!value) {
1109
- throw new Error("Trying to deserialize unknown symbol");
1110
- }
1111
- return value;
1112
- });
1113
- var constructorToName = [
1114
- Int8Array,
1115
- Uint8Array,
1116
- Int16Array,
1117
- Uint16Array,
1118
- Int32Array,
1119
- Uint32Array,
1120
- Float32Array,
1121
- Float64Array,
1122
- Uint8ClampedArray
1123
- ].reduce((obj, ctor) => {
1124
- obj[ctor.name] = ctor;
1125
- return obj;
1126
- }, {});
1127
- var typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a2) => {
1128
- const ctor = constructorToName[a2[1]];
1129
- if (!ctor) {
1130
- throw new Error("Trying to deserialize unknown typed array");
1131
- }
1132
- return new ctor(v);
1133
- });
1134
- function isInstanceOfRegisteredClass(potentialClass, superJson) {
1135
- if (potentialClass?.constructor) {
1136
- const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
1137
- return isRegistered;
1138
- }
1139
- return false;
1140
- }
1141
- var classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
1142
- const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
1143
- return ["class", identifier];
1144
- }, (clazz, superJson) => {
1145
- const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
1146
- if (!allowedProps) {
1147
- return { ...clazz };
1148
- }
1149
- const result = {};
1150
- allowedProps.forEach((prop) => {
1151
- result[prop] = clazz[prop];
1152
- });
1153
- return result;
1154
- }, (v, a2, superJson) => {
1155
- const clazz = superJson.classRegistry.getValue(a2[1]);
1156
- if (!clazz) {
1157
- throw new Error(`Trying to deserialize unknown class '${a2[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
1158
- }
1159
- return Object.assign(Object.create(clazz.prototype), v);
1160
- });
1161
- var customRule = compositeTransformation((value, superJson) => {
1162
- return !!superJson.customTransformerRegistry.findApplicable(value);
1163
- }, (value, superJson) => {
1164
- const transformer = superJson.customTransformerRegistry.findApplicable(value);
1165
- return ["custom", transformer.name];
1166
- }, (value, superJson) => {
1167
- const transformer = superJson.customTransformerRegistry.findApplicable(value);
1168
- return transformer.serialize(value);
1169
- }, (v, a2, superJson) => {
1170
- const transformer = superJson.customTransformerRegistry.findByName(a2[1]);
1171
- if (!transformer) {
1172
- throw new Error("Trying to deserialize unknown custom value");
1173
- }
1174
- return transformer.deserialize(v);
1175
- });
1176
- var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
1177
- var transformValue = (value, superJson) => {
1178
- const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
1179
- if (applicableCompositeRule) {
1180
- return {
1181
- value: applicableCompositeRule.transform(value, superJson),
1182
- type: applicableCompositeRule.annotation(value, superJson)
1183
- };
1184
- }
1185
- const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
1186
- if (applicableSimpleRule) {
1187
- return {
1188
- value: applicableSimpleRule.transform(value, superJson),
1189
- type: applicableSimpleRule.annotation
1190
- };
1191
- }
1192
- return void 0;
1193
- };
1194
- var simpleRulesByAnnotation = {};
1195
- simpleRules.forEach((rule) => {
1196
- simpleRulesByAnnotation[rule.annotation] = rule;
1197
- });
1198
- var untransformValue = (json, type, superJson) => {
1199
- if (isArray(type)) {
1200
- switch (type[0]) {
1201
- case "symbol":
1202
- return symbolRule.untransform(json, type, superJson);
1203
- case "class":
1204
- return classRule.untransform(json, type, superJson);
1205
- case "custom":
1206
- return customRule.untransform(json, type, superJson);
1207
- case "typed-array":
1208
- return typedArrayRule.untransform(json, type, superJson);
1209
- default:
1210
- throw new Error("Unknown transformation: " + type);
1211
- }
1212
- } else {
1213
- const transformation = simpleRulesByAnnotation[type];
1214
- if (!transformation) {
1215
- throw new Error("Unknown transformation: " + type);
1216
- }
1217
- return transformation.untransform(json, superJson);
1218
- }
1219
- };
1220
-
1221
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/accessDeep.js
1222
- var getNthKey = (value, n2) => {
1223
- if (n2 > value.size)
1224
- throw new Error("index out of bounds");
1225
- const keys = value.keys();
1226
- while (n2 > 0) {
1227
- keys.next();
1228
- n2--;
1229
- }
1230
- return keys.next().value;
1231
- };
1232
- function validatePath(path) {
1233
- if (includes(path, "__proto__")) {
1234
- throw new Error("__proto__ is not allowed as a property");
1235
- }
1236
- if (includes(path, "prototype")) {
1237
- throw new Error("prototype is not allowed as a property");
1238
- }
1239
- if (includes(path, "constructor")) {
1240
- throw new Error("constructor is not allowed as a property");
1241
- }
1242
- }
1243
- var getDeep = (object, path) => {
1244
- validatePath(path);
1245
- for (let i2 = 0; i2 < path.length; i2++) {
1246
- const key = path[i2];
1247
- if (isSet(object)) {
1248
- object = getNthKey(object, +key);
1249
- } else if (isMap(object)) {
1250
- const row = +key;
1251
- const type = +path[++i2] === 0 ? "key" : "value";
1252
- const keyOfRow = getNthKey(object, row);
1253
- switch (type) {
1254
- case "key":
1255
- object = keyOfRow;
1256
- break;
1257
- case "value":
1258
- object = object.get(keyOfRow);
1259
- break;
1260
- }
1261
- } else {
1262
- object = object[key];
1263
- }
1264
- }
1265
- return object;
1266
- };
1267
- var setDeep = (object, path, mapper) => {
1268
- validatePath(path);
1269
- if (path.length === 0) {
1270
- return mapper(object);
1271
- }
1272
- let parent = object;
1273
- for (let i2 = 0; i2 < path.length - 1; i2++) {
1274
- const key = path[i2];
1275
- if (isArray(parent)) {
1276
- const index = +key;
1277
- parent = parent[index];
1278
- } else if (isPlainObject(parent)) {
1279
- parent = parent[key];
1280
- } else if (isSet(parent)) {
1281
- const row = +key;
1282
- parent = getNthKey(parent, row);
1283
- } else if (isMap(parent)) {
1284
- const isEnd = i2 === path.length - 2;
1285
- if (isEnd) {
1286
- break;
1287
- }
1288
- const row = +key;
1289
- const type = +path[++i2] === 0 ? "key" : "value";
1290
- const keyOfRow = getNthKey(parent, row);
1291
- switch (type) {
1292
- case "key":
1293
- parent = keyOfRow;
1294
- break;
1295
- case "value":
1296
- parent = parent.get(keyOfRow);
1297
- break;
1298
- }
1299
- }
1300
- }
1301
- const lastKey = path[path.length - 1];
1302
- if (isArray(parent)) {
1303
- parent[+lastKey] = mapper(parent[+lastKey]);
1304
- } else if (isPlainObject(parent)) {
1305
- parent[lastKey] = mapper(parent[lastKey]);
1306
- }
1307
- if (isSet(parent)) {
1308
- const oldValue = getNthKey(parent, +lastKey);
1309
- const newValue = mapper(oldValue);
1310
- if (oldValue !== newValue) {
1311
- parent.delete(oldValue);
1312
- parent.add(newValue);
1313
- }
1314
- }
1315
- if (isMap(parent)) {
1316
- const row = +path[path.length - 2];
1317
- const keyToRow = getNthKey(parent, row);
1318
- const type = +lastKey === 0 ? "key" : "value";
1319
- switch (type) {
1320
- case "key": {
1321
- const newKey = mapper(keyToRow);
1322
- parent.set(newKey, parent.get(keyToRow));
1323
- if (newKey !== keyToRow) {
1324
- parent.delete(keyToRow);
1325
- }
1326
- break;
1327
- }
1328
- case "value": {
1329
- parent.set(keyToRow, mapper(parent.get(keyToRow)));
1330
- break;
1331
- }
1332
- }
1333
- }
1334
- return object;
1335
- };
1336
-
1337
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/plainer.js
1338
- function traverse(tree, walker2, origin = []) {
1339
- if (!tree) {
1340
- return;
1341
- }
1342
- if (!isArray(tree)) {
1343
- forEach(tree, (subtree, key) => traverse(subtree, walker2, [...origin, ...parsePath(key)]));
1344
- return;
1345
- }
1346
- const [nodeValue, children] = tree;
1347
- if (children) {
1348
- forEach(children, (child, key) => {
1349
- traverse(child, walker2, [...origin, ...parsePath(key)]);
1350
- });
1351
- }
1352
- walker2(nodeValue, origin);
1353
- }
1354
- function applyValueAnnotations(plain, annotations, superJson) {
1355
- traverse(annotations, (type, path) => {
1356
- plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
1357
- });
1358
- return plain;
1359
- }
1360
- function applyReferentialEqualityAnnotations(plain, annotations) {
1361
- function apply(identicalPaths, path) {
1362
- const object = getDeep(plain, parsePath(path));
1363
- identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
1364
- plain = setDeep(plain, identicalObjectPath, () => object);
1365
- });
1366
- }
1367
- if (isArray(annotations)) {
1368
- const [root, other] = annotations;
1369
- root.forEach((identicalPath) => {
1370
- plain = setDeep(plain, parsePath(identicalPath), () => plain);
1371
- });
1372
- if (other) {
1373
- forEach(other, apply);
1374
- }
1375
- } else {
1376
- forEach(annotations, apply);
1377
- }
1378
- return plain;
1379
- }
1380
- var isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
1381
- function addIdentity(object, path, identities) {
1382
- const existingSet = identities.get(object);
1383
- if (existingSet) {
1384
- existingSet.push(path);
1385
- } else {
1386
- identities.set(object, [path]);
1387
- }
1388
- }
1389
- function generateReferentialEqualityAnnotations(identitites, dedupe) {
1390
- const result = {};
1391
- let rootEqualityPaths = void 0;
1392
- identitites.forEach((paths) => {
1393
- if (paths.length <= 1) {
1394
- return;
1395
- }
1396
- if (!dedupe) {
1397
- paths = paths.map((path) => path.map(String)).sort((a2, b) => a2.length - b.length);
1398
- }
1399
- const [representativePath, ...identicalPaths] = paths;
1400
- if (representativePath.length === 0) {
1401
- rootEqualityPaths = identicalPaths.map(stringifyPath);
1402
- } else {
1403
- result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
1404
- }
1405
- });
1406
- if (rootEqualityPaths) {
1407
- if (isEmptyObject(result)) {
1408
- return [rootEqualityPaths];
1409
- } else {
1410
- return [rootEqualityPaths, result];
1411
- }
1412
- } else {
1413
- return isEmptyObject(result) ? void 0 : result;
1414
- }
1415
- }
1416
- var walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
1417
- const primitive = isPrimitive(object);
1418
- if (!primitive) {
1419
- addIdentity(object, path, identities);
1420
- const seen = seenObjects.get(object);
1421
- if (seen) {
1422
- return dedupe ? {
1423
- transformedValue: null
1424
- } : seen;
1425
- }
1426
- }
1427
- if (!isDeep(object, superJson)) {
1428
- const transformed2 = transformValue(object, superJson);
1429
- const result2 = transformed2 ? {
1430
- transformedValue: transformed2.value,
1431
- annotations: [transformed2.type]
1432
- } : {
1433
- transformedValue: object
1434
- };
1435
- if (!primitive) {
1436
- seenObjects.set(object, result2);
1437
- }
1438
- return result2;
1439
- }
1440
- if (includes(objectsInThisPath, object)) {
1441
- return {
1442
- transformedValue: null
1443
- };
1444
- }
1445
- const transformationResult = transformValue(object, superJson);
1446
- const transformed = transformationResult?.value ?? object;
1447
- const transformedValue = isArray(transformed) ? [] : {};
1448
- const innerAnnotations = {};
1449
- forEach(transformed, (value, index) => {
1450
- if (index === "__proto__" || index === "constructor" || index === "prototype") {
1451
- throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
1452
- }
1453
- const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
1454
- transformedValue[index] = recursiveResult.transformedValue;
1455
- if (isArray(recursiveResult.annotations)) {
1456
- innerAnnotations[index] = recursiveResult.annotations;
1457
- } else if (isPlainObject(recursiveResult.annotations)) {
1458
- forEach(recursiveResult.annotations, (tree, key) => {
1459
- innerAnnotations[escapeKey(index) + "." + key] = tree;
1460
- });
1461
- }
1462
- });
1463
- const result = isEmptyObject(innerAnnotations) ? {
1464
- transformedValue,
1465
- annotations: !!transformationResult ? [transformationResult.type] : void 0
1466
- } : {
1467
- transformedValue,
1468
- annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
1469
- };
1470
- if (!primitive) {
1471
- seenObjects.set(object, result);
1472
- }
1473
- return result;
1474
- };
1475
-
1476
- // ../../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
1477
- function getType2(payload) {
1478
- return Object.prototype.toString.call(payload).slice(8, -1);
1479
- }
1480
- function isArray2(payload) {
1481
- return getType2(payload) === "Array";
1482
- }
1483
- function isPlainObject2(payload) {
1484
- if (getType2(payload) !== "Object")
1485
- return false;
1486
- const prototype = Object.getPrototypeOf(payload);
1487
- return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
1488
- }
1489
-
1490
- // ../../node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js
1491
- function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
1492
- const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
1493
- if (propType === "enumerable")
1494
- carry[key] = newVal;
1495
- if (includeNonenumerable && propType === "nonenumerable") {
1496
- Object.defineProperty(carry, key, {
1497
- value: newVal,
1498
- enumerable: false,
1499
- writable: true,
1500
- configurable: true
1501
- });
1502
- }
1503
- }
1504
- function copy(target, options = {}) {
1505
- if (isArray2(target)) {
1506
- return target.map((item) => copy(item, options));
1507
- }
1508
- if (!isPlainObject2(target)) {
1509
- return target;
1510
- }
1511
- const props = Object.getOwnPropertyNames(target);
1512
- const symbols = Object.getOwnPropertySymbols(target);
1513
- return [...props, ...symbols].reduce((carry, key) => {
1514
- if (isArray2(options.props) && !options.props.includes(key)) {
1515
- return carry;
1516
- }
1517
- const val = target[key];
1518
- const newVal = copy(val, options);
1519
- assignProp(carry, key, newVal, target, options.nonenumerable);
1520
- return carry;
1521
- }, {});
1522
- }
1523
-
1524
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/index.js
1525
- var SuperJSON = class {
1526
- /**
1527
- * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
1528
- */
1529
- constructor({ dedupe = false } = {}) {
1530
- this.classRegistry = new ClassRegistry();
1531
- this.symbolRegistry = new Registry((s3) => s3.description ?? "");
1532
- this.customTransformerRegistry = new CustomTransformerRegistry();
1533
- this.allowedErrorProps = [];
1534
- this.dedupe = dedupe;
1535
- }
1536
- serialize(object) {
1537
- const identities = /* @__PURE__ */ new Map();
1538
- const output = walker(object, identities, this, this.dedupe);
1539
- const res = {
1540
- json: output.transformedValue
1541
- };
1542
- if (output.annotations) {
1543
- res.meta = {
1544
- ...res.meta,
1545
- values: output.annotations
1546
- };
1547
- }
1548
- const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
1549
- if (equalityAnnotations) {
1550
- res.meta = {
1551
- ...res.meta,
1552
- referentialEqualities: equalityAnnotations
1553
- };
1554
- }
1555
- return res;
1556
- }
1557
- deserialize(payload) {
1558
- const { json, meta } = payload;
1559
- let result = copy(json);
1560
- if (meta?.values) {
1561
- result = applyValueAnnotations(result, meta.values, this);
1562
- }
1563
- if (meta?.referentialEqualities) {
1564
- result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
1565
- }
1566
- return result;
1567
- }
1568
- stringify(object) {
1569
- return JSON.stringify(this.serialize(object));
1570
- }
1571
- parse(string) {
1572
- return this.deserialize(JSON.parse(string));
1573
- }
1574
- registerClass(v, options) {
1575
- this.classRegistry.register(v, options);
1576
- }
1577
- registerSymbol(v, identifier) {
1578
- this.symbolRegistry.register(v, identifier);
1579
- }
1580
- registerCustom(transformer, name) {
1581
- this.customTransformerRegistry.register({
1582
- name,
1583
- ...transformer
1584
- });
1585
- }
1586
- allowErrorProps(...props) {
1587
- this.allowedErrorProps.push(...props);
1588
- }
1589
- };
1590
- SuperJSON.defaultInstance = new SuperJSON();
1591
- SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
1592
- SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
1593
- SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
1594
- SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
1595
- SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
1596
- SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
1597
- SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
1598
- SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
1599
- var stringify = SuperJSON.stringify;
1600
-
1601
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Options.js
1602
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
1603
- var defaultOptions = {
1604
- name: void 0,
1605
- $refStrategy: "root",
1606
- basePath: ["#"],
1607
- effectStrategy: "input",
1608
- pipeStrategy: "all",
1609
- dateStrategy: "format:date-time",
1610
- mapStrategy: "entries",
1611
- removeAdditionalStrategy: "passthrough",
1612
- allowedAdditionalProperties: true,
1613
- rejectedAdditionalProperties: false,
1614
- definitionPath: "definitions",
1615
- target: "jsonSchema7",
1616
- strictUnions: false,
1617
- definitions: {},
1618
- errorMessages: false,
1619
- markdownDescription: false,
1620
- patternStrategy: "escape",
1621
- applyRegexFlags: false,
1622
- emailStrategy: "format:email",
1623
- base64Strategy: "contentEncoding:base64",
1624
- nameStrategy: "ref"
1625
- };
1626
- var getDefaultOptions = (options) => typeof options === "string" ? {
1627
- ...defaultOptions,
1628
- name: options
1629
- } : {
1630
- ...defaultOptions,
1631
- ...options
1632
- };
1633
-
1634
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Refs.js
1635
- var getRefs = (options) => {
1636
- const _options = getDefaultOptions(options);
1637
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1638
- return {
1639
- ..._options,
1640
- currentPath,
1641
- propertyPath: void 0,
1642
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
1643
- def._def,
1644
- {
1645
- def: def._def,
1646
- path: [..._options.basePath, _options.definitionPath, name],
1647
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1648
- jsonSchema: void 0
1649
- }
1650
- ]))
1651
- };
1652
- };
1653
-
1654
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
1655
- function addErrorMessage(res, key, errorMessage, refs) {
1656
- if (!refs?.errorMessages)
1657
- return;
1658
- if (errorMessage) {
1659
- res.errorMessage = {
1660
- ...res.errorMessage,
1661
- [key]: errorMessage
1662
- };
1663
- }
1664
- }
1665
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
1666
- res[key] = value;
1667
- addErrorMessage(res, key, errorMessage, refs);
1668
- }
1669
-
1670
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
1671
- function parseAnyDef() {
1672
- return {};
1673
- }
1674
- function parseArrayDef(def, refs) {
1675
- const res = {
1676
- type: "array"
1677
- };
1678
- if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
1679
- res.items = parseDef(def.type._def, {
1680
- ...refs,
1681
- currentPath: [...refs.currentPath, "items"]
1682
- });
1683
- }
1684
- if (def.minLength) {
1685
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
1686
- }
1687
- if (def.maxLength) {
1688
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
1689
- }
1690
- if (def.exactLength) {
1691
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
1692
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
1693
- }
1694
- return res;
1695
- }
1696
-
1697
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
1698
- function parseBigintDef(def, refs) {
1699
- const res = {
1700
- type: "integer",
1701
- format: "int64"
1702
- };
1703
- if (!def.checks)
1704
- return res;
1705
- for (const check of def.checks) {
1706
- switch (check.kind) {
1707
- case "min":
1708
- if (refs.target === "jsonSchema7") {
1709
- if (check.inclusive) {
1710
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1711
- } else {
1712
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1713
- }
1714
- } else {
1715
- if (!check.inclusive) {
1716
- res.exclusiveMinimum = true;
1717
- }
1718
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1719
- }
1720
- break;
1721
- case "max":
1722
- if (refs.target === "jsonSchema7") {
1723
- if (check.inclusive) {
1724
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1725
- } else {
1726
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1727
- }
1728
- } else {
1729
- if (!check.inclusive) {
1730
- res.exclusiveMaximum = true;
1731
- }
1732
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1733
- }
1734
- break;
1735
- case "multipleOf":
1736
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1737
- break;
1738
- }
1739
- }
1740
- return res;
1741
- }
1742
-
1743
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
1744
- function parseBooleanDef() {
1745
- return {
1746
- type: "boolean"
1747
- };
1748
- }
1749
-
1750
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
1751
- function parseBrandedDef(_def, refs) {
1752
- return parseDef(_def.type._def, refs);
1753
- }
1754
-
1755
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
1756
- var parseCatchDef = (def, refs) => {
1757
- return parseDef(def.innerType._def, refs);
1758
- };
1759
-
1760
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
1761
- function parseDateDef(def, refs, overrideDateStrategy) {
1762
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
1763
- if (Array.isArray(strategy)) {
1764
- return {
1765
- anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item))
1766
- };
1767
- }
1768
- switch (strategy) {
1769
- case "string":
1770
- case "format:date-time":
1771
- return {
1772
- type: "string",
1773
- format: "date-time"
1774
- };
1775
- case "format:date":
1776
- return {
1777
- type: "string",
1778
- format: "date"
1779
- };
1780
- case "integer":
1781
- return integerDateParser(def, refs);
1782
- }
1783
- }
1784
- var integerDateParser = (def, refs) => {
1785
- const res = {
1786
- type: "integer",
1787
- format: "unix-time"
1788
- };
1789
- if (refs.target === "openApi3") {
1790
- return res;
1791
- }
1792
- for (const check of def.checks) {
1793
- switch (check.kind) {
1794
- case "min":
1795
- setResponseValueAndErrors(
1796
- res,
1797
- "minimum",
1798
- check.value,
1799
- // This is in milliseconds
1800
- check.message,
1801
- refs
1802
- );
1803
- break;
1804
- case "max":
1805
- setResponseValueAndErrors(
1806
- res,
1807
- "maximum",
1808
- check.value,
1809
- // This is in milliseconds
1810
- check.message,
1811
- refs
1812
- );
1813
- break;
1814
- }
1815
- }
1816
- return res;
1817
- };
1818
-
1819
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
1820
- function parseDefaultDef(_def, refs) {
1821
- return {
1822
- ...parseDef(_def.innerType._def, refs),
1823
- default: _def.defaultValue()
1824
- };
1825
- }
1826
-
1827
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
1828
- function parseEffectsDef(_def, refs) {
1829
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
1830
- }
1831
-
1832
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
1833
- function parseEnumDef(def) {
1834
- return {
1835
- type: "string",
1836
- enum: Array.from(def.values)
1837
- };
1838
- }
1839
-
1840
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
1841
- var isJsonSchema7AllOfType = (type) => {
1842
- if ("type" in type && type.type === "string")
1843
- return false;
1844
- return "allOf" in type;
1845
- };
1846
- function parseIntersectionDef(def, refs) {
1847
- const allOf = [
1848
- parseDef(def.left._def, {
1849
- ...refs,
1850
- currentPath: [...refs.currentPath, "allOf", "0"]
1851
- }),
1852
- parseDef(def.right._def, {
1853
- ...refs,
1854
- currentPath: [...refs.currentPath, "allOf", "1"]
1855
- })
1856
- ].filter((x2) => !!x2);
1857
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
1858
- const mergedAllOf = [];
1859
- allOf.forEach((schema) => {
1860
- if (isJsonSchema7AllOfType(schema)) {
1861
- mergedAllOf.push(...schema.allOf);
1862
- if (schema.unevaluatedProperties === void 0) {
1863
- unevaluatedProperties = void 0;
1864
- }
1865
- } else {
1866
- let nestedSchema = schema;
1867
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
1868
- const { additionalProperties, ...rest } = schema;
1869
- nestedSchema = rest;
1870
- } else {
1871
- unevaluatedProperties = void 0;
1872
- }
1873
- mergedAllOf.push(nestedSchema);
1874
- }
1875
- });
1876
- return mergedAllOf.length ? {
1877
- allOf: mergedAllOf,
1878
- ...unevaluatedProperties
1879
- } : void 0;
1880
- }
1881
-
1882
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
1883
- function parseLiteralDef(def, refs) {
1884
- const parsedType = typeof def.value;
1885
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1886
- return {
1887
- type: Array.isArray(def.value) ? "array" : "object"
1888
- };
1889
- }
1890
- if (refs.target === "openApi3") {
1891
- return {
1892
- type: parsedType === "bigint" ? "integer" : parsedType,
1893
- enum: [def.value]
1894
- };
1895
- }
1896
- return {
1897
- type: parsedType === "bigint" ? "integer" : parsedType,
1898
- const: def.value
1899
- };
1900
- }
1901
-
1902
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
1903
- var emojiRegex = void 0;
1904
- var zodPatterns = {
1905
- /**
1906
- * `c` was changed to `[cC]` to replicate /i flag
1907
- */
1908
- cuid: /^[cC][^\s-]{8,}$/,
1909
- cuid2: /^[0-9a-z]+$/,
1910
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1911
- /**
1912
- * `a-z` was added to replicate /i flag
1913
- */
1914
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1915
- /**
1916
- * Constructed a valid Unicode RegExp
1917
- *
1918
- * Lazily instantiate since this type of regex isn't supported
1919
- * in all envs (e.g. React Native).
1920
- *
1921
- * See:
1922
- * https://github.com/colinhacks/zod/issues/2433
1923
- * Fix in Zod:
1924
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1925
- */
1926
- emoji: () => {
1927
- if (emojiRegex === void 0) {
1928
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
1929
- }
1930
- return emojiRegex;
1931
- },
1932
- /**
1933
- * Unused
1934
- */
1935
- 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}$/,
1936
- /**
1937
- * Unused
1938
- */
1939
- 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])$/,
1940
- 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])$/,
1941
- /**
1942
- * Unused
1943
- */
1944
- 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})))$/,
1945
- 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])$/,
1946
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1947
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1948
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
1949
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1950
- };
1951
- function parseStringDef(def, refs) {
1952
- const res = {
1953
- type: "string"
1954
- };
1955
- if (def.checks) {
1956
- for (const check of def.checks) {
1957
- switch (check.kind) {
1958
- case "min":
1959
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
1960
- break;
1961
- case "max":
1962
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
1963
- break;
1964
- case "email":
1965
- switch (refs.emailStrategy) {
1966
- case "format:email":
1967
- addFormat(res, "email", check.message, refs);
1968
- break;
1969
- case "format:idn-email":
1970
- addFormat(res, "idn-email", check.message, refs);
1971
- break;
1972
- case "pattern:zod":
1973
- addPattern(res, zodPatterns.email, check.message, refs);
1974
- break;
1975
- }
1976
- break;
1977
- case "url":
1978
- addFormat(res, "uri", check.message, refs);
1979
- break;
1980
- case "uuid":
1981
- addFormat(res, "uuid", check.message, refs);
1982
- break;
1983
- case "regex":
1984
- addPattern(res, check.regex, check.message, refs);
1985
- break;
1986
- case "cuid":
1987
- addPattern(res, zodPatterns.cuid, check.message, refs);
1988
- break;
1989
- case "cuid2":
1990
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1991
- break;
1992
- case "startsWith":
1993
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
1994
- break;
1995
- case "endsWith":
1996
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
1997
- break;
1998
- case "datetime":
1999
- addFormat(res, "date-time", check.message, refs);
2000
- break;
2001
- case "date":
2002
- addFormat(res, "date", check.message, refs);
2003
- break;
2004
- case "time":
2005
- addFormat(res, "time", check.message, refs);
2006
- break;
2007
- case "duration":
2008
- addFormat(res, "duration", check.message, refs);
2009
- break;
2010
- case "length":
2011
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
2012
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
2013
- break;
2014
- case "includes": {
2015
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
2016
- break;
2017
- }
2018
- case "ip": {
2019
- if (check.version !== "v6") {
2020
- addFormat(res, "ipv4", check.message, refs);
2021
- }
2022
- if (check.version !== "v4") {
2023
- addFormat(res, "ipv6", check.message, refs);
2024
- }
2025
- break;
2026
- }
2027
- case "base64url":
2028
- addPattern(res, zodPatterns.base64url, check.message, refs);
2029
- break;
2030
- case "jwt":
2031
- addPattern(res, zodPatterns.jwt, check.message, refs);
2032
- break;
2033
- case "cidr": {
2034
- if (check.version !== "v6") {
2035
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
2036
- }
2037
- if (check.version !== "v4") {
2038
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
2039
- }
2040
- break;
2041
- }
2042
- case "emoji":
2043
- addPattern(res, zodPatterns.emoji(), check.message, refs);
2044
- break;
2045
- case "ulid": {
2046
- addPattern(res, zodPatterns.ulid, check.message, refs);
2047
- break;
2048
- }
2049
- case "base64": {
2050
- switch (refs.base64Strategy) {
2051
- case "format:binary": {
2052
- addFormat(res, "binary", check.message, refs);
2053
- break;
2054
- }
2055
- case "contentEncoding:base64": {
2056
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
2057
- break;
2058
- }
2059
- case "pattern:zod": {
2060
- addPattern(res, zodPatterns.base64, check.message, refs);
2061
- break;
2062
- }
2063
- }
2064
- break;
2065
- }
2066
- case "nanoid": {
2067
- addPattern(res, zodPatterns.nanoid, check.message, refs);
2068
- }
2069
- }
2070
- }
2071
- }
2072
- return res;
2073
- }
2074
- function escapeLiteralCheckValue(literal, refs) {
2075
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
2076
- }
2077
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
2078
- function escapeNonAlphaNumeric(source) {
2079
- let result = "";
2080
- for (let i2 = 0; i2 < source.length; i2++) {
2081
- if (!ALPHA_NUMERIC.has(source[i2])) {
2082
- result += "\\";
2083
- }
2084
- result += source[i2];
2085
- }
2086
- return result;
2087
- }
2088
- function addFormat(schema, value, message, refs) {
2089
- if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
2090
- if (!schema.anyOf) {
2091
- schema.anyOf = [];
2092
- }
2093
- if (schema.format) {
2094
- schema.anyOf.push({
2095
- format: schema.format,
2096
- ...schema.errorMessage && refs.errorMessages && {
2097
- errorMessage: { format: schema.errorMessage.format }
2098
- }
2099
- });
2100
- delete schema.format;
2101
- if (schema.errorMessage) {
2102
- delete schema.errorMessage.format;
2103
- if (Object.keys(schema.errorMessage).length === 0) {
2104
- delete schema.errorMessage;
2105
- }
2106
- }
2107
- }
2108
- schema.anyOf.push({
2109
- format: value,
2110
- ...message && refs.errorMessages && { errorMessage: { format: message } }
2111
- });
2112
- } else {
2113
- setResponseValueAndErrors(schema, "format", value, message, refs);
2114
- }
2115
- }
2116
- function addPattern(schema, regex, message, refs) {
2117
- if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
2118
- if (!schema.allOf) {
2119
- schema.allOf = [];
2120
- }
2121
- if (schema.pattern) {
2122
- schema.allOf.push({
2123
- pattern: schema.pattern,
2124
- ...schema.errorMessage && refs.errorMessages && {
2125
- errorMessage: { pattern: schema.errorMessage.pattern }
2126
- }
2127
- });
2128
- delete schema.pattern;
2129
- if (schema.errorMessage) {
2130
- delete schema.errorMessage.pattern;
2131
- if (Object.keys(schema.errorMessage).length === 0) {
2132
- delete schema.errorMessage;
2133
- }
2134
- }
2135
- }
2136
- schema.allOf.push({
2137
- pattern: stringifyRegExpWithFlags(regex, refs),
2138
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
2139
- });
2140
- } else {
2141
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
2142
- }
2143
- }
2144
- function stringifyRegExpWithFlags(regex, refs) {
2145
- if (!refs.applyRegexFlags || !regex.flags) {
2146
- return regex.source;
2147
- }
2148
- const flags = {
2149
- i: regex.flags.includes("i"),
2150
- m: regex.flags.includes("m"),
2151
- s: regex.flags.includes("s")
2152
- // `.` matches newlines
2153
- };
2154
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
2155
- let pattern = "";
2156
- let isEscaped = false;
2157
- let inCharGroup = false;
2158
- let inCharRange = false;
2159
- for (let i2 = 0; i2 < source.length; i2++) {
2160
- if (isEscaped) {
2161
- pattern += source[i2];
2162
- isEscaped = false;
2163
- continue;
2164
- }
2165
- if (flags.i) {
2166
- if (inCharGroup) {
2167
- if (source[i2].match(/[a-z]/)) {
2168
- if (inCharRange) {
2169
- pattern += source[i2];
2170
- pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase();
2171
- inCharRange = false;
2172
- } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) {
2173
- pattern += source[i2];
2174
- inCharRange = true;
2175
- } else {
2176
- pattern += `${source[i2]}${source[i2].toUpperCase()}`;
2177
- }
2178
- continue;
2179
- }
2180
- } else if (source[i2].match(/[a-z]/)) {
2181
- pattern += `[${source[i2]}${source[i2].toUpperCase()}]`;
2182
- continue;
2183
- }
2184
- }
2185
- if (flags.m) {
2186
- if (source[i2] === "^") {
2187
- pattern += `(^|(?<=[\r
2188
- ]))`;
2189
- continue;
2190
- } else if (source[i2] === "$") {
2191
- pattern += `($|(?=[\r
2192
- ]))`;
2193
- continue;
2194
- }
2195
- }
2196
- if (flags.s && source[i2] === ".") {
2197
- pattern += inCharGroup ? `${source[i2]}\r
2198
- ` : `[${source[i2]}\r
2199
- ]`;
2200
- continue;
2201
- }
2202
- pattern += source[i2];
2203
- if (source[i2] === "\\") {
2204
- isEscaped = true;
2205
- } else if (inCharGroup && source[i2] === "]") {
2206
- inCharGroup = false;
2207
- } else if (!inCharGroup && source[i2] === "[") {
2208
- inCharGroup = true;
2209
- }
2210
- }
2211
- return pattern;
2212
- }
2213
-
2214
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
2215
- function parseRecordDef(def, refs) {
2216
- if (refs.target === "openAi") {
2217
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
2218
- }
2219
- if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
2220
- return {
2221
- type: "object",
2222
- required: def.keyType._def.values,
2223
- properties: def.keyType._def.values.reduce((acc, key) => ({
2224
- ...acc,
2225
- [key]: parseDef(def.valueType._def, {
2226
- ...refs,
2227
- currentPath: [...refs.currentPath, "properties", key]
2228
- }) ?? {}
2229
- }), {}),
2230
- additionalProperties: refs.rejectedAdditionalProperties
2231
- };
2232
- }
2233
- const schema = {
2234
- type: "object",
2235
- additionalProperties: parseDef(def.valueType._def, {
2236
- ...refs,
2237
- currentPath: [...refs.currentPath, "additionalProperties"]
2238
- }) ?? refs.allowedAdditionalProperties
2239
- };
2240
- if (refs.target === "openApi3") {
2241
- return schema;
2242
- }
2243
- if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
2244
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
2245
- return {
2246
- ...schema,
2247
- propertyNames: keyType
2248
- };
2249
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
2250
- return {
2251
- ...schema,
2252
- propertyNames: {
2253
- enum: def.keyType._def.values
2254
- }
2255
- };
2256
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
2257
- const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
2258
- return {
2259
- ...schema,
2260
- propertyNames: keyType
2261
- };
2262
- }
2263
- return schema;
2264
- }
2265
-
2266
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
2267
- function parseMapDef(def, refs) {
2268
- if (refs.mapStrategy === "record") {
2269
- return parseRecordDef(def, refs);
2270
- }
2271
- const keys = parseDef(def.keyType._def, {
2272
- ...refs,
2273
- currentPath: [...refs.currentPath, "items", "items", "0"]
2274
- }) || {};
2275
- const values = parseDef(def.valueType._def, {
2276
- ...refs,
2277
- currentPath: [...refs.currentPath, "items", "items", "1"]
2278
- }) || {};
2279
- return {
2280
- type: "array",
2281
- maxItems: 125,
2282
- items: {
2283
- type: "array",
2284
- items: [keys, values],
2285
- minItems: 2,
2286
- maxItems: 2
2287
- }
2288
- };
2289
- }
2290
-
2291
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
2292
- function parseNativeEnumDef(def) {
2293
- const object = def.values;
2294
- const actualKeys = Object.keys(def.values).filter((key) => {
2295
- return typeof object[object[key]] !== "number";
2296
- });
2297
- const actualValues = actualKeys.map((key) => object[key]);
2298
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
2299
- return {
2300
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
2301
- enum: actualValues
2302
- };
2303
- }
2304
-
2305
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
2306
- function parseNeverDef() {
2307
- return {
2308
- not: {}
2309
- };
2310
- }
2311
-
2312
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
2313
- function parseNullDef(refs) {
2314
- return refs.target === "openApi3" ? {
2315
- enum: ["null"],
2316
- nullable: true
2317
- } : {
2318
- type: "null"
2319
- };
2320
- }
2321
-
2322
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
2323
- var primitiveMappings = {
2324
- ZodString: "string",
2325
- ZodNumber: "number",
2326
- ZodBigInt: "integer",
2327
- ZodBoolean: "boolean",
2328
- ZodNull: "null"
2329
- };
2330
- function parseUnionDef(def, refs) {
2331
- if (refs.target === "openApi3")
2332
- return asAnyOf(def, refs);
2333
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
2334
- if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
2335
- const types = options.reduce((types2, x2) => {
2336
- const type = primitiveMappings[x2._def.typeName];
2337
- return type && !types2.includes(type) ? [...types2, type] : types2;
2338
- }, []);
2339
- return {
2340
- type: types.length > 1 ? types : types[0]
2341
- };
2342
- } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
2343
- const types = options.reduce((acc, x2) => {
2344
- const type = typeof x2._def.value;
2345
- switch (type) {
2346
- case "string":
2347
- case "number":
2348
- case "boolean":
2349
- return [...acc, type];
2350
- case "bigint":
2351
- return [...acc, "integer"];
2352
- case "object":
2353
- if (x2._def.value === null)
2354
- return [...acc, "null"];
2355
- case "symbol":
2356
- case "undefined":
2357
- case "function":
2358
- default:
2359
- return acc;
2360
- }
2361
- }, []);
2362
- if (types.length === options.length) {
2363
- const uniqueTypes = types.filter((x2, i2, a2) => a2.indexOf(x2) === i2);
2364
- return {
2365
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
2366
- enum: options.reduce((acc, x2) => {
2367
- return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
2368
- }, [])
2369
- };
2370
- }
2371
- } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
2372
- return {
2373
- type: "string",
2374
- enum: options.reduce((acc, x2) => [
2375
- ...acc,
2376
- ...x2._def.values.filter((x3) => !acc.includes(x3))
2377
- ], [])
2378
- };
2379
- }
2380
- return asAnyOf(def, refs);
2381
- }
2382
- var asAnyOf = (def, refs) => {
2383
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i2) => parseDef(x2._def, {
2384
- ...refs,
2385
- currentPath: [...refs.currentPath, "anyOf", `${i2}`]
2386
- })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
2387
- return anyOf.length ? { anyOf } : void 0;
2388
- };
2389
-
2390
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
2391
- function parseNullableDef(def, refs) {
2392
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
2393
- if (refs.target === "openApi3") {
2394
- return {
2395
- type: primitiveMappings[def.innerType._def.typeName],
2396
- nullable: true
2397
- };
2398
- }
2399
- return {
2400
- type: [
2401
- primitiveMappings[def.innerType._def.typeName],
2402
- "null"
2403
- ]
2404
- };
2405
- }
2406
- if (refs.target === "openApi3") {
2407
- const base2 = parseDef(def.innerType._def, {
2408
- ...refs,
2409
- currentPath: [...refs.currentPath]
2410
- });
2411
- if (base2 && "$ref" in base2)
2412
- return { allOf: [base2], nullable: true };
2413
- return base2 && { ...base2, nullable: true };
2414
- }
2415
- const base = parseDef(def.innerType._def, {
2416
- ...refs,
2417
- currentPath: [...refs.currentPath, "anyOf", "0"]
2418
- });
2419
- return base && { anyOf: [base, { type: "null" }] };
2420
- }
2421
-
2422
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
2423
- function parseNumberDef(def, refs) {
2424
- const res = {
2425
- type: "number"
2426
- };
2427
- if (!def.checks)
2428
- return res;
2429
- for (const check of def.checks) {
2430
- switch (check.kind) {
2431
- case "int":
2432
- res.type = "integer";
2433
- addErrorMessage(res, "type", check.message, refs);
2434
- break;
2435
- case "min":
2436
- if (refs.target === "jsonSchema7") {
2437
- if (check.inclusive) {
2438
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2439
- } else {
2440
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
2441
- }
2442
- } else {
2443
- if (!check.inclusive) {
2444
- res.exclusiveMinimum = true;
2445
- }
2446
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2447
- }
2448
- break;
2449
- case "max":
2450
- if (refs.target === "jsonSchema7") {
2451
- if (check.inclusive) {
2452
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2453
- } else {
2454
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
2455
- }
2456
- } else {
2457
- if (!check.inclusive) {
2458
- res.exclusiveMaximum = true;
2459
- }
2460
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2461
- }
2462
- break;
2463
- case "multipleOf":
2464
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
2465
- break;
2466
- }
2467
- }
2468
- return res;
2469
- }
2470
- function parseObjectDef(def, refs) {
2471
- const forceOptionalIntoNullable = refs.target === "openAi";
2472
- const result = {
2473
- type: "object",
2474
- properties: {}
2475
- };
2476
- const required = [];
2477
- const shape = def.shape();
2478
- for (const propName in shape) {
2479
- let propDef = shape[propName];
2480
- if (propDef === void 0 || propDef._def === void 0) {
2481
- continue;
2482
- }
2483
- let propOptional = safeIsOptional(propDef);
2484
- if (propOptional && forceOptionalIntoNullable) {
2485
- if (propDef instanceof ZodOptional) {
2486
- propDef = propDef._def.innerType;
2487
- }
2488
- if (!propDef.isNullable()) {
2489
- propDef = propDef.nullable();
2490
- }
2491
- propOptional = false;
2492
- }
2493
- const parsedDef = parseDef(propDef._def, {
2494
- ...refs,
2495
- currentPath: [...refs.currentPath, "properties", propName],
2496
- propertyPath: [...refs.currentPath, "properties", propName]
2497
- });
2498
- if (parsedDef === void 0) {
2499
- continue;
2500
- }
2501
- result.properties[propName] = parsedDef;
2502
- if (!propOptional) {
2503
- required.push(propName);
2504
- }
2505
- }
2506
- if (required.length) {
2507
- result.required = required;
2508
- }
2509
- const additionalProperties = decideAdditionalProperties(def, refs);
2510
- if (additionalProperties !== void 0) {
2511
- result.additionalProperties = additionalProperties;
2512
- }
2513
- return result;
2514
- }
2515
- function decideAdditionalProperties(def, refs) {
2516
- if (def.catchall._def.typeName !== "ZodNever") {
2517
- return parseDef(def.catchall._def, {
2518
- ...refs,
2519
- currentPath: [...refs.currentPath, "additionalProperties"]
2520
- });
2521
- }
2522
- switch (def.unknownKeys) {
2523
- case "passthrough":
2524
- return refs.allowedAdditionalProperties;
2525
- case "strict":
2526
- return refs.rejectedAdditionalProperties;
2527
- case "strip":
2528
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
2529
- }
2530
- }
2531
- function safeIsOptional(schema) {
2532
- try {
2533
- return schema.isOptional();
2534
- } catch {
2535
- return true;
2536
- }
2537
- }
2538
-
2539
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
2540
- var parseOptionalDef = (def, refs) => {
2541
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
2542
- return parseDef(def.innerType._def, refs);
2543
- }
2544
- const innerSchema = parseDef(def.innerType._def, {
2545
- ...refs,
2546
- currentPath: [...refs.currentPath, "anyOf", "1"]
2547
- });
2548
- return innerSchema ? {
2549
- anyOf: [
2550
- {
2551
- not: {}
2552
- },
2553
- innerSchema
2554
- ]
2555
- } : {};
2556
- };
2557
-
2558
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
2559
- var parsePipelineDef = (def, refs) => {
2560
- if (refs.pipeStrategy === "input") {
2561
- return parseDef(def.in._def, refs);
2562
- } else if (refs.pipeStrategy === "output") {
2563
- return parseDef(def.out._def, refs);
2564
- }
2565
- const a2 = parseDef(def.in._def, {
2566
- ...refs,
2567
- currentPath: [...refs.currentPath, "allOf", "0"]
2568
- });
2569
- const b = parseDef(def.out._def, {
2570
- ...refs,
2571
- currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"]
2572
- });
2573
- return {
2574
- allOf: [a2, b].filter((x2) => x2 !== void 0)
2575
- };
2576
- };
2577
-
2578
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
2579
- function parsePromiseDef(def, refs) {
2580
- return parseDef(def.type._def, refs);
2581
- }
2582
-
2583
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
2584
- function parseSetDef(def, refs) {
2585
- const items = parseDef(def.valueType._def, {
2586
- ...refs,
2587
- currentPath: [...refs.currentPath, "items"]
2588
- });
2589
- const schema = {
2590
- type: "array",
2591
- uniqueItems: true,
2592
- items
2593
- };
2594
- if (def.minSize) {
2595
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
2596
- }
2597
- if (def.maxSize) {
2598
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
2599
- }
2600
- return schema;
2601
- }
2602
-
2603
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
2604
- function parseTupleDef(def, refs) {
2605
- if (def.rest) {
2606
- return {
2607
- type: "array",
2608
- minItems: def.items.length,
2609
- items: def.items.map((x2, i2) => parseDef(x2._def, {
2610
- ...refs,
2611
- currentPath: [...refs.currentPath, "items", `${i2}`]
2612
- })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
2613
- additionalItems: parseDef(def.rest._def, {
2614
- ...refs,
2615
- currentPath: [...refs.currentPath, "additionalItems"]
2616
- })
2617
- };
2618
- } else {
2619
- return {
2620
- type: "array",
2621
- minItems: def.items.length,
2622
- maxItems: def.items.length,
2623
- items: def.items.map((x2, i2) => parseDef(x2._def, {
2624
- ...refs,
2625
- currentPath: [...refs.currentPath, "items", `${i2}`]
2626
- })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
2627
- };
2628
- }
2629
- }
2630
-
2631
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
2632
- function parseUndefinedDef() {
2633
- return {
2634
- not: {}
2635
- };
2636
- }
2637
-
2638
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
2639
- function parseUnknownDef() {
2640
- return {};
2641
- }
2642
-
2643
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
2644
- var parseReadonlyDef = (def, refs) => {
2645
- return parseDef(def.innerType._def, refs);
2646
- };
2647
-
2648
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/selectParser.js
2649
- var selectParser = (def, typeName, refs) => {
2650
- switch (typeName) {
2651
- case ZodFirstPartyTypeKind.ZodString:
2652
- return parseStringDef(def, refs);
2653
- case ZodFirstPartyTypeKind.ZodNumber:
2654
- return parseNumberDef(def, refs);
2655
- case ZodFirstPartyTypeKind.ZodObject:
2656
- return parseObjectDef(def, refs);
2657
- case ZodFirstPartyTypeKind.ZodBigInt:
2658
- return parseBigintDef(def, refs);
2659
- case ZodFirstPartyTypeKind.ZodBoolean:
2660
- return parseBooleanDef();
2661
- case ZodFirstPartyTypeKind.ZodDate:
2662
- return parseDateDef(def, refs);
2663
- case ZodFirstPartyTypeKind.ZodUndefined:
2664
- return parseUndefinedDef();
2665
- case ZodFirstPartyTypeKind.ZodNull:
2666
- return parseNullDef(refs);
2667
- case ZodFirstPartyTypeKind.ZodArray:
2668
- return parseArrayDef(def, refs);
2669
- case ZodFirstPartyTypeKind.ZodUnion:
2670
- case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
2671
- return parseUnionDef(def, refs);
2672
- case ZodFirstPartyTypeKind.ZodIntersection:
2673
- return parseIntersectionDef(def, refs);
2674
- case ZodFirstPartyTypeKind.ZodTuple:
2675
- return parseTupleDef(def, refs);
2676
- case ZodFirstPartyTypeKind.ZodRecord:
2677
- return parseRecordDef(def, refs);
2678
- case ZodFirstPartyTypeKind.ZodLiteral:
2679
- return parseLiteralDef(def, refs);
2680
- case ZodFirstPartyTypeKind.ZodEnum:
2681
- return parseEnumDef(def);
2682
- case ZodFirstPartyTypeKind.ZodNativeEnum:
2683
- return parseNativeEnumDef(def);
2684
- case ZodFirstPartyTypeKind.ZodNullable:
2685
- return parseNullableDef(def, refs);
2686
- case ZodFirstPartyTypeKind.ZodOptional:
2687
- return parseOptionalDef(def, refs);
2688
- case ZodFirstPartyTypeKind.ZodMap:
2689
- return parseMapDef(def, refs);
2690
- case ZodFirstPartyTypeKind.ZodSet:
2691
- return parseSetDef(def, refs);
2692
- case ZodFirstPartyTypeKind.ZodLazy:
2693
- return () => def.getter()._def;
2694
- case ZodFirstPartyTypeKind.ZodPromise:
2695
- return parsePromiseDef(def, refs);
2696
- case ZodFirstPartyTypeKind.ZodNaN:
2697
- case ZodFirstPartyTypeKind.ZodNever:
2698
- return parseNeverDef();
2699
- case ZodFirstPartyTypeKind.ZodEffects:
2700
- return parseEffectsDef(def, refs);
2701
- case ZodFirstPartyTypeKind.ZodAny:
2702
- return parseAnyDef();
2703
- case ZodFirstPartyTypeKind.ZodUnknown:
2704
- return parseUnknownDef();
2705
- case ZodFirstPartyTypeKind.ZodDefault:
2706
- return parseDefaultDef(def, refs);
2707
- case ZodFirstPartyTypeKind.ZodBranded:
2708
- return parseBrandedDef(def, refs);
2709
- case ZodFirstPartyTypeKind.ZodReadonly:
2710
- return parseReadonlyDef(def, refs);
2711
- case ZodFirstPartyTypeKind.ZodCatch:
2712
- return parseCatchDef(def, refs);
2713
- case ZodFirstPartyTypeKind.ZodPipeline:
2714
- return parsePipelineDef(def, refs);
2715
- case ZodFirstPartyTypeKind.ZodFunction:
2716
- case ZodFirstPartyTypeKind.ZodVoid:
2717
- case ZodFirstPartyTypeKind.ZodSymbol:
2718
- return void 0;
2719
- default:
2720
- return /* @__PURE__ */ ((_) => void 0)();
2721
- }
2722
- };
2723
-
2724
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parseDef.js
2725
- function parseDef(def, refs, forceResolution = false) {
2726
- const seenItem = refs.seen.get(def);
2727
- if (refs.override) {
2728
- const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
2729
- if (overrideResult !== ignoreOverride) {
2730
- return overrideResult;
2731
- }
2732
- }
2733
- if (seenItem && !forceResolution) {
2734
- const seenSchema = get$ref(seenItem, refs);
2735
- if (seenSchema !== void 0) {
2736
- return seenSchema;
2737
- }
2738
- }
2739
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2740
- refs.seen.set(def, newItem);
2741
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2742
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2743
- if (jsonSchema) {
2744
- addMeta(def, refs, jsonSchema);
2745
- }
2746
- if (refs.postProcess) {
2747
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
2748
- newItem.jsonSchema = jsonSchema;
2749
- return postProcessResult;
2750
- }
2751
- newItem.jsonSchema = jsonSchema;
2752
- return jsonSchema;
2753
- }
2754
- var get$ref = (item, refs) => {
2755
- switch (refs.$refStrategy) {
2756
- case "root":
2757
- return { $ref: item.path.join("/") };
2758
- case "relative":
2759
- return { $ref: getRelativePath(refs.currentPath, item.path) };
2760
- case "none":
2761
- case "seen": {
2762
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2763
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
2764
- return {};
2765
- }
2766
- return refs.$refStrategy === "seen" ? {} : void 0;
2767
- }
2768
- }
2769
- };
2770
- var getRelativePath = (pathA, pathB) => {
2771
- let i2 = 0;
2772
- for (; i2 < pathA.length && i2 < pathB.length; i2++) {
2773
- if (pathA[i2] !== pathB[i2])
2774
- break;
2775
- }
2776
- return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/");
2777
- };
2778
- var addMeta = (def, refs, jsonSchema) => {
2779
- if (def.description) {
2780
- jsonSchema.description = def.description;
2781
- if (refs.markdownDescription) {
2782
- jsonSchema.markdownDescription = def.description;
2783
- }
2784
- }
2785
- return jsonSchema;
2786
- };
2787
-
2788
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
2789
- var zodToJsonSchema = (schema, options) => {
2790
- const refs = getRefs(options);
2791
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
2792
- ...acc,
2793
- [name2]: parseDef(schema2._def, {
2794
- ...refs,
2795
- currentPath: [...refs.basePath, refs.definitionPath, name2]
2796
- }, true) ?? {}
2797
- }), {}) : void 0;
2798
- const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
2799
- const main = parseDef(schema._def, name === void 0 ? refs : {
2800
- ...refs,
2801
- currentPath: [...refs.basePath, refs.definitionPath, name]
2802
- }, false) ?? {};
2803
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2804
- if (title !== void 0) {
2805
- main.title = title;
2806
- }
2807
- const combined = name === void 0 ? definitions ? {
2808
- ...main,
2809
- [refs.definitionPath]: definitions
2810
- } : main : {
2811
- $ref: [
2812
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2813
- refs.definitionPath,
2814
- name
2815
- ].join("/"),
2816
- [refs.definitionPath]: {
2817
- ...definitions,
2818
- [name]: main
2819
- }
2820
- };
2821
- if (refs.target === "jsonSchema7") {
2822
- combined.$schema = "http://json-schema.org/draft-07/schema#";
2823
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
2824
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
2825
- }
2826
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
2827
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
2828
- }
2829
- return combined;
2830
- };
2831
-
2832
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/index.js
2833
- var esm_default = zodToJsonSchema;
2834
- function handleError(error2, defaultMessage) {
2835
- console.error(defaultMessage, error2);
2836
- const apiError = error2;
844
+ function handleError(error, defaultMessage) {
845
+ const apiError = error;
2837
846
  throw new HTTPException(apiError.status || 500, {
2838
847
  message: apiError.message || defaultMessage
2839
848
  });
@@ -2845,153 +854,71 @@ function errorHandler(err, c2) {
2845
854
  console.error(err);
2846
855
  return c2.json({ error: "Internal Server Error" }, 500);
2847
856
  }
2848
- function validateBody(body) {
2849
- const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
2850
- if (!value) {
2851
- acc[key] = `${key} is required`;
2852
- }
2853
- return acc;
2854
- }, {});
2855
- if (Object.keys(errorResponse).length > 0) {
2856
- throw new HTTPException(400, { message: JSON.stringify(errorResponse) });
2857
- }
2858
- }
2859
857
 
2860
858
  // src/server/handlers/agents.ts
2861
859
  async function getAgentsHandler(c2) {
2862
- try {
2863
- const mastra = c2.get("mastra");
2864
- const agents = mastra.getAgents();
2865
- const serializedAgents = Object.entries(agents).reduce((acc, [_id, _agent]) => {
2866
- const agent = _agent;
2867
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc2, [key, tool]) => {
2868
- const _tool = tool;
2869
- acc2[key] = {
2870
- ..._tool,
2871
- inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2872
- outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2873
- };
2874
- return acc2;
2875
- }, {});
2876
- acc[_id] = {
2877
- name: agent.name,
2878
- instructions: agent.instructions,
2879
- tools: serializedAgentTools,
2880
- provider: agent.llm?.getProvider(),
2881
- modelId: agent.llm?.getModelId()
2882
- };
2883
- return acc;
2884
- }, {});
2885
- return c2.json(serializedAgents);
2886
- } catch (error2) {
2887
- return handleError(error2, "Error getting agents");
2888
- }
860
+ const serializedAgents = await getAgentsHandler$1({ mastra: c2.get("mastra") });
861
+ return c2.json(serializedAgents);
2889
862
  }
2890
863
  async function getAgentByIdHandler(c2) {
2891
- try {
2892
- const mastra = c2.get("mastra");
2893
- const agentId = c2.req.param("agentId");
2894
- const agent = mastra.getAgent(agentId);
2895
- if (!agent) {
2896
- throw new HTTPException(404, { message: "Agent not found" });
2897
- }
2898
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc, [key, tool]) => {
2899
- const _tool = tool;
2900
- acc[key] = {
2901
- ..._tool,
2902
- inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2903
- outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2904
- };
2905
- return acc;
2906
- }, {});
2907
- return c2.json({
2908
- name: agent.name,
2909
- instructions: agent.instructions,
2910
- tools: serializedAgentTools,
2911
- provider: agent.llm?.getProvider(),
2912
- modelId: agent.llm?.getModelId()
2913
- });
2914
- } catch (error2) {
2915
- return handleError(error2, "Error getting agent");
2916
- }
864
+ const mastra = c2.get("mastra");
865
+ const agentId = c2.req.param("agentId");
866
+ const result = await getAgentByIdHandler$1({
867
+ mastra,
868
+ agentId
869
+ });
870
+ return c2.json(result);
2917
871
  }
2918
872
  async function getEvalsByAgentIdHandler(c2) {
2919
- try {
2920
- const mastra = c2.get("mastra");
2921
- const agentId = c2.req.param("agentId");
2922
- const agent = mastra.getAgent(agentId);
2923
- const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "test") || [];
2924
- return c2.json({
2925
- id: agentId,
2926
- name: agent.name,
2927
- instructions: agent.instructions,
2928
- evals
2929
- });
2930
- } catch (error2) {
2931
- return handleError(error2, "Error getting test evals");
2932
- }
873
+ const mastra = c2.get("mastra");
874
+ const agentId = c2.req.param("agentId");
875
+ const result = await getEvalsByAgentIdHandler$1({
876
+ mastra,
877
+ agentId
878
+ });
879
+ return c2.json(result);
2933
880
  }
2934
881
  async function getLiveEvalsByAgentIdHandler(c2) {
2935
- try {
2936
- const mastra = c2.get("mastra");
2937
- const agentId = c2.req.param("agentId");
2938
- const agent = mastra.getAgent(agentId);
2939
- const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "live") || [];
2940
- return c2.json({
2941
- id: agentId,
2942
- name: agent.name,
2943
- instructions: agent.instructions,
2944
- evals
2945
- });
2946
- } catch (error2) {
2947
- return handleError(error2, "Error getting live evals");
2948
- }
882
+ const mastra = c2.get("mastra");
883
+ const agentId = c2.req.param("agentId");
884
+ const result = await getLiveEvalsByAgentIdHandler$1({
885
+ mastra,
886
+ agentId
887
+ });
888
+ return c2.json(result);
2949
889
  }
2950
890
  async function generateHandler(c2) {
2951
891
  try {
2952
892
  const mastra = c2.get("mastra");
2953
893
  const agentId = c2.req.param("agentId");
2954
- const agent = mastra.getAgent(agentId);
2955
- if (!agent) {
2956
- throw new HTTPException(404, { message: "Agent not found" });
2957
- }
2958
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
2959
- validateBody({ messages });
894
+ const { resourceId, resourceid, ...body } = await c2.req.json();
2960
895
  const finalResourceId = resourceId ?? resourceid;
2961
- const result = await agent.generate(messages, { threadId, resourceId: finalResourceId, output, runId, ...rest });
896
+ const result = await generateHandler$2({
897
+ mastra,
898
+ agentId,
899
+ resourceId: finalResourceId,
900
+ ...body
901
+ });
2962
902
  return c2.json(result);
2963
- } catch (error2) {
2964
- return handleError(error2, "Error generating from agent");
903
+ } catch (error) {
904
+ return handleError(error, "Error generating from agent");
2965
905
  }
2966
906
  }
2967
907
  async function streamGenerateHandler(c2) {
2968
908
  try {
2969
909
  const mastra = c2.get("mastra");
2970
910
  const agentId = c2.req.param("agentId");
2971
- const agent = mastra.getAgent(agentId);
2972
- if (!agent) {
2973
- throw new HTTPException(404, { message: "Agent not found" });
2974
- }
2975
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
2976
- validateBody({ messages });
911
+ const { resourceId, resourceid, ...body } = await c2.req.json();
2977
912
  const finalResourceId = resourceId ?? resourceid;
2978
- const streamResult = await agent.stream(messages, {
2979
- threadId,
913
+ const streamResponse = await streamGenerateHandler$2({
914
+ mastra,
915
+ agentId,
2980
916
  resourceId: finalResourceId,
2981
- output,
2982
- runId,
2983
- ...rest
2984
- });
2985
- const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
2986
- sendUsage: true,
2987
- sendReasoning: true,
2988
- getErrorMessage: (error2) => {
2989
- return `An error occurred while processing your request. ${error2 instanceof Error ? error2.message : JSON.stringify(error2)}`;
2990
- }
917
+ ...body
2991
918
  });
2992
919
  return streamResponse;
2993
- } catch (error2) {
2994
- return handleError(error2, "Error streaming from agent");
920
+ } catch (error) {
921
+ return handleError(error, "Error streaming from agent");
2995
922
  }
2996
923
  }
2997
924
  async function setAgentInstructionsHandler(c2) {
@@ -3017,15 +944,15 @@ async function setAgentInstructionsHandler(c2) {
3017
944
  },
3018
945
  200
3019
946
  );
3020
- } catch (error2) {
3021
- return handleError(error2, "Error setting agent instructions");
947
+ } catch (error) {
948
+ return handleError(error, "Error setting agent instructions");
3022
949
  }
3023
950
  }
3024
951
 
3025
952
  // src/server/handlers/client.ts
3026
953
  var clients = /* @__PURE__ */ new Set();
3027
954
  function handleClientsRefresh(c2) {
3028
- const stream = new ReadableStream({
955
+ const stream2 = new ReadableStream({
3029
956
  start(controller) {
3030
957
  clients.add(controller);
3031
958
  controller.enqueue("data: connected\n\n");
@@ -3034,7 +961,7 @@ function handleClientsRefresh(c2) {
3034
961
  });
3035
962
  }
3036
963
  });
3037
- return new Response(stream, {
964
+ return new Response(stream2, {
3038
965
  headers: {
3039
966
  "Content-Type": "text/event-stream",
3040
967
  "Cache-Control": "no-cache",
@@ -3057,13 +984,13 @@ async function getLogsHandler(c2) {
3057
984
  try {
3058
985
  const mastra = c2.get("mastra");
3059
986
  const transportId = c2.req.query("transportId");
3060
- if (!transportId) {
3061
- throw new HTTPException(400, { message: "transportId is required" });
3062
- }
3063
- const logs = await mastra.getLogs(transportId);
987
+ const logs = await getLogsHandler$1({
988
+ mastra,
989
+ transportId
990
+ });
3064
991
  return c2.json(logs);
3065
- } catch (error2) {
3066
- return handleError(error2, "Error getting logs");
992
+ } catch (error) {
993
+ return handleError(error, "Error getting logs");
3067
994
  }
3068
995
  }
3069
996
  async function getLogsByRunIdHandler(c2) {
@@ -3071,282 +998,199 @@ async function getLogsByRunIdHandler(c2) {
3071
998
  const mastra = c2.get("mastra");
3072
999
  const runId = c2.req.param("runId");
3073
1000
  const transportId = c2.req.query("transportId");
3074
- if (!transportId) {
3075
- throw new HTTPException(400, { message: "transportId is required" });
3076
- }
3077
- const logs = await mastra.getLogsByRunId({ runId, transportId });
1001
+ const logs = await getLogsByRunIdHandler$1({
1002
+ mastra,
1003
+ runId,
1004
+ transportId
1005
+ });
3078
1006
  return c2.json(logs);
3079
- } catch (error2) {
3080
- return handleError(error2, "Error getting logs by run ID");
1007
+ } catch (error) {
1008
+ return handleError(error, "Error getting logs by run ID");
3081
1009
  }
3082
1010
  }
3083
1011
  async function getLogTransports(c2) {
3084
1012
  try {
3085
1013
  const mastra = c2.get("mastra");
3086
- const logger2 = mastra.getLogger();
3087
- const transports = logger2.transports;
3088
- return c2.json({
3089
- transports: Object.keys(transports)
1014
+ const result = await getLogTransports$1({
1015
+ mastra
3090
1016
  });
3091
- } catch (e2) {
3092
- return handleError(e2, "Error getting log Transports ");
3093
- }
3094
- }
3095
- function getMemoryFromContext(c2) {
3096
- const mastra = c2.get("mastra");
3097
- const agentId = c2.req.query("agentId");
3098
- const agent = agentId ? mastra.getAgent(agentId) : null;
3099
- if (agentId && !agent) {
3100
- throw new HTTPException(404, { message: "Agent not found" });
1017
+ return c2.json(result);
1018
+ } catch (error) {
1019
+ return handleError(error, "Error getting log Transports");
3101
1020
  }
3102
- const memory = agent?.getMemory?.() || mastra.memory;
3103
- return memory;
3104
1021
  }
3105
1022
  async function getMemoryStatusHandler(c2) {
3106
1023
  try {
3107
- const memory = getMemoryFromContext(c2);
3108
- if (!memory) {
3109
- return c2.json({ result: false });
3110
- }
3111
- return c2.json({ result: true });
3112
- } catch (error2) {
3113
- return handleError(error2, "Error getting memory status");
1024
+ const mastra = c2.get("mastra");
1025
+ const agentId = c2.req.query("agentId");
1026
+ const result = await getMemoryStatusHandler$1({
1027
+ mastra,
1028
+ agentId
1029
+ });
1030
+ return c2.json(result);
1031
+ } catch (error) {
1032
+ return handleError(error, "Error getting memory status");
3114
1033
  }
3115
1034
  }
3116
1035
  async function getThreadsHandler(c2) {
3117
1036
  try {
3118
- const { resourceid } = c2.req.query();
3119
- const memory = getMemoryFromContext(c2);
3120
- if (!memory) {
3121
- throw new HTTPException(400, { message: "Memory is not initialized" });
3122
- }
3123
- if (!resourceid) {
3124
- throw new HTTPException(400, { message: "Resource ID is required" });
3125
- }
3126
- const threads = await memory.getThreadsByResourceId({ resourceId: resourceid });
3127
- return c2.json(threads);
3128
- } catch (error2) {
3129
- return handleError(error2, "Error getting threads");
1037
+ const mastra = c2.get("mastra");
1038
+ const agentId = c2.req.query("agentId");
1039
+ const resourceId = c2.req.query("resourceid");
1040
+ const result = await getThreadsHandler$1({
1041
+ mastra,
1042
+ agentId,
1043
+ resourceId
1044
+ });
1045
+ return c2.json(result);
1046
+ } catch (error) {
1047
+ return handleError(error, "Error getting threads");
3130
1048
  }
3131
1049
  }
3132
1050
  async function getThreadByIdHandler(c2) {
3133
1051
  try {
3134
- const memory = getMemoryFromContext(c2);
1052
+ const mastra = c2.get("mastra");
1053
+ const agentId = c2.req.query("agentId");
3135
1054
  const threadId = c2.req.param("threadId");
3136
- if (!memory) {
3137
- throw new HTTPException(400, { message: "Memory is not initialized" });
3138
- }
3139
- const thread = await memory.getThreadById({ threadId });
3140
- if (!thread) {
3141
- throw new HTTPException(404, { message: "Thread not found" });
3142
- }
3143
- return c2.json(thread);
3144
- } catch (error2) {
3145
- return handleError(error2, "Error getting thread");
1055
+ const result = await getThreadByIdHandler$1({
1056
+ mastra,
1057
+ agentId,
1058
+ threadId
1059
+ });
1060
+ return c2.json(result);
1061
+ } catch (error) {
1062
+ return handleError(error, "Error getting thread");
3146
1063
  }
3147
1064
  }
3148
1065
  async function saveMessagesHandler(c2) {
3149
1066
  try {
3150
- const memory = getMemoryFromContext(c2);
3151
- const { messages } = await c2.req.json();
3152
- if (!memory) {
3153
- throw new HTTPException(400, { message: "Memory is not initialized" });
3154
- }
3155
- validateBody({ messages });
3156
- if (!Array.isArray(messages)) {
3157
- throw new HTTPException(400, { message: "Messages should be an array" });
3158
- }
3159
- const processedMessages = messages.map((message) => ({
3160
- ...message,
3161
- id: memory.generateId(),
3162
- createdAt: message.createdAt ? new Date(message.createdAt) : /* @__PURE__ */ new Date()
3163
- }));
3164
- const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
1067
+ const mastra = c2.get("mastra");
1068
+ const agentId = c2.req.query("agentId");
1069
+ const body = await c2.req.json();
1070
+ const result = await saveMessagesHandler$1({
1071
+ mastra,
1072
+ agentId,
1073
+ body
1074
+ });
3165
1075
  return c2.json(result);
3166
- } catch (error2) {
3167
- return handleError(error2, "Error saving messages");
1076
+ } catch (error) {
1077
+ return handleError(error, "Error saving messages");
3168
1078
  }
3169
1079
  }
3170
1080
  async function createThreadHandler(c2) {
3171
1081
  try {
3172
- const memory = getMemoryFromContext(c2);
3173
- const { title, metadata, resourceid, threadId } = await c2.req.json();
3174
- if (!memory) {
3175
- throw new HTTPException(400, { message: "Memory is not initialized" });
3176
- }
3177
- validateBody({ resourceid });
3178
- const result = await memory.createThread({ resourceId: resourceid, title, metadata, threadId });
1082
+ const mastra = c2.get("mastra");
1083
+ const agentId = c2.req.query("agentId");
1084
+ const body = await c2.req.json();
1085
+ const result = await createThreadHandler$1({
1086
+ mastra,
1087
+ agentId,
1088
+ body
1089
+ });
3179
1090
  return c2.json(result);
3180
- } catch (error2) {
3181
- return handleError(error2, "Error saving thread to memory");
1091
+ } catch (error) {
1092
+ return handleError(error, "Error saving thread to memory");
3182
1093
  }
3183
1094
  }
3184
1095
  async function updateThreadHandler(c2) {
3185
1096
  try {
3186
- const memory = getMemoryFromContext(c2);
1097
+ const mastra = c2.get("mastra");
1098
+ const agentId = c2.req.query("agentId");
3187
1099
  const threadId = c2.req.param("threadId");
3188
- const { title, metadata, resourceid } = await c2.req.json();
3189
- const updatedAt = /* @__PURE__ */ new Date();
3190
- if (!memory) {
3191
- throw new HTTPException(400, { message: "Memory is not initialized" });
3192
- }
3193
- const thread = await memory.getThreadById({ threadId });
3194
- if (!thread) {
3195
- throw new HTTPException(404, { message: "Thread not found" });
3196
- }
3197
- const updatedThread = {
3198
- ...thread,
3199
- title: title || thread.title,
3200
- metadata: metadata || thread.metadata,
3201
- resourceId: resourceid || thread.resourceId,
3202
- createdAt: thread.createdAt,
3203
- updatedAt
3204
- };
3205
- const result = await memory.saveThread({ thread: updatedThread });
1100
+ const body = await c2.req.json();
1101
+ const result = await updateThreadHandler$1({
1102
+ mastra,
1103
+ agentId,
1104
+ threadId,
1105
+ body
1106
+ });
3206
1107
  return c2.json(result);
3207
- } catch (error2) {
3208
- return handleError(error2, "Error updating thread");
1108
+ } catch (error) {
1109
+ return handleError(error, "Error updating thread");
3209
1110
  }
3210
1111
  }
3211
1112
  async function deleteThreadHandler(c2) {
3212
1113
  try {
3213
- const memory = getMemoryFromContext(c2);
1114
+ const mastra = c2.get("mastra");
1115
+ const agentId = c2.req.query("agentId");
3214
1116
  const threadId = c2.req.param("threadId");
3215
- if (!memory) {
3216
- throw new HTTPException(400, { message: "Memory is not initialized" });
3217
- }
3218
- const thread = await memory.getThreadById({ threadId });
3219
- if (!thread) {
3220
- throw new HTTPException(404, { message: "Thread not found" });
3221
- }
3222
- await memory.deleteThread(threadId);
3223
- return c2.json({ result: "Thread deleted" });
3224
- } catch (error2) {
3225
- return handleError(error2, "Error deleting thread");
1117
+ const result = await deleteThreadHandler$1({
1118
+ mastra,
1119
+ agentId,
1120
+ threadId
1121
+ });
1122
+ return c2.json(result);
1123
+ } catch (error) {
1124
+ return handleError(error, "Error deleting thread");
3226
1125
  }
3227
1126
  }
3228
1127
  async function getMessagesHandler(c2) {
3229
1128
  try {
3230
- const memory = getMemoryFromContext(c2);
1129
+ const mastra = c2.get("mastra");
1130
+ const agentId = c2.req.query("agentId");
3231
1131
  const threadId = c2.req.param("threadId");
3232
- if (!memory) {
3233
- return c2.json({ error: "Memory is not initialized" }, 400);
3234
- }
3235
- const thread = await memory.getThreadById({ threadId });
3236
- if (!thread) {
3237
- return c2.json({ error: "Thread not found" }, 404);
3238
- }
3239
- const result = await memory.query({ threadId });
1132
+ const result = await getMessagesHandler$1({
1133
+ mastra,
1134
+ agentId,
1135
+ threadId
1136
+ });
3240
1137
  return c2.json(result);
3241
- } catch (error2) {
3242
- return handleError(error2, "Error getting messages");
1138
+ } catch (error) {
1139
+ return handleError(error, "Error getting messages");
3243
1140
  }
3244
1141
  }
3245
1142
  async function getNetworksHandler(c2) {
3246
1143
  try {
3247
1144
  const mastra = c2.get("mastra");
3248
- const networks = mastra.getNetworks();
3249
- const serializedNetworks = networks.map((network) => {
3250
- const routingAgent = network.getRoutingAgent();
3251
- const agents = network.getAgents();
3252
- return {
3253
- id: network.formatAgentId(routingAgent.name),
3254
- name: routingAgent.name,
3255
- instructions: routingAgent.instructions,
3256
- agents: agents.map((agent) => ({
3257
- name: agent.name,
3258
- provider: agent.llm?.getProvider(),
3259
- modelId: agent.llm?.getModelId()
3260
- })),
3261
- routingModel: {
3262
- provider: routingAgent.llm?.getProvider(),
3263
- modelId: routingAgent.llm?.getModelId()
3264
- }
3265
- };
1145
+ const networks = await getNetworksHandler$1({
1146
+ mastra
3266
1147
  });
3267
- return c2.json(serializedNetworks);
3268
- } catch (error2) {
3269
- return handleError(error2, "Error getting networks");
1148
+ return c2.json(networks);
1149
+ } catch (error) {
1150
+ return handleError(error, "Error getting networks");
3270
1151
  }
3271
1152
  }
3272
1153
  async function getNetworkByIdHandler(c2) {
3273
1154
  try {
3274
1155
  const mastra = c2.get("mastra");
3275
1156
  const networkId = c2.req.param("networkId");
3276
- const networks = mastra.getNetworks();
3277
- const network = networks.find((network2) => {
3278
- const routingAgent2 = network2.getRoutingAgent();
3279
- return network2.formatAgentId(routingAgent2.name) === networkId;
1157
+ const network = await getNetworkByIdHandler$1({
1158
+ mastra,
1159
+ networkId
3280
1160
  });
3281
- if (!network) {
3282
- return c2.json({ error: "Network not found" }, 404);
3283
- }
3284
- const routingAgent = network.getRoutingAgent();
3285
- const agents = network.getAgents();
3286
- const serializedNetwork = {
3287
- id: network.formatAgentId(routingAgent.name),
3288
- name: routingAgent.name,
3289
- instructions: routingAgent.instructions,
3290
- agents: agents.map((agent) => ({
3291
- name: agent.name,
3292
- provider: agent.llm?.getProvider(),
3293
- modelId: agent.llm?.getModelId()
3294
- })),
3295
- routingModel: {
3296
- provider: routingAgent.llm?.getProvider(),
3297
- modelId: routingAgent.llm?.getModelId()
3298
- }
3299
- };
3300
- return c2.json(serializedNetwork);
3301
- } catch (error2) {
3302
- return handleError(error2, "Error getting network by ID");
1161
+ return c2.json(network);
1162
+ } catch (error) {
1163
+ return handleError(error, "Error getting network by ID");
3303
1164
  }
3304
1165
  }
3305
1166
  async function generateHandler2(c2) {
3306
1167
  try {
3307
1168
  const mastra = c2.get("mastra");
3308
1169
  const networkId = c2.req.param("networkId");
3309
- const network = mastra.getNetwork(networkId);
3310
- if (!network) {
3311
- throw new HTTPException(404, { message: "Network not found" });
3312
- }
3313
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
3314
- validateBody({ messages });
3315
- const finalResourceId = resourceId ?? resourceid;
3316
- const result = await network.generate(messages, { threadId, resourceId: finalResourceId, output, runId, ...rest });
1170
+ const body = await c2.req.json();
1171
+ const result = await generateHandler$1({
1172
+ mastra,
1173
+ networkId,
1174
+ body
1175
+ });
3317
1176
  return c2.json(result);
3318
- } catch (error2) {
3319
- return handleError(error2, "Error generating from network");
1177
+ } catch (error) {
1178
+ return handleError(error, "Error generating from network");
3320
1179
  }
3321
1180
  }
3322
1181
  async function streamGenerateHandler2(c2) {
3323
1182
  try {
3324
1183
  const mastra = c2.get("mastra");
3325
1184
  const networkId = c2.req.param("networkId");
3326
- const network = mastra.getNetwork(networkId);
3327
- if (!network) {
3328
- throw new HTTPException(404, { message: "Network not found" });
3329
- }
3330
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
3331
- validateBody({ messages });
3332
- const finalResourceId = resourceId ?? resourceid;
3333
- const streamResult = await network.stream(messages, {
3334
- threadId,
3335
- resourceId: finalResourceId,
3336
- output,
3337
- runId,
3338
- ...rest
3339
- });
3340
- const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
3341
- sendUsage: true,
3342
- sendReasoning: true,
3343
- getErrorMessage: (error2) => {
3344
- return `An error occurred while processing your request. ${error2 instanceof Error ? error2.message : JSON.stringify(error2)}`;
3345
- }
1185
+ const body = await c2.req.json();
1186
+ const streamResponse = await streamGenerateHandler$1({
1187
+ mastra,
1188
+ networkId,
1189
+ body
3346
1190
  });
3347
1191
  return streamResponse;
3348
- } catch (error2) {
3349
- return handleError(error2, "Error streaming from network");
1192
+ } catch (error) {
1193
+ return handleError(error, "Error streaming from network");
3350
1194
  }
3351
1195
  }
3352
1196
  async function generateSystemPromptHandler(c2) {
@@ -3382,8 +1226,8 @@ async function generateSystemPromptHandler(c2) {
3382
1226
 
3383
1227
  `
3384
1228
  ).join("");
3385
- } catch (error2) {
3386
- mastra.getLogger().error(`Error fetching evals`, { error: error2 });
1229
+ } catch (error) {
1230
+ mastra.getLogger().error(`Error fetching evals`, { error });
3387
1231
  }
3388
1232
  const ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `
3389
1233
  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.
@@ -3454,8 +1298,8 @@ ${evalSummary}` : ""}
3454
1298
  }
3455
1299
  );
3456
1300
  return c2.json(result?.object || {});
3457
- } catch (error2) {
3458
- return handleError(error2, "Error generating system prompt");
1301
+ } catch (error) {
1302
+ return handleError(error, "Error generating system prompt");
3459
1303
  }
3460
1304
  }
3461
1305
 
@@ -3466,189 +1310,68 @@ async function rootHandler(c2) {
3466
1310
  async function getTelemetryHandler(c2) {
3467
1311
  try {
3468
1312
  const mastra = c2.get("mastra");
3469
- const telemetry = mastra.getTelemetry();
3470
- const storage = mastra.getStorage();
3471
1313
  const { name, scope, page, perPage } = c2.req.query();
3472
1314
  const attribute = c2.req.queries("attribute");
3473
- if (!telemetry) {
3474
- throw new HTTPException(400, { message: "Telemetry is not initialized" });
3475
- }
3476
- if (!storage) {
3477
- throw new HTTPException(400, { message: "Storage is not initialized" });
3478
- }
3479
- const attributes = attribute ? Object.fromEntries(
3480
- (Array.isArray(attribute) ? attribute : [attribute]).map((attr) => {
3481
- const [key, value] = attr.split(":");
3482
- return [key, value];
3483
- })
3484
- ) : void 0;
3485
- const traces = await storage.getTraces({
3486
- name,
3487
- scope,
3488
- page: Number(page ?? 0),
3489
- perPage: Number(perPage ?? 100),
3490
- attributes
1315
+ const traces = await getTelemetryHandler$1({
1316
+ mastra,
1317
+ body: { name, scope, page: Number(page ?? 0), perPage: Number(perPage ?? 100), attribute }
3491
1318
  });
3492
1319
  return c2.json({ traces });
3493
- } catch (error2) {
3494
- return handleError(error2, "Error saving messages");
1320
+ } catch (error) {
1321
+ return handleError(error, "Error getting telemetry traces");
3495
1322
  }
3496
1323
  }
3497
1324
  async function storeTelemetryHandler(c2) {
3498
1325
  try {
3499
1326
  const body = await c2.req.json();
3500
1327
  const mastra = c2.get("mastra");
3501
- const storage = mastra.getStorage();
3502
- const now = /* @__PURE__ */ new Date();
3503
- const items = body?.resourceSpans?.[0]?.scopeSpans;
3504
- const allSpans = items.reduce((acc, scopedSpans) => {
3505
- const { scope, spans } = scopedSpans;
3506
- for (const span of spans) {
3507
- const {
3508
- spanId,
3509
- parentSpanId,
3510
- traceId,
3511
- name,
3512
- kind,
3513
- attributes,
3514
- status,
3515
- events,
3516
- links,
3517
- startTimeUnixNano,
3518
- endTimeUnixNano,
3519
- ...rest
3520
- } = span;
3521
- const startTime = Number(BigInt(startTimeUnixNano) / 1000n);
3522
- const endTime = Number(BigInt(endTimeUnixNano) / 1000n);
3523
- acc.push({
3524
- id: spanId,
3525
- parentSpanId,
3526
- traceId,
3527
- name,
3528
- scope: scope.name,
3529
- kind,
3530
- status: JSON.stringify(status),
3531
- events: JSON.stringify(events),
3532
- links: JSON.stringify(links),
3533
- attributes: JSON.stringify(
3534
- attributes.reduce((acc2, attr) => {
3535
- const valueKey = Object.keys(attr.value)[0];
3536
- if (valueKey) {
3537
- acc2[attr.key] = attr.value[valueKey];
3538
- }
3539
- return acc2;
3540
- }, {})
3541
- ),
3542
- startTime,
3543
- endTime,
3544
- other: JSON.stringify(rest),
3545
- createdAt: now
3546
- });
3547
- }
3548
- return acc;
3549
- }, []);
3550
- return storage.__batchInsert({
3551
- tableName: TABLE_TRACES,
3552
- records: allSpans
3553
- }).then(() => {
3554
- return c2.json(
3555
- {
3556
- status: "success",
3557
- message: "Traces received and processed successfully",
3558
- traceCount: body.resourceSpans?.length || 0
3559
- },
3560
- 200
3561
- );
3562
- }).catch((e2) => {
3563
- return c2.json(
3564
- {
3565
- status: "error",
3566
- message: "Failed to process traces",
3567
- // @ts-ignore
3568
- error: error.message
3569
- },
3570
- 500
3571
- );
3572
- });
3573
- } catch (error2) {
3574
- console.error("Error processing traces:", error2);
3575
- return c2.json(
3576
- {
3577
- status: "error",
3578
- message: "Failed to process traces",
3579
- // @ts-ignore
3580
- error: error2.message
3581
- },
3582
- 500
3583
- );
1328
+ const result = await storeTelemetryHandler$1({ mastra, body });
1329
+ if (result.status === "error") {
1330
+ return c2.json(result, 500);
1331
+ }
1332
+ return c2.json(result, 200);
1333
+ } catch (error) {
1334
+ return handleError(error, "Error storing telemetry traces");
3584
1335
  }
3585
1336
  }
3586
1337
  async function getToolsHandler(c2) {
3587
1338
  try {
3588
1339
  const tools = c2.get("tools");
3589
- if (!tools) {
3590
- return c2.json({});
3591
- }
3592
- const serializedTools = Object.entries(tools).reduce(
3593
- (acc, [id, _tool]) => {
3594
- const tool = _tool;
3595
- acc[id] = {
3596
- ...tool,
3597
- inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3598
- outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3599
- };
3600
- return acc;
3601
- },
3602
- {}
3603
- );
3604
- return c2.json(serializedTools);
3605
- } catch (error2) {
3606
- return handleError(error2, "Error getting tools");
1340
+ const result = await getToolsHandler$1({
1341
+ tools
1342
+ });
1343
+ return c2.json(result);
1344
+ } catch (error) {
1345
+ return handleError(error, "Error getting tools");
3607
1346
  }
3608
1347
  }
3609
1348
  async function getToolByIdHandler(c2) {
3610
1349
  try {
3611
1350
  const tools = c2.get("tools");
3612
1351
  const toolId = c2.req.param("toolId");
3613
- const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3614
- if (!tool) {
3615
- throw new HTTPException(404, { message: "Tool not found" });
3616
- }
3617
- const serializedTool = {
3618
- ...tool,
3619
- inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3620
- outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3621
- };
3622
- return c2.json(serializedTool);
3623
- } catch (error2) {
3624
- return handleError(error2, "Error getting tool");
1352
+ const result = await getToolByIdHandler$1({
1353
+ tools,
1354
+ toolId
1355
+ });
1356
+ return c2.json(result);
1357
+ } catch (error) {
1358
+ return handleError(error, "Error getting tool");
3625
1359
  }
3626
1360
  }
3627
1361
  function executeToolHandler(tools) {
3628
1362
  return async (c2) => {
3629
1363
  try {
1364
+ const mastra = c2.get("mastra");
3630
1365
  const toolId = decodeURIComponent(c2.req.param("toolId"));
3631
- const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3632
- if (!tool) {
3633
- return c2.json({ error: "Tool not found" }, 404);
3634
- }
3635
- if (!tool?.execute) {
3636
- return c2.json({ error: "Tool is not executable" }, 400);
3637
- }
3638
1366
  const { data } = await c2.req.json();
3639
- const mastra = c2.get("mastra");
3640
- if (isVercelTool(tool)) {
3641
- const result2 = await tool.execute(data);
3642
- return c2.json(result2);
3643
- }
3644
- const result = await tool.execute({
3645
- context: data,
1367
+ const result = await executeToolHandler$1(tools)({
3646
1368
  mastra,
3647
- runId: mastra.runId
1369
+ toolId,
1370
+ data
3648
1371
  });
3649
1372
  return c2.json(result);
3650
- } catch (error2) {
3651
- return handleError(error2, "Error executing tool");
1373
+ } catch (error) {
1374
+ return handleError(error, "Error executing tool");
3652
1375
  }
3653
1376
  };
3654
1377
  }
@@ -3657,175 +1380,150 @@ async function executeAgentToolHandler(c2) {
3657
1380
  const mastra = c2.get("mastra");
3658
1381
  const agentId = c2.req.param("agentId");
3659
1382
  const toolId = c2.req.param("toolId");
3660
- const agent = mastra.getAgent(agentId);
3661
- const tool = Object.values(agent?.tools || {}).find((tool2) => tool2.id === toolId);
3662
- if (!tool) {
3663
- throw new HTTPException(404, { message: "Tool not found" });
3664
- }
3665
- if (!tool?.execute) {
3666
- return c2.json({ error: "Tool is not executable" }, 400);
3667
- }
3668
1383
  const { data } = await c2.req.json();
3669
- if (isVercelTool(tool)) {
3670
- const result2 = await tool.execute(data);
3671
- return c2.json(result2);
3672
- }
3673
- const result = await tool.execute({
3674
- context: data,
1384
+ const result = await executeAgentToolHandler$1({
3675
1385
  mastra,
3676
- runId: agentId
1386
+ agentId,
1387
+ toolId,
1388
+ data
3677
1389
  });
3678
1390
  return c2.json(result);
3679
- } catch (error2) {
3680
- return handleError(error2, "Error executing tool");
1391
+ } catch (error) {
1392
+ return handleError(error, "Error executing tool");
3681
1393
  }
3682
1394
  }
3683
- var getVector = (c2, vectorName) => {
3684
- const vector = c2.get("mastra").getVector(vectorName);
3685
- if (!vector) {
3686
- throw new HTTPException(404, { message: `Vector store ${vectorName} not found` });
3687
- }
3688
- return vector;
3689
- };
3690
1395
  async function upsertVectors(c2) {
3691
1396
  try {
1397
+ const mastra = c2.get("mastra");
3692
1398
  const vectorName = c2.req.param("vectorName");
3693
- const { indexName, vectors, metadata, ids } = await c2.req.json();
3694
- if (!indexName || !vectors || !Array.isArray(vectors)) {
3695
- throw new HTTPException(400, { message: "Invalid request body. indexName and vectors array are required." });
3696
- }
3697
- const vector = getVector(c2, vectorName);
3698
- const result = await vector.upsert({ indexName, vectors, metadata, ids });
1399
+ const body = await c2.req.json();
1400
+ const result = await upsertVectors$1({
1401
+ mastra,
1402
+ vectorName,
1403
+ index: body
1404
+ });
3699
1405
  return c2.json({ ids: result });
3700
- } catch (error2) {
3701
- return handleError(error2, "Error upserting vectors");
1406
+ } catch (error) {
1407
+ return handleError(error, "Error upserting vectors");
3702
1408
  }
3703
1409
  }
3704
1410
  async function createIndex(c2) {
3705
1411
  try {
1412
+ const mastra = c2.get("mastra");
3706
1413
  const vectorName = c2.req.param("vectorName");
3707
- const { indexName, dimension, metric } = await c2.req.json();
3708
- if (!indexName || typeof dimension !== "number" || dimension <= 0) {
3709
- throw new HTTPException(400, {
3710
- message: "Invalid request body. indexName and positive dimension number are required."
3711
- });
3712
- }
3713
- if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
3714
- throw new HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
3715
- }
3716
- const vector = getVector(c2, vectorName);
3717
- await vector.createIndex({ indexName, dimension, metric });
1414
+ const body = await c2.req.json();
1415
+ await createIndex$1({
1416
+ mastra,
1417
+ vectorName,
1418
+ index: body
1419
+ });
3718
1420
  return c2.json({ success: true });
3719
- } catch (error2) {
3720
- return handleError(error2, "Error creating index");
1421
+ } catch (error) {
1422
+ return handleError(error, "Error creating index");
3721
1423
  }
3722
1424
  }
3723
1425
  async function queryVectors(c2) {
3724
1426
  try {
1427
+ const mastra = c2.get("mastra");
3725
1428
  const vectorName = c2.req.param("vectorName");
3726
1429
  const { indexName, queryVector, topK = 10, filter, includeVector = false } = await c2.req.json();
3727
- if (!indexName || !queryVector || !Array.isArray(queryVector)) {
3728
- throw new HTTPException(400, { message: "Invalid request body. indexName and queryVector array are required." });
3729
- }
3730
- const vector = getVector(c2, vectorName);
3731
- const results = await vector.query({ indexName, queryVector, topK, filter, includeVector });
1430
+ const results = await queryVectors$1({
1431
+ mastra,
1432
+ vectorName,
1433
+ query: { indexName, queryVector, topK, filter, includeVector }
1434
+ });
3732
1435
  return c2.json({ results });
3733
- } catch (error2) {
3734
- return handleError(error2, "Error querying vectors");
1436
+ } catch (error) {
1437
+ return handleError(error, "Error querying vectors");
3735
1438
  }
3736
1439
  }
3737
1440
  async function listIndexes(c2) {
3738
1441
  try {
1442
+ const mastra = c2.get("mastra");
3739
1443
  const vectorName = c2.req.param("vectorName");
3740
- const vector = getVector(c2, vectorName);
3741
- const indexes = await vector.listIndexes();
3742
- return c2.json({ indexes: indexes.filter(Boolean) });
3743
- } catch (error2) {
3744
- return handleError(error2, "Error listing indexes");
1444
+ const indexes = await listIndexes$1({
1445
+ mastra,
1446
+ vectorName
1447
+ });
1448
+ return c2.json({ indexes });
1449
+ } catch (error) {
1450
+ return handleError(error, "Error listing indexes");
3745
1451
  }
3746
1452
  }
3747
1453
  async function describeIndex(c2) {
3748
1454
  try {
1455
+ const mastra = c2.get("mastra");
3749
1456
  const vectorName = c2.req.param("vectorName");
3750
1457
  const indexName = c2.req.param("indexName");
3751
1458
  if (!indexName) {
3752
1459
  throw new HTTPException(400, { message: "Index name is required" });
3753
1460
  }
3754
- const vector = getVector(c2, vectorName);
3755
- const stats = await vector.describeIndex(indexName);
1461
+ const stats = await describeIndex$1({
1462
+ mastra,
1463
+ vectorName,
1464
+ indexName
1465
+ });
3756
1466
  return c2.json({
3757
1467
  dimension: stats.dimension,
3758
1468
  count: stats.count,
3759
1469
  metric: stats.metric?.toLowerCase()
3760
1470
  });
3761
- } catch (error2) {
3762
- return handleError(error2, "Error describing index");
1471
+ } catch (error) {
1472
+ return handleError(error, "Error describing index");
3763
1473
  }
3764
1474
  }
3765
1475
  async function deleteIndex(c2) {
3766
1476
  try {
1477
+ const mastra = c2.get("mastra");
3767
1478
  const vectorName = c2.req.param("vectorName");
3768
1479
  const indexName = c2.req.param("indexName");
3769
1480
  if (!indexName) {
3770
1481
  throw new HTTPException(400, { message: "Index name is required" });
3771
1482
  }
3772
- const vector = getVector(c2, vectorName);
3773
- await vector.deleteIndex(indexName);
1483
+ await deleteIndex$1({
1484
+ mastra,
1485
+ vectorName,
1486
+ indexName
1487
+ });
3774
1488
  return c2.json({ success: true });
3775
- } catch (error2) {
3776
- return handleError(error2, "Error deleting index");
1489
+ } catch (error) {
1490
+ return handleError(error, "Error deleting index");
3777
1491
  }
3778
1492
  }
3779
1493
  async function getSpeakersHandler(c2) {
3780
1494
  try {
3781
1495
  const mastra = c2.get("mastra");
3782
1496
  const agentId = c2.req.param("agentId");
3783
- const agent = mastra.getAgent(agentId);
3784
- if (!agent) {
3785
- throw new HTTPException(404, { message: "Agent not found" });
3786
- }
3787
- if (!agent.voice) {
3788
- throw new HTTPException(400, { message: "Agent does not have voice capabilities" });
3789
- }
3790
- const speakers = await agent.getSpeakers();
1497
+ const speakers = await getSpeakersHandler$1({
1498
+ mastra,
1499
+ agentId
1500
+ });
3791
1501
  return c2.json(speakers);
3792
- } catch (error2) {
3793
- return handleError(error2, "Error getting speakers");
1502
+ } catch (error) {
1503
+ return handleError(error, "Error getting speakers");
3794
1504
  }
3795
1505
  }
3796
1506
  async function speakHandler(c2) {
3797
1507
  try {
3798
1508
  const mastra = c2.get("mastra");
3799
1509
  const agentId = c2.req.param("agentId");
3800
- const agent = mastra.getAgent(agentId);
3801
- if (!agent) {
3802
- throw new HTTPException(404, { message: "Agent not found" });
3803
- }
3804
- if (!agent.voice) {
3805
- throw new HTTPException(400, { message: "Agent does not have voice capabilities" });
3806
- }
3807
1510
  const { input, options } = await c2.req.json();
3808
- await validateBody({ input });
3809
- const audioStream = await agent.voice.speak(input, options);
1511
+ const audioStream = await generateSpeechHandler({
1512
+ mastra,
1513
+ agentId,
1514
+ body: { text: input, speakerId: options?.speakerId }
1515
+ });
3810
1516
  c2.header("Content-Type", `audio/${options?.filetype ?? "mp3"}`);
3811
1517
  c2.header("Transfer-Encoding", "chunked");
3812
1518
  return c2.body(audioStream);
3813
- } catch (error2) {
3814
- return handleError(error2, "Error generating speech");
1519
+ } catch (error) {
1520
+ return handleError(error, "Error generating speech");
3815
1521
  }
3816
1522
  }
3817
1523
  async function listenHandler(c2) {
3818
1524
  try {
3819
1525
  const mastra = c2.get("mastra");
3820
1526
  const agentId = c2.req.param("agentId");
3821
- const agent = mastra.getAgent(agentId);
3822
- const logger2 = mastra.getLogger();
3823
- if (!agent) {
3824
- throw new HTTPException(404, { message: "Agent not found" });
3825
- }
3826
- if (!agent.voice) {
3827
- throw new HTTPException(400, { message: "Agent does not have voice capabilities" });
3828
- }
3829
1527
  const formData = await c2.req.formData();
3830
1528
  const audioFile = formData.get("audio");
3831
1529
  const options = formData.get("options");
@@ -3833,115 +1531,76 @@ async function listenHandler(c2) {
3833
1531
  throw new HTTPException(400, { message: "Audio file is required" });
3834
1532
  }
3835
1533
  const audioData = await audioFile.arrayBuffer();
3836
- const audioStream = new Readable();
3837
- audioStream.push(Buffer.from(audioData));
3838
- audioStream.push(null);
3839
- let parsedOptions;
1534
+ let parsedOptions = {};
3840
1535
  try {
3841
1536
  parsedOptions = options ? JSON.parse(options) : {};
3842
- } catch (error2) {
3843
- if (error2 instanceof SyntaxError) {
3844
- logger2.error("Invalid JSON in options:", error2);
3845
- }
3846
- parsedOptions = {};
1537
+ } catch {
3847
1538
  }
3848
- const transcription = await agent.voice.listen(audioStream, parsedOptions);
1539
+ const transcription = await transcribeSpeechHandler({
1540
+ mastra,
1541
+ agentId,
1542
+ body: {
1543
+ audioData: Buffer.from(audioData),
1544
+ options: parsedOptions
1545
+ }
1546
+ });
3849
1547
  return c2.json({ text: transcription });
3850
- } catch (error2) {
3851
- return handleError(error2, "Error transcribing speech");
1548
+ } catch (error) {
1549
+ return handleError(error, "Error transcribing speech");
3852
1550
  }
3853
1551
  }
3854
1552
  async function getWorkflowsHandler(c2) {
3855
1553
  try {
3856
1554
  const mastra = c2.get("mastra");
3857
- const workflows = mastra.getWorkflows({ serialized: false });
3858
- const _workflows = Object.entries(workflows).reduce((acc, [key, workflow]) => {
3859
- acc[key] = {
3860
- stepGraph: workflow.stepGraph,
3861
- stepSubscriberGraph: workflow.stepSubscriberGraph,
3862
- serializedStepGraph: workflow.serializedStepGraph,
3863
- serializedStepSubscriberGraph: workflow.serializedStepSubscriberGraph,
3864
- name: workflow.name,
3865
- triggerSchema: workflow.triggerSchema ? stringify(esm_default(workflow.triggerSchema)) : void 0,
3866
- steps: Object.entries(workflow.steps).reduce((acc2, [key2, step]) => {
3867
- const _step = step;
3868
- acc2[key2] = {
3869
- ..._step,
3870
- inputSchema: _step.inputSchema ? stringify(esm_default(_step.inputSchema)) : void 0,
3871
- outputSchema: _step.outputSchema ? stringify(esm_default(_step.outputSchema)) : void 0
3872
- };
3873
- return acc2;
3874
- }, {})
3875
- };
3876
- return acc;
3877
- }, {});
3878
- return c2.json(_workflows);
3879
- } catch (error2) {
3880
- return handleError(error2, "Error getting workflows");
1555
+ const workflows = await getWorkflowsHandler$1({
1556
+ mastra
1557
+ });
1558
+ return c2.json(workflows);
1559
+ } catch (error) {
1560
+ return handleError(error, "Error getting workflows");
3881
1561
  }
3882
1562
  }
3883
1563
  async function getWorkflowByIdHandler(c2) {
3884
1564
  try {
3885
1565
  const mastra = c2.get("mastra");
3886
1566
  const workflowId = c2.req.param("workflowId");
3887
- const workflow = mastra.getWorkflow(workflowId);
3888
- const triggerSchema = workflow?.triggerSchema;
3889
- const stepGraph = workflow.stepGraph;
3890
- const stepSubscriberGraph = workflow.stepSubscriberGraph;
3891
- const serializedStepGraph = workflow.serializedStepGraph;
3892
- const serializedStepSubscriberGraph = workflow.serializedStepSubscriberGraph;
3893
- const serializedSteps = Object.entries(workflow.steps).reduce((acc, [key, step]) => {
3894
- const _step = step;
3895
- acc[key] = {
3896
- ..._step,
3897
- inputSchema: _step.inputSchema ? stringify(esm_default(_step.inputSchema)) : void 0,
3898
- outputSchema: _step.outputSchema ? stringify(esm_default(_step.outputSchema)) : void 0
3899
- };
3900
- return acc;
3901
- }, {});
3902
- return c2.json({
3903
- name: workflow.name,
3904
- triggerSchema: triggerSchema ? stringify(esm_default(triggerSchema)) : void 0,
3905
- steps: serializedSteps,
3906
- stepGraph,
3907
- stepSubscriberGraph,
3908
- serializedStepGraph,
3909
- serializedStepSubscriberGraph
1567
+ const workflow = await getWorkflowByIdHandler$1({
1568
+ mastra,
1569
+ workflowId
3910
1570
  });
3911
- } catch (error2) {
3912
- return handleError(error2, "Error getting workflow");
1571
+ return c2.json(workflow);
1572
+ } catch (error) {
1573
+ return handleError(error, "Error getting workflow");
3913
1574
  }
3914
1575
  }
3915
1576
  async function startAsyncWorkflowHandler(c2) {
3916
1577
  try {
3917
1578
  const mastra = c2.get("mastra");
3918
1579
  const workflowId = c2.req.param("workflowId");
3919
- const workflow = mastra.getWorkflow(workflowId);
3920
- const body = await c2.req.json();
1580
+ const triggerData = await c2.req.json();
3921
1581
  const runId = c2.req.query("runId");
3922
- if (!runId) {
3923
- throw new HTTPException(400, { message: "runId required to start run" });
3924
- }
3925
- const run = workflow.getRun(runId);
3926
- if (!run) {
3927
- throw new HTTPException(404, { message: "Workflow run not found" });
3928
- }
3929
- const result = await run.start({
3930
- triggerData: body
1582
+ const result = await startAsyncWorkflowHandler$1({
1583
+ mastra,
1584
+ workflowId,
1585
+ runId,
1586
+ triggerData
3931
1587
  });
3932
1588
  return c2.json(result);
3933
- } catch (error2) {
3934
- return handleError(error2, "Error executing workflow");
1589
+ } catch (error) {
1590
+ return handleError(error, "Error executing workflow");
3935
1591
  }
3936
1592
  }
3937
1593
  async function createRunHandler(c2) {
3938
1594
  try {
3939
1595
  const mastra = c2.get("mastra");
3940
1596
  const workflowId = c2.req.param("workflowId");
3941
- const workflow = mastra.getWorkflow(workflowId);
3942
1597
  const prevRunId = c2.req.query("runId");
3943
- const { runId } = workflow.createRun({ runId: prevRunId });
3944
- return c2.json({ runId });
1598
+ const result = await createRunHandler$1({
1599
+ mastra,
1600
+ workflowId,
1601
+ runId: prevRunId
1602
+ });
1603
+ return c2.json(result);
3945
1604
  } catch (e2) {
3946
1605
  return handleError(e2, "Error creating run");
3947
1606
  }
@@ -3950,105 +1609,95 @@ async function startWorkflowRunHandler(c2) {
3950
1609
  try {
3951
1610
  const mastra = c2.get("mastra");
3952
1611
  const workflowId = c2.req.param("workflowId");
3953
- const workflow = mastra.getWorkflow(workflowId);
3954
- const body = await c2.req.json();
1612
+ const triggerData = await c2.req.json();
3955
1613
  const runId = c2.req.query("runId");
3956
- if (!runId) {
3957
- throw new HTTPException(400, { message: "runId required to start run" });
3958
- }
3959
- const run = workflow.getRun(runId);
3960
- if (!run) {
3961
- throw new HTTPException(404, { message: "Workflow run not found" });
3962
- }
3963
- run.start({
3964
- triggerData: body
1614
+ await startWorkflowRunHandler$1({
1615
+ mastra,
1616
+ workflowId,
1617
+ runId,
1618
+ triggerData
3965
1619
  });
3966
1620
  return c2.json({ message: "Workflow run started" });
3967
1621
  } catch (e2) {
3968
1622
  return handleError(e2, "Error starting workflow run");
3969
1623
  }
3970
1624
  }
3971
- async function watchWorkflowHandler(c2) {
1625
+ function watchWorkflowHandler(c2) {
3972
1626
  try {
3973
1627
  const mastra = c2.get("mastra");
3974
1628
  const logger2 = mastra.getLogger();
3975
1629
  const workflowId = c2.req.param("workflowId");
3976
- const workflow = mastra.getWorkflow(workflowId);
3977
1630
  const runId = c2.req.query("runId");
3978
1631
  if (!runId) {
3979
1632
  throw new HTTPException(400, { message: "runId required to watch workflow" });
3980
1633
  }
3981
- const run = workflow.getRun(runId);
3982
- if (!run) {
3983
- throw new HTTPException(404, { message: "Workflow run not found" });
3984
- }
3985
- return streamText(
1634
+ return stream(
3986
1635
  c2,
3987
- async (stream) => {
3988
- return new Promise((_resolve, _reject) => {
3989
- let unwatch = run.watch(({ activePaths, runId: runId2, timestamp, results }) => {
3990
- const activePathsObj = Object.fromEntries(activePaths);
3991
- void stream.write(JSON.stringify({ activePaths: activePathsObj, runId: runId2, timestamp, results }) + "");
1636
+ async (stream2) => {
1637
+ try {
1638
+ const result = await watchWorkflowHandler$1({
1639
+ mastra,
1640
+ workflowId,
1641
+ runId
3992
1642
  });
3993
- stream.onAbort(() => {
3994
- unwatch?.();
1643
+ stream2.onAbort(() => {
1644
+ if (!result.locked) {
1645
+ return result.cancel();
1646
+ }
3995
1647
  });
3996
- });
1648
+ for await (const chunk of result) {
1649
+ await stream2.write(chunk.toString() + "");
1650
+ }
1651
+ } catch (err) {
1652
+ console.log(err);
1653
+ }
3997
1654
  },
3998
- async (err, stream) => {
1655
+ async (err) => {
3999
1656
  logger2.error("Error in watch stream: " + err?.message);
4000
- stream.abort();
4001
- await stream.close();
4002
1657
  }
4003
1658
  );
4004
- } catch (error2) {
4005
- return handleError(error2, "Error watching workflow");
1659
+ } catch (error) {
1660
+ return handleError(error, "Error watching workflow");
4006
1661
  }
4007
1662
  }
4008
1663
  async function resumeAsyncWorkflowHandler(c2) {
4009
1664
  try {
4010
1665
  const mastra = c2.get("mastra");
4011
1666
  const workflowId = c2.req.param("workflowId");
4012
- const workflow = mastra.getWorkflow(workflowId);
4013
1667
  const runId = c2.req.query("runId");
4014
1668
  const { stepId, context } = await c2.req.json();
4015
1669
  if (!runId) {
4016
1670
  throw new HTTPException(400, { message: "runId required to resume workflow" });
4017
1671
  }
4018
- const run = workflow.getRun(runId);
4019
- if (!run) {
4020
- throw new HTTPException(404, { message: "Workflow run not found" });
4021
- }
4022
- const result = await run.resume({
4023
- stepId,
4024
- context
1672
+ const result = await resumeAsyncWorkflowHandler$1({
1673
+ mastra,
1674
+ workflowId,
1675
+ runId,
1676
+ body: { stepId, context }
4025
1677
  });
4026
1678
  return c2.json(result);
4027
- } catch (error2) {
4028
- return handleError(error2, "Error resuming workflow step");
1679
+ } catch (error) {
1680
+ return handleError(error, "Error resuming workflow step");
4029
1681
  }
4030
1682
  }
4031
1683
  async function resumeWorkflowHandler(c2) {
4032
1684
  try {
4033
1685
  const mastra = c2.get("mastra");
4034
1686
  const workflowId = c2.req.param("workflowId");
4035
- const workflow = mastra.getWorkflow(workflowId);
4036
1687
  const runId = c2.req.query("runId");
4037
1688
  const { stepId, context } = await c2.req.json();
4038
1689
  if (!runId) {
4039
1690
  throw new HTTPException(400, { message: "runId required to resume workflow" });
4040
1691
  }
4041
- const run = workflow.getRun(runId);
4042
- if (!run) {
4043
- throw new HTTPException(404, { message: "Workflow run not found" });
4044
- }
4045
- run.resume({
4046
- stepId,
4047
- context
1692
+ await resumeWorkflowHandler$1({
1693
+ mastra,
1694
+ workflowId,
1695
+ runId,
1696
+ body: { stepId, context }
4048
1697
  });
4049
1698
  return c2.json({ message: "Workflow run resumed" });
4050
- } catch (error2) {
4051
- return handleError(error2, "Error resuming workflow");
1699
+ } catch (error) {
1700
+ return handleError(error, "Error resuming workflow");
4052
1701
  }
4053
1702
  }
4054
1703
 
@@ -4199,7 +1848,23 @@ async function createHonoServer(mastra, options = {}) {
4199
1848
  c2.set("mastra", mastra);
4200
1849
  c2.set("tools", tools);
4201
1850
  c2.set("playground", options.playground === true);
4202
- await next();
1851
+ const requestId = c2.req.header("x-request-id") ?? randomUUID();
1852
+ const span = Telemetry.getActiveSpan();
1853
+ if (span) {
1854
+ span.setAttribute("http.request_id", requestId);
1855
+ span.updateName(`${c2.req.method} ${c2.req.path}`);
1856
+ const newCtx = Telemetry.setBaggage({
1857
+ "http.request_id": requestId
1858
+ });
1859
+ await new Promise((resolve) => {
1860
+ Telemetry.withContext(newCtx, async () => {
1861
+ await next();
1862
+ resolve(true);
1863
+ });
1864
+ });
1865
+ } else {
1866
+ await next();
1867
+ }
4203
1868
  });
4204
1869
  const bodyLimitOptions = {
4205
1870
  maxSize: 4.5 * 1024 * 1024,