@mastra/deployer 0.2.5 → 0.2.6-alpha.10

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