@mastra/ai-sdk 0.0.0-safe-stringify-telemetry-20251205024938 → 0.0.0-salesman-20260127182805
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.
- package/CHANGELOG.md +833 -145
- package/README.md +60 -0
- package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1719 -0
- package/dist/chat-route.d.ts +46 -8
- package/dist/chat-route.d.ts.map +1 -1
- package/dist/chunk-AAQDCHJY.js +293 -0
- package/dist/chunk-AAQDCHJY.js.map +1 -0
- package/dist/chunk-CCJXHQQO.cjs +296 -0
- package/dist/chunk-CCJXHQQO.cjs.map +1 -0
- package/dist/chunk-DES3K4SD.cjs +17 -0
- package/dist/chunk-DES3K4SD.cjs.map +1 -0
- package/dist/chunk-VUNV25KB.js +14 -0
- package/dist/chunk-VUNV25KB.js.map +1 -0
- package/dist/convert-messages.d.ts +90 -0
- package/dist/convert-messages.d.ts.map +1 -0
- package/dist/convert-streams.d.ts +82 -0
- package/dist/convert-streams.d.ts.map +1 -0
- package/dist/helpers.d.ts +10 -4
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.cjs +3547 -115
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3533 -125
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +157 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/network-route.d.ts +65 -5
- package/dist/network-route.d.ts.map +1 -1
- package/dist/to-ai-sdk-format.d.ts +11 -78
- package/dist/to-ai-sdk-format.d.ts.map +1 -1
- package/dist/token-36YTPVWD.cjs +63 -0
- package/dist/token-36YTPVWD.cjs.map +1 -0
- package/dist/token-ZFKXETJY.js +61 -0
- package/dist/token-ZFKXETJY.js.map +1 -0
- package/dist/token-util-737PGIQA.cjs +9 -0
- package/dist/token-util-737PGIQA.cjs.map +1 -0
- package/dist/token-util-SD2EI4DD.js +7 -0
- package/dist/token-util-SD2EI4DD.js.map +1 -0
- package/dist/transformers.d.ts +17 -15
- package/dist/transformers.d.ts.map +1 -1
- package/dist/ui.cjs +15 -0
- package/dist/ui.cjs.map +1 -0
- package/dist/ui.d.ts +2 -0
- package/dist/ui.d.ts.map +1 -0
- package/dist/ui.js +12 -0
- package/dist/ui.js.map +1 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/workflow-route.d.ts +65 -0
- package/dist/workflow-route.d.ts.map +1 -1
- package/package.json +25 -17
package/dist/index.js
CHANGED
|
@@ -1,8 +1,2803 @@
|
|
|
1
1
|
import { registerApiRoute } from '@mastra/core/server';
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
2
|
+
import * as z4 from 'zod/v4';
|
|
3
|
+
import { z } from 'zod/v4';
|
|
4
|
+
import { ZodFirstPartyTypeKind } from 'zod/v3';
|
|
5
|
+
import { TransformStream as TransformStream$1, ReadableStream as ReadableStream$1 } from 'stream/web';
|
|
6
|
+
import { convertFullStreamChunkToMastra, DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core/stream';
|
|
7
|
+
import { TripWire, MessageList, aiV5ModelMessageToV2PromptMessage } from '@mastra/core/agent';
|
|
8
|
+
import { RequestContext } from '@mastra/core/di';
|
|
9
|
+
import { WorkingMemory, MessageHistory, SemanticRecall } from '@mastra/core/processors';
|
|
4
10
|
|
|
5
|
-
//
|
|
11
|
+
// ../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
|
|
12
|
+
var marker = "vercel.ai.error";
|
|
13
|
+
var symbol = Symbol.for(marker);
|
|
14
|
+
var _a;
|
|
15
|
+
var _AISDKError = class _AISDKError2 extends Error {
|
|
16
|
+
/**
|
|
17
|
+
* Creates an AI SDK Error.
|
|
18
|
+
*
|
|
19
|
+
* @param {Object} params - The parameters for creating the error.
|
|
20
|
+
* @param {string} params.name - The name of the error.
|
|
21
|
+
* @param {string} params.message - The error message.
|
|
22
|
+
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
23
|
+
*/
|
|
24
|
+
constructor({
|
|
25
|
+
name: name143,
|
|
26
|
+
message,
|
|
27
|
+
cause
|
|
28
|
+
}) {
|
|
29
|
+
super(message);
|
|
30
|
+
this[_a] = true;
|
|
31
|
+
this.name = name143;
|
|
32
|
+
this.cause = cause;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Checks if the given error is an AI SDK Error.
|
|
36
|
+
* @param {unknown} error - The error to check.
|
|
37
|
+
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
38
|
+
*/
|
|
39
|
+
static isInstance(error) {
|
|
40
|
+
return _AISDKError2.hasMarker(error, marker);
|
|
41
|
+
}
|
|
42
|
+
static hasMarker(error, marker153) {
|
|
43
|
+
const markerSymbol = Symbol.for(marker153);
|
|
44
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
_a = symbol;
|
|
48
|
+
var AISDKError = _AISDKError;
|
|
49
|
+
function getErrorMessage(error) {
|
|
50
|
+
if (error == null) {
|
|
51
|
+
return "unknown error";
|
|
52
|
+
}
|
|
53
|
+
if (typeof error === "string") {
|
|
54
|
+
return error;
|
|
55
|
+
}
|
|
56
|
+
if (error instanceof Error) {
|
|
57
|
+
return error.message;
|
|
58
|
+
}
|
|
59
|
+
return JSON.stringify(error);
|
|
60
|
+
}
|
|
61
|
+
var name3 = "AI_InvalidArgumentError";
|
|
62
|
+
var marker4 = `vercel.ai.error.${name3}`;
|
|
63
|
+
var symbol4 = Symbol.for(marker4);
|
|
64
|
+
var _a4;
|
|
65
|
+
var InvalidArgumentError = class extends AISDKError {
|
|
66
|
+
constructor({
|
|
67
|
+
message,
|
|
68
|
+
cause,
|
|
69
|
+
argument
|
|
70
|
+
}) {
|
|
71
|
+
super({ name: name3, message, cause });
|
|
72
|
+
this[_a4] = true;
|
|
73
|
+
this.argument = argument;
|
|
74
|
+
}
|
|
75
|
+
static isInstance(error) {
|
|
76
|
+
return AISDKError.hasMarker(error, marker4);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
_a4 = symbol4;
|
|
80
|
+
var name6 = "AI_JSONParseError";
|
|
81
|
+
var marker7 = `vercel.ai.error.${name6}`;
|
|
82
|
+
var symbol7 = Symbol.for(marker7);
|
|
83
|
+
var _a7;
|
|
84
|
+
var JSONParseError = class extends AISDKError {
|
|
85
|
+
constructor({ text: text2, cause }) {
|
|
86
|
+
super({
|
|
87
|
+
name: name6,
|
|
88
|
+
message: `JSON parsing failed: Text: ${text2}.
|
|
89
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
90
|
+
cause
|
|
91
|
+
});
|
|
92
|
+
this[_a7] = true;
|
|
93
|
+
this.text = text2;
|
|
94
|
+
}
|
|
95
|
+
static isInstance(error) {
|
|
96
|
+
return AISDKError.hasMarker(error, marker7);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
_a7 = symbol7;
|
|
100
|
+
var name12 = "AI_TypeValidationError";
|
|
101
|
+
var marker13 = `vercel.ai.error.${name12}`;
|
|
102
|
+
var symbol13 = Symbol.for(marker13);
|
|
103
|
+
var _a13;
|
|
104
|
+
var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
|
|
105
|
+
constructor({ value, cause }) {
|
|
106
|
+
super({
|
|
107
|
+
name: name12,
|
|
108
|
+
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
109
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
110
|
+
cause
|
|
111
|
+
});
|
|
112
|
+
this[_a13] = true;
|
|
113
|
+
this.value = value;
|
|
114
|
+
}
|
|
115
|
+
static isInstance(error) {
|
|
116
|
+
return AISDKError.hasMarker(error, marker13);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Wraps an error into a TypeValidationError.
|
|
120
|
+
* If the cause is already a TypeValidationError with the same value, it returns the cause.
|
|
121
|
+
* Otherwise, it creates a new TypeValidationError.
|
|
122
|
+
*
|
|
123
|
+
* @param {Object} params - The parameters for wrapping the error.
|
|
124
|
+
* @param {unknown} params.value - The value that failed validation.
|
|
125
|
+
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
126
|
+
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
127
|
+
*/
|
|
128
|
+
static wrap({
|
|
129
|
+
value,
|
|
130
|
+
cause
|
|
131
|
+
}) {
|
|
132
|
+
return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
_a13 = symbol13;
|
|
136
|
+
var TypeValidationError = _TypeValidationError;
|
|
137
|
+
var createIdGenerator = ({
|
|
138
|
+
prefix,
|
|
139
|
+
size = 16,
|
|
140
|
+
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
141
|
+
separator = "-"
|
|
142
|
+
} = {}) => {
|
|
143
|
+
const generator = () => {
|
|
144
|
+
const alphabetLength = alphabet.length;
|
|
145
|
+
const chars = new Array(size);
|
|
146
|
+
for (let i = 0; i < size; i++) {
|
|
147
|
+
chars[i] = alphabet[Math.random() * alphabetLength | 0];
|
|
148
|
+
}
|
|
149
|
+
return chars.join("");
|
|
150
|
+
};
|
|
151
|
+
if (prefix == null) {
|
|
152
|
+
return generator;
|
|
153
|
+
}
|
|
154
|
+
if (alphabet.includes(separator)) {
|
|
155
|
+
throw new InvalidArgumentError({
|
|
156
|
+
argument: "separator",
|
|
157
|
+
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return () => `${prefix}${separator}${generator()}`;
|
|
161
|
+
};
|
|
162
|
+
var generateId = createIdGenerator();
|
|
163
|
+
function getErrorMessage2(error) {
|
|
164
|
+
if (error == null) {
|
|
165
|
+
return "unknown error";
|
|
166
|
+
}
|
|
167
|
+
if (typeof error === "string") {
|
|
168
|
+
return error;
|
|
169
|
+
}
|
|
170
|
+
if (error instanceof Error) {
|
|
171
|
+
return error.message;
|
|
172
|
+
}
|
|
173
|
+
return JSON.stringify(error);
|
|
174
|
+
}
|
|
175
|
+
var suspectProtoRx = /"__proto__"\s*:/;
|
|
176
|
+
var suspectConstructorRx = /"constructor"\s*:/;
|
|
177
|
+
function _parse(text2) {
|
|
178
|
+
const obj = JSON.parse(text2);
|
|
179
|
+
if (obj === null || typeof obj !== "object") {
|
|
180
|
+
return obj;
|
|
181
|
+
}
|
|
182
|
+
if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
|
|
183
|
+
return obj;
|
|
184
|
+
}
|
|
185
|
+
return filter(obj);
|
|
186
|
+
}
|
|
187
|
+
function filter(obj) {
|
|
188
|
+
let next = [obj];
|
|
189
|
+
while (next.length) {
|
|
190
|
+
const nodes = next;
|
|
191
|
+
next = [];
|
|
192
|
+
for (const node of nodes) {
|
|
193
|
+
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
|
|
194
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
195
|
+
}
|
|
196
|
+
if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
|
|
197
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
198
|
+
}
|
|
199
|
+
for (const key in node) {
|
|
200
|
+
const value = node[key];
|
|
201
|
+
if (value && typeof value === "object") {
|
|
202
|
+
next.push(value);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return obj;
|
|
208
|
+
}
|
|
209
|
+
function secureJsonParse(text2) {
|
|
210
|
+
const { stackTraceLimit } = Error;
|
|
211
|
+
try {
|
|
212
|
+
Error.stackTraceLimit = 0;
|
|
213
|
+
} catch (e) {
|
|
214
|
+
return _parse(text2);
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
return _parse(text2);
|
|
218
|
+
} finally {
|
|
219
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
|
|
223
|
+
function validator(validate) {
|
|
224
|
+
return { [validatorSymbol]: true, validate };
|
|
225
|
+
}
|
|
226
|
+
function isValidator(value) {
|
|
227
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
228
|
+
}
|
|
229
|
+
function asValidator(value) {
|
|
230
|
+
return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
|
|
231
|
+
}
|
|
232
|
+
function standardSchemaValidator(standardSchema) {
|
|
233
|
+
return validator(async (value) => {
|
|
234
|
+
const result = await standardSchema["~standard"].validate(value);
|
|
235
|
+
return result.issues == null ? { success: true, value: result.value } : {
|
|
236
|
+
success: false,
|
|
237
|
+
error: new TypeValidationError({
|
|
238
|
+
value,
|
|
239
|
+
cause: result.issues
|
|
240
|
+
})
|
|
241
|
+
};
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
async function validateTypes({
|
|
245
|
+
value,
|
|
246
|
+
schema
|
|
247
|
+
}) {
|
|
248
|
+
const result = await safeValidateTypes({ value, schema });
|
|
249
|
+
if (!result.success) {
|
|
250
|
+
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
251
|
+
}
|
|
252
|
+
return result.value;
|
|
253
|
+
}
|
|
254
|
+
async function safeValidateTypes({
|
|
255
|
+
value,
|
|
256
|
+
schema
|
|
257
|
+
}) {
|
|
258
|
+
const validator2 = asValidator(schema);
|
|
259
|
+
try {
|
|
260
|
+
if (validator2.validate == null) {
|
|
261
|
+
return { success: true, value, rawValue: value };
|
|
262
|
+
}
|
|
263
|
+
const result = await validator2.validate(value);
|
|
264
|
+
if (result.success) {
|
|
265
|
+
return { success: true, value: result.value, rawValue: value };
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
success: false,
|
|
269
|
+
error: TypeValidationError.wrap({ value, cause: result.error }),
|
|
270
|
+
rawValue: value
|
|
271
|
+
};
|
|
272
|
+
} catch (error) {
|
|
273
|
+
return {
|
|
274
|
+
success: false,
|
|
275
|
+
error: TypeValidationError.wrap({ value, cause: error }),
|
|
276
|
+
rawValue: value
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async function safeParseJSON({
|
|
281
|
+
text: text2,
|
|
282
|
+
schema
|
|
283
|
+
}) {
|
|
284
|
+
try {
|
|
285
|
+
const value = secureJsonParse(text2);
|
|
286
|
+
if (schema == null) {
|
|
287
|
+
return { success: true, value, rawValue: value };
|
|
288
|
+
}
|
|
289
|
+
return await safeValidateTypes({ value, schema });
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return {
|
|
292
|
+
success: false,
|
|
293
|
+
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
|
|
294
|
+
rawValue: void 0
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
var getRelativePath = (pathA, pathB) => {
|
|
299
|
+
let i = 0;
|
|
300
|
+
for (; i < pathA.length && i < pathB.length; i++) {
|
|
301
|
+
if (pathA[i] !== pathB[i]) break;
|
|
302
|
+
}
|
|
303
|
+
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
|
|
304
|
+
};
|
|
305
|
+
var ignoreOverride = /* @__PURE__ */ Symbol(
|
|
306
|
+
"Let zodToJsonSchema decide on which parser to use"
|
|
307
|
+
);
|
|
308
|
+
var defaultOptions = {
|
|
309
|
+
name: void 0,
|
|
310
|
+
$refStrategy: "root",
|
|
311
|
+
basePath: ["#"],
|
|
312
|
+
effectStrategy: "input",
|
|
313
|
+
pipeStrategy: "all",
|
|
314
|
+
dateStrategy: "format:date-time",
|
|
315
|
+
mapStrategy: "entries",
|
|
316
|
+
removeAdditionalStrategy: "passthrough",
|
|
317
|
+
allowedAdditionalProperties: true,
|
|
318
|
+
rejectedAdditionalProperties: false,
|
|
319
|
+
definitionPath: "definitions",
|
|
320
|
+
strictUnions: false,
|
|
321
|
+
definitions: {},
|
|
322
|
+
errorMessages: false,
|
|
323
|
+
patternStrategy: "escape",
|
|
324
|
+
applyRegexFlags: false,
|
|
325
|
+
emailStrategy: "format:email",
|
|
326
|
+
base64Strategy: "contentEncoding:base64",
|
|
327
|
+
nameStrategy: "ref"
|
|
328
|
+
};
|
|
329
|
+
var getDefaultOptions = (options) => typeof options === "string" ? {
|
|
330
|
+
...defaultOptions,
|
|
331
|
+
name: options
|
|
332
|
+
} : {
|
|
333
|
+
...defaultOptions,
|
|
334
|
+
...options
|
|
335
|
+
};
|
|
336
|
+
function parseAnyDef() {
|
|
337
|
+
return {};
|
|
338
|
+
}
|
|
339
|
+
function parseArrayDef(def, refs) {
|
|
340
|
+
var _a16, _b, _c;
|
|
341
|
+
const res = {
|
|
342
|
+
type: "array"
|
|
343
|
+
};
|
|
344
|
+
if (((_a16 = def.type) == null ? void 0 : _a16._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
|
|
345
|
+
res.items = parseDef(def.type._def, {
|
|
346
|
+
...refs,
|
|
347
|
+
currentPath: [...refs.currentPath, "items"]
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
if (def.minLength) {
|
|
351
|
+
res.minItems = def.minLength.value;
|
|
352
|
+
}
|
|
353
|
+
if (def.maxLength) {
|
|
354
|
+
res.maxItems = def.maxLength.value;
|
|
355
|
+
}
|
|
356
|
+
if (def.exactLength) {
|
|
357
|
+
res.minItems = def.exactLength.value;
|
|
358
|
+
res.maxItems = def.exactLength.value;
|
|
359
|
+
}
|
|
360
|
+
return res;
|
|
361
|
+
}
|
|
362
|
+
function parseBigintDef(def) {
|
|
363
|
+
const res = {
|
|
364
|
+
type: "integer",
|
|
365
|
+
format: "int64"
|
|
366
|
+
};
|
|
367
|
+
if (!def.checks) return res;
|
|
368
|
+
for (const check of def.checks) {
|
|
369
|
+
switch (check.kind) {
|
|
370
|
+
case "min":
|
|
371
|
+
if (check.inclusive) {
|
|
372
|
+
res.minimum = check.value;
|
|
373
|
+
} else {
|
|
374
|
+
res.exclusiveMinimum = check.value;
|
|
375
|
+
}
|
|
376
|
+
break;
|
|
377
|
+
case "max":
|
|
378
|
+
if (check.inclusive) {
|
|
379
|
+
res.maximum = check.value;
|
|
380
|
+
} else {
|
|
381
|
+
res.exclusiveMaximum = check.value;
|
|
382
|
+
}
|
|
383
|
+
break;
|
|
384
|
+
case "multipleOf":
|
|
385
|
+
res.multipleOf = check.value;
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return res;
|
|
390
|
+
}
|
|
391
|
+
function parseBooleanDef() {
|
|
392
|
+
return { type: "boolean" };
|
|
393
|
+
}
|
|
394
|
+
function parseBrandedDef(_def, refs) {
|
|
395
|
+
return parseDef(_def.type._def, refs);
|
|
396
|
+
}
|
|
397
|
+
var parseCatchDef = (def, refs) => {
|
|
398
|
+
return parseDef(def.innerType._def, refs);
|
|
399
|
+
};
|
|
400
|
+
function parseDateDef(def, refs, overrideDateStrategy) {
|
|
401
|
+
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
|
|
402
|
+
if (Array.isArray(strategy)) {
|
|
403
|
+
return {
|
|
404
|
+
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
switch (strategy) {
|
|
408
|
+
case "string":
|
|
409
|
+
case "format:date-time":
|
|
410
|
+
return {
|
|
411
|
+
type: "string",
|
|
412
|
+
format: "date-time"
|
|
413
|
+
};
|
|
414
|
+
case "format:date":
|
|
415
|
+
return {
|
|
416
|
+
type: "string",
|
|
417
|
+
format: "date"
|
|
418
|
+
};
|
|
419
|
+
case "integer":
|
|
420
|
+
return integerDateParser(def);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
var integerDateParser = (def) => {
|
|
424
|
+
const res = {
|
|
425
|
+
type: "integer",
|
|
426
|
+
format: "unix-time"
|
|
427
|
+
};
|
|
428
|
+
for (const check of def.checks) {
|
|
429
|
+
switch (check.kind) {
|
|
430
|
+
case "min":
|
|
431
|
+
res.minimum = check.value;
|
|
432
|
+
break;
|
|
433
|
+
case "max":
|
|
434
|
+
res.maximum = check.value;
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return res;
|
|
439
|
+
};
|
|
440
|
+
function parseDefaultDef(_def, refs) {
|
|
441
|
+
return {
|
|
442
|
+
...parseDef(_def.innerType._def, refs),
|
|
443
|
+
default: _def.defaultValue()
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function parseEffectsDef(_def, refs) {
|
|
447
|
+
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
|
|
448
|
+
}
|
|
449
|
+
function parseEnumDef(def) {
|
|
450
|
+
return {
|
|
451
|
+
type: "string",
|
|
452
|
+
enum: Array.from(def.values)
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
var isJsonSchema7AllOfType = (type) => {
|
|
456
|
+
if ("type" in type && type.type === "string") return false;
|
|
457
|
+
return "allOf" in type;
|
|
458
|
+
};
|
|
459
|
+
function parseIntersectionDef(def, refs) {
|
|
460
|
+
const allOf = [
|
|
461
|
+
parseDef(def.left._def, {
|
|
462
|
+
...refs,
|
|
463
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
464
|
+
}),
|
|
465
|
+
parseDef(def.right._def, {
|
|
466
|
+
...refs,
|
|
467
|
+
currentPath: [...refs.currentPath, "allOf", "1"]
|
|
468
|
+
})
|
|
469
|
+
].filter((x) => !!x);
|
|
470
|
+
const mergedAllOf = [];
|
|
471
|
+
allOf.forEach((schema) => {
|
|
472
|
+
if (isJsonSchema7AllOfType(schema)) {
|
|
473
|
+
mergedAllOf.push(...schema.allOf);
|
|
474
|
+
} else {
|
|
475
|
+
let nestedSchema = schema;
|
|
476
|
+
if ("additionalProperties" in schema && schema.additionalProperties === false) {
|
|
477
|
+
const { additionalProperties, ...rest } = schema;
|
|
478
|
+
nestedSchema = rest;
|
|
479
|
+
}
|
|
480
|
+
mergedAllOf.push(nestedSchema);
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
|
|
484
|
+
}
|
|
485
|
+
function parseLiteralDef(def) {
|
|
486
|
+
const parsedType = typeof def.value;
|
|
487
|
+
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
|
|
488
|
+
return {
|
|
489
|
+
type: Array.isArray(def.value) ? "array" : "object"
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
return {
|
|
493
|
+
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
494
|
+
const: def.value
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
var emojiRegex = void 0;
|
|
498
|
+
var zodPatterns = {
|
|
499
|
+
/**
|
|
500
|
+
* `c` was changed to `[cC]` to replicate /i flag
|
|
501
|
+
*/
|
|
502
|
+
cuid: /^[cC][^\s-]{8,}$/,
|
|
503
|
+
cuid2: /^[0-9a-z]+$/,
|
|
504
|
+
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
505
|
+
/**
|
|
506
|
+
* `a-z` was added to replicate /i flag
|
|
507
|
+
*/
|
|
508
|
+
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
509
|
+
/**
|
|
510
|
+
* Constructed a valid Unicode RegExp
|
|
511
|
+
*
|
|
512
|
+
* Lazily instantiate since this type of regex isn't supported
|
|
513
|
+
* in all envs (e.g. React Native).
|
|
514
|
+
*
|
|
515
|
+
* See:
|
|
516
|
+
* https://github.com/colinhacks/zod/issues/2433
|
|
517
|
+
* Fix in Zod:
|
|
518
|
+
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
|
|
519
|
+
*/
|
|
520
|
+
emoji: () => {
|
|
521
|
+
if (emojiRegex === void 0) {
|
|
522
|
+
emojiRegex = RegExp(
|
|
523
|
+
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
|
|
524
|
+
"u"
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
return emojiRegex;
|
|
528
|
+
},
|
|
529
|
+
/**
|
|
530
|
+
* Unused
|
|
531
|
+
*/
|
|
532
|
+
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}$/,
|
|
533
|
+
/**
|
|
534
|
+
* Unused
|
|
535
|
+
*/
|
|
536
|
+
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])$/,
|
|
537
|
+
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])$/,
|
|
538
|
+
/**
|
|
539
|
+
* Unused
|
|
540
|
+
*/
|
|
541
|
+
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})))$/,
|
|
542
|
+
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])$/,
|
|
543
|
+
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
|
|
544
|
+
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
|
|
545
|
+
nanoid: /^[a-zA-Z0-9_-]{21}$/,
|
|
546
|
+
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
|
|
547
|
+
};
|
|
548
|
+
function parseStringDef(def, refs) {
|
|
549
|
+
const res = {
|
|
550
|
+
type: "string"
|
|
551
|
+
};
|
|
552
|
+
if (def.checks) {
|
|
553
|
+
for (const check of def.checks) {
|
|
554
|
+
switch (check.kind) {
|
|
555
|
+
case "min":
|
|
556
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
557
|
+
break;
|
|
558
|
+
case "max":
|
|
559
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
560
|
+
break;
|
|
561
|
+
case "email":
|
|
562
|
+
switch (refs.emailStrategy) {
|
|
563
|
+
case "format:email":
|
|
564
|
+
addFormat(res, "email", check.message, refs);
|
|
565
|
+
break;
|
|
566
|
+
case "format:idn-email":
|
|
567
|
+
addFormat(res, "idn-email", check.message, refs);
|
|
568
|
+
break;
|
|
569
|
+
case "pattern:zod":
|
|
570
|
+
addPattern(res, zodPatterns.email, check.message, refs);
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
break;
|
|
574
|
+
case "url":
|
|
575
|
+
addFormat(res, "uri", check.message, refs);
|
|
576
|
+
break;
|
|
577
|
+
case "uuid":
|
|
578
|
+
addFormat(res, "uuid", check.message, refs);
|
|
579
|
+
break;
|
|
580
|
+
case "regex":
|
|
581
|
+
addPattern(res, check.regex, check.message, refs);
|
|
582
|
+
break;
|
|
583
|
+
case "cuid":
|
|
584
|
+
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
585
|
+
break;
|
|
586
|
+
case "cuid2":
|
|
587
|
+
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
588
|
+
break;
|
|
589
|
+
case "startsWith":
|
|
590
|
+
addPattern(
|
|
591
|
+
res,
|
|
592
|
+
RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
|
|
593
|
+
check.message,
|
|
594
|
+
refs
|
|
595
|
+
);
|
|
596
|
+
break;
|
|
597
|
+
case "endsWith":
|
|
598
|
+
addPattern(
|
|
599
|
+
res,
|
|
600
|
+
RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
|
|
601
|
+
check.message,
|
|
602
|
+
refs
|
|
603
|
+
);
|
|
604
|
+
break;
|
|
605
|
+
case "datetime":
|
|
606
|
+
addFormat(res, "date-time", check.message, refs);
|
|
607
|
+
break;
|
|
608
|
+
case "date":
|
|
609
|
+
addFormat(res, "date", check.message, refs);
|
|
610
|
+
break;
|
|
611
|
+
case "time":
|
|
612
|
+
addFormat(res, "time", check.message, refs);
|
|
613
|
+
break;
|
|
614
|
+
case "duration":
|
|
615
|
+
addFormat(res, "duration", check.message, refs);
|
|
616
|
+
break;
|
|
617
|
+
case "length":
|
|
618
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
619
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
620
|
+
break;
|
|
621
|
+
case "includes": {
|
|
622
|
+
addPattern(
|
|
623
|
+
res,
|
|
624
|
+
RegExp(escapeLiteralCheckValue(check.value, refs)),
|
|
625
|
+
check.message,
|
|
626
|
+
refs
|
|
627
|
+
);
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
case "ip": {
|
|
631
|
+
if (check.version !== "v6") {
|
|
632
|
+
addFormat(res, "ipv4", check.message, refs);
|
|
633
|
+
}
|
|
634
|
+
if (check.version !== "v4") {
|
|
635
|
+
addFormat(res, "ipv6", check.message, refs);
|
|
636
|
+
}
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
case "base64url":
|
|
640
|
+
addPattern(res, zodPatterns.base64url, check.message, refs);
|
|
641
|
+
break;
|
|
642
|
+
case "jwt":
|
|
643
|
+
addPattern(res, zodPatterns.jwt, check.message, refs);
|
|
644
|
+
break;
|
|
645
|
+
case "cidr": {
|
|
646
|
+
if (check.version !== "v6") {
|
|
647
|
+
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
|
|
648
|
+
}
|
|
649
|
+
if (check.version !== "v4") {
|
|
650
|
+
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
|
|
651
|
+
}
|
|
652
|
+
break;
|
|
653
|
+
}
|
|
654
|
+
case "emoji":
|
|
655
|
+
addPattern(res, zodPatterns.emoji(), check.message, refs);
|
|
656
|
+
break;
|
|
657
|
+
case "ulid": {
|
|
658
|
+
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
case "base64": {
|
|
662
|
+
switch (refs.base64Strategy) {
|
|
663
|
+
case "format:binary": {
|
|
664
|
+
addFormat(res, "binary", check.message, refs);
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
case "contentEncoding:base64": {
|
|
668
|
+
res.contentEncoding = "base64";
|
|
669
|
+
break;
|
|
670
|
+
}
|
|
671
|
+
case "pattern:zod": {
|
|
672
|
+
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
case "nanoid": {
|
|
679
|
+
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return res;
|
|
685
|
+
}
|
|
686
|
+
function escapeLiteralCheckValue(literal, refs) {
|
|
687
|
+
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
|
|
688
|
+
}
|
|
689
|
+
var ALPHA_NUMERIC = new Set(
|
|
690
|
+
"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
|
|
691
|
+
);
|
|
692
|
+
function escapeNonAlphaNumeric(source) {
|
|
693
|
+
let result = "";
|
|
694
|
+
for (let i = 0; i < source.length; i++) {
|
|
695
|
+
if (!ALPHA_NUMERIC.has(source[i])) {
|
|
696
|
+
result += "\\";
|
|
697
|
+
}
|
|
698
|
+
result += source[i];
|
|
699
|
+
}
|
|
700
|
+
return result;
|
|
701
|
+
}
|
|
702
|
+
function addFormat(schema, value, message, refs) {
|
|
703
|
+
var _a16;
|
|
704
|
+
if (schema.format || ((_a16 = schema.anyOf) == null ? void 0 : _a16.some((x) => x.format))) {
|
|
705
|
+
if (!schema.anyOf) {
|
|
706
|
+
schema.anyOf = [];
|
|
707
|
+
}
|
|
708
|
+
if (schema.format) {
|
|
709
|
+
schema.anyOf.push({
|
|
710
|
+
format: schema.format
|
|
711
|
+
});
|
|
712
|
+
delete schema.format;
|
|
713
|
+
}
|
|
714
|
+
schema.anyOf.push({
|
|
715
|
+
format: value,
|
|
716
|
+
...message && refs.errorMessages && { errorMessage: { format: message } }
|
|
717
|
+
});
|
|
718
|
+
} else {
|
|
719
|
+
schema.format = value;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
function addPattern(schema, regex, message, refs) {
|
|
723
|
+
var _a16;
|
|
724
|
+
if (schema.pattern || ((_a16 = schema.allOf) == null ? void 0 : _a16.some((x) => x.pattern))) {
|
|
725
|
+
if (!schema.allOf) {
|
|
726
|
+
schema.allOf = [];
|
|
727
|
+
}
|
|
728
|
+
if (schema.pattern) {
|
|
729
|
+
schema.allOf.push({
|
|
730
|
+
pattern: schema.pattern
|
|
731
|
+
});
|
|
732
|
+
delete schema.pattern;
|
|
733
|
+
}
|
|
734
|
+
schema.allOf.push({
|
|
735
|
+
pattern: stringifyRegExpWithFlags(regex, refs),
|
|
736
|
+
...message && refs.errorMessages && { errorMessage: { pattern: message } }
|
|
737
|
+
});
|
|
738
|
+
} else {
|
|
739
|
+
schema.pattern = stringifyRegExpWithFlags(regex, refs);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
function stringifyRegExpWithFlags(regex, refs) {
|
|
743
|
+
var _a16;
|
|
744
|
+
if (!refs.applyRegexFlags || !regex.flags) {
|
|
745
|
+
return regex.source;
|
|
746
|
+
}
|
|
747
|
+
const flags = {
|
|
748
|
+
i: regex.flags.includes("i"),
|
|
749
|
+
// Case-insensitive
|
|
750
|
+
m: regex.flags.includes("m"),
|
|
751
|
+
// `^` and `$` matches adjacent to newline characters
|
|
752
|
+
s: regex.flags.includes("s")
|
|
753
|
+
// `.` matches newlines
|
|
754
|
+
};
|
|
755
|
+
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
756
|
+
let pattern = "";
|
|
757
|
+
let isEscaped = false;
|
|
758
|
+
let inCharGroup = false;
|
|
759
|
+
let inCharRange = false;
|
|
760
|
+
for (let i = 0; i < source.length; i++) {
|
|
761
|
+
if (isEscaped) {
|
|
762
|
+
pattern += source[i];
|
|
763
|
+
isEscaped = false;
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
if (flags.i) {
|
|
767
|
+
if (inCharGroup) {
|
|
768
|
+
if (source[i].match(/[a-z]/)) {
|
|
769
|
+
if (inCharRange) {
|
|
770
|
+
pattern += source[i];
|
|
771
|
+
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
772
|
+
inCharRange = false;
|
|
773
|
+
} else if (source[i + 1] === "-" && ((_a16 = source[i + 2]) == null ? void 0 : _a16.match(/[a-z]/))) {
|
|
774
|
+
pattern += source[i];
|
|
775
|
+
inCharRange = true;
|
|
776
|
+
} else {
|
|
777
|
+
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
778
|
+
}
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
} else if (source[i].match(/[a-z]/)) {
|
|
782
|
+
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
783
|
+
continue;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
if (flags.m) {
|
|
787
|
+
if (source[i] === "^") {
|
|
788
|
+
pattern += `(^|(?<=[\r
|
|
789
|
+
]))`;
|
|
790
|
+
continue;
|
|
791
|
+
} else if (source[i] === "$") {
|
|
792
|
+
pattern += `($|(?=[\r
|
|
793
|
+
]))`;
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (flags.s && source[i] === ".") {
|
|
798
|
+
pattern += inCharGroup ? `${source[i]}\r
|
|
799
|
+
` : `[${source[i]}\r
|
|
800
|
+
]`;
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
pattern += source[i];
|
|
804
|
+
if (source[i] === "\\") {
|
|
805
|
+
isEscaped = true;
|
|
806
|
+
} else if (inCharGroup && source[i] === "]") {
|
|
807
|
+
inCharGroup = false;
|
|
808
|
+
} else if (!inCharGroup && source[i] === "[") {
|
|
809
|
+
inCharGroup = true;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return pattern;
|
|
813
|
+
}
|
|
814
|
+
function parseRecordDef(def, refs) {
|
|
815
|
+
var _a16, _b, _c, _d, _e, _f;
|
|
816
|
+
const schema = {
|
|
817
|
+
type: "object",
|
|
818
|
+
additionalProperties: (_a16 = parseDef(def.valueType._def, {
|
|
819
|
+
...refs,
|
|
820
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
821
|
+
})) != null ? _a16 : refs.allowedAdditionalProperties
|
|
822
|
+
};
|
|
823
|
+
if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
|
|
824
|
+
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
825
|
+
return {
|
|
826
|
+
...schema,
|
|
827
|
+
propertyNames: keyType
|
|
828
|
+
};
|
|
829
|
+
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
|
|
830
|
+
return {
|
|
831
|
+
...schema,
|
|
832
|
+
propertyNames: {
|
|
833
|
+
enum: def.keyType._def.values
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
} else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
|
|
837
|
+
const { type, ...keyType } = parseBrandedDef(
|
|
838
|
+
def.keyType._def,
|
|
839
|
+
refs
|
|
840
|
+
);
|
|
841
|
+
return {
|
|
842
|
+
...schema,
|
|
843
|
+
propertyNames: keyType
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
return schema;
|
|
847
|
+
}
|
|
848
|
+
function parseMapDef(def, refs) {
|
|
849
|
+
if (refs.mapStrategy === "record") {
|
|
850
|
+
return parseRecordDef(def, refs);
|
|
851
|
+
}
|
|
852
|
+
const keys = parseDef(def.keyType._def, {
|
|
853
|
+
...refs,
|
|
854
|
+
currentPath: [...refs.currentPath, "items", "items", "0"]
|
|
855
|
+
}) || parseAnyDef();
|
|
856
|
+
const values = parseDef(def.valueType._def, {
|
|
857
|
+
...refs,
|
|
858
|
+
currentPath: [...refs.currentPath, "items", "items", "1"]
|
|
859
|
+
}) || parseAnyDef();
|
|
860
|
+
return {
|
|
861
|
+
type: "array",
|
|
862
|
+
maxItems: 125,
|
|
863
|
+
items: {
|
|
864
|
+
type: "array",
|
|
865
|
+
items: [keys, values],
|
|
866
|
+
minItems: 2,
|
|
867
|
+
maxItems: 2
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
function parseNativeEnumDef(def) {
|
|
872
|
+
const object2 = def.values;
|
|
873
|
+
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
874
|
+
return typeof object2[object2[key]] !== "number";
|
|
875
|
+
});
|
|
876
|
+
const actualValues = actualKeys.map((key) => object2[key]);
|
|
877
|
+
const parsedTypes = Array.from(
|
|
878
|
+
new Set(actualValues.map((values) => typeof values))
|
|
879
|
+
);
|
|
880
|
+
return {
|
|
881
|
+
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
|
|
882
|
+
enum: actualValues
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
function parseNeverDef() {
|
|
886
|
+
return { not: parseAnyDef() };
|
|
887
|
+
}
|
|
888
|
+
function parseNullDef() {
|
|
889
|
+
return {
|
|
890
|
+
type: "null"
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
var primitiveMappings = {
|
|
894
|
+
ZodString: "string",
|
|
895
|
+
ZodNumber: "number",
|
|
896
|
+
ZodBigInt: "integer",
|
|
897
|
+
ZodBoolean: "boolean",
|
|
898
|
+
ZodNull: "null"
|
|
899
|
+
};
|
|
900
|
+
function parseUnionDef(def, refs) {
|
|
901
|
+
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
|
|
902
|
+
if (options.every(
|
|
903
|
+
(x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
|
|
904
|
+
)) {
|
|
905
|
+
const types = options.reduce((types2, x) => {
|
|
906
|
+
const type = primitiveMappings[x._def.typeName];
|
|
907
|
+
return type && !types2.includes(type) ? [...types2, type] : types2;
|
|
908
|
+
}, []);
|
|
909
|
+
return {
|
|
910
|
+
type: types.length > 1 ? types : types[0]
|
|
911
|
+
};
|
|
912
|
+
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
|
|
913
|
+
const types = options.reduce(
|
|
914
|
+
(acc, x) => {
|
|
915
|
+
const type = typeof x._def.value;
|
|
916
|
+
switch (type) {
|
|
917
|
+
case "string":
|
|
918
|
+
case "number":
|
|
919
|
+
case "boolean":
|
|
920
|
+
return [...acc, type];
|
|
921
|
+
case "bigint":
|
|
922
|
+
return [...acc, "integer"];
|
|
923
|
+
case "object":
|
|
924
|
+
if (x._def.value === null) return [...acc, "null"];
|
|
925
|
+
case "symbol":
|
|
926
|
+
case "undefined":
|
|
927
|
+
case "function":
|
|
928
|
+
default:
|
|
929
|
+
return acc;
|
|
930
|
+
}
|
|
931
|
+
},
|
|
932
|
+
[]
|
|
933
|
+
);
|
|
934
|
+
if (types.length === options.length) {
|
|
935
|
+
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
|
|
936
|
+
return {
|
|
937
|
+
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
|
|
938
|
+
enum: options.reduce(
|
|
939
|
+
(acc, x) => {
|
|
940
|
+
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
|
|
941
|
+
},
|
|
942
|
+
[]
|
|
943
|
+
)
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
} else if (options.every((x) => x._def.typeName === "ZodEnum")) {
|
|
947
|
+
return {
|
|
948
|
+
type: "string",
|
|
949
|
+
enum: options.reduce(
|
|
950
|
+
(acc, x) => [
|
|
951
|
+
...acc,
|
|
952
|
+
...x._def.values.filter((x2) => !acc.includes(x2))
|
|
953
|
+
],
|
|
954
|
+
[]
|
|
955
|
+
)
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
return asAnyOf(def, refs);
|
|
959
|
+
}
|
|
960
|
+
var asAnyOf = (def, refs) => {
|
|
961
|
+
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
|
|
962
|
+
(x, i) => parseDef(x._def, {
|
|
963
|
+
...refs,
|
|
964
|
+
currentPath: [...refs.currentPath, "anyOf", `${i}`]
|
|
965
|
+
})
|
|
966
|
+
).filter(
|
|
967
|
+
(x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
|
|
968
|
+
);
|
|
969
|
+
return anyOf.length ? { anyOf } : void 0;
|
|
970
|
+
};
|
|
971
|
+
function parseNullableDef(def, refs) {
|
|
972
|
+
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
|
|
973
|
+
def.innerType._def.typeName
|
|
974
|
+
) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
|
|
975
|
+
return {
|
|
976
|
+
type: [
|
|
977
|
+
primitiveMappings[def.innerType._def.typeName],
|
|
978
|
+
"null"
|
|
979
|
+
]
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
const base = parseDef(def.innerType._def, {
|
|
983
|
+
...refs,
|
|
984
|
+
currentPath: [...refs.currentPath, "anyOf", "0"]
|
|
985
|
+
});
|
|
986
|
+
return base && { anyOf: [base, { type: "null" }] };
|
|
987
|
+
}
|
|
988
|
+
function parseNumberDef(def) {
|
|
989
|
+
const res = {
|
|
990
|
+
type: "number"
|
|
991
|
+
};
|
|
992
|
+
if (!def.checks) return res;
|
|
993
|
+
for (const check of def.checks) {
|
|
994
|
+
switch (check.kind) {
|
|
995
|
+
case "int":
|
|
996
|
+
res.type = "integer";
|
|
997
|
+
break;
|
|
998
|
+
case "min":
|
|
999
|
+
if (check.inclusive) {
|
|
1000
|
+
res.minimum = check.value;
|
|
1001
|
+
} else {
|
|
1002
|
+
res.exclusiveMinimum = check.value;
|
|
1003
|
+
}
|
|
1004
|
+
break;
|
|
1005
|
+
case "max":
|
|
1006
|
+
if (check.inclusive) {
|
|
1007
|
+
res.maximum = check.value;
|
|
1008
|
+
} else {
|
|
1009
|
+
res.exclusiveMaximum = check.value;
|
|
1010
|
+
}
|
|
1011
|
+
break;
|
|
1012
|
+
case "multipleOf":
|
|
1013
|
+
res.multipleOf = check.value;
|
|
1014
|
+
break;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
return res;
|
|
1018
|
+
}
|
|
1019
|
+
function parseObjectDef(def, refs) {
|
|
1020
|
+
const result = {
|
|
1021
|
+
type: "object",
|
|
1022
|
+
properties: {}
|
|
1023
|
+
};
|
|
1024
|
+
const required = [];
|
|
1025
|
+
const shape = def.shape();
|
|
1026
|
+
for (const propName in shape) {
|
|
1027
|
+
let propDef = shape[propName];
|
|
1028
|
+
if (propDef === void 0 || propDef._def === void 0) {
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
const propOptional = safeIsOptional(propDef);
|
|
1032
|
+
const parsedDef = parseDef(propDef._def, {
|
|
1033
|
+
...refs,
|
|
1034
|
+
currentPath: [...refs.currentPath, "properties", propName],
|
|
1035
|
+
propertyPath: [...refs.currentPath, "properties", propName]
|
|
1036
|
+
});
|
|
1037
|
+
if (parsedDef === void 0) {
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
result.properties[propName] = parsedDef;
|
|
1041
|
+
if (!propOptional) {
|
|
1042
|
+
required.push(propName);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
if (required.length) {
|
|
1046
|
+
result.required = required;
|
|
1047
|
+
}
|
|
1048
|
+
const additionalProperties = decideAdditionalProperties(def, refs);
|
|
1049
|
+
if (additionalProperties !== void 0) {
|
|
1050
|
+
result.additionalProperties = additionalProperties;
|
|
1051
|
+
}
|
|
1052
|
+
return result;
|
|
1053
|
+
}
|
|
1054
|
+
function decideAdditionalProperties(def, refs) {
|
|
1055
|
+
if (def.catchall._def.typeName !== "ZodNever") {
|
|
1056
|
+
return parseDef(def.catchall._def, {
|
|
1057
|
+
...refs,
|
|
1058
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
switch (def.unknownKeys) {
|
|
1062
|
+
case "passthrough":
|
|
1063
|
+
return refs.allowedAdditionalProperties;
|
|
1064
|
+
case "strict":
|
|
1065
|
+
return refs.rejectedAdditionalProperties;
|
|
1066
|
+
case "strip":
|
|
1067
|
+
return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
function safeIsOptional(schema) {
|
|
1071
|
+
try {
|
|
1072
|
+
return schema.isOptional();
|
|
1073
|
+
} catch (e) {
|
|
1074
|
+
return true;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
var parseOptionalDef = (def, refs) => {
|
|
1078
|
+
var _a16;
|
|
1079
|
+
if (refs.currentPath.toString() === ((_a16 = refs.propertyPath) == null ? void 0 : _a16.toString())) {
|
|
1080
|
+
return parseDef(def.innerType._def, refs);
|
|
1081
|
+
}
|
|
1082
|
+
const innerSchema = parseDef(def.innerType._def, {
|
|
1083
|
+
...refs,
|
|
1084
|
+
currentPath: [...refs.currentPath, "anyOf", "1"]
|
|
1085
|
+
});
|
|
1086
|
+
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
|
|
1087
|
+
};
|
|
1088
|
+
var parsePipelineDef = (def, refs) => {
|
|
1089
|
+
if (refs.pipeStrategy === "input") {
|
|
1090
|
+
return parseDef(def.in._def, refs);
|
|
1091
|
+
} else if (refs.pipeStrategy === "output") {
|
|
1092
|
+
return parseDef(def.out._def, refs);
|
|
1093
|
+
}
|
|
1094
|
+
const a = parseDef(def.in._def, {
|
|
1095
|
+
...refs,
|
|
1096
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
1097
|
+
});
|
|
1098
|
+
const b = parseDef(def.out._def, {
|
|
1099
|
+
...refs,
|
|
1100
|
+
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
|
|
1101
|
+
});
|
|
1102
|
+
return {
|
|
1103
|
+
allOf: [a, b].filter((x) => x !== void 0)
|
|
1104
|
+
};
|
|
1105
|
+
};
|
|
1106
|
+
function parsePromiseDef(def, refs) {
|
|
1107
|
+
return parseDef(def.type._def, refs);
|
|
1108
|
+
}
|
|
1109
|
+
function parseSetDef(def, refs) {
|
|
1110
|
+
const items = parseDef(def.valueType._def, {
|
|
1111
|
+
...refs,
|
|
1112
|
+
currentPath: [...refs.currentPath, "items"]
|
|
1113
|
+
});
|
|
1114
|
+
const schema = {
|
|
1115
|
+
type: "array",
|
|
1116
|
+
uniqueItems: true,
|
|
1117
|
+
items
|
|
1118
|
+
};
|
|
1119
|
+
if (def.minSize) {
|
|
1120
|
+
schema.minItems = def.minSize.value;
|
|
1121
|
+
}
|
|
1122
|
+
if (def.maxSize) {
|
|
1123
|
+
schema.maxItems = def.maxSize.value;
|
|
1124
|
+
}
|
|
1125
|
+
return schema;
|
|
1126
|
+
}
|
|
1127
|
+
function parseTupleDef(def, refs) {
|
|
1128
|
+
if (def.rest) {
|
|
1129
|
+
return {
|
|
1130
|
+
type: "array",
|
|
1131
|
+
minItems: def.items.length,
|
|
1132
|
+
items: def.items.map(
|
|
1133
|
+
(x, i) => parseDef(x._def, {
|
|
1134
|
+
...refs,
|
|
1135
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1136
|
+
})
|
|
1137
|
+
).reduce(
|
|
1138
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1139
|
+
[]
|
|
1140
|
+
),
|
|
1141
|
+
additionalItems: parseDef(def.rest._def, {
|
|
1142
|
+
...refs,
|
|
1143
|
+
currentPath: [...refs.currentPath, "additionalItems"]
|
|
1144
|
+
})
|
|
1145
|
+
};
|
|
1146
|
+
} else {
|
|
1147
|
+
return {
|
|
1148
|
+
type: "array",
|
|
1149
|
+
minItems: def.items.length,
|
|
1150
|
+
maxItems: def.items.length,
|
|
1151
|
+
items: def.items.map(
|
|
1152
|
+
(x, i) => parseDef(x._def, {
|
|
1153
|
+
...refs,
|
|
1154
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1155
|
+
})
|
|
1156
|
+
).reduce(
|
|
1157
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1158
|
+
[]
|
|
1159
|
+
)
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
function parseUndefinedDef() {
|
|
1164
|
+
return {
|
|
1165
|
+
not: parseAnyDef()
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
function parseUnknownDef() {
|
|
1169
|
+
return parseAnyDef();
|
|
1170
|
+
}
|
|
1171
|
+
var parseReadonlyDef = (def, refs) => {
|
|
1172
|
+
return parseDef(def.innerType._def, refs);
|
|
1173
|
+
};
|
|
1174
|
+
var selectParser = (def, typeName, refs) => {
|
|
1175
|
+
switch (typeName) {
|
|
1176
|
+
case ZodFirstPartyTypeKind.ZodString:
|
|
1177
|
+
return parseStringDef(def, refs);
|
|
1178
|
+
case ZodFirstPartyTypeKind.ZodNumber:
|
|
1179
|
+
return parseNumberDef(def);
|
|
1180
|
+
case ZodFirstPartyTypeKind.ZodObject:
|
|
1181
|
+
return parseObjectDef(def, refs);
|
|
1182
|
+
case ZodFirstPartyTypeKind.ZodBigInt:
|
|
1183
|
+
return parseBigintDef(def);
|
|
1184
|
+
case ZodFirstPartyTypeKind.ZodBoolean:
|
|
1185
|
+
return parseBooleanDef();
|
|
1186
|
+
case ZodFirstPartyTypeKind.ZodDate:
|
|
1187
|
+
return parseDateDef(def, refs);
|
|
1188
|
+
case ZodFirstPartyTypeKind.ZodUndefined:
|
|
1189
|
+
return parseUndefinedDef();
|
|
1190
|
+
case ZodFirstPartyTypeKind.ZodNull:
|
|
1191
|
+
return parseNullDef();
|
|
1192
|
+
case ZodFirstPartyTypeKind.ZodArray:
|
|
1193
|
+
return parseArrayDef(def, refs);
|
|
1194
|
+
case ZodFirstPartyTypeKind.ZodUnion:
|
|
1195
|
+
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
|
|
1196
|
+
return parseUnionDef(def, refs);
|
|
1197
|
+
case ZodFirstPartyTypeKind.ZodIntersection:
|
|
1198
|
+
return parseIntersectionDef(def, refs);
|
|
1199
|
+
case ZodFirstPartyTypeKind.ZodTuple:
|
|
1200
|
+
return parseTupleDef(def, refs);
|
|
1201
|
+
case ZodFirstPartyTypeKind.ZodRecord:
|
|
1202
|
+
return parseRecordDef(def, refs);
|
|
1203
|
+
case ZodFirstPartyTypeKind.ZodLiteral:
|
|
1204
|
+
return parseLiteralDef(def);
|
|
1205
|
+
case ZodFirstPartyTypeKind.ZodEnum:
|
|
1206
|
+
return parseEnumDef(def);
|
|
1207
|
+
case ZodFirstPartyTypeKind.ZodNativeEnum:
|
|
1208
|
+
return parseNativeEnumDef(def);
|
|
1209
|
+
case ZodFirstPartyTypeKind.ZodNullable:
|
|
1210
|
+
return parseNullableDef(def, refs);
|
|
1211
|
+
case ZodFirstPartyTypeKind.ZodOptional:
|
|
1212
|
+
return parseOptionalDef(def, refs);
|
|
1213
|
+
case ZodFirstPartyTypeKind.ZodMap:
|
|
1214
|
+
return parseMapDef(def, refs);
|
|
1215
|
+
case ZodFirstPartyTypeKind.ZodSet:
|
|
1216
|
+
return parseSetDef(def, refs);
|
|
1217
|
+
case ZodFirstPartyTypeKind.ZodLazy:
|
|
1218
|
+
return () => def.getter()._def;
|
|
1219
|
+
case ZodFirstPartyTypeKind.ZodPromise:
|
|
1220
|
+
return parsePromiseDef(def, refs);
|
|
1221
|
+
case ZodFirstPartyTypeKind.ZodNaN:
|
|
1222
|
+
case ZodFirstPartyTypeKind.ZodNever:
|
|
1223
|
+
return parseNeverDef();
|
|
1224
|
+
case ZodFirstPartyTypeKind.ZodEffects:
|
|
1225
|
+
return parseEffectsDef(def, refs);
|
|
1226
|
+
case ZodFirstPartyTypeKind.ZodAny:
|
|
1227
|
+
return parseAnyDef();
|
|
1228
|
+
case ZodFirstPartyTypeKind.ZodUnknown:
|
|
1229
|
+
return parseUnknownDef();
|
|
1230
|
+
case ZodFirstPartyTypeKind.ZodDefault:
|
|
1231
|
+
return parseDefaultDef(def, refs);
|
|
1232
|
+
case ZodFirstPartyTypeKind.ZodBranded:
|
|
1233
|
+
return parseBrandedDef(def, refs);
|
|
1234
|
+
case ZodFirstPartyTypeKind.ZodReadonly:
|
|
1235
|
+
return parseReadonlyDef(def, refs);
|
|
1236
|
+
case ZodFirstPartyTypeKind.ZodCatch:
|
|
1237
|
+
return parseCatchDef(def, refs);
|
|
1238
|
+
case ZodFirstPartyTypeKind.ZodPipeline:
|
|
1239
|
+
return parsePipelineDef(def, refs);
|
|
1240
|
+
case ZodFirstPartyTypeKind.ZodFunction:
|
|
1241
|
+
case ZodFirstPartyTypeKind.ZodVoid:
|
|
1242
|
+
case ZodFirstPartyTypeKind.ZodSymbol:
|
|
1243
|
+
return void 0;
|
|
1244
|
+
default:
|
|
1245
|
+
return /* @__PURE__ */ ((_) => void 0)();
|
|
1246
|
+
}
|
|
1247
|
+
};
|
|
1248
|
+
function parseDef(def, refs, forceResolution = false) {
|
|
1249
|
+
var _a16;
|
|
1250
|
+
const seenItem = refs.seen.get(def);
|
|
1251
|
+
if (refs.override) {
|
|
1252
|
+
const overrideResult = (_a16 = refs.override) == null ? void 0 : _a16.call(
|
|
1253
|
+
refs,
|
|
1254
|
+
def,
|
|
1255
|
+
refs,
|
|
1256
|
+
seenItem,
|
|
1257
|
+
forceResolution
|
|
1258
|
+
);
|
|
1259
|
+
if (overrideResult !== ignoreOverride) {
|
|
1260
|
+
return overrideResult;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
if (seenItem && !forceResolution) {
|
|
1264
|
+
const seenSchema = get$ref(seenItem, refs);
|
|
1265
|
+
if (seenSchema !== void 0) {
|
|
1266
|
+
return seenSchema;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
|
|
1270
|
+
refs.seen.set(def, newItem);
|
|
1271
|
+
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
|
|
1272
|
+
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
|
|
1273
|
+
if (jsonSchema2) {
|
|
1274
|
+
addMeta(def, refs, jsonSchema2);
|
|
1275
|
+
}
|
|
1276
|
+
if (refs.postProcess) {
|
|
1277
|
+
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
|
|
1278
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1279
|
+
return postProcessResult;
|
|
1280
|
+
}
|
|
1281
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1282
|
+
return jsonSchema2;
|
|
1283
|
+
}
|
|
1284
|
+
var get$ref = (item, refs) => {
|
|
1285
|
+
switch (refs.$refStrategy) {
|
|
1286
|
+
case "root":
|
|
1287
|
+
return { $ref: item.path.join("/") };
|
|
1288
|
+
case "relative":
|
|
1289
|
+
return { $ref: getRelativePath(refs.currentPath, item.path) };
|
|
1290
|
+
case "none":
|
|
1291
|
+
case "seen": {
|
|
1292
|
+
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
|
|
1293
|
+
console.warn(
|
|
1294
|
+
`Recursive reference detected at ${refs.currentPath.join(
|
|
1295
|
+
"/"
|
|
1296
|
+
)}! Defaulting to any`
|
|
1297
|
+
);
|
|
1298
|
+
return parseAnyDef();
|
|
1299
|
+
}
|
|
1300
|
+
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
};
|
|
1304
|
+
var addMeta = (def, refs, jsonSchema2) => {
|
|
1305
|
+
if (def.description) {
|
|
1306
|
+
jsonSchema2.description = def.description;
|
|
1307
|
+
}
|
|
1308
|
+
return jsonSchema2;
|
|
1309
|
+
};
|
|
1310
|
+
var getRefs = (options) => {
|
|
1311
|
+
const _options = getDefaultOptions(options);
|
|
1312
|
+
const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
|
|
1313
|
+
return {
|
|
1314
|
+
..._options,
|
|
1315
|
+
currentPath,
|
|
1316
|
+
propertyPath: void 0,
|
|
1317
|
+
seen: new Map(
|
|
1318
|
+
Object.entries(_options.definitions).map(([name16, def]) => [
|
|
1319
|
+
def._def,
|
|
1320
|
+
{
|
|
1321
|
+
def: def._def,
|
|
1322
|
+
path: [..._options.basePath, _options.definitionPath, name16],
|
|
1323
|
+
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
|
|
1324
|
+
jsonSchema: void 0
|
|
1325
|
+
}
|
|
1326
|
+
])
|
|
1327
|
+
)
|
|
1328
|
+
};
|
|
1329
|
+
};
|
|
1330
|
+
var zodToJsonSchema = (schema, options) => {
|
|
1331
|
+
var _a16;
|
|
1332
|
+
const refs = getRefs(options);
|
|
1333
|
+
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
|
|
1334
|
+
(acc, [name23, schema2]) => {
|
|
1335
|
+
var _a23;
|
|
1336
|
+
return {
|
|
1337
|
+
...acc,
|
|
1338
|
+
[name23]: (_a23 = parseDef(
|
|
1339
|
+
schema2._def,
|
|
1340
|
+
{
|
|
1341
|
+
...refs,
|
|
1342
|
+
currentPath: [...refs.basePath, refs.definitionPath, name23]
|
|
1343
|
+
},
|
|
1344
|
+
true
|
|
1345
|
+
)) != null ? _a23 : parseAnyDef()
|
|
1346
|
+
};
|
|
1347
|
+
},
|
|
1348
|
+
{}
|
|
1349
|
+
) : void 0;
|
|
1350
|
+
const name16 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
|
|
1351
|
+
const main = (_a16 = parseDef(
|
|
1352
|
+
schema._def,
|
|
1353
|
+
name16 === void 0 ? refs : {
|
|
1354
|
+
...refs,
|
|
1355
|
+
currentPath: [...refs.basePath, refs.definitionPath, name16]
|
|
1356
|
+
},
|
|
1357
|
+
false
|
|
1358
|
+
)) != null ? _a16 : parseAnyDef();
|
|
1359
|
+
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
|
|
1360
|
+
if (title !== void 0) {
|
|
1361
|
+
main.title = title;
|
|
1362
|
+
}
|
|
1363
|
+
const combined = name16 === void 0 ? definitions ? {
|
|
1364
|
+
...main,
|
|
1365
|
+
[refs.definitionPath]: definitions
|
|
1366
|
+
} : main : {
|
|
1367
|
+
$ref: [
|
|
1368
|
+
...refs.$refStrategy === "relative" ? [] : refs.basePath,
|
|
1369
|
+
refs.definitionPath,
|
|
1370
|
+
name16
|
|
1371
|
+
].join("/"),
|
|
1372
|
+
[refs.definitionPath]: {
|
|
1373
|
+
...definitions,
|
|
1374
|
+
[name16]: main
|
|
1375
|
+
}
|
|
1376
|
+
};
|
|
1377
|
+
combined.$schema = "http://json-schema.org/draft-07/schema#";
|
|
1378
|
+
return combined;
|
|
1379
|
+
};
|
|
1380
|
+
var zod_to_json_schema_default = zodToJsonSchema;
|
|
1381
|
+
function zod3Schema(zodSchema2, options) {
|
|
1382
|
+
var _a16;
|
|
1383
|
+
const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
|
|
1384
|
+
return jsonSchema(
|
|
1385
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1386
|
+
() => zod_to_json_schema_default(zodSchema2, {
|
|
1387
|
+
$refStrategy: useReferences ? "root" : "none"
|
|
1388
|
+
}),
|
|
1389
|
+
{
|
|
1390
|
+
validate: async (value) => {
|
|
1391
|
+
const result = await zodSchema2.safeParseAsync(value);
|
|
1392
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
);
|
|
1396
|
+
}
|
|
1397
|
+
function zod4Schema(zodSchema2, options) {
|
|
1398
|
+
var _a16;
|
|
1399
|
+
const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
|
|
1400
|
+
return jsonSchema(
|
|
1401
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1402
|
+
() => z4.toJSONSchema(zodSchema2, {
|
|
1403
|
+
target: "draft-7",
|
|
1404
|
+
io: "output",
|
|
1405
|
+
reused: useReferences ? "ref" : "inline"
|
|
1406
|
+
}),
|
|
1407
|
+
{
|
|
1408
|
+
validate: async (value) => {
|
|
1409
|
+
const result = await z4.safeParseAsync(zodSchema2, value);
|
|
1410
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
function isZod4Schema(zodSchema2) {
|
|
1416
|
+
return "_zod" in zodSchema2;
|
|
1417
|
+
}
|
|
1418
|
+
function zodSchema(zodSchema2, options) {
|
|
1419
|
+
if (isZod4Schema(zodSchema2)) {
|
|
1420
|
+
return zod4Schema(zodSchema2);
|
|
1421
|
+
} else {
|
|
1422
|
+
return zod3Schema(zodSchema2);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
|
|
1426
|
+
function jsonSchema(jsonSchema2, {
|
|
1427
|
+
validate
|
|
1428
|
+
} = {}) {
|
|
1429
|
+
return {
|
|
1430
|
+
[schemaSymbol]: true,
|
|
1431
|
+
_type: void 0,
|
|
1432
|
+
// should never be used directly
|
|
1433
|
+
[validatorSymbol]: true,
|
|
1434
|
+
get jsonSchema() {
|
|
1435
|
+
if (typeof jsonSchema2 === "function") {
|
|
1436
|
+
jsonSchema2 = jsonSchema2();
|
|
1437
|
+
}
|
|
1438
|
+
return jsonSchema2;
|
|
1439
|
+
},
|
|
1440
|
+
validate
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
function isSchema(value) {
|
|
1444
|
+
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
|
|
1445
|
+
}
|
|
1446
|
+
function asSchema(schema) {
|
|
1447
|
+
return schema == null ? jsonSchema({
|
|
1448
|
+
properties: {},
|
|
1449
|
+
additionalProperties: false
|
|
1450
|
+
}) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
|
|
1451
|
+
}
|
|
1452
|
+
var __defProp = Object.defineProperty;
|
|
1453
|
+
var __export = (target, all) => {
|
|
1454
|
+
for (var name16 in all)
|
|
1455
|
+
__defProp(target, name16, { get: all[name16], enumerable: true });
|
|
1456
|
+
};
|
|
1457
|
+
var name62 = "AI_NoObjectGeneratedError";
|
|
1458
|
+
var marker62 = `vercel.ai.error.${name62}`;
|
|
1459
|
+
var symbol62 = Symbol.for(marker62);
|
|
1460
|
+
var _a62;
|
|
1461
|
+
var NoObjectGeneratedError = class extends AISDKError {
|
|
1462
|
+
constructor({
|
|
1463
|
+
message = "No object generated.",
|
|
1464
|
+
cause,
|
|
1465
|
+
text: text2,
|
|
1466
|
+
response,
|
|
1467
|
+
usage,
|
|
1468
|
+
finishReason
|
|
1469
|
+
}) {
|
|
1470
|
+
super({ name: name62, message, cause });
|
|
1471
|
+
this[_a62] = true;
|
|
1472
|
+
this.text = text2;
|
|
1473
|
+
this.response = response;
|
|
1474
|
+
this.usage = usage;
|
|
1475
|
+
this.finishReason = finishReason;
|
|
1476
|
+
}
|
|
1477
|
+
static isInstance(error) {
|
|
1478
|
+
return AISDKError.hasMarker(error, marker62);
|
|
1479
|
+
}
|
|
1480
|
+
};
|
|
1481
|
+
_a62 = symbol62;
|
|
1482
|
+
var dataContentSchema = z.union([
|
|
1483
|
+
z.string(),
|
|
1484
|
+
z.instanceof(Uint8Array),
|
|
1485
|
+
z.instanceof(ArrayBuffer),
|
|
1486
|
+
z.custom(
|
|
1487
|
+
// Buffer might not be available in some environments such as CloudFlare:
|
|
1488
|
+
(value) => {
|
|
1489
|
+
var _a16, _b;
|
|
1490
|
+
return (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;
|
|
1491
|
+
},
|
|
1492
|
+
{ message: "Must be a Buffer" }
|
|
1493
|
+
)
|
|
1494
|
+
]);
|
|
1495
|
+
var jsonValueSchema = z.lazy(
|
|
1496
|
+
() => z.union([
|
|
1497
|
+
z.null(),
|
|
1498
|
+
z.string(),
|
|
1499
|
+
z.number(),
|
|
1500
|
+
z.boolean(),
|
|
1501
|
+
z.record(z.string(), jsonValueSchema),
|
|
1502
|
+
z.array(jsonValueSchema)
|
|
1503
|
+
])
|
|
1504
|
+
);
|
|
1505
|
+
var providerMetadataSchema = z.record(
|
|
1506
|
+
z.string(),
|
|
1507
|
+
z.record(z.string(), jsonValueSchema)
|
|
1508
|
+
);
|
|
1509
|
+
var textPartSchema = z.object({
|
|
1510
|
+
type: z.literal("text"),
|
|
1511
|
+
text: z.string(),
|
|
1512
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1513
|
+
});
|
|
1514
|
+
var imagePartSchema = z.object({
|
|
1515
|
+
type: z.literal("image"),
|
|
1516
|
+
image: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1517
|
+
mediaType: z.string().optional(),
|
|
1518
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1519
|
+
});
|
|
1520
|
+
var filePartSchema = z.object({
|
|
1521
|
+
type: z.literal("file"),
|
|
1522
|
+
data: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1523
|
+
filename: z.string().optional(),
|
|
1524
|
+
mediaType: z.string(),
|
|
1525
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1526
|
+
});
|
|
1527
|
+
var reasoningPartSchema = z.object({
|
|
1528
|
+
type: z.literal("reasoning"),
|
|
1529
|
+
text: z.string(),
|
|
1530
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1531
|
+
});
|
|
1532
|
+
var toolCallPartSchema = z.object({
|
|
1533
|
+
type: z.literal("tool-call"),
|
|
1534
|
+
toolCallId: z.string(),
|
|
1535
|
+
toolName: z.string(),
|
|
1536
|
+
input: z.unknown(),
|
|
1537
|
+
providerOptions: providerMetadataSchema.optional(),
|
|
1538
|
+
providerExecuted: z.boolean().optional()
|
|
1539
|
+
});
|
|
1540
|
+
var outputSchema = z.discriminatedUnion("type", [
|
|
1541
|
+
z.object({
|
|
1542
|
+
type: z.literal("text"),
|
|
1543
|
+
value: z.string()
|
|
1544
|
+
}),
|
|
1545
|
+
z.object({
|
|
1546
|
+
type: z.literal("json"),
|
|
1547
|
+
value: jsonValueSchema
|
|
1548
|
+
}),
|
|
1549
|
+
z.object({
|
|
1550
|
+
type: z.literal("error-text"),
|
|
1551
|
+
value: z.string()
|
|
1552
|
+
}),
|
|
1553
|
+
z.object({
|
|
1554
|
+
type: z.literal("error-json"),
|
|
1555
|
+
value: jsonValueSchema
|
|
1556
|
+
}),
|
|
1557
|
+
z.object({
|
|
1558
|
+
type: z.literal("content"),
|
|
1559
|
+
value: z.array(
|
|
1560
|
+
z.union([
|
|
1561
|
+
z.object({
|
|
1562
|
+
type: z.literal("text"),
|
|
1563
|
+
text: z.string()
|
|
1564
|
+
}),
|
|
1565
|
+
z.object({
|
|
1566
|
+
type: z.literal("media"),
|
|
1567
|
+
data: z.string(),
|
|
1568
|
+
mediaType: z.string()
|
|
1569
|
+
})
|
|
1570
|
+
])
|
|
1571
|
+
)
|
|
1572
|
+
})
|
|
1573
|
+
]);
|
|
1574
|
+
var toolResultPartSchema = z.object({
|
|
1575
|
+
type: z.literal("tool-result"),
|
|
1576
|
+
toolCallId: z.string(),
|
|
1577
|
+
toolName: z.string(),
|
|
1578
|
+
output: outputSchema,
|
|
1579
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1580
|
+
});
|
|
1581
|
+
var systemModelMessageSchema = z.object(
|
|
1582
|
+
{
|
|
1583
|
+
role: z.literal("system"),
|
|
1584
|
+
content: z.string(),
|
|
1585
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1586
|
+
}
|
|
1587
|
+
);
|
|
1588
|
+
var userModelMessageSchema = z.object({
|
|
1589
|
+
role: z.literal("user"),
|
|
1590
|
+
content: z.union([
|
|
1591
|
+
z.string(),
|
|
1592
|
+
z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
|
|
1593
|
+
]),
|
|
1594
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1595
|
+
});
|
|
1596
|
+
var assistantModelMessageSchema = z.object({
|
|
1597
|
+
role: z.literal("assistant"),
|
|
1598
|
+
content: z.union([
|
|
1599
|
+
z.string(),
|
|
1600
|
+
z.array(
|
|
1601
|
+
z.union([
|
|
1602
|
+
textPartSchema,
|
|
1603
|
+
filePartSchema,
|
|
1604
|
+
reasoningPartSchema,
|
|
1605
|
+
toolCallPartSchema,
|
|
1606
|
+
toolResultPartSchema
|
|
1607
|
+
])
|
|
1608
|
+
)
|
|
1609
|
+
]),
|
|
1610
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1611
|
+
});
|
|
1612
|
+
var toolModelMessageSchema = z.object({
|
|
1613
|
+
role: z.literal("tool"),
|
|
1614
|
+
content: z.array(toolResultPartSchema),
|
|
1615
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1616
|
+
});
|
|
1617
|
+
z.union([
|
|
1618
|
+
systemModelMessageSchema,
|
|
1619
|
+
userModelMessageSchema,
|
|
1620
|
+
assistantModelMessageSchema,
|
|
1621
|
+
toolModelMessageSchema
|
|
1622
|
+
]);
|
|
1623
|
+
function asArray(value) {
|
|
1624
|
+
return value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
1625
|
+
}
|
|
1626
|
+
createIdGenerator({
|
|
1627
|
+
prefix: "aitxt",
|
|
1628
|
+
size: 24
|
|
1629
|
+
});
|
|
1630
|
+
function prepareHeaders(headers, defaultHeaders) {
|
|
1631
|
+
const responseHeaders = new Headers(headers != null ? headers : {});
|
|
1632
|
+
for (const [key, value] of Object.entries(defaultHeaders)) {
|
|
1633
|
+
if (!responseHeaders.has(key)) {
|
|
1634
|
+
responseHeaders.set(key, value);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
return responseHeaders;
|
|
1638
|
+
}
|
|
1639
|
+
var JsonToSseTransformStream = class extends TransformStream {
|
|
1640
|
+
constructor() {
|
|
1641
|
+
super({
|
|
1642
|
+
transform(part, controller) {
|
|
1643
|
+
controller.enqueue(`data: ${JSON.stringify(part)}
|
|
1644
|
+
|
|
1645
|
+
`);
|
|
1646
|
+
},
|
|
1647
|
+
flush(controller) {
|
|
1648
|
+
controller.enqueue("data: [DONE]\n\n");
|
|
1649
|
+
}
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
var UI_MESSAGE_STREAM_HEADERS = {
|
|
1654
|
+
"content-type": "text/event-stream",
|
|
1655
|
+
"cache-control": "no-cache",
|
|
1656
|
+
connection: "keep-alive",
|
|
1657
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
|
1658
|
+
"x-accel-buffering": "no"
|
|
1659
|
+
// disable nginx buffering
|
|
1660
|
+
};
|
|
1661
|
+
function createUIMessageStreamResponse({
|
|
1662
|
+
status,
|
|
1663
|
+
statusText,
|
|
1664
|
+
headers,
|
|
1665
|
+
stream,
|
|
1666
|
+
consumeSseStream
|
|
1667
|
+
}) {
|
|
1668
|
+
let sseStream = stream.pipeThrough(new JsonToSseTransformStream());
|
|
1669
|
+
if (consumeSseStream) {
|
|
1670
|
+
const [stream1, stream2] = sseStream.tee();
|
|
1671
|
+
sseStream = stream1;
|
|
1672
|
+
consumeSseStream({ stream: stream2 });
|
|
1673
|
+
}
|
|
1674
|
+
return new Response(sseStream.pipeThrough(new TextEncoderStream()), {
|
|
1675
|
+
status,
|
|
1676
|
+
statusText,
|
|
1677
|
+
headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
function isDataUIMessageChunk(chunk) {
|
|
1681
|
+
return chunk.type.startsWith("data-");
|
|
1682
|
+
}
|
|
1683
|
+
function mergeObjects(base, overrides) {
|
|
1684
|
+
if (base === void 0 && overrides === void 0) {
|
|
1685
|
+
return void 0;
|
|
1686
|
+
}
|
|
1687
|
+
if (base === void 0) {
|
|
1688
|
+
return overrides;
|
|
1689
|
+
}
|
|
1690
|
+
if (overrides === void 0) {
|
|
1691
|
+
return base;
|
|
1692
|
+
}
|
|
1693
|
+
const result = { ...base };
|
|
1694
|
+
for (const key in overrides) {
|
|
1695
|
+
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
|
|
1696
|
+
const overridesValue = overrides[key];
|
|
1697
|
+
if (overridesValue === void 0)
|
|
1698
|
+
continue;
|
|
1699
|
+
const baseValue = key in base ? base[key] : void 0;
|
|
1700
|
+
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
|
|
1701
|
+
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
|
|
1702
|
+
if (isSourceObject && isTargetObject) {
|
|
1703
|
+
result[key] = mergeObjects(
|
|
1704
|
+
baseValue,
|
|
1705
|
+
overridesValue
|
|
1706
|
+
);
|
|
1707
|
+
} else {
|
|
1708
|
+
result[key] = overridesValue;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
return result;
|
|
1713
|
+
}
|
|
1714
|
+
function fixJson(input) {
|
|
1715
|
+
const stack = ["ROOT"];
|
|
1716
|
+
let lastValidIndex = -1;
|
|
1717
|
+
let literalStart = null;
|
|
1718
|
+
function processValueStart(char, i, swapState) {
|
|
1719
|
+
{
|
|
1720
|
+
switch (char) {
|
|
1721
|
+
case '"': {
|
|
1722
|
+
lastValidIndex = i;
|
|
1723
|
+
stack.pop();
|
|
1724
|
+
stack.push(swapState);
|
|
1725
|
+
stack.push("INSIDE_STRING");
|
|
1726
|
+
break;
|
|
1727
|
+
}
|
|
1728
|
+
case "f":
|
|
1729
|
+
case "t":
|
|
1730
|
+
case "n": {
|
|
1731
|
+
lastValidIndex = i;
|
|
1732
|
+
literalStart = i;
|
|
1733
|
+
stack.pop();
|
|
1734
|
+
stack.push(swapState);
|
|
1735
|
+
stack.push("INSIDE_LITERAL");
|
|
1736
|
+
break;
|
|
1737
|
+
}
|
|
1738
|
+
case "-": {
|
|
1739
|
+
stack.pop();
|
|
1740
|
+
stack.push(swapState);
|
|
1741
|
+
stack.push("INSIDE_NUMBER");
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
case "0":
|
|
1745
|
+
case "1":
|
|
1746
|
+
case "2":
|
|
1747
|
+
case "3":
|
|
1748
|
+
case "4":
|
|
1749
|
+
case "5":
|
|
1750
|
+
case "6":
|
|
1751
|
+
case "7":
|
|
1752
|
+
case "8":
|
|
1753
|
+
case "9": {
|
|
1754
|
+
lastValidIndex = i;
|
|
1755
|
+
stack.pop();
|
|
1756
|
+
stack.push(swapState);
|
|
1757
|
+
stack.push("INSIDE_NUMBER");
|
|
1758
|
+
break;
|
|
1759
|
+
}
|
|
1760
|
+
case "{": {
|
|
1761
|
+
lastValidIndex = i;
|
|
1762
|
+
stack.pop();
|
|
1763
|
+
stack.push(swapState);
|
|
1764
|
+
stack.push("INSIDE_OBJECT_START");
|
|
1765
|
+
break;
|
|
1766
|
+
}
|
|
1767
|
+
case "[": {
|
|
1768
|
+
lastValidIndex = i;
|
|
1769
|
+
stack.pop();
|
|
1770
|
+
stack.push(swapState);
|
|
1771
|
+
stack.push("INSIDE_ARRAY_START");
|
|
1772
|
+
break;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
function processAfterObjectValue(char, i) {
|
|
1778
|
+
switch (char) {
|
|
1779
|
+
case ",": {
|
|
1780
|
+
stack.pop();
|
|
1781
|
+
stack.push("INSIDE_OBJECT_AFTER_COMMA");
|
|
1782
|
+
break;
|
|
1783
|
+
}
|
|
1784
|
+
case "}": {
|
|
1785
|
+
lastValidIndex = i;
|
|
1786
|
+
stack.pop();
|
|
1787
|
+
break;
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
function processAfterArrayValue(char, i) {
|
|
1792
|
+
switch (char) {
|
|
1793
|
+
case ",": {
|
|
1794
|
+
stack.pop();
|
|
1795
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1796
|
+
break;
|
|
1797
|
+
}
|
|
1798
|
+
case "]": {
|
|
1799
|
+
lastValidIndex = i;
|
|
1800
|
+
stack.pop();
|
|
1801
|
+
break;
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
for (let i = 0; i < input.length; i++) {
|
|
1806
|
+
const char = input[i];
|
|
1807
|
+
const currentState = stack[stack.length - 1];
|
|
1808
|
+
switch (currentState) {
|
|
1809
|
+
case "ROOT":
|
|
1810
|
+
processValueStart(char, i, "FINISH");
|
|
1811
|
+
break;
|
|
1812
|
+
case "INSIDE_OBJECT_START": {
|
|
1813
|
+
switch (char) {
|
|
1814
|
+
case '"': {
|
|
1815
|
+
stack.pop();
|
|
1816
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1817
|
+
break;
|
|
1818
|
+
}
|
|
1819
|
+
case "}": {
|
|
1820
|
+
lastValidIndex = i;
|
|
1821
|
+
stack.pop();
|
|
1822
|
+
break;
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
break;
|
|
1826
|
+
}
|
|
1827
|
+
case "INSIDE_OBJECT_AFTER_COMMA": {
|
|
1828
|
+
switch (char) {
|
|
1829
|
+
case '"': {
|
|
1830
|
+
stack.pop();
|
|
1831
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1832
|
+
break;
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
break;
|
|
1836
|
+
}
|
|
1837
|
+
case "INSIDE_OBJECT_KEY": {
|
|
1838
|
+
switch (char) {
|
|
1839
|
+
case '"': {
|
|
1840
|
+
stack.pop();
|
|
1841
|
+
stack.push("INSIDE_OBJECT_AFTER_KEY");
|
|
1842
|
+
break;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
break;
|
|
1846
|
+
}
|
|
1847
|
+
case "INSIDE_OBJECT_AFTER_KEY": {
|
|
1848
|
+
switch (char) {
|
|
1849
|
+
case ":": {
|
|
1850
|
+
stack.pop();
|
|
1851
|
+
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
|
|
1852
|
+
break;
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
break;
|
|
1856
|
+
}
|
|
1857
|
+
case "INSIDE_OBJECT_BEFORE_VALUE": {
|
|
1858
|
+
processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
1862
|
+
processAfterObjectValue(char, i);
|
|
1863
|
+
break;
|
|
1864
|
+
}
|
|
1865
|
+
case "INSIDE_STRING": {
|
|
1866
|
+
switch (char) {
|
|
1867
|
+
case '"': {
|
|
1868
|
+
stack.pop();
|
|
1869
|
+
lastValidIndex = i;
|
|
1870
|
+
break;
|
|
1871
|
+
}
|
|
1872
|
+
case "\\": {
|
|
1873
|
+
stack.push("INSIDE_STRING_ESCAPE");
|
|
1874
|
+
break;
|
|
1875
|
+
}
|
|
1876
|
+
default: {
|
|
1877
|
+
lastValidIndex = i;
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
break;
|
|
1881
|
+
}
|
|
1882
|
+
case "INSIDE_ARRAY_START": {
|
|
1883
|
+
switch (char) {
|
|
1884
|
+
case "]": {
|
|
1885
|
+
lastValidIndex = i;
|
|
1886
|
+
stack.pop();
|
|
1887
|
+
break;
|
|
1888
|
+
}
|
|
1889
|
+
default: {
|
|
1890
|
+
lastValidIndex = i;
|
|
1891
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1892
|
+
break;
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
break;
|
|
1896
|
+
}
|
|
1897
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
1898
|
+
switch (char) {
|
|
1899
|
+
case ",": {
|
|
1900
|
+
stack.pop();
|
|
1901
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1902
|
+
break;
|
|
1903
|
+
}
|
|
1904
|
+
case "]": {
|
|
1905
|
+
lastValidIndex = i;
|
|
1906
|
+
stack.pop();
|
|
1907
|
+
break;
|
|
1908
|
+
}
|
|
1909
|
+
default: {
|
|
1910
|
+
lastValidIndex = i;
|
|
1911
|
+
break;
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
break;
|
|
1915
|
+
}
|
|
1916
|
+
case "INSIDE_ARRAY_AFTER_COMMA": {
|
|
1917
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1918
|
+
break;
|
|
1919
|
+
}
|
|
1920
|
+
case "INSIDE_STRING_ESCAPE": {
|
|
1921
|
+
stack.pop();
|
|
1922
|
+
lastValidIndex = i;
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
case "INSIDE_NUMBER": {
|
|
1926
|
+
switch (char) {
|
|
1927
|
+
case "0":
|
|
1928
|
+
case "1":
|
|
1929
|
+
case "2":
|
|
1930
|
+
case "3":
|
|
1931
|
+
case "4":
|
|
1932
|
+
case "5":
|
|
1933
|
+
case "6":
|
|
1934
|
+
case "7":
|
|
1935
|
+
case "8":
|
|
1936
|
+
case "9": {
|
|
1937
|
+
lastValidIndex = i;
|
|
1938
|
+
break;
|
|
1939
|
+
}
|
|
1940
|
+
case "e":
|
|
1941
|
+
case "E":
|
|
1942
|
+
case "-":
|
|
1943
|
+
case ".": {
|
|
1944
|
+
break;
|
|
1945
|
+
}
|
|
1946
|
+
case ",": {
|
|
1947
|
+
stack.pop();
|
|
1948
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1949
|
+
processAfterArrayValue(char, i);
|
|
1950
|
+
}
|
|
1951
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1952
|
+
processAfterObjectValue(char, i);
|
|
1953
|
+
}
|
|
1954
|
+
break;
|
|
1955
|
+
}
|
|
1956
|
+
case "}": {
|
|
1957
|
+
stack.pop();
|
|
1958
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1959
|
+
processAfterObjectValue(char, i);
|
|
1960
|
+
}
|
|
1961
|
+
break;
|
|
1962
|
+
}
|
|
1963
|
+
case "]": {
|
|
1964
|
+
stack.pop();
|
|
1965
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1966
|
+
processAfterArrayValue(char, i);
|
|
1967
|
+
}
|
|
1968
|
+
break;
|
|
1969
|
+
}
|
|
1970
|
+
default: {
|
|
1971
|
+
stack.pop();
|
|
1972
|
+
break;
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
break;
|
|
1976
|
+
}
|
|
1977
|
+
case "INSIDE_LITERAL": {
|
|
1978
|
+
const partialLiteral = input.substring(literalStart, i + 1);
|
|
1979
|
+
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
|
|
1980
|
+
stack.pop();
|
|
1981
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1982
|
+
processAfterObjectValue(char, i);
|
|
1983
|
+
} else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1984
|
+
processAfterArrayValue(char, i);
|
|
1985
|
+
}
|
|
1986
|
+
} else {
|
|
1987
|
+
lastValidIndex = i;
|
|
1988
|
+
}
|
|
1989
|
+
break;
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
let result = input.slice(0, lastValidIndex + 1);
|
|
1994
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
1995
|
+
const state = stack[i];
|
|
1996
|
+
switch (state) {
|
|
1997
|
+
case "INSIDE_STRING": {
|
|
1998
|
+
result += '"';
|
|
1999
|
+
break;
|
|
2000
|
+
}
|
|
2001
|
+
case "INSIDE_OBJECT_KEY":
|
|
2002
|
+
case "INSIDE_OBJECT_AFTER_KEY":
|
|
2003
|
+
case "INSIDE_OBJECT_AFTER_COMMA":
|
|
2004
|
+
case "INSIDE_OBJECT_START":
|
|
2005
|
+
case "INSIDE_OBJECT_BEFORE_VALUE":
|
|
2006
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
2007
|
+
result += "}";
|
|
2008
|
+
break;
|
|
2009
|
+
}
|
|
2010
|
+
case "INSIDE_ARRAY_START":
|
|
2011
|
+
case "INSIDE_ARRAY_AFTER_COMMA":
|
|
2012
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
2013
|
+
result += "]";
|
|
2014
|
+
break;
|
|
2015
|
+
}
|
|
2016
|
+
case "INSIDE_LITERAL": {
|
|
2017
|
+
const partialLiteral = input.substring(literalStart, input.length);
|
|
2018
|
+
if ("true".startsWith(partialLiteral)) {
|
|
2019
|
+
result += "true".slice(partialLiteral.length);
|
|
2020
|
+
} else if ("false".startsWith(partialLiteral)) {
|
|
2021
|
+
result += "false".slice(partialLiteral.length);
|
|
2022
|
+
} else if ("null".startsWith(partialLiteral)) {
|
|
2023
|
+
result += "null".slice(partialLiteral.length);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
return result;
|
|
2029
|
+
}
|
|
2030
|
+
async function parsePartialJson(jsonText) {
|
|
2031
|
+
if (jsonText === void 0) {
|
|
2032
|
+
return { value: void 0, state: "undefined-input" };
|
|
2033
|
+
}
|
|
2034
|
+
let result = await safeParseJSON({ text: jsonText });
|
|
2035
|
+
if (result.success) {
|
|
2036
|
+
return { value: result.value, state: "successful-parse" };
|
|
2037
|
+
}
|
|
2038
|
+
result = await safeParseJSON({ text: fixJson(jsonText) });
|
|
2039
|
+
if (result.success) {
|
|
2040
|
+
return { value: result.value, state: "repaired-parse" };
|
|
2041
|
+
}
|
|
2042
|
+
return { value: void 0, state: "failed-parse" };
|
|
2043
|
+
}
|
|
2044
|
+
function isToolUIPart(part) {
|
|
2045
|
+
return part.type.startsWith("tool-");
|
|
2046
|
+
}
|
|
2047
|
+
function getToolName(part) {
|
|
2048
|
+
return part.type.split("-").slice(1).join("-");
|
|
2049
|
+
}
|
|
2050
|
+
function createStreamingUIMessageState({
|
|
2051
|
+
lastMessage,
|
|
2052
|
+
messageId
|
|
2053
|
+
}) {
|
|
2054
|
+
return {
|
|
2055
|
+
message: (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
|
|
2056
|
+
id: messageId,
|
|
2057
|
+
metadata: void 0,
|
|
2058
|
+
role: "assistant",
|
|
2059
|
+
parts: []
|
|
2060
|
+
},
|
|
2061
|
+
activeTextParts: {},
|
|
2062
|
+
activeReasoningParts: {},
|
|
2063
|
+
partialToolCalls: {}
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
function processUIMessageStream({
|
|
2067
|
+
stream,
|
|
2068
|
+
messageMetadataSchema,
|
|
2069
|
+
dataPartSchemas,
|
|
2070
|
+
runUpdateMessageJob,
|
|
2071
|
+
onError,
|
|
2072
|
+
onToolCall,
|
|
2073
|
+
onData
|
|
2074
|
+
}) {
|
|
2075
|
+
return stream.pipeThrough(
|
|
2076
|
+
new TransformStream({
|
|
2077
|
+
async transform(chunk, controller) {
|
|
2078
|
+
await runUpdateMessageJob(async ({ state, write }) => {
|
|
2079
|
+
var _a16, _b, _c, _d;
|
|
2080
|
+
function getToolInvocation(toolCallId) {
|
|
2081
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2082
|
+
const toolInvocation = toolInvocations.find(
|
|
2083
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2084
|
+
);
|
|
2085
|
+
if (toolInvocation == null) {
|
|
2086
|
+
throw new Error(
|
|
2087
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2088
|
+
);
|
|
2089
|
+
}
|
|
2090
|
+
return toolInvocation;
|
|
2091
|
+
}
|
|
2092
|
+
function getDynamicToolInvocation(toolCallId) {
|
|
2093
|
+
const toolInvocations = state.message.parts.filter(
|
|
2094
|
+
(part) => part.type === "dynamic-tool"
|
|
2095
|
+
);
|
|
2096
|
+
const toolInvocation = toolInvocations.find(
|
|
2097
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2098
|
+
);
|
|
2099
|
+
if (toolInvocation == null) {
|
|
2100
|
+
throw new Error(
|
|
2101
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2102
|
+
);
|
|
2103
|
+
}
|
|
2104
|
+
return toolInvocation;
|
|
2105
|
+
}
|
|
2106
|
+
function updateToolPart(options) {
|
|
2107
|
+
var _a17;
|
|
2108
|
+
const part = state.message.parts.find(
|
|
2109
|
+
(part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
|
|
2110
|
+
);
|
|
2111
|
+
const anyOptions = options;
|
|
2112
|
+
const anyPart = part;
|
|
2113
|
+
if (part != null) {
|
|
2114
|
+
part.state = options.state;
|
|
2115
|
+
anyPart.input = anyOptions.input;
|
|
2116
|
+
anyPart.output = anyOptions.output;
|
|
2117
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2118
|
+
anyPart.rawInput = anyOptions.rawInput;
|
|
2119
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2120
|
+
anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
|
|
2121
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2122
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2123
|
+
}
|
|
2124
|
+
} else {
|
|
2125
|
+
state.message.parts.push({
|
|
2126
|
+
type: `tool-${options.toolName}`,
|
|
2127
|
+
toolCallId: options.toolCallId,
|
|
2128
|
+
state: options.state,
|
|
2129
|
+
input: anyOptions.input,
|
|
2130
|
+
output: anyOptions.output,
|
|
2131
|
+
rawInput: anyOptions.rawInput,
|
|
2132
|
+
errorText: anyOptions.errorText,
|
|
2133
|
+
providerExecuted: anyOptions.providerExecuted,
|
|
2134
|
+
preliminary: anyOptions.preliminary,
|
|
2135
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
function updateDynamicToolPart(options) {
|
|
2140
|
+
var _a17, _b2;
|
|
2141
|
+
const part = state.message.parts.find(
|
|
2142
|
+
(part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
|
|
2143
|
+
);
|
|
2144
|
+
const anyOptions = options;
|
|
2145
|
+
const anyPart = part;
|
|
2146
|
+
if (part != null) {
|
|
2147
|
+
part.state = options.state;
|
|
2148
|
+
anyPart.toolName = options.toolName;
|
|
2149
|
+
anyPart.input = anyOptions.input;
|
|
2150
|
+
anyPart.output = anyOptions.output;
|
|
2151
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2152
|
+
anyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;
|
|
2153
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2154
|
+
anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;
|
|
2155
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2156
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2157
|
+
}
|
|
2158
|
+
} else {
|
|
2159
|
+
state.message.parts.push({
|
|
2160
|
+
type: "dynamic-tool",
|
|
2161
|
+
toolName: options.toolName,
|
|
2162
|
+
toolCallId: options.toolCallId,
|
|
2163
|
+
state: options.state,
|
|
2164
|
+
input: anyOptions.input,
|
|
2165
|
+
output: anyOptions.output,
|
|
2166
|
+
errorText: anyOptions.errorText,
|
|
2167
|
+
preliminary: anyOptions.preliminary,
|
|
2168
|
+
providerExecuted: anyOptions.providerExecuted,
|
|
2169
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
async function updateMessageMetadata(metadata) {
|
|
2174
|
+
if (metadata != null) {
|
|
2175
|
+
const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
|
|
2176
|
+
if (messageMetadataSchema != null) {
|
|
2177
|
+
await validateTypes({
|
|
2178
|
+
value: mergedMetadata,
|
|
2179
|
+
schema: messageMetadataSchema
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
state.message.metadata = mergedMetadata;
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
switch (chunk.type) {
|
|
2186
|
+
case "text-start": {
|
|
2187
|
+
const textPart = {
|
|
2188
|
+
type: "text",
|
|
2189
|
+
text: "",
|
|
2190
|
+
providerMetadata: chunk.providerMetadata,
|
|
2191
|
+
state: "streaming"
|
|
2192
|
+
};
|
|
2193
|
+
state.activeTextParts[chunk.id] = textPart;
|
|
2194
|
+
state.message.parts.push(textPart);
|
|
2195
|
+
write();
|
|
2196
|
+
break;
|
|
2197
|
+
}
|
|
2198
|
+
case "text-delta": {
|
|
2199
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2200
|
+
textPart.text += chunk.delta;
|
|
2201
|
+
textPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;
|
|
2202
|
+
write();
|
|
2203
|
+
break;
|
|
2204
|
+
}
|
|
2205
|
+
case "text-end": {
|
|
2206
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2207
|
+
textPart.state = "done";
|
|
2208
|
+
textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;
|
|
2209
|
+
delete state.activeTextParts[chunk.id];
|
|
2210
|
+
write();
|
|
2211
|
+
break;
|
|
2212
|
+
}
|
|
2213
|
+
case "reasoning-start": {
|
|
2214
|
+
const reasoningPart = {
|
|
2215
|
+
type: "reasoning",
|
|
2216
|
+
text: "",
|
|
2217
|
+
providerMetadata: chunk.providerMetadata,
|
|
2218
|
+
state: "streaming"
|
|
2219
|
+
};
|
|
2220
|
+
state.activeReasoningParts[chunk.id] = reasoningPart;
|
|
2221
|
+
state.message.parts.push(reasoningPart);
|
|
2222
|
+
write();
|
|
2223
|
+
break;
|
|
2224
|
+
}
|
|
2225
|
+
case "reasoning-delta": {
|
|
2226
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2227
|
+
reasoningPart.text += chunk.delta;
|
|
2228
|
+
reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
|
|
2229
|
+
write();
|
|
2230
|
+
break;
|
|
2231
|
+
}
|
|
2232
|
+
case "reasoning-end": {
|
|
2233
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2234
|
+
reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
|
|
2235
|
+
reasoningPart.state = "done";
|
|
2236
|
+
delete state.activeReasoningParts[chunk.id];
|
|
2237
|
+
write();
|
|
2238
|
+
break;
|
|
2239
|
+
}
|
|
2240
|
+
case "file": {
|
|
2241
|
+
state.message.parts.push({
|
|
2242
|
+
type: "file",
|
|
2243
|
+
mediaType: chunk.mediaType,
|
|
2244
|
+
url: chunk.url
|
|
2245
|
+
});
|
|
2246
|
+
write();
|
|
2247
|
+
break;
|
|
2248
|
+
}
|
|
2249
|
+
case "source-url": {
|
|
2250
|
+
state.message.parts.push({
|
|
2251
|
+
type: "source-url",
|
|
2252
|
+
sourceId: chunk.sourceId,
|
|
2253
|
+
url: chunk.url,
|
|
2254
|
+
title: chunk.title,
|
|
2255
|
+
providerMetadata: chunk.providerMetadata
|
|
2256
|
+
});
|
|
2257
|
+
write();
|
|
2258
|
+
break;
|
|
2259
|
+
}
|
|
2260
|
+
case "source-document": {
|
|
2261
|
+
state.message.parts.push({
|
|
2262
|
+
type: "source-document",
|
|
2263
|
+
sourceId: chunk.sourceId,
|
|
2264
|
+
mediaType: chunk.mediaType,
|
|
2265
|
+
title: chunk.title,
|
|
2266
|
+
filename: chunk.filename,
|
|
2267
|
+
providerMetadata: chunk.providerMetadata
|
|
2268
|
+
});
|
|
2269
|
+
write();
|
|
2270
|
+
break;
|
|
2271
|
+
}
|
|
2272
|
+
case "tool-input-start": {
|
|
2273
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2274
|
+
state.partialToolCalls[chunk.toolCallId] = {
|
|
2275
|
+
text: "",
|
|
2276
|
+
toolName: chunk.toolName,
|
|
2277
|
+
index: toolInvocations.length,
|
|
2278
|
+
dynamic: chunk.dynamic
|
|
2279
|
+
};
|
|
2280
|
+
if (chunk.dynamic) {
|
|
2281
|
+
updateDynamicToolPart({
|
|
2282
|
+
toolCallId: chunk.toolCallId,
|
|
2283
|
+
toolName: chunk.toolName,
|
|
2284
|
+
state: "input-streaming",
|
|
2285
|
+
input: void 0,
|
|
2286
|
+
providerExecuted: chunk.providerExecuted
|
|
2287
|
+
});
|
|
2288
|
+
} else {
|
|
2289
|
+
updateToolPart({
|
|
2290
|
+
toolCallId: chunk.toolCallId,
|
|
2291
|
+
toolName: chunk.toolName,
|
|
2292
|
+
state: "input-streaming",
|
|
2293
|
+
input: void 0,
|
|
2294
|
+
providerExecuted: chunk.providerExecuted
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
write();
|
|
2298
|
+
break;
|
|
2299
|
+
}
|
|
2300
|
+
case "tool-input-delta": {
|
|
2301
|
+
const partialToolCall = state.partialToolCalls[chunk.toolCallId];
|
|
2302
|
+
partialToolCall.text += chunk.inputTextDelta;
|
|
2303
|
+
const { value: partialArgs } = await parsePartialJson(
|
|
2304
|
+
partialToolCall.text
|
|
2305
|
+
);
|
|
2306
|
+
if (partialToolCall.dynamic) {
|
|
2307
|
+
updateDynamicToolPart({
|
|
2308
|
+
toolCallId: chunk.toolCallId,
|
|
2309
|
+
toolName: partialToolCall.toolName,
|
|
2310
|
+
state: "input-streaming",
|
|
2311
|
+
input: partialArgs
|
|
2312
|
+
});
|
|
2313
|
+
} else {
|
|
2314
|
+
updateToolPart({
|
|
2315
|
+
toolCallId: chunk.toolCallId,
|
|
2316
|
+
toolName: partialToolCall.toolName,
|
|
2317
|
+
state: "input-streaming",
|
|
2318
|
+
input: partialArgs
|
|
2319
|
+
});
|
|
2320
|
+
}
|
|
2321
|
+
write();
|
|
2322
|
+
break;
|
|
2323
|
+
}
|
|
2324
|
+
case "tool-input-available": {
|
|
2325
|
+
if (chunk.dynamic) {
|
|
2326
|
+
updateDynamicToolPart({
|
|
2327
|
+
toolCallId: chunk.toolCallId,
|
|
2328
|
+
toolName: chunk.toolName,
|
|
2329
|
+
state: "input-available",
|
|
2330
|
+
input: chunk.input,
|
|
2331
|
+
providerExecuted: chunk.providerExecuted,
|
|
2332
|
+
providerMetadata: chunk.providerMetadata
|
|
2333
|
+
});
|
|
2334
|
+
} else {
|
|
2335
|
+
updateToolPart({
|
|
2336
|
+
toolCallId: chunk.toolCallId,
|
|
2337
|
+
toolName: chunk.toolName,
|
|
2338
|
+
state: "input-available",
|
|
2339
|
+
input: chunk.input,
|
|
2340
|
+
providerExecuted: chunk.providerExecuted,
|
|
2341
|
+
providerMetadata: chunk.providerMetadata
|
|
2342
|
+
});
|
|
2343
|
+
}
|
|
2344
|
+
write();
|
|
2345
|
+
if (onToolCall && !chunk.providerExecuted) {
|
|
2346
|
+
await onToolCall({
|
|
2347
|
+
toolCall: chunk
|
|
2348
|
+
});
|
|
2349
|
+
}
|
|
2350
|
+
break;
|
|
2351
|
+
}
|
|
2352
|
+
case "tool-input-error": {
|
|
2353
|
+
if (chunk.dynamic) {
|
|
2354
|
+
updateDynamicToolPart({
|
|
2355
|
+
toolCallId: chunk.toolCallId,
|
|
2356
|
+
toolName: chunk.toolName,
|
|
2357
|
+
state: "output-error",
|
|
2358
|
+
input: chunk.input,
|
|
2359
|
+
errorText: chunk.errorText,
|
|
2360
|
+
providerExecuted: chunk.providerExecuted,
|
|
2361
|
+
providerMetadata: chunk.providerMetadata
|
|
2362
|
+
});
|
|
2363
|
+
} else {
|
|
2364
|
+
updateToolPart({
|
|
2365
|
+
toolCallId: chunk.toolCallId,
|
|
2366
|
+
toolName: chunk.toolName,
|
|
2367
|
+
state: "output-error",
|
|
2368
|
+
input: void 0,
|
|
2369
|
+
rawInput: chunk.input,
|
|
2370
|
+
errorText: chunk.errorText,
|
|
2371
|
+
providerExecuted: chunk.providerExecuted,
|
|
2372
|
+
providerMetadata: chunk.providerMetadata
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
write();
|
|
2376
|
+
break;
|
|
2377
|
+
}
|
|
2378
|
+
case "tool-output-available": {
|
|
2379
|
+
if (chunk.dynamic) {
|
|
2380
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2381
|
+
chunk.toolCallId
|
|
2382
|
+
);
|
|
2383
|
+
updateDynamicToolPart({
|
|
2384
|
+
toolCallId: chunk.toolCallId,
|
|
2385
|
+
toolName: toolInvocation.toolName,
|
|
2386
|
+
state: "output-available",
|
|
2387
|
+
input: toolInvocation.input,
|
|
2388
|
+
output: chunk.output,
|
|
2389
|
+
preliminary: chunk.preliminary
|
|
2390
|
+
});
|
|
2391
|
+
} else {
|
|
2392
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2393
|
+
updateToolPart({
|
|
2394
|
+
toolCallId: chunk.toolCallId,
|
|
2395
|
+
toolName: getToolName(toolInvocation),
|
|
2396
|
+
state: "output-available",
|
|
2397
|
+
input: toolInvocation.input,
|
|
2398
|
+
output: chunk.output,
|
|
2399
|
+
providerExecuted: chunk.providerExecuted,
|
|
2400
|
+
preliminary: chunk.preliminary
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
write();
|
|
2404
|
+
break;
|
|
2405
|
+
}
|
|
2406
|
+
case "tool-output-error": {
|
|
2407
|
+
if (chunk.dynamic) {
|
|
2408
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2409
|
+
chunk.toolCallId
|
|
2410
|
+
);
|
|
2411
|
+
updateDynamicToolPart({
|
|
2412
|
+
toolCallId: chunk.toolCallId,
|
|
2413
|
+
toolName: toolInvocation.toolName,
|
|
2414
|
+
state: "output-error",
|
|
2415
|
+
input: toolInvocation.input,
|
|
2416
|
+
errorText: chunk.errorText,
|
|
2417
|
+
providerExecuted: chunk.providerExecuted
|
|
2418
|
+
});
|
|
2419
|
+
} else {
|
|
2420
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2421
|
+
updateToolPart({
|
|
2422
|
+
toolCallId: chunk.toolCallId,
|
|
2423
|
+
toolName: getToolName(toolInvocation),
|
|
2424
|
+
state: "output-error",
|
|
2425
|
+
input: toolInvocation.input,
|
|
2426
|
+
rawInput: toolInvocation.rawInput,
|
|
2427
|
+
errorText: chunk.errorText,
|
|
2428
|
+
providerExecuted: chunk.providerExecuted
|
|
2429
|
+
});
|
|
2430
|
+
}
|
|
2431
|
+
write();
|
|
2432
|
+
break;
|
|
2433
|
+
}
|
|
2434
|
+
case "start-step": {
|
|
2435
|
+
state.message.parts.push({ type: "step-start" });
|
|
2436
|
+
break;
|
|
2437
|
+
}
|
|
2438
|
+
case "finish-step": {
|
|
2439
|
+
state.activeTextParts = {};
|
|
2440
|
+
state.activeReasoningParts = {};
|
|
2441
|
+
break;
|
|
2442
|
+
}
|
|
2443
|
+
case "start": {
|
|
2444
|
+
if (chunk.messageId != null) {
|
|
2445
|
+
state.message.id = chunk.messageId;
|
|
2446
|
+
}
|
|
2447
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2448
|
+
if (chunk.messageId != null || chunk.messageMetadata != null) {
|
|
2449
|
+
write();
|
|
2450
|
+
}
|
|
2451
|
+
break;
|
|
2452
|
+
}
|
|
2453
|
+
case "finish": {
|
|
2454
|
+
if (chunk.finishReason != null) {
|
|
2455
|
+
state.finishReason = chunk.finishReason;
|
|
2456
|
+
}
|
|
2457
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2458
|
+
if (chunk.messageMetadata != null) {
|
|
2459
|
+
write();
|
|
2460
|
+
}
|
|
2461
|
+
break;
|
|
2462
|
+
}
|
|
2463
|
+
case "message-metadata": {
|
|
2464
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2465
|
+
if (chunk.messageMetadata != null) {
|
|
2466
|
+
write();
|
|
2467
|
+
}
|
|
2468
|
+
break;
|
|
2469
|
+
}
|
|
2470
|
+
case "error": {
|
|
2471
|
+
onError == null ? void 0 : onError(new Error(chunk.errorText));
|
|
2472
|
+
break;
|
|
2473
|
+
}
|
|
2474
|
+
default: {
|
|
2475
|
+
if (isDataUIMessageChunk(chunk)) {
|
|
2476
|
+
if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {
|
|
2477
|
+
await validateTypes({
|
|
2478
|
+
value: chunk.data,
|
|
2479
|
+
schema: dataPartSchemas[chunk.type]
|
|
2480
|
+
});
|
|
2481
|
+
}
|
|
2482
|
+
const dataChunk = chunk;
|
|
2483
|
+
if (dataChunk.transient) {
|
|
2484
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2485
|
+
break;
|
|
2486
|
+
}
|
|
2487
|
+
const existingUIPart = dataChunk.id != null ? state.message.parts.find(
|
|
2488
|
+
(chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id
|
|
2489
|
+
) : void 0;
|
|
2490
|
+
if (existingUIPart != null) {
|
|
2491
|
+
existingUIPart.data = dataChunk.data;
|
|
2492
|
+
} else {
|
|
2493
|
+
state.message.parts.push(dataChunk);
|
|
2494
|
+
}
|
|
2495
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2496
|
+
write();
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
controller.enqueue(chunk);
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
})
|
|
2504
|
+
);
|
|
2505
|
+
}
|
|
2506
|
+
function handleUIMessageStreamFinish({
|
|
2507
|
+
messageId,
|
|
2508
|
+
originalMessages = [],
|
|
2509
|
+
onFinish,
|
|
2510
|
+
onError,
|
|
2511
|
+
stream
|
|
2512
|
+
}) {
|
|
2513
|
+
let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
|
|
2514
|
+
if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
|
|
2515
|
+
lastMessage = void 0;
|
|
2516
|
+
} else {
|
|
2517
|
+
messageId = lastMessage.id;
|
|
2518
|
+
}
|
|
2519
|
+
let isAborted = false;
|
|
2520
|
+
const idInjectedStream = stream.pipeThrough(
|
|
2521
|
+
new TransformStream({
|
|
2522
|
+
transform(chunk, controller) {
|
|
2523
|
+
if (chunk.type === "start") {
|
|
2524
|
+
const startChunk = chunk;
|
|
2525
|
+
if (startChunk.messageId == null && messageId != null) {
|
|
2526
|
+
startChunk.messageId = messageId;
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
if (chunk.type === "abort") {
|
|
2530
|
+
isAborted = true;
|
|
2531
|
+
}
|
|
2532
|
+
controller.enqueue(chunk);
|
|
2533
|
+
}
|
|
2534
|
+
})
|
|
2535
|
+
);
|
|
2536
|
+
if (onFinish == null) {
|
|
2537
|
+
return idInjectedStream;
|
|
2538
|
+
}
|
|
2539
|
+
const state = createStreamingUIMessageState({
|
|
2540
|
+
lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,
|
|
2541
|
+
messageId: messageId != null ? messageId : ""
|
|
2542
|
+
// will be overridden by the stream
|
|
2543
|
+
});
|
|
2544
|
+
const runUpdateMessageJob = async (job) => {
|
|
2545
|
+
await job({ state, write: () => {
|
|
2546
|
+
} });
|
|
2547
|
+
};
|
|
2548
|
+
let finishCalled = false;
|
|
2549
|
+
const callOnFinish = async () => {
|
|
2550
|
+
if (finishCalled || !onFinish) {
|
|
2551
|
+
return;
|
|
2552
|
+
}
|
|
2553
|
+
finishCalled = true;
|
|
2554
|
+
const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
|
|
2555
|
+
await onFinish({
|
|
2556
|
+
isAborted,
|
|
2557
|
+
isContinuation,
|
|
2558
|
+
responseMessage: state.message,
|
|
2559
|
+
messages: [
|
|
2560
|
+
...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
|
|
2561
|
+
state.message
|
|
2562
|
+
],
|
|
2563
|
+
finishReason: state.finishReason
|
|
2564
|
+
});
|
|
2565
|
+
};
|
|
2566
|
+
return processUIMessageStream({
|
|
2567
|
+
stream: idInjectedStream,
|
|
2568
|
+
runUpdateMessageJob,
|
|
2569
|
+
onError
|
|
2570
|
+
}).pipeThrough(
|
|
2571
|
+
new TransformStream({
|
|
2572
|
+
transform(chunk, controller) {
|
|
2573
|
+
controller.enqueue(chunk);
|
|
2574
|
+
},
|
|
2575
|
+
// @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility
|
|
2576
|
+
async cancel() {
|
|
2577
|
+
await callOnFinish();
|
|
2578
|
+
},
|
|
2579
|
+
async flush() {
|
|
2580
|
+
await callOnFinish();
|
|
2581
|
+
}
|
|
2582
|
+
})
|
|
2583
|
+
);
|
|
2584
|
+
}
|
|
2585
|
+
createIdGenerator({
|
|
2586
|
+
prefix: "aitxt",
|
|
2587
|
+
size: 24
|
|
2588
|
+
});
|
|
2589
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2590
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2591
|
+
var output_exports = {};
|
|
2592
|
+
__export(output_exports, {
|
|
2593
|
+
object: () => object,
|
|
2594
|
+
text: () => text
|
|
2595
|
+
});
|
|
2596
|
+
var text = () => ({
|
|
2597
|
+
type: "text",
|
|
2598
|
+
responseFormat: { type: "text" },
|
|
2599
|
+
async parsePartial({ text: text2 }) {
|
|
2600
|
+
return { partial: text2 };
|
|
2601
|
+
},
|
|
2602
|
+
async parseOutput({ text: text2 }) {
|
|
2603
|
+
return text2;
|
|
2604
|
+
}
|
|
2605
|
+
});
|
|
2606
|
+
var object = ({
|
|
2607
|
+
schema: inputSchema
|
|
2608
|
+
}) => {
|
|
2609
|
+
const schema = asSchema(inputSchema);
|
|
2610
|
+
return {
|
|
2611
|
+
type: "object",
|
|
2612
|
+
responseFormat: {
|
|
2613
|
+
type: "json",
|
|
2614
|
+
schema: schema.jsonSchema
|
|
2615
|
+
},
|
|
2616
|
+
async parsePartial({ text: text2 }) {
|
|
2617
|
+
const result = await parsePartialJson(text2);
|
|
2618
|
+
switch (result.state) {
|
|
2619
|
+
case "failed-parse":
|
|
2620
|
+
case "undefined-input":
|
|
2621
|
+
return void 0;
|
|
2622
|
+
case "repaired-parse":
|
|
2623
|
+
case "successful-parse":
|
|
2624
|
+
return {
|
|
2625
|
+
// Note: currently no validation of partial results:
|
|
2626
|
+
partial: result.value
|
|
2627
|
+
};
|
|
2628
|
+
default: {
|
|
2629
|
+
const _exhaustiveCheck = result.state;
|
|
2630
|
+
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
},
|
|
2634
|
+
async parseOutput({ text: text2 }, context) {
|
|
2635
|
+
const parseResult = await safeParseJSON({ text: text2 });
|
|
2636
|
+
if (!parseResult.success) {
|
|
2637
|
+
throw new NoObjectGeneratedError({
|
|
2638
|
+
message: "No object generated: could not parse the response.",
|
|
2639
|
+
cause: parseResult.error,
|
|
2640
|
+
text: text2,
|
|
2641
|
+
response: context.response,
|
|
2642
|
+
usage: context.usage,
|
|
2643
|
+
finishReason: context.finishReason
|
|
2644
|
+
});
|
|
2645
|
+
}
|
|
2646
|
+
const validationResult = await safeValidateTypes({
|
|
2647
|
+
value: parseResult.value,
|
|
2648
|
+
schema
|
|
2649
|
+
});
|
|
2650
|
+
if (!validationResult.success) {
|
|
2651
|
+
throw new NoObjectGeneratedError({
|
|
2652
|
+
message: "No object generated: response did not match schema.",
|
|
2653
|
+
cause: validationResult.error,
|
|
2654
|
+
text: text2,
|
|
2655
|
+
response: context.response,
|
|
2656
|
+
usage: context.usage,
|
|
2657
|
+
finishReason: context.finishReason
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
return validationResult.value;
|
|
2661
|
+
}
|
|
2662
|
+
};
|
|
2663
|
+
};
|
|
2664
|
+
var wrapLanguageModel = ({
|
|
2665
|
+
model,
|
|
2666
|
+
middleware: middlewareArg,
|
|
2667
|
+
modelId,
|
|
2668
|
+
providerId
|
|
2669
|
+
}) => {
|
|
2670
|
+
return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {
|
|
2671
|
+
return doWrap({ model: wrappedModel, middleware, modelId, providerId });
|
|
2672
|
+
}, model);
|
|
2673
|
+
};
|
|
2674
|
+
var doWrap = ({
|
|
2675
|
+
model,
|
|
2676
|
+
middleware: {
|
|
2677
|
+
transformParams,
|
|
2678
|
+
wrapGenerate,
|
|
2679
|
+
wrapStream,
|
|
2680
|
+
overrideProvider,
|
|
2681
|
+
overrideModelId,
|
|
2682
|
+
overrideSupportedUrls
|
|
2683
|
+
},
|
|
2684
|
+
modelId,
|
|
2685
|
+
providerId
|
|
2686
|
+
}) => {
|
|
2687
|
+
var _a16, _b, _c;
|
|
2688
|
+
async function doTransform({
|
|
2689
|
+
params,
|
|
2690
|
+
type
|
|
2691
|
+
}) {
|
|
2692
|
+
return transformParams ? await transformParams({ params, type, model }) : params;
|
|
2693
|
+
}
|
|
2694
|
+
return {
|
|
2695
|
+
specificationVersion: "v2",
|
|
2696
|
+
provider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,
|
|
2697
|
+
modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
|
|
2698
|
+
supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
|
|
2699
|
+
async doGenerate(params) {
|
|
2700
|
+
const transformedParams = await doTransform({ params, type: "generate" });
|
|
2701
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2702
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2703
|
+
return wrapGenerate ? wrapGenerate({
|
|
2704
|
+
doGenerate,
|
|
2705
|
+
doStream,
|
|
2706
|
+
params: transformedParams,
|
|
2707
|
+
model
|
|
2708
|
+
}) : doGenerate();
|
|
2709
|
+
},
|
|
2710
|
+
async doStream(params) {
|
|
2711
|
+
const transformedParams = await doTransform({ params, type: "stream" });
|
|
2712
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2713
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2714
|
+
return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();
|
|
2715
|
+
}
|
|
2716
|
+
};
|
|
2717
|
+
};
|
|
2718
|
+
function createUIMessageStream({
|
|
2719
|
+
execute,
|
|
2720
|
+
onError = getErrorMessage2,
|
|
2721
|
+
originalMessages,
|
|
2722
|
+
onFinish,
|
|
2723
|
+
generateId: generateId3 = generateId
|
|
2724
|
+
}) {
|
|
2725
|
+
let controller;
|
|
2726
|
+
const ongoingStreamPromises = [];
|
|
2727
|
+
const stream = new ReadableStream({
|
|
2728
|
+
start(controllerArg) {
|
|
2729
|
+
controller = controllerArg;
|
|
2730
|
+
}
|
|
2731
|
+
});
|
|
2732
|
+
function safeEnqueue(data) {
|
|
2733
|
+
try {
|
|
2734
|
+
controller.enqueue(data);
|
|
2735
|
+
} catch (error) {
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
try {
|
|
2739
|
+
const result = execute({
|
|
2740
|
+
writer: {
|
|
2741
|
+
write(part) {
|
|
2742
|
+
safeEnqueue(part);
|
|
2743
|
+
},
|
|
2744
|
+
merge(streamArg) {
|
|
2745
|
+
ongoingStreamPromises.push(
|
|
2746
|
+
(async () => {
|
|
2747
|
+
const reader = streamArg.getReader();
|
|
2748
|
+
while (true) {
|
|
2749
|
+
const { done, value } = await reader.read();
|
|
2750
|
+
if (done)
|
|
2751
|
+
break;
|
|
2752
|
+
safeEnqueue(value);
|
|
2753
|
+
}
|
|
2754
|
+
})().catch((error) => {
|
|
2755
|
+
safeEnqueue({
|
|
2756
|
+
type: "error",
|
|
2757
|
+
errorText: onError(error)
|
|
2758
|
+
});
|
|
2759
|
+
})
|
|
2760
|
+
);
|
|
2761
|
+
},
|
|
2762
|
+
onError
|
|
2763
|
+
}
|
|
2764
|
+
});
|
|
2765
|
+
if (result) {
|
|
2766
|
+
ongoingStreamPromises.push(
|
|
2767
|
+
result.catch((error) => {
|
|
2768
|
+
safeEnqueue({
|
|
2769
|
+
type: "error",
|
|
2770
|
+
errorText: onError(error)
|
|
2771
|
+
});
|
|
2772
|
+
})
|
|
2773
|
+
);
|
|
2774
|
+
}
|
|
2775
|
+
} catch (error) {
|
|
2776
|
+
safeEnqueue({
|
|
2777
|
+
type: "error",
|
|
2778
|
+
errorText: onError(error)
|
|
2779
|
+
});
|
|
2780
|
+
}
|
|
2781
|
+
const waitForStreams = new Promise(async (resolve2) => {
|
|
2782
|
+
while (ongoingStreamPromises.length > 0) {
|
|
2783
|
+
await ongoingStreamPromises.shift();
|
|
2784
|
+
}
|
|
2785
|
+
resolve2();
|
|
2786
|
+
});
|
|
2787
|
+
waitForStreams.finally(() => {
|
|
2788
|
+
try {
|
|
2789
|
+
controller.close();
|
|
2790
|
+
} catch (error) {
|
|
2791
|
+
}
|
|
2792
|
+
});
|
|
2793
|
+
return handleUIMessageStreamFinish({
|
|
2794
|
+
stream,
|
|
2795
|
+
messageId: generateId3(),
|
|
2796
|
+
originalMessages,
|
|
2797
|
+
onFinish,
|
|
2798
|
+
onError
|
|
2799
|
+
});
|
|
2800
|
+
}
|
|
6
2801
|
|
|
7
2802
|
// src/utils.ts
|
|
8
2803
|
var isDataChunkType = (chunk) => {
|
|
@@ -20,6 +2815,8 @@ var isMastraTextStreamChunk = (chunk) => {
|
|
|
20
2815
|
"source",
|
|
21
2816
|
"tool-input-start",
|
|
22
2817
|
"tool-input-delta",
|
|
2818
|
+
"tool-call-approval",
|
|
2819
|
+
"tool-call-suspended",
|
|
23
2820
|
"tool-call",
|
|
24
2821
|
"tool-result",
|
|
25
2822
|
"tool-error",
|
|
@@ -30,6 +2827,8 @@ var isMastraTextStreamChunk = (chunk) => {
|
|
|
30
2827
|
"finish",
|
|
31
2828
|
"abort",
|
|
32
2829
|
"tool-input-end",
|
|
2830
|
+
"object",
|
|
2831
|
+
"tripwire",
|
|
33
2832
|
"raw"
|
|
34
2833
|
].includes(chunk.type);
|
|
35
2834
|
};
|
|
@@ -55,6 +2854,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
|
|
|
55
2854
|
};
|
|
56
2855
|
|
|
57
2856
|
// src/helpers.ts
|
|
2857
|
+
function toAISDKFinishReason(reason) {
|
|
2858
|
+
if (reason === "tripwire" || reason === "retry") {
|
|
2859
|
+
return "other";
|
|
2860
|
+
}
|
|
2861
|
+
return reason;
|
|
2862
|
+
}
|
|
58
2863
|
function convertMastraChunkToAISDKv5({
|
|
59
2864
|
chunk,
|
|
60
2865
|
mode = "stream"
|
|
@@ -62,7 +2867,9 @@ function convertMastraChunkToAISDKv5({
|
|
|
62
2867
|
switch (chunk.type) {
|
|
63
2868
|
case "start":
|
|
64
2869
|
return {
|
|
65
|
-
type: "start"
|
|
2870
|
+
type: "start",
|
|
2871
|
+
// Preserve messageId from the payload so it can be sent to useChat
|
|
2872
|
+
...chunk.payload?.messageId ? { messageId: chunk.payload.messageId } : {}
|
|
66
2873
|
};
|
|
67
2874
|
case "step-start":
|
|
68
2875
|
const { messageId: _messageId, ...rest } = chunk.payload;
|
|
@@ -79,7 +2886,8 @@ function convertMastraChunkToAISDKv5({
|
|
|
79
2886
|
case "finish": {
|
|
80
2887
|
return {
|
|
81
2888
|
type: "finish",
|
|
82
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
2889
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
2890
|
+
// Cast needed: Mastra's LanguageModelUsage has optional properties, AI SDK has required-but-nullable
|
|
83
2891
|
totalUsage: chunk.payload.output.usage
|
|
84
2892
|
};
|
|
85
2893
|
}
|
|
@@ -171,7 +2979,8 @@ function convertMastraChunkToAISDKv5({
|
|
|
171
2979
|
runId: chunk.runId,
|
|
172
2980
|
toolCallId: chunk.payload.toolCallId,
|
|
173
2981
|
toolName: chunk.payload.toolName,
|
|
174
|
-
args: chunk.payload.args
|
|
2982
|
+
args: chunk.payload.args,
|
|
2983
|
+
resumeSchema: chunk.payload.resumeSchema
|
|
175
2984
|
}
|
|
176
2985
|
};
|
|
177
2986
|
case "tool-call-suspended":
|
|
@@ -182,7 +2991,8 @@ function convertMastraChunkToAISDKv5({
|
|
|
182
2991
|
runId: chunk.runId,
|
|
183
2992
|
toolCallId: chunk.payload.toolCallId,
|
|
184
2993
|
toolName: chunk.payload.toolName,
|
|
185
|
-
suspendPayload: chunk.payload.suspendPayload
|
|
2994
|
+
suspendPayload: chunk.payload.suspendPayload,
|
|
2995
|
+
resumeSchema: chunk.payload.resumeSchema
|
|
186
2996
|
}
|
|
187
2997
|
};
|
|
188
2998
|
case "tool-call-input-streaming-start":
|
|
@@ -218,7 +3028,7 @@ function convertMastraChunkToAISDKv5({
|
|
|
218
3028
|
...rest2
|
|
219
3029
|
},
|
|
220
3030
|
usage: chunk.payload.output.usage,
|
|
221
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
3031
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
222
3032
|
providerMetadata
|
|
223
3033
|
};
|
|
224
3034
|
}
|
|
@@ -279,7 +3089,10 @@ function convertMastraChunkToAISDKv5({
|
|
|
279
3089
|
return {
|
|
280
3090
|
type: "data-tripwire",
|
|
281
3091
|
data: {
|
|
282
|
-
|
|
3092
|
+
reason: chunk.payload.reason,
|
|
3093
|
+
retry: chunk.payload.retry,
|
|
3094
|
+
metadata: chunk.payload.metadata,
|
|
3095
|
+
processorId: chunk.payload.processorId
|
|
283
3096
|
}
|
|
284
3097
|
};
|
|
285
3098
|
default:
|
|
@@ -445,7 +3258,8 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
445
3258
|
${JSON.stringify(part)}`
|
|
446
3259
|
);
|
|
447
3260
|
}
|
|
448
|
-
|
|
3261
|
+
const { type, data, id } = part.output;
|
|
3262
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
449
3263
|
}
|
|
450
3264
|
return;
|
|
451
3265
|
}
|
|
@@ -472,10 +3286,11 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
472
3286
|
}
|
|
473
3287
|
case "start": {
|
|
474
3288
|
if (sendStart) {
|
|
3289
|
+
const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
|
|
475
3290
|
return {
|
|
476
3291
|
type: "start",
|
|
477
3292
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
|
|
478
|
-
...
|
|
3293
|
+
...messageId != null ? { messageId } : {}
|
|
479
3294
|
};
|
|
480
3295
|
}
|
|
481
3296
|
return;
|
|
@@ -506,7 +3321,8 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
506
3321
|
${JSON.stringify(part)}`
|
|
507
3322
|
);
|
|
508
3323
|
}
|
|
509
|
-
|
|
3324
|
+
const { type, data, id } = part;
|
|
3325
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
510
3326
|
}
|
|
511
3327
|
return;
|
|
512
3328
|
}
|
|
@@ -514,12 +3330,12 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
514
3330
|
}
|
|
515
3331
|
|
|
516
3332
|
// src/transformers.ts
|
|
517
|
-
var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
|
|
3333
|
+
var PRIMITIVE_CACHE_SYMBOL = /* @__PURE__ */ Symbol("primitive-cache");
|
|
518
3334
|
function WorkflowStreamToAISDKTransformer({
|
|
519
3335
|
includeTextStreamParts
|
|
520
3336
|
} = {}) {
|
|
521
3337
|
const bufferedWorkflows = /* @__PURE__ */ new Map();
|
|
522
|
-
return new TransformStream({
|
|
3338
|
+
return new TransformStream$1({
|
|
523
3339
|
start(controller) {
|
|
524
3340
|
controller.enqueue({
|
|
525
3341
|
type: "start"
|
|
@@ -538,7 +3354,7 @@ function WorkflowStreamToAISDKTransformer({
|
|
|
538
3354
|
}
|
|
539
3355
|
function AgentNetworkToAISDKTransformer() {
|
|
540
3356
|
const bufferedNetworks = /* @__PURE__ */ new Map();
|
|
541
|
-
return new TransformStream({
|
|
3357
|
+
return new TransformStream$1({
|
|
542
3358
|
start(controller) {
|
|
543
3359
|
controller.enqueue({
|
|
544
3360
|
type: "start"
|
|
@@ -551,14 +3367,22 @@ function AgentNetworkToAISDKTransformer() {
|
|
|
551
3367
|
},
|
|
552
3368
|
transform(chunk, controller) {
|
|
553
3369
|
const transformed = transformNetwork(chunk, bufferedNetworks);
|
|
554
|
-
if (transformed)
|
|
3370
|
+
if (transformed) {
|
|
3371
|
+
if (Array.isArray(transformed)) {
|
|
3372
|
+
for (const item of transformed) {
|
|
3373
|
+
controller.enqueue(item);
|
|
3374
|
+
}
|
|
3375
|
+
} else {
|
|
3376
|
+
controller.enqueue(transformed);
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
555
3379
|
}
|
|
556
3380
|
});
|
|
557
3381
|
}
|
|
558
3382
|
function AgentStreamToAISDKTransformer({
|
|
559
3383
|
lastMessageId,
|
|
560
|
-
sendStart,
|
|
561
|
-
sendFinish,
|
|
3384
|
+
sendStart = true,
|
|
3385
|
+
sendFinish = true,
|
|
562
3386
|
sendReasoning,
|
|
563
3387
|
sendSources,
|
|
564
3388
|
messageMetadata,
|
|
@@ -567,7 +3391,7 @@ function AgentStreamToAISDKTransformer({
|
|
|
567
3391
|
let bufferedSteps = /* @__PURE__ */ new Map();
|
|
568
3392
|
let tripwireOccurred = false;
|
|
569
3393
|
let finishEventSent = false;
|
|
570
|
-
return new TransformStream({
|
|
3394
|
+
return new TransformStream$1({
|
|
571
3395
|
transform(chunk, controller) {
|
|
572
3396
|
if (chunk.type === "tripwire") {
|
|
573
3397
|
tripwireOccurred = true;
|
|
@@ -864,7 +3688,8 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
|
|
|
864
3688
|
${JSON.stringify(output)}`
|
|
865
3689
|
);
|
|
866
3690
|
}
|
|
867
|
-
|
|
3691
|
+
const { type, data, id } = output;
|
|
3692
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
868
3693
|
}
|
|
869
3694
|
return null;
|
|
870
3695
|
}
|
|
@@ -876,7 +3701,12 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
|
|
|
876
3701
|
${JSON.stringify(payload)}`
|
|
877
3702
|
);
|
|
878
3703
|
}
|
|
879
|
-
|
|
3704
|
+
const { type, data, id } = payload;
|
|
3705
|
+
return {
|
|
3706
|
+
type,
|
|
3707
|
+
data,
|
|
3708
|
+
...id !== void 0 && { id }
|
|
3709
|
+
};
|
|
880
3710
|
}
|
|
881
3711
|
return null;
|
|
882
3712
|
}
|
|
@@ -890,7 +3720,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
890
3720
|
name: payload.payload.networkId,
|
|
891
3721
|
steps: [],
|
|
892
3722
|
usage: null,
|
|
893
|
-
output: null
|
|
3723
|
+
output: null,
|
|
3724
|
+
hasEmittedText: false
|
|
894
3725
|
});
|
|
895
3726
|
}
|
|
896
3727
|
const current = bufferedNetworks.get(payload.runId);
|
|
@@ -925,6 +3756,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
925
3756
|
case "routing-agent-text-start": {
|
|
926
3757
|
const current = bufferedNetworks.get(payload.runId);
|
|
927
3758
|
if (!current) return null;
|
|
3759
|
+
current.hasEmittedText = true;
|
|
928
3760
|
return {
|
|
929
3761
|
type: "text-start",
|
|
930
3762
|
id: payload.runId
|
|
@@ -933,6 +3765,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
933
3765
|
case "routing-agent-text-delta": {
|
|
934
3766
|
const current = bufferedNetworks.get(payload.runId);
|
|
935
3767
|
if (!current) return null;
|
|
3768
|
+
current.hasEmittedText = true;
|
|
936
3769
|
return {
|
|
937
3770
|
type: "text-delta",
|
|
938
3771
|
id: payload.runId,
|
|
@@ -1107,15 +3940,25 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
1107
3940
|
case "network-execution-event-step-finish": {
|
|
1108
3941
|
const current = bufferedNetworks.get(payload.runId);
|
|
1109
3942
|
if (!current) return null;
|
|
1110
|
-
|
|
3943
|
+
const resultText = payload.payload?.result;
|
|
3944
|
+
const dataNetworkChunk = {
|
|
1111
3945
|
type: isNested ? "data-tool-network" : "data-network",
|
|
1112
3946
|
id: payload.runId,
|
|
1113
3947
|
data: {
|
|
1114
3948
|
...current,
|
|
1115
3949
|
status: "finished",
|
|
1116
|
-
output:
|
|
3950
|
+
output: resultText ?? current.output
|
|
1117
3951
|
}
|
|
1118
3952
|
};
|
|
3953
|
+
if (!current.hasEmittedText && resultText && typeof resultText === "string" && resultText.length > 0) {
|
|
3954
|
+
current.hasEmittedText = true;
|
|
3955
|
+
return [
|
|
3956
|
+
{ type: "text-start", id: payload.runId },
|
|
3957
|
+
{ type: "text-delta", id: payload.runId, delta: resultText },
|
|
3958
|
+
dataNetworkChunk
|
|
3959
|
+
];
|
|
3960
|
+
}
|
|
3961
|
+
return dataNetworkChunk;
|
|
1119
3962
|
}
|
|
1120
3963
|
case "network-execution-event-finish": {
|
|
1121
3964
|
const current = bufferedNetworks.get(payload.runId);
|
|
@@ -1131,7 +3974,31 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
1131
3974
|
}
|
|
1132
3975
|
};
|
|
1133
3976
|
}
|
|
3977
|
+
case "network-object":
|
|
3978
|
+
case "network-object-result": {
|
|
3979
|
+
return null;
|
|
3980
|
+
}
|
|
1134
3981
|
default: {
|
|
3982
|
+
if (isAgentExecutionDataChunkType(payload)) {
|
|
3983
|
+
if (!("data" in payload.payload)) {
|
|
3984
|
+
throw new Error(
|
|
3985
|
+
`UI Messages require a data property when using data- prefixed chunks
|
|
3986
|
+
${JSON.stringify(payload)}`
|
|
3987
|
+
);
|
|
3988
|
+
}
|
|
3989
|
+
const { type, data, id } = payload.payload;
|
|
3990
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
3991
|
+
}
|
|
3992
|
+
if (isWorkflowExecutionDataChunkType(payload)) {
|
|
3993
|
+
if (!("data" in payload.payload)) {
|
|
3994
|
+
throw new Error(
|
|
3995
|
+
`UI Messages require a data property when using data- prefixed chunks
|
|
3996
|
+
${JSON.stringify(payload)}`
|
|
3997
|
+
);
|
|
3998
|
+
}
|
|
3999
|
+
const { type, data, id } = payload.payload;
|
|
4000
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
4001
|
+
}
|
|
1135
4002
|
if (payload.type.startsWith("agent-execution-event-")) {
|
|
1136
4003
|
const stepId = payload.payload.runId;
|
|
1137
4004
|
const current = bufferedNetworks.get(payload.runId);
|
|
@@ -1146,6 +4013,15 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
1146
4013
|
const { request, response, ...data } = result.data;
|
|
1147
4014
|
step.task = data;
|
|
1148
4015
|
}
|
|
4016
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4017
|
+
return {
|
|
4018
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4019
|
+
id: payload.runId,
|
|
4020
|
+
data: {
|
|
4021
|
+
...current,
|
|
4022
|
+
status: "running"
|
|
4023
|
+
}
|
|
4024
|
+
};
|
|
1149
4025
|
}
|
|
1150
4026
|
if (payload.type.startsWith("workflow-execution-event-")) {
|
|
1151
4027
|
const stepId = payload.payload.runId;
|
|
@@ -1155,60 +4031,49 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
1155
4031
|
if (!step) {
|
|
1156
4032
|
return null;
|
|
1157
4033
|
}
|
|
1158
|
-
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
1159
|
-
const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
1160
|
-
if (result && "data" in result) {
|
|
1161
|
-
const data = result.data;
|
|
1162
|
-
step.task = data;
|
|
1163
|
-
if (data.name && step.task) {
|
|
1164
|
-
step.task.id = data.name;
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
if (isDataChunkType(payload)) {
|
|
1169
|
-
if (!("data" in payload)) {
|
|
1170
|
-
throw new Error(
|
|
1171
|
-
`UI Messages require a data property when using data- prefixed chunks
|
|
1172
|
-
${JSON.stringify(payload)}`
|
|
1173
|
-
);
|
|
1174
|
-
}
|
|
1175
|
-
const { type, data } = payload;
|
|
1176
|
-
return { type, data };
|
|
1177
|
-
}
|
|
1178
|
-
if (isAgentExecutionDataChunkType(payload)) {
|
|
1179
|
-
if (!("data" in payload.payload)) {
|
|
1180
|
-
throw new Error(
|
|
1181
|
-
`UI Messages require a data property when using data- prefixed chunks
|
|
1182
|
-
${JSON.stringify(payload)}`
|
|
1183
|
-
);
|
|
4034
|
+
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
4035
|
+
const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
4036
|
+
if (result && "data" in result) {
|
|
4037
|
+
const data = result.data;
|
|
4038
|
+
step.task = data;
|
|
4039
|
+
if (data.name && step.task) {
|
|
4040
|
+
step.task.id = data.name;
|
|
4041
|
+
}
|
|
1184
4042
|
}
|
|
1185
|
-
|
|
1186
|
-
return {
|
|
4043
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4044
|
+
return {
|
|
4045
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4046
|
+
id: payload.runId,
|
|
4047
|
+
data: {
|
|
4048
|
+
...current,
|
|
4049
|
+
status: "running"
|
|
4050
|
+
}
|
|
4051
|
+
};
|
|
1187
4052
|
}
|
|
1188
|
-
if (
|
|
1189
|
-
if (!("data" in payload
|
|
4053
|
+
if (isDataChunkType(payload)) {
|
|
4054
|
+
if (!("data" in payload)) {
|
|
1190
4055
|
throw new Error(
|
|
1191
4056
|
`UI Messages require a data property when using data- prefixed chunks
|
|
1192
4057
|
${JSON.stringify(payload)}`
|
|
1193
4058
|
);
|
|
1194
4059
|
}
|
|
1195
|
-
const { type, data } = payload
|
|
1196
|
-
return { type, data };
|
|
4060
|
+
const { type, data, id } = payload;
|
|
4061
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
1197
4062
|
}
|
|
1198
4063
|
return null;
|
|
1199
4064
|
}
|
|
1200
4065
|
}
|
|
1201
4066
|
}
|
|
1202
4067
|
|
|
1203
|
-
// src/
|
|
1204
|
-
function
|
|
4068
|
+
// src/convert-streams.ts
|
|
4069
|
+
function toAISdkV5Stream(stream, options = {
|
|
1205
4070
|
from: "agent",
|
|
1206
4071
|
sendStart: true,
|
|
1207
4072
|
sendFinish: true
|
|
1208
4073
|
}) {
|
|
1209
4074
|
const from = options?.from;
|
|
1210
4075
|
if (from === "workflow") {
|
|
1211
|
-
const includeTextStreamParts = options?.includeTextStreamParts ??
|
|
4076
|
+
const includeTextStreamParts = options?.includeTextStreamParts ?? true;
|
|
1212
4077
|
return stream.pipeThrough(
|
|
1213
4078
|
WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
|
|
1214
4079
|
);
|
|
@@ -1231,10 +4096,65 @@ function toAISdkFormat(stream, options = {
|
|
|
1231
4096
|
}
|
|
1232
4097
|
|
|
1233
4098
|
// src/chat-route.ts
|
|
4099
|
+
async function handleChatStream({
|
|
4100
|
+
mastra,
|
|
4101
|
+
agentId,
|
|
4102
|
+
params,
|
|
4103
|
+
defaultOptions: defaultOptions2,
|
|
4104
|
+
sendStart = true,
|
|
4105
|
+
sendFinish = true,
|
|
4106
|
+
sendReasoning = false,
|
|
4107
|
+
sendSources = false
|
|
4108
|
+
}) {
|
|
4109
|
+
const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
|
|
4110
|
+
if (resumeData && !runId) {
|
|
4111
|
+
throw new Error("runId is required when resumeData is provided");
|
|
4112
|
+
}
|
|
4113
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4114
|
+
if (!agentObj) {
|
|
4115
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4116
|
+
}
|
|
4117
|
+
if (!Array.isArray(messages)) {
|
|
4118
|
+
throw new Error("Messages must be an array of UIMessage objects");
|
|
4119
|
+
}
|
|
4120
|
+
let lastMessageId;
|
|
4121
|
+
let messagesToSend = messages;
|
|
4122
|
+
if (messages.length > 0) {
|
|
4123
|
+
const lastMessage = messages[messages.length - 1];
|
|
4124
|
+
if (lastMessage?.role === "assistant") {
|
|
4125
|
+
lastMessageId = lastMessage.id;
|
|
4126
|
+
if (trigger === "regenerate-message") {
|
|
4127
|
+
messagesToSend = messages.slice(0, -1);
|
|
4128
|
+
}
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4131
|
+
const mergedOptions = {
|
|
4132
|
+
...defaultOptions2,
|
|
4133
|
+
...rest,
|
|
4134
|
+
...runId && { runId },
|
|
4135
|
+
requestContext: requestContext || defaultOptions2?.requestContext
|
|
4136
|
+
};
|
|
4137
|
+
const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messagesToSend, mergedOptions);
|
|
4138
|
+
return createUIMessageStream({
|
|
4139
|
+
originalMessages: messages,
|
|
4140
|
+
execute: async ({ writer }) => {
|
|
4141
|
+
for await (const part of toAISdkV5Stream(result, {
|
|
4142
|
+
from: "agent",
|
|
4143
|
+
lastMessageId,
|
|
4144
|
+
sendStart,
|
|
4145
|
+
sendFinish,
|
|
4146
|
+
sendReasoning,
|
|
4147
|
+
sendSources
|
|
4148
|
+
})) {
|
|
4149
|
+
writer.write(part);
|
|
4150
|
+
}
|
|
4151
|
+
}
|
|
4152
|
+
});
|
|
4153
|
+
}
|
|
1234
4154
|
function chatRoute({
|
|
1235
4155
|
path = "/chat/:agentId",
|
|
1236
4156
|
agent,
|
|
1237
|
-
defaultOptions,
|
|
4157
|
+
defaultOptions: defaultOptions2,
|
|
1238
4158
|
sendStart = true,
|
|
1239
4159
|
sendFinish = true,
|
|
1240
4160
|
sendReasoning = false,
|
|
@@ -1267,6 +4187,14 @@ function chatRoute({
|
|
|
1267
4187
|
schema: {
|
|
1268
4188
|
type: "object",
|
|
1269
4189
|
properties: {
|
|
4190
|
+
resumeData: {
|
|
4191
|
+
type: "object",
|
|
4192
|
+
description: "Resume data for the agent"
|
|
4193
|
+
},
|
|
4194
|
+
runId: {
|
|
4195
|
+
type: "string",
|
|
4196
|
+
description: "The run ID required when resuming an agent execution"
|
|
4197
|
+
},
|
|
1270
4198
|
messages: {
|
|
1271
4199
|
type: "array",
|
|
1272
4200
|
description: "Array of messages in the conversation",
|
|
@@ -1337,9 +4265,9 @@ function chatRoute({
|
|
|
1337
4265
|
}
|
|
1338
4266
|
},
|
|
1339
4267
|
handler: async (c) => {
|
|
1340
|
-
const
|
|
4268
|
+
const params = await c.req.json();
|
|
1341
4269
|
const mastra = c.get("mastra");
|
|
1342
|
-
const
|
|
4270
|
+
const contextRequestContext = c.get("requestContext");
|
|
1343
4271
|
let agentToUse = agent;
|
|
1344
4272
|
if (!agent) {
|
|
1345
4273
|
const agentId = c.req.param("agentId");
|
|
@@ -1350,39 +4278,25 @@ function chatRoute({
|
|
|
1350
4278
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1351
4279
|
);
|
|
1352
4280
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
4281
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4282
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4283
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
1355
4284
|
}
|
|
1356
4285
|
if (!agentToUse) {
|
|
1357
4286
|
throw new Error("Agent ID is required");
|
|
1358
4287
|
}
|
|
1359
|
-
const
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
}
|
|
1372
|
-
const uiMessageStream = createUIMessageStream({
|
|
1373
|
-
originalMessages: messages,
|
|
1374
|
-
execute: async ({ writer }) => {
|
|
1375
|
-
for await (const part of toAISdkFormat(result, {
|
|
1376
|
-
from: "agent",
|
|
1377
|
-
lastMessageId,
|
|
1378
|
-
sendStart,
|
|
1379
|
-
sendFinish,
|
|
1380
|
-
sendReasoning,
|
|
1381
|
-
sendSources
|
|
1382
|
-
})) {
|
|
1383
|
-
writer.write(part);
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
4288
|
+
const uiMessageStream = await handleChatStream({
|
|
4289
|
+
mastra,
|
|
4290
|
+
agentId: agentToUse,
|
|
4291
|
+
params: {
|
|
4292
|
+
...params,
|
|
4293
|
+
requestContext: effectiveRequestContext
|
|
4294
|
+
},
|
|
4295
|
+
defaultOptions: defaultOptions2,
|
|
4296
|
+
sendStart,
|
|
4297
|
+
sendFinish,
|
|
4298
|
+
sendReasoning,
|
|
4299
|
+
sendSources
|
|
1386
4300
|
});
|
|
1387
4301
|
return createUIMessageStreamResponse({
|
|
1388
4302
|
stream: uiMessageStream
|
|
@@ -1390,10 +4304,31 @@ function chatRoute({
|
|
|
1390
4304
|
}
|
|
1391
4305
|
});
|
|
1392
4306
|
}
|
|
4307
|
+
async function handleWorkflowStream({
|
|
4308
|
+
mastra,
|
|
4309
|
+
workflowId,
|
|
4310
|
+
params,
|
|
4311
|
+
includeTextStreamParts = true
|
|
4312
|
+
}) {
|
|
4313
|
+
const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
|
|
4314
|
+
const workflowObj = mastra.getWorkflowById(workflowId);
|
|
4315
|
+
if (!workflowObj) {
|
|
4316
|
+
throw new Error(`Workflow ${workflowId} not found`);
|
|
4317
|
+
}
|
|
4318
|
+
const run = await workflowObj.createRun({ runId, resourceId, ...rest });
|
|
4319
|
+
const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
|
|
4320
|
+
return createUIMessageStream({
|
|
4321
|
+
execute: async ({ writer }) => {
|
|
4322
|
+
for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
|
|
4323
|
+
writer.write(part);
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
});
|
|
4327
|
+
}
|
|
1393
4328
|
function workflowRoute({
|
|
1394
4329
|
path = "/api/workflows/:workflowId/stream",
|
|
1395
4330
|
workflow,
|
|
1396
|
-
includeTextStreamParts =
|
|
4331
|
+
includeTextStreamParts = true
|
|
1397
4332
|
}) {
|
|
1398
4333
|
if (!workflow && !path.includes("/:workflowId")) {
|
|
1399
4334
|
throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
|
|
@@ -1424,7 +4359,7 @@ function workflowRoute({
|
|
|
1424
4359
|
resourceId: { type: "string" },
|
|
1425
4360
|
inputData: { type: "object", additionalProperties: true },
|
|
1426
4361
|
resumeData: { type: "object", additionalProperties: true },
|
|
1427
|
-
|
|
4362
|
+
requestContext: { type: "object", additionalProperties: true },
|
|
1428
4363
|
tracingOptions: { type: "object", additionalProperties: true },
|
|
1429
4364
|
step: { type: "string" }
|
|
1430
4365
|
}
|
|
@@ -1444,9 +4379,9 @@ function workflowRoute({
|
|
|
1444
4379
|
}
|
|
1445
4380
|
},
|
|
1446
4381
|
handler: async (c) => {
|
|
1447
|
-
const
|
|
4382
|
+
const params = await c.req.json();
|
|
1448
4383
|
const mastra = c.get("mastra");
|
|
1449
|
-
const
|
|
4384
|
+
const contextRequestContext = c.get("requestContext");
|
|
1450
4385
|
let workflowToUse = workflow;
|
|
1451
4386
|
if (!workflow) {
|
|
1452
4387
|
const workflowId = c.req.param("workflowId");
|
|
@@ -1460,32 +4395,51 @@ function workflowRoute({
|
|
|
1460
4395
|
if (!workflowToUse) {
|
|
1461
4396
|
throw new Error("Workflow ID is required");
|
|
1462
4397
|
}
|
|
1463
|
-
|
|
1464
|
-
if (!workflowObj) {
|
|
1465
|
-
throw new Error(`Workflow ${workflowToUse} not found`);
|
|
1466
|
-
}
|
|
1467
|
-
if (runtimeContext && rest.runtimeContext) {
|
|
4398
|
+
if (contextRequestContext && params.requestContext) {
|
|
1468
4399
|
mastra.getLogger()?.warn(
|
|
1469
|
-
`"
|
|
4400
|
+
`"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
|
|
1470
4401
|
);
|
|
1471
4402
|
}
|
|
1472
|
-
const
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
4403
|
+
const uiMessageStream = await handleWorkflowStream({
|
|
4404
|
+
mastra,
|
|
4405
|
+
workflowId: workflowToUse,
|
|
4406
|
+
params: {
|
|
4407
|
+
...params,
|
|
4408
|
+
requestContext: contextRequestContext || params.requestContext
|
|
4409
|
+
},
|
|
4410
|
+
includeTextStreamParts
|
|
1480
4411
|
});
|
|
1481
4412
|
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
1482
4413
|
}
|
|
1483
4414
|
});
|
|
1484
4415
|
}
|
|
4416
|
+
async function handleNetworkStream({
|
|
4417
|
+
mastra,
|
|
4418
|
+
agentId,
|
|
4419
|
+
params,
|
|
4420
|
+
defaultOptions: defaultOptions2
|
|
4421
|
+
}) {
|
|
4422
|
+
const { messages, ...rest } = params;
|
|
4423
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4424
|
+
if (!agentObj) {
|
|
4425
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4426
|
+
}
|
|
4427
|
+
const result = await agentObj.network(messages, {
|
|
4428
|
+
...defaultOptions2,
|
|
4429
|
+
...rest
|
|
4430
|
+
});
|
|
4431
|
+
return createUIMessageStream({
|
|
4432
|
+
execute: async ({ writer }) => {
|
|
4433
|
+
for await (const part of toAISdkV5Stream(result, { from: "network" })) {
|
|
4434
|
+
writer.write(part);
|
|
4435
|
+
}
|
|
4436
|
+
}
|
|
4437
|
+
});
|
|
4438
|
+
}
|
|
1485
4439
|
function networkRoute({
|
|
1486
4440
|
path = "/network/:agentId",
|
|
1487
4441
|
agent,
|
|
1488
|
-
defaultOptions
|
|
4442
|
+
defaultOptions: defaultOptions2
|
|
1489
4443
|
}) {
|
|
1490
4444
|
if (!agent && !path.includes("/:agentId")) {
|
|
1491
4445
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1513,13 +4467,12 @@ function networkRoute({
|
|
|
1513
4467
|
type: "object",
|
|
1514
4468
|
properties: {
|
|
1515
4469
|
messages: { type: "array", items: { type: "object" } },
|
|
1516
|
-
|
|
4470
|
+
requestContext: { type: "object", additionalProperties: true },
|
|
1517
4471
|
runId: { type: "string" },
|
|
1518
4472
|
maxSteps: { type: "number" },
|
|
1519
4473
|
threadId: { type: "string" },
|
|
1520
4474
|
resourceId: { type: "string" },
|
|
1521
4475
|
modelSettings: { type: "object", additionalProperties: true },
|
|
1522
|
-
telemetry: { type: "object", additionalProperties: true },
|
|
1523
4476
|
tools: { type: "array", items: { type: "object" } }
|
|
1524
4477
|
},
|
|
1525
4478
|
required: ["messages"]
|
|
@@ -1543,8 +4496,9 @@ function networkRoute({
|
|
|
1543
4496
|
}
|
|
1544
4497
|
},
|
|
1545
4498
|
handler: async (c) => {
|
|
1546
|
-
const
|
|
4499
|
+
const params = await c.req.json();
|
|
1547
4500
|
const mastra = c.get("mastra");
|
|
4501
|
+
const contextRequestContext = c.get("requestContext");
|
|
1548
4502
|
let agentToUse = agent;
|
|
1549
4503
|
if (!agent) {
|
|
1550
4504
|
const agentId = c.req.param("agentId");
|
|
@@ -1555,29 +4509,483 @@ function networkRoute({
|
|
|
1555
4509
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1556
4510
|
);
|
|
1557
4511
|
}
|
|
4512
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4513
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4514
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
4515
|
+
}
|
|
1558
4516
|
if (!agentToUse) {
|
|
1559
4517
|
throw new Error("Agent ID is required");
|
|
1560
4518
|
}
|
|
1561
|
-
const
|
|
1562
|
-
|
|
1563
|
-
|
|
4519
|
+
const uiMessageStream = await handleNetworkStream({
|
|
4520
|
+
mastra,
|
|
4521
|
+
agentId: agentToUse,
|
|
4522
|
+
params: {
|
|
4523
|
+
...params,
|
|
4524
|
+
requestContext: effectiveRequestContext
|
|
4525
|
+
},
|
|
4526
|
+
defaultOptions: defaultOptions2
|
|
4527
|
+
});
|
|
4528
|
+
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
4529
|
+
}
|
|
4530
|
+
});
|
|
4531
|
+
}
|
|
4532
|
+
function withMastra(model, options = {}) {
|
|
4533
|
+
const { memory, inputProcessors = [], outputProcessors = [] } = options;
|
|
4534
|
+
const allInputProcessors = [...inputProcessors];
|
|
4535
|
+
const allOutputProcessors = [...outputProcessors];
|
|
4536
|
+
if (memory) {
|
|
4537
|
+
const { storage, lastMessages, semanticRecall, workingMemory } = memory;
|
|
4538
|
+
const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
|
|
4539
|
+
if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
|
|
4540
|
+
let template;
|
|
4541
|
+
if (workingMemory.template) {
|
|
4542
|
+
template = {
|
|
4543
|
+
format: "markdown",
|
|
4544
|
+
content: workingMemory.template
|
|
4545
|
+
};
|
|
4546
|
+
}
|
|
4547
|
+
const workingMemoryProcessor = new WorkingMemory({
|
|
4548
|
+
storage,
|
|
4549
|
+
template,
|
|
4550
|
+
scope: workingMemory.scope,
|
|
4551
|
+
useVNext: "version" in workingMemory && workingMemory.version === "vnext"
|
|
4552
|
+
});
|
|
4553
|
+
allInputProcessors.push(workingMemoryProcessor);
|
|
4554
|
+
}
|
|
4555
|
+
if (lastMessages !== false && lastMessages !== void 0) {
|
|
4556
|
+
const messageHistory = new MessageHistory({
|
|
4557
|
+
storage,
|
|
4558
|
+
lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
|
|
4559
|
+
});
|
|
4560
|
+
allInputProcessors.push(messageHistory);
|
|
4561
|
+
allOutputProcessors.push(messageHistory);
|
|
4562
|
+
}
|
|
4563
|
+
if (semanticRecall) {
|
|
4564
|
+
const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
|
|
4565
|
+
const semanticRecallProcessor = new SemanticRecall({
|
|
4566
|
+
storage,
|
|
4567
|
+
vector,
|
|
4568
|
+
embedder,
|
|
4569
|
+
indexName: indexName || "memory_messages",
|
|
4570
|
+
...semanticConfig
|
|
4571
|
+
});
|
|
4572
|
+
allInputProcessors.push(semanticRecallProcessor);
|
|
4573
|
+
allOutputProcessors.push(semanticRecallProcessor);
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
return wrapLanguageModel({
|
|
4577
|
+
model,
|
|
4578
|
+
middleware: createProcessorMiddleware({
|
|
4579
|
+
inputProcessors: allInputProcessors,
|
|
4580
|
+
outputProcessors: allOutputProcessors,
|
|
4581
|
+
memory: memory ? {
|
|
4582
|
+
threadId: memory.threadId,
|
|
4583
|
+
resourceId: memory.resourceId
|
|
4584
|
+
} : void 0
|
|
4585
|
+
})
|
|
4586
|
+
});
|
|
4587
|
+
}
|
|
4588
|
+
function createProcessorMiddleware(options) {
|
|
4589
|
+
const { inputProcessors = [], outputProcessors = [], memory } = options;
|
|
4590
|
+
const requestContext = new RequestContext();
|
|
4591
|
+
if (memory) {
|
|
4592
|
+
requestContext.set("MastraMemory", {
|
|
4593
|
+
thread: memory.threadId ? { id: memory.threadId } : void 0,
|
|
4594
|
+
resourceId: memory.resourceId,
|
|
4595
|
+
memoryConfig: memory.config
|
|
4596
|
+
});
|
|
4597
|
+
}
|
|
4598
|
+
return {
|
|
4599
|
+
middlewareVersion: "v2",
|
|
4600
|
+
/**
|
|
4601
|
+
* Transform params runs input processors (processInput)
|
|
4602
|
+
*/
|
|
4603
|
+
async transformParams({ params }) {
|
|
4604
|
+
const messageList = new MessageList({
|
|
4605
|
+
threadId: memory?.threadId,
|
|
4606
|
+
resourceId: memory?.resourceId
|
|
4607
|
+
});
|
|
4608
|
+
for (const msg of params.prompt) {
|
|
4609
|
+
if (msg.role === "system") {
|
|
4610
|
+
messageList.addSystem(msg.content);
|
|
4611
|
+
} else {
|
|
4612
|
+
messageList.add(msg, "input");
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
for (const processor of inputProcessors) {
|
|
4616
|
+
if (processor.processInput) {
|
|
4617
|
+
try {
|
|
4618
|
+
await processor.processInput({
|
|
4619
|
+
messages: messageList.get.input.db(),
|
|
4620
|
+
systemMessages: messageList.getAllSystemMessages(),
|
|
4621
|
+
messageList,
|
|
4622
|
+
requestContext,
|
|
4623
|
+
abort: (reason) => {
|
|
4624
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4625
|
+
}
|
|
4626
|
+
});
|
|
4627
|
+
} catch (error) {
|
|
4628
|
+
if (error instanceof TripWire) {
|
|
4629
|
+
return {
|
|
4630
|
+
...params,
|
|
4631
|
+
providerOptions: {
|
|
4632
|
+
...params.providerOptions,
|
|
4633
|
+
mastraProcessors: {
|
|
4634
|
+
tripwire: true,
|
|
4635
|
+
reason: error.message
|
|
4636
|
+
}
|
|
4637
|
+
}
|
|
4638
|
+
};
|
|
4639
|
+
}
|
|
4640
|
+
throw error;
|
|
4641
|
+
}
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
const newPrompt = messageList.get.all.aiV5.prompt().map(aiV5ModelMessageToV2PromptMessage);
|
|
4645
|
+
return {
|
|
4646
|
+
...params,
|
|
4647
|
+
prompt: newPrompt
|
|
4648
|
+
};
|
|
4649
|
+
},
|
|
4650
|
+
/**
|
|
4651
|
+
* Wrap generate for non-streaming output processing
|
|
4652
|
+
*/
|
|
4653
|
+
async wrapGenerate({ doGenerate, params }) {
|
|
4654
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4655
|
+
if (processorState?.tripwire) {
|
|
4656
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4657
|
+
return {
|
|
4658
|
+
content: [{ type: "text", text: reason }],
|
|
4659
|
+
finishReason: "stop",
|
|
4660
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
4661
|
+
warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
|
|
4662
|
+
};
|
|
1564
4663
|
}
|
|
1565
|
-
const result = await
|
|
1566
|
-
|
|
1567
|
-
|
|
4664
|
+
const result = await doGenerate();
|
|
4665
|
+
if (!outputProcessors.length) return result;
|
|
4666
|
+
const messageList = new MessageList({
|
|
4667
|
+
threadId: memory?.threadId,
|
|
4668
|
+
resourceId: memory?.resourceId
|
|
1568
4669
|
});
|
|
1569
|
-
const
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
4670
|
+
for (const msg of params.prompt) {
|
|
4671
|
+
if (msg.role === "system") {
|
|
4672
|
+
messageList.addSystem(msg.content);
|
|
4673
|
+
} else {
|
|
4674
|
+
messageList.add(msg, "input");
|
|
4675
|
+
}
|
|
4676
|
+
}
|
|
4677
|
+
const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
|
|
4678
|
+
const responseMessage = {
|
|
4679
|
+
id: crypto.randomUUID(),
|
|
4680
|
+
role: "assistant",
|
|
4681
|
+
content: {
|
|
4682
|
+
format: 2,
|
|
4683
|
+
parts: [{ type: "text", text: textContent }]
|
|
4684
|
+
},
|
|
4685
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
4686
|
+
...memory?.threadId && { threadId: memory.threadId },
|
|
4687
|
+
...memory?.resourceId && { resourceId: memory.resourceId }
|
|
4688
|
+
};
|
|
4689
|
+
messageList.add(responseMessage, "response");
|
|
4690
|
+
for (const processor of outputProcessors) {
|
|
4691
|
+
if (processor.processOutputResult) {
|
|
4692
|
+
try {
|
|
4693
|
+
await processor.processOutputResult({
|
|
4694
|
+
messages: messageList.get.all.db(),
|
|
4695
|
+
messageList,
|
|
4696
|
+
requestContext,
|
|
4697
|
+
abort: (reason) => {
|
|
4698
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4699
|
+
}
|
|
4700
|
+
});
|
|
4701
|
+
} catch (error) {
|
|
4702
|
+
if (error instanceof TripWire) {
|
|
4703
|
+
return {
|
|
4704
|
+
content: [{ type: "text", text: error.message }],
|
|
4705
|
+
finishReason: "stop",
|
|
4706
|
+
usage: result.usage,
|
|
4707
|
+
warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
|
|
4708
|
+
};
|
|
4709
|
+
}
|
|
4710
|
+
throw error;
|
|
1573
4711
|
}
|
|
1574
4712
|
}
|
|
4713
|
+
}
|
|
4714
|
+
const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
|
|
4715
|
+
return {
|
|
4716
|
+
...result,
|
|
4717
|
+
content: [{ type: "text", text: processedText }]
|
|
4718
|
+
};
|
|
4719
|
+
},
|
|
4720
|
+
/**
|
|
4721
|
+
* Wrap stream for streaming output processing
|
|
4722
|
+
*/
|
|
4723
|
+
async wrapStream({ doStream, params }) {
|
|
4724
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4725
|
+
if (processorState?.tripwire) {
|
|
4726
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4727
|
+
return {
|
|
4728
|
+
stream: createBlockedStream(reason)
|
|
4729
|
+
};
|
|
4730
|
+
}
|
|
4731
|
+
const { stream, ...rest } = await doStream();
|
|
4732
|
+
if (!outputProcessors.length) return { stream, ...rest };
|
|
4733
|
+
const processorStates = /* @__PURE__ */ new Map();
|
|
4734
|
+
const runId = crypto.randomUUID();
|
|
4735
|
+
const transformedStream = stream.pipeThrough(
|
|
4736
|
+
new TransformStream$1({
|
|
4737
|
+
async transform(chunk, controller) {
|
|
4738
|
+
let mastraChunk = convertFullStreamChunkToMastra(
|
|
4739
|
+
chunk,
|
|
4740
|
+
{ runId }
|
|
4741
|
+
);
|
|
4742
|
+
if (!mastraChunk) {
|
|
4743
|
+
controller.enqueue(chunk);
|
|
4744
|
+
return;
|
|
4745
|
+
}
|
|
4746
|
+
for (const processor of outputProcessors) {
|
|
4747
|
+
if (processor.processOutputStream && mastraChunk) {
|
|
4748
|
+
let state = processorStates.get(processor.id);
|
|
4749
|
+
if (!state) {
|
|
4750
|
+
state = { streamParts: [], customState: {} };
|
|
4751
|
+
processorStates.set(processor.id, state);
|
|
4752
|
+
}
|
|
4753
|
+
state.streamParts.push(mastraChunk);
|
|
4754
|
+
try {
|
|
4755
|
+
const result = await processor.processOutputStream({
|
|
4756
|
+
part: mastraChunk,
|
|
4757
|
+
streamParts: state.streamParts,
|
|
4758
|
+
state: state.customState,
|
|
4759
|
+
requestContext,
|
|
4760
|
+
abort: (reason) => {
|
|
4761
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4762
|
+
}
|
|
4763
|
+
});
|
|
4764
|
+
if (result === null || result === void 0) {
|
|
4765
|
+
mastraChunk = void 0;
|
|
4766
|
+
} else {
|
|
4767
|
+
mastraChunk = result;
|
|
4768
|
+
}
|
|
4769
|
+
} catch (error) {
|
|
4770
|
+
if (error instanceof TripWire) {
|
|
4771
|
+
controller.enqueue({
|
|
4772
|
+
type: "error",
|
|
4773
|
+
error: new Error(error.message)
|
|
4774
|
+
});
|
|
4775
|
+
controller.terminate();
|
|
4776
|
+
return;
|
|
4777
|
+
}
|
|
4778
|
+
throw error;
|
|
4779
|
+
}
|
|
4780
|
+
}
|
|
4781
|
+
}
|
|
4782
|
+
if (mastraChunk) {
|
|
4783
|
+
const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
|
|
4784
|
+
if (aiChunk) {
|
|
4785
|
+
controller.enqueue(aiChunk);
|
|
4786
|
+
}
|
|
4787
|
+
}
|
|
4788
|
+
}
|
|
4789
|
+
})
|
|
4790
|
+
);
|
|
4791
|
+
return { stream: transformedStream, ...rest };
|
|
4792
|
+
}
|
|
4793
|
+
};
|
|
4794
|
+
}
|
|
4795
|
+
function createBlockedStream(reason) {
|
|
4796
|
+
return new ReadableStream$1({
|
|
4797
|
+
start(controller) {
|
|
4798
|
+
const id = crypto.randomUUID();
|
|
4799
|
+
controller.enqueue({
|
|
4800
|
+
type: "text-start",
|
|
4801
|
+
id
|
|
1575
4802
|
});
|
|
1576
|
-
|
|
4803
|
+
controller.enqueue({
|
|
4804
|
+
type: "text-delta",
|
|
4805
|
+
id,
|
|
4806
|
+
delta: reason
|
|
4807
|
+
});
|
|
4808
|
+
controller.enqueue({
|
|
4809
|
+
type: "text-end",
|
|
4810
|
+
id
|
|
4811
|
+
});
|
|
4812
|
+
controller.enqueue({
|
|
4813
|
+
type: "finish",
|
|
4814
|
+
finishReason: "stop",
|
|
4815
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
|
|
4816
|
+
});
|
|
4817
|
+
controller.close();
|
|
1577
4818
|
}
|
|
1578
4819
|
});
|
|
1579
4820
|
}
|
|
4821
|
+
function extractTextFromMastraMessage(msg) {
|
|
4822
|
+
const content = msg.content;
|
|
4823
|
+
if (typeof content === "string") {
|
|
4824
|
+
return content;
|
|
4825
|
+
}
|
|
4826
|
+
if (content?.parts) {
|
|
4827
|
+
return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
|
|
4828
|
+
}
|
|
4829
|
+
return "";
|
|
4830
|
+
}
|
|
4831
|
+
function convertMastraChunkToAISDKStreamPart(chunk) {
|
|
4832
|
+
switch (chunk.type) {
|
|
4833
|
+
// Text streaming
|
|
4834
|
+
case "text-start":
|
|
4835
|
+
return {
|
|
4836
|
+
type: "text-start",
|
|
4837
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4838
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4839
|
+
};
|
|
4840
|
+
case "text-delta":
|
|
4841
|
+
return {
|
|
4842
|
+
type: "text-delta",
|
|
4843
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4844
|
+
delta: chunk.payload.text,
|
|
4845
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4846
|
+
};
|
|
4847
|
+
case "text-end":
|
|
4848
|
+
return {
|
|
4849
|
+
type: "text-end",
|
|
4850
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4851
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4852
|
+
};
|
|
4853
|
+
// Reasoning streaming
|
|
4854
|
+
case "reasoning-start":
|
|
4855
|
+
return {
|
|
4856
|
+
type: "reasoning-start",
|
|
4857
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4858
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4859
|
+
};
|
|
4860
|
+
case "reasoning-delta":
|
|
4861
|
+
return {
|
|
4862
|
+
type: "reasoning-delta",
|
|
4863
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4864
|
+
delta: chunk.payload.text,
|
|
4865
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4866
|
+
};
|
|
4867
|
+
case "reasoning-end":
|
|
4868
|
+
return {
|
|
4869
|
+
type: "reasoning-end",
|
|
4870
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4871
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4872
|
+
};
|
|
4873
|
+
// Tool call (complete)
|
|
4874
|
+
case "tool-call":
|
|
4875
|
+
return {
|
|
4876
|
+
type: "tool-call",
|
|
4877
|
+
toolCallId: chunk.payload.toolCallId,
|
|
4878
|
+
toolName: chunk.payload.toolName,
|
|
4879
|
+
input: JSON.stringify(chunk.payload.args),
|
|
4880
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4881
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4882
|
+
};
|
|
4883
|
+
// Tool call input streaming
|
|
4884
|
+
case "tool-call-input-streaming-start":
|
|
4885
|
+
return {
|
|
4886
|
+
type: "tool-input-start",
|
|
4887
|
+
id: chunk.payload.toolCallId,
|
|
4888
|
+
toolName: chunk.payload.toolName,
|
|
4889
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4890
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4891
|
+
};
|
|
4892
|
+
case "tool-call-delta":
|
|
4893
|
+
return {
|
|
4894
|
+
type: "tool-input-delta",
|
|
4895
|
+
id: chunk.payload.toolCallId,
|
|
4896
|
+
delta: chunk.payload.argsTextDelta,
|
|
4897
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4898
|
+
};
|
|
4899
|
+
case "tool-call-input-streaming-end":
|
|
4900
|
+
return {
|
|
4901
|
+
type: "tool-input-end",
|
|
4902
|
+
id: chunk.payload.toolCallId,
|
|
4903
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4904
|
+
};
|
|
4905
|
+
// Tool result
|
|
4906
|
+
case "tool-result":
|
|
4907
|
+
return {
|
|
4908
|
+
type: "tool-result",
|
|
4909
|
+
toolCallId: chunk.payload.toolCallId,
|
|
4910
|
+
toolName: chunk.payload.toolName,
|
|
4911
|
+
result: { type: "json", value: chunk.payload.result },
|
|
4912
|
+
isError: chunk.payload.isError,
|
|
4913
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4914
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4915
|
+
};
|
|
4916
|
+
// Source (citations)
|
|
4917
|
+
case "source":
|
|
4918
|
+
if (chunk.payload.sourceType === "url") {
|
|
4919
|
+
return {
|
|
4920
|
+
type: "source",
|
|
4921
|
+
sourceType: "url",
|
|
4922
|
+
id: chunk.payload.id,
|
|
4923
|
+
url: chunk.payload.url,
|
|
4924
|
+
title: chunk.payload.title,
|
|
4925
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4926
|
+
};
|
|
4927
|
+
} else {
|
|
4928
|
+
return {
|
|
4929
|
+
type: "source",
|
|
4930
|
+
sourceType: "document",
|
|
4931
|
+
id: chunk.payload.id,
|
|
4932
|
+
mediaType: chunk.payload.mimeType,
|
|
4933
|
+
title: chunk.payload.title,
|
|
4934
|
+
filename: chunk.payload.filename,
|
|
4935
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4936
|
+
};
|
|
4937
|
+
}
|
|
4938
|
+
// File output
|
|
4939
|
+
case "file":
|
|
4940
|
+
return {
|
|
4941
|
+
type: "file",
|
|
4942
|
+
data: chunk.payload.data || chunk.payload.base64,
|
|
4943
|
+
mediaType: chunk.payload.mimeType
|
|
4944
|
+
};
|
|
4945
|
+
// Response metadata
|
|
4946
|
+
case "response-metadata":
|
|
4947
|
+
return {
|
|
4948
|
+
type: "response-metadata",
|
|
4949
|
+
...chunk.payload
|
|
4950
|
+
};
|
|
4951
|
+
// Raw provider data
|
|
4952
|
+
case "raw":
|
|
4953
|
+
return {
|
|
4954
|
+
type: "raw",
|
|
4955
|
+
rawValue: chunk.payload
|
|
4956
|
+
};
|
|
4957
|
+
// Finish
|
|
4958
|
+
case "finish": {
|
|
4959
|
+
const usage = chunk.payload.output?.usage;
|
|
4960
|
+
return {
|
|
4961
|
+
type: "finish",
|
|
4962
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
|
|
4963
|
+
usage: usage ? {
|
|
4964
|
+
inputTokens: usage.inputTokens || 0,
|
|
4965
|
+
outputTokens: usage.outputTokens || 0,
|
|
4966
|
+
totalTokens: usage.totalTokens || 0
|
|
4967
|
+
} : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
4968
|
+
providerMetadata: chunk.payload.metadata?.providerMetadata
|
|
4969
|
+
};
|
|
4970
|
+
}
|
|
4971
|
+
// Error
|
|
4972
|
+
case "error":
|
|
4973
|
+
return {
|
|
4974
|
+
type: "error",
|
|
4975
|
+
error: chunk.payload.error || chunk.payload
|
|
4976
|
+
};
|
|
4977
|
+
default:
|
|
4978
|
+
return null;
|
|
4979
|
+
}
|
|
4980
|
+
}
|
|
4981
|
+
|
|
4982
|
+
// src/to-ai-sdk-format.ts
|
|
4983
|
+
function toAISdkFormat() {
|
|
4984
|
+
throw new Error(
|
|
4985
|
+
'toAISdkFormat() has been deprecated. Please use toAISdkStream() instead.\n\nMigration:\n import { toAISdkFormat } from "@mastra/ai-sdk";\n // Change to:\n import { toAISdkStream } from "@mastra/ai-sdk";\n\nThe function signature remains the same.'
|
|
4986
|
+
);
|
|
4987
|
+
}
|
|
1580
4988
|
|
|
1581
|
-
export { chatRoute, networkRoute, toAISdkFormat, workflowRoute };
|
|
4989
|
+
export { chatRoute, handleChatStream, handleNetworkStream, handleWorkflowStream, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, withMastra, workflowRoute };
|
|
1582
4990
|
//# sourceMappingURL=index.js.map
|
|
1583
4991
|
//# sourceMappingURL=index.js.map
|