@mastra/valkey 0.0.0 → 0.2.0

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/dist/index.js ADDED
@@ -0,0 +1,1758 @@
1
+ import { MessageList } from "@mastra/core/agent";
2
+ import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
3
+ import { MastraStorage, MemoryStorage, ScoresStorage, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCORERS, TABLE_THREADS, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, filterByDateRange, jsonValueEquals, matchesExpectedWorkflowStatus, normalizePerPage, serializeDate, storageMessageMatchesMetadataFilter, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
4
+ import crypto$1 from "crypto";
5
+ import { saveScorePayloadSchema } from "@mastra/core/evals";
6
+ import { Batch, Decoder, GlideClient } from "@valkey/valkey-glide";
7
+ import { MastraServerCache } from "@mastra/core/cache";
8
+ //#region src/storage/domains/utils.ts
9
+ /**
10
+ * Generate a Valkey key from table name and key parts.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * getKey('mastra_threads', { id: 'thread-123' });
15
+ * // Returns: 'mastra_threads:id:thread-123'
16
+ *
17
+ * getKey('mastra_messages', { threadId: 'thread-123', id: 'msg-456' });
18
+ * // Returns: 'mastra_messages:threadId:thread-123:id:msg-456'
19
+ * ```
20
+ */
21
+ function getKey(tableName, keys) {
22
+ return `${tableName}:${Object.entries(keys).filter(([_, value]) => value !== void 0).map(([key, value]) => {
23
+ if (value && typeof value === "object") return `${key}:${JSON.stringify(value)}`;
24
+ return `${key}:${value}`;
25
+ }).join(":")}`;
26
+ }
27
+ /**
28
+ * Process a record for storage, generating the appropriate key and serializing dates.
29
+ */
30
+ function processRecord(tableName, record) {
31
+ let key;
32
+ if (tableName === TABLE_MESSAGES) key = getKey(tableName, {
33
+ threadId: record.threadId,
34
+ id: record.id
35
+ });
36
+ else if (tableName === TABLE_WORKFLOW_SNAPSHOT) key = getKey(tableName, {
37
+ namespace: record.namespace || "workflows",
38
+ workflow_name: record.workflow_name,
39
+ run_id: record.run_id,
40
+ ...record.resourceId ? { resourceId: record.resourceId } : {}
41
+ });
42
+ else key = getKey(tableName, { id: record.id });
43
+ const processedRecord = {
44
+ ...record,
45
+ createdAt: serializeDate(record.createdAt),
46
+ updatedAt: serializeDate(record.updatedAt)
47
+ };
48
+ return {
49
+ key,
50
+ processedRecord
51
+ };
52
+ }
53
+ //#endregion
54
+ //#region src/storage/db/index.ts
55
+ var ValkeyDB = class {
56
+ client;
57
+ constructor({ client }) {
58
+ this.client = client;
59
+ }
60
+ getClient() {
61
+ return this.client;
62
+ }
63
+ async insert({ tableName, record }) {
64
+ const { key, processedRecord } = processRecord(tableName, record);
65
+ try {
66
+ await this.client.set(key, JSON.stringify(processedRecord));
67
+ } catch (error) {
68
+ throw new MastraError({
69
+ id: createStorageErrorId("VALKEY", "INSERT", "FAILED"),
70
+ domain: ErrorDomain.STORAGE,
71
+ category: ErrorCategory.THIRD_PARTY,
72
+ details: { tableName }
73
+ }, error);
74
+ }
75
+ }
76
+ async get({ tableName, keys }) {
77
+ const key = getKey(tableName, keys);
78
+ try {
79
+ const data = await this.client.get(key);
80
+ if (!data) return null;
81
+ return JSON.parse(data);
82
+ } catch (error) {
83
+ throw new MastraError({
84
+ id: createStorageErrorId("VALKEY", "LOAD", "FAILED"),
85
+ domain: ErrorDomain.STORAGE,
86
+ category: ErrorCategory.THIRD_PARTY,
87
+ details: { tableName }
88
+ }, error);
89
+ }
90
+ }
91
+ async scanAndDelete(pattern, batchSize = 1e4) {
92
+ let cursor = "0";
93
+ let totalDeleted = 0;
94
+ do {
95
+ const result = await this.client.scan(cursor, {
96
+ MATCH: pattern,
97
+ COUNT: batchSize
98
+ });
99
+ if (result.keys.length > 0) {
100
+ await this.client.del(result.keys);
101
+ totalDeleted += result.keys.length;
102
+ }
103
+ cursor = result.cursor;
104
+ } while (cursor !== "0");
105
+ return totalDeleted;
106
+ }
107
+ async scanKeys(pattern, batchSize = 1e4) {
108
+ let cursor = "0";
109
+ const keys = [];
110
+ do {
111
+ const result = await this.client.scan(cursor, {
112
+ MATCH: pattern,
113
+ COUNT: batchSize
114
+ });
115
+ keys.push(...result.keys);
116
+ cursor = result.cursor;
117
+ } while (cursor !== "0");
118
+ return keys;
119
+ }
120
+ async deleteData({ tableName }) {
121
+ const pattern = `${tableName}:*`;
122
+ try {
123
+ await this.scanAndDelete(pattern);
124
+ } catch (error) {
125
+ throw new MastraError({
126
+ id: createStorageErrorId("VALKEY", "CLEAR_TABLE", "FAILED"),
127
+ domain: ErrorDomain.STORAGE,
128
+ category: ErrorCategory.THIRD_PARTY,
129
+ details: { tableName }
130
+ }, error);
131
+ }
132
+ }
133
+ };
134
+ //#endregion
135
+ //#region src/storage/domains/memory/index.ts
136
+ var StoreMemoryValkey = class extends MemoryStorage {
137
+ supportsPartialThreadUpdate = true;
138
+ client;
139
+ db;
140
+ constructor(config) {
141
+ super();
142
+ this.client = config.client;
143
+ this.db = new ValkeyDB({ client: config.client });
144
+ }
145
+ async dangerouslyClearAll() {
146
+ await this.db.deleteData({ tableName: TABLE_THREADS });
147
+ await this.db.deleteData({ tableName: TABLE_MESSAGES });
148
+ await this.db.deleteData({ tableName: TABLE_RESOURCES });
149
+ await this.db.scanAndDelete("msg-idx:*");
150
+ await this.db.scanAndDelete("thread:*:messages");
151
+ }
152
+ async getThreadById({ threadId, resourceId }) {
153
+ try {
154
+ const thread = await this.db.get({
155
+ tableName: TABLE_THREADS,
156
+ keys: { id: threadId }
157
+ });
158
+ if (!thread || resourceId !== void 0 && thread.resourceId !== resourceId) return null;
159
+ return {
160
+ ...thread,
161
+ createdAt: ensureDate(thread.createdAt),
162
+ updatedAt: ensureDate(thread.updatedAt),
163
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
164
+ };
165
+ } catch (error) {
166
+ throw new MastraError({
167
+ id: createStorageErrorId("VALKEY", "GET_THREAD_BY_ID", "FAILED"),
168
+ domain: ErrorDomain.STORAGE,
169
+ category: ErrorCategory.THIRD_PARTY,
170
+ details: { threadId }
171
+ }, error);
172
+ }
173
+ }
174
+ async listThreadsByResourceId(args) {
175
+ return this.listThreads(args);
176
+ }
177
+ async listThreads(args) {
178
+ const { page = 0, perPage: perPageInput, orderBy, filter } = args;
179
+ const { field, direction } = this.parseOrderBy(orderBy);
180
+ try {
181
+ this.validatePaginationInput(page, perPageInput ?? 100);
182
+ } catch (error) {
183
+ throw new MastraError({
184
+ id: createStorageErrorId("VALKEY", "LIST_THREADS", "INVALID_PAGE"),
185
+ domain: ErrorDomain.STORAGE,
186
+ category: ErrorCategory.USER,
187
+ details: {
188
+ page,
189
+ ...perPageInput !== void 0 && { perPage: perPageInput }
190
+ }
191
+ }, error instanceof Error ? error : /* @__PURE__ */ new Error("Invalid pagination parameters"));
192
+ }
193
+ const perPage = normalizePerPage(perPageInput, 100);
194
+ try {
195
+ this.validateMetadataKeys(filter?.metadata);
196
+ } catch (error) {
197
+ throw new MastraError({
198
+ id: createStorageErrorId("VALKEY", "LIST_THREADS", "INVALID_METADATA_KEY"),
199
+ domain: ErrorDomain.STORAGE,
200
+ category: ErrorCategory.USER,
201
+ details: { metadataKeys: filter?.metadata ? Object.keys(filter.metadata).join(", ") : "" }
202
+ }, error instanceof Error ? error : /* @__PURE__ */ new Error("Invalid metadata key"));
203
+ }
204
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
205
+ try {
206
+ let allThreads = [];
207
+ const pattern = `${TABLE_THREADS}:*`;
208
+ const keys = await this.db.scanKeys(pattern);
209
+ if (keys.length === 0) return {
210
+ threads: [],
211
+ total: 0,
212
+ page,
213
+ perPage: perPageForResponse,
214
+ hasMore: false
215
+ };
216
+ const results = await this.client.mGet(keys);
217
+ for (let i = 0; i < results.length; i++) {
218
+ const data = results[i];
219
+ if (!data) continue;
220
+ const thread = JSON.parse(data);
221
+ if (filter?.resourceId && thread.resourceId !== filter.resourceId) continue;
222
+ if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
223
+ const threadMetadata = typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata;
224
+ if (!Object.entries(filter.metadata).every(([key, value]) => jsonValueEquals(threadMetadata?.[key], value))) continue;
225
+ }
226
+ allThreads.push({
227
+ ...thread,
228
+ createdAt: ensureDate(thread.createdAt),
229
+ updatedAt: ensureDate(thread.updatedAt),
230
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
231
+ });
232
+ }
233
+ const sortedThreads = this.sortThreads(allThreads, field, direction);
234
+ const total = sortedThreads.length;
235
+ const end = perPageInput === false ? total : offset + perPage;
236
+ return {
237
+ threads: sortedThreads.slice(offset, end),
238
+ total,
239
+ page,
240
+ perPage: perPageForResponse,
241
+ hasMore: perPageInput === false ? false : end < total
242
+ };
243
+ } catch (error) {
244
+ if (error instanceof MastraError && error.category === ErrorCategory.USER) throw error;
245
+ const mastraError = new MastraError({
246
+ id: createStorageErrorId("VALKEY", "LIST_THREADS", "FAILED"),
247
+ domain: ErrorDomain.STORAGE,
248
+ category: ErrorCategory.THIRD_PARTY,
249
+ details: {
250
+ ...filter?.resourceId && { resourceId: filter.resourceId },
251
+ hasMetadataFilter: !!filter?.metadata,
252
+ page,
253
+ perPage
254
+ }
255
+ }, error);
256
+ this.logger.trackException(mastraError);
257
+ this.logger.error(mastraError.toString());
258
+ throw mastraError;
259
+ }
260
+ }
261
+ async saveThread({ thread }) {
262
+ try {
263
+ await this.db.insert({
264
+ tableName: TABLE_THREADS,
265
+ record: thread
266
+ });
267
+ return thread;
268
+ } catch (error) {
269
+ const mastraError = new MastraError({
270
+ id: createStorageErrorId("VALKEY", "SAVE_THREAD", "FAILED"),
271
+ domain: ErrorDomain.STORAGE,
272
+ category: ErrorCategory.THIRD_PARTY,
273
+ details: { threadId: thread.id }
274
+ }, error);
275
+ this.logger.trackException(mastraError);
276
+ this.logger.error(mastraError.toString());
277
+ throw mastraError;
278
+ }
279
+ }
280
+ async updateThread({ id, title, metadata }) {
281
+ const thread = await this.getThreadById({ threadId: id });
282
+ if (!thread) throw new MastraError({
283
+ id: createStorageErrorId("VALKEY", "UPDATE_THREAD", "FAILED"),
284
+ domain: ErrorDomain.STORAGE,
285
+ category: ErrorCategory.USER,
286
+ text: `Thread ${id} not found`,
287
+ details: { threadId: id }
288
+ });
289
+ const updatedThread = {
290
+ ...thread,
291
+ title: title ?? thread.title,
292
+ metadata: {
293
+ ...thread.metadata,
294
+ ...metadata
295
+ },
296
+ updatedAt: /* @__PURE__ */ new Date()
297
+ };
298
+ try {
299
+ await this.saveThread({ thread: updatedThread });
300
+ return updatedThread;
301
+ } catch (error) {
302
+ throw new MastraError({
303
+ id: createStorageErrorId("VALKEY", "UPDATE_THREAD", "FAILED"),
304
+ domain: ErrorDomain.STORAGE,
305
+ category: ErrorCategory.THIRD_PARTY,
306
+ details: { threadId: id }
307
+ }, error);
308
+ }
309
+ }
310
+ async deleteThread({ threadId }) {
311
+ const threadKey = getKey(TABLE_THREADS, { id: threadId });
312
+ const threadMessagesKey = getThreadMessagesKey(threadId);
313
+ try {
314
+ const messageIds = await this.client.zRange(threadMessagesKey, 0, -1);
315
+ const multi = this.client.multi();
316
+ multi.del(threadKey);
317
+ multi.del(threadMessagesKey);
318
+ for (const messageId of messageIds) {
319
+ const messageKey = getMessageKey(threadId, messageId);
320
+ multi.del(messageKey);
321
+ multi.del(getMessageIndexKey(messageId));
322
+ }
323
+ await multi.exec();
324
+ await this.db.scanAndDelete(getMessageKey(threadId, "*"));
325
+ } catch (error) {
326
+ throw new MastraError({
327
+ id: createStorageErrorId("VALKEY", "DELETE_THREAD", "FAILED"),
328
+ domain: ErrorDomain.STORAGE,
329
+ category: ErrorCategory.THIRD_PARTY,
330
+ details: { threadId }
331
+ }, error);
332
+ }
333
+ }
334
+ async saveMessages(args) {
335
+ const { messages } = args;
336
+ if (messages.length === 0) return { messages: [] };
337
+ const threadId = messages[0]?.threadId;
338
+ try {
339
+ if (!threadId) throw new Error("Thread ID is required");
340
+ if (!await this.getThreadById({ threadId })) throw new Error(`Thread ${threadId} not found`);
341
+ } catch (error) {
342
+ throw new MastraError({
343
+ id: createStorageErrorId("VALKEY", "SAVE_MESSAGES", "INVALID_ARGS"),
344
+ domain: ErrorDomain.STORAGE,
345
+ category: ErrorCategory.USER
346
+ }, error);
347
+ }
348
+ const messagesWithIndex = messages.map((message, index) => {
349
+ if (!message.threadId) throw new Error(`Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`);
350
+ if (!message.resourceId) throw new Error(`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`);
351
+ return {
352
+ ...message,
353
+ _index: index
354
+ };
355
+ });
356
+ const threadKey = getKey(TABLE_THREADS, { id: threadId });
357
+ const existingThreadData = await this.client.get(threadKey);
358
+ const existingThread = existingThreadData ? JSON.parse(existingThreadData) : null;
359
+ try {
360
+ const batchSize = 1e3;
361
+ const existingThreadIds = await this.client.mGet(messagesWithIndex.map((message) => getMessageIndexKey(message.id)));
362
+ for (let i = 0; i < messagesWithIndex.length; i += batchSize) {
363
+ const batch = messagesWithIndex.slice(i, i + batchSize);
364
+ const batchExistingThreadIds = existingThreadIds.slice(i, i + batch.length);
365
+ const multi = this.client.multi();
366
+ for (const [batchIndex, message] of batch.entries()) {
367
+ const key = getMessageKey(message.threadId, message.id);
368
+ const score = getMessageScore(message);
369
+ const existingThreadId = batchExistingThreadIds[batchIndex];
370
+ if (existingThreadId && existingThreadId !== message.threadId) {
371
+ const existingMessageKey = getMessageKey(existingThreadId, message.id);
372
+ multi.del(existingMessageKey);
373
+ multi.zRem(getThreadMessagesKey(existingThreadId), message.id);
374
+ }
375
+ multi.set(key, JSON.stringify(message));
376
+ multi.set(getMessageIndexKey(message.id), message.threadId);
377
+ multi.zAdd(getThreadMessagesKey(message.threadId), {
378
+ score,
379
+ value: message.id
380
+ });
381
+ }
382
+ if (i === 0 && existingThread) {
383
+ const updatedThread = {
384
+ ...existingThread,
385
+ updatedAt: /* @__PURE__ */ new Date()
386
+ };
387
+ multi.set(threadKey, JSON.stringify(processRecord(TABLE_THREADS, updatedThread).processedRecord));
388
+ }
389
+ await multi.exec();
390
+ }
391
+ return { messages: new MessageList().add(messages, "memory").get.all.db() };
392
+ } catch (error) {
393
+ throw new MastraError({
394
+ id: createStorageErrorId("VALKEY", "SAVE_MESSAGES", "FAILED"),
395
+ domain: ErrorDomain.STORAGE,
396
+ category: ErrorCategory.THIRD_PARTY,
397
+ details: { threadId }
398
+ }, error);
399
+ }
400
+ }
401
+ async getThreadIdForMessage(messageId) {
402
+ const indexedThreadId = await this.client.get(getMessageIndexKey(messageId));
403
+ if (indexedThreadId) return indexedThreadId;
404
+ const keys = await this.db.scanKeys(getMessageKey("*", messageId));
405
+ if (keys.length === 0) return null;
406
+ const messageData = await this.client.get(keys[0]);
407
+ if (!messageData) return null;
408
+ const message = JSON.parse(messageData);
409
+ if (message.threadId) await this.client.set(getMessageIndexKey(messageId), message.threadId);
410
+ return message.threadId || null;
411
+ }
412
+ /**
413
+ * Fetches the messages named by `include` together with their surrounding context.
414
+ *
415
+ * @param include - Message ids to pin, each with an optional before/after window.
416
+ * @param resourceId - When set, drops any pinned or context message owned by another
417
+ * resource so an id from another resource returns nothing.
418
+ */
419
+ async getIncludedMessages(include, resourceId) {
420
+ if (!include?.length) return [];
421
+ const messageIds = /* @__PURE__ */ new Set();
422
+ const messageIdToThreadIds = {};
423
+ for (const item of include) {
424
+ const itemThreadId = await this.getThreadIdForMessage(item.id);
425
+ if (!itemThreadId) continue;
426
+ const itemThreadMessagesKey = getThreadMessagesKey(itemThreadId);
427
+ if (resourceId !== void 0) {
428
+ const threadMessageIds = await this.client.zRange(itemThreadMessagesKey, 0, -1);
429
+ const threadMessages = (await this.client.mGet(threadMessageIds.map((id) => getMessageKey(itemThreadId, id)))).filter((data) => data !== null).map((data) => JSON.parse(data)).filter((message) => message.resourceId === resourceId);
430
+ const targetIndex = threadMessages.findIndex((message) => message.id === item.id);
431
+ if (targetIndex === -1) continue;
432
+ const start = Math.max(0, targetIndex - (item.withPreviousMessages ?? 0));
433
+ const end = Math.min(threadMessages.length, targetIndex + (item.withNextMessages ?? 0) + 1);
434
+ for (const message of threadMessages.slice(start, end)) {
435
+ messageIds.add(message.id);
436
+ messageIdToThreadIds[message.id] = itemThreadId;
437
+ }
438
+ continue;
439
+ }
440
+ messageIds.add(item.id);
441
+ messageIdToThreadIds[item.id] = itemThreadId;
442
+ const rank = await this.client.zRank(itemThreadMessagesKey, item.id);
443
+ if (rank === null) continue;
444
+ if (item.withPreviousMessages) {
445
+ const start = Math.max(0, rank - item.withPreviousMessages);
446
+ (rank === 0 ? [] : await this.client.zRange(itemThreadMessagesKey, start, rank - 1)).forEach((id) => {
447
+ messageIds.add(id);
448
+ messageIdToThreadIds[id] = itemThreadId;
449
+ });
450
+ }
451
+ if (item.withNextMessages) (await this.client.zRange(itemThreadMessagesKey, rank + 1, rank + item.withNextMessages)).forEach((id) => {
452
+ messageIds.add(id);
453
+ messageIdToThreadIds[id] = itemThreadId;
454
+ });
455
+ }
456
+ if (messageIds.size === 0) return [];
457
+ const keysToFetch = Array.from(messageIds).map((id) => getMessageKey(messageIdToThreadIds[id], id));
458
+ const includedMessages = (await this.client.mGet(keysToFetch)).filter((data) => data !== null).map((data) => JSON.parse(data));
459
+ return resourceId ? includedMessages.filter((message) => message.resourceId === resourceId) : includedMessages;
460
+ }
461
+ parseStoredMessage(storedMessage) {
462
+ const defaultMessageContent = {
463
+ format: 2,
464
+ parts: [{
465
+ type: "text",
466
+ text: ""
467
+ }]
468
+ };
469
+ const { _index, ...rest } = storedMessage;
470
+ return {
471
+ ...rest,
472
+ createdAt: new Date(rest.createdAt),
473
+ content: rest.content || defaultMessageContent
474
+ };
475
+ }
476
+ async listMessagesById({ messageIds }) {
477
+ if (messageIds.length === 0) return { messages: [] };
478
+ try {
479
+ const rawMessages = [];
480
+ const indexKeys = messageIds.map((id) => getMessageIndexKey(id));
481
+ const indexResults = await this.client.mGet(indexKeys);
482
+ const indexedIds = [];
483
+ const unindexedIds = [];
484
+ messageIds.forEach((id, i) => {
485
+ const threadId = indexResults[i];
486
+ if (threadId) {
487
+ indexedIds.push({
488
+ messageId: id,
489
+ threadId
490
+ });
491
+ return;
492
+ }
493
+ unindexedIds.push(id);
494
+ });
495
+ if (indexedIds.length > 0) {
496
+ const messageKeys = indexedIds.map(({ messageId, threadId }) => getMessageKey(threadId, messageId));
497
+ const messageResults = await this.client.mGet(messageKeys);
498
+ for (const data of messageResults) if (data) rawMessages.push(JSON.parse(data));
499
+ }
500
+ if (unindexedIds.length > 0) {
501
+ const threadKeys = await this.db.scanKeys("thread:*:messages");
502
+ const foundMessages = (await Promise.all(threadKeys.map(async (threadKey) => {
503
+ const threadId = threadKey.split(":")[1];
504
+ if (!threadId) throw new Error(`Failed to parse thread ID from thread key "${threadKey}"`);
505
+ const msgKeys = unindexedIds.map((id) => getMessageKey(threadId, id));
506
+ return this.client.mGet(msgKeys);
507
+ }))).flat(1).filter((data) => !!data).map((data) => JSON.parse(data));
508
+ rawMessages.push(...foundMessages);
509
+ if (foundMessages.length > 0) {
510
+ const multi = this.client.multi();
511
+ foundMessages.forEach((msg) => {
512
+ if (msg.threadId) multi.set(getMessageIndexKey(msg.id), msg.threadId);
513
+ });
514
+ await multi.exec();
515
+ }
516
+ }
517
+ return { messages: new MessageList().add(rawMessages.map(this.parseStoredMessage), "memory").get.all.db() };
518
+ } catch (error) {
519
+ throw new MastraError({
520
+ id: createStorageErrorId("VALKEY", "LIST_MESSAGES_BY_ID", "FAILED"),
521
+ domain: ErrorDomain.STORAGE,
522
+ category: ErrorCategory.THIRD_PARTY,
523
+ details: { messageIds: JSON.stringify(messageIds) }
524
+ }, error);
525
+ }
526
+ }
527
+ async listMessages(args) {
528
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
529
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
530
+ const threadIdsSet = new Set(threadIds);
531
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) throw new MastraError({
532
+ id: createStorageErrorId("VALKEY", "LIST_MESSAGES", "INVALID_THREAD_ID"),
533
+ domain: ErrorDomain.STORAGE,
534
+ category: ErrorCategory.USER,
535
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
536
+ }, /* @__PURE__ */ new Error("threadId must be a non-empty string or array of non-empty strings"));
537
+ const perPage = normalizePerPage(perPageInput, 40);
538
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
539
+ const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
540
+ try {
541
+ if (page < 0) throw new MastraError({
542
+ id: createStorageErrorId("VALKEY", "LIST_MESSAGES", "INVALID_PAGE"),
543
+ domain: ErrorDomain.STORAGE,
544
+ category: ErrorCategory.USER,
545
+ details: { page }
546
+ }, /* @__PURE__ */ new Error("page must be >= 0"));
547
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
548
+ const getFieldValue = (msg) => {
549
+ if (field === "createdAt") return new Date(msg.createdAt).getTime();
550
+ const value = msg[field];
551
+ if (typeof value === "number") return value;
552
+ if (value instanceof Date) return value.getTime();
553
+ return 0;
554
+ };
555
+ if (perPage === 0 && (!include || include.length === 0)) return {
556
+ messages: [],
557
+ total: 0,
558
+ page,
559
+ perPage: perPageForResponse,
560
+ hasMore: false
561
+ };
562
+ let includedMessages = [];
563
+ if (include && include.length > 0) includedMessages = (await this.getIncludedMessages(include, resourceId)).map(this.parseStoredMessage);
564
+ if (perPage === 0 && include && include.length > 0) return {
565
+ messages: new MessageList().add(includedMessages, "memory").get.all.db().sort((a, b) => {
566
+ const aValue = getFieldValue(a);
567
+ const bValue = getFieldValue(b);
568
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
569
+ }),
570
+ total: 0,
571
+ page,
572
+ perPage: perPageForResponse,
573
+ hasMore: false
574
+ };
575
+ const allMessageIdsWithThreads = [];
576
+ for (const tid of threadIds) {
577
+ const threadMessagesKey = getThreadMessagesKey(tid);
578
+ const msgIds = await this.client.zRange(threadMessagesKey, 0, -1);
579
+ for (const mid of msgIds) allMessageIdsWithThreads.push({
580
+ threadId: tid,
581
+ messageId: mid
582
+ });
583
+ }
584
+ if (allMessageIdsWithThreads.length === 0) return {
585
+ messages: [],
586
+ total: 0,
587
+ page,
588
+ perPage: perPageForResponse,
589
+ hasMore: false
590
+ };
591
+ const messageKeys = allMessageIdsWithThreads.map(({ threadId: tid, messageId }) => getMessageKey(tid, messageId));
592
+ let messagesData = (await this.client.mGet(messageKeys)).filter((data) => data !== null).map((data) => JSON.parse(data)).map(this.parseStoredMessage);
593
+ if (resourceId) messagesData = messagesData.filter((msg) => msg.resourceId === resourceId);
594
+ messagesData = filterByDateRange(messagesData, (msg) => new Date(msg.createdAt), filter?.dateRange);
595
+ messagesData = messagesData.filter((message) => storageMessageMatchesMetadataFilter(message.content, metadataFilter));
596
+ messagesData.sort((a, b) => {
597
+ const aValue = getFieldValue(a);
598
+ const bValue = getFieldValue(b);
599
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
600
+ });
601
+ const total = messagesData.length;
602
+ const start = offset;
603
+ const end = perPageInput === false ? total : start + perPage;
604
+ const paginatedMessages = messagesData.slice(start, end);
605
+ const messageIdsSet = /* @__PURE__ */ new Set();
606
+ const allMessages = [];
607
+ for (const msg of paginatedMessages) {
608
+ if (messageIdsSet.has(msg.id)) continue;
609
+ allMessages.push(msg);
610
+ messageIdsSet.add(msg.id);
611
+ }
612
+ for (const msg of includedMessages) {
613
+ if (messageIdsSet.has(msg.id)) continue;
614
+ allMessages.push(msg);
615
+ messageIdsSet.add(msg.id);
616
+ }
617
+ let finalMessages = new MessageList().add(allMessages, "memory").get.all.db();
618
+ finalMessages = finalMessages.sort((a, b) => {
619
+ const aValue = getFieldValue(a);
620
+ const bValue = getFieldValue(b);
621
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
622
+ });
623
+ const returnedThreadMessageIds = new Set(finalMessages.filter((message) => message.threadId && threadIdsSet.has(message.threadId)).map((message) => message.id));
624
+ const hasMore = perPageInput !== false && (metadataFilter || returnedThreadMessageIds.size < total) && offset + paginatedMessages.length < total;
625
+ return {
626
+ messages: finalMessages,
627
+ total,
628
+ page,
629
+ perPage: perPageForResponse,
630
+ hasMore
631
+ };
632
+ } catch (error) {
633
+ if (error instanceof MastraError && error.category === ErrorCategory.USER) throw error;
634
+ const mastraError = new MastraError({
635
+ id: createStorageErrorId("VALKEY", "LIST_MESSAGES", "FAILED"),
636
+ domain: ErrorDomain.STORAGE,
637
+ category: ErrorCategory.THIRD_PARTY,
638
+ details: {
639
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
640
+ resourceId: resourceId ?? ""
641
+ }
642
+ }, error);
643
+ this.logger.error(mastraError.toString());
644
+ this.logger.trackException(mastraError);
645
+ throw mastraError;
646
+ }
647
+ }
648
+ async getResourceById({ resourceId }) {
649
+ try {
650
+ const key = `${TABLE_RESOURCES}:${resourceId}`;
651
+ const data = await this.client.get(key);
652
+ if (!data) return null;
653
+ const resource = JSON.parse(data);
654
+ return {
655
+ ...resource,
656
+ createdAt: new Date(resource.createdAt),
657
+ updatedAt: new Date(resource.updatedAt),
658
+ workingMemory: typeof resource.workingMemory === "object" ? JSON.stringify(resource.workingMemory) : resource.workingMemory,
659
+ metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata) : resource.metadata
660
+ };
661
+ } catch (error) {
662
+ this.logger.error("Error getting resource by ID:", error);
663
+ throw error;
664
+ }
665
+ }
666
+ async saveResource({ resource }) {
667
+ try {
668
+ const key = `${TABLE_RESOURCES}:${resource.id}`;
669
+ const serializedResource = {
670
+ ...resource,
671
+ metadata: JSON.stringify(resource.metadata),
672
+ createdAt: resource.createdAt.toISOString(),
673
+ updatedAt: resource.updatedAt.toISOString()
674
+ };
675
+ await this.client.set(key, JSON.stringify(serializedResource));
676
+ return resource;
677
+ } catch (error) {
678
+ this.logger.error("Error saving resource:", error);
679
+ throw error;
680
+ }
681
+ }
682
+ async updateResource({ resourceId, workingMemory, metadata }) {
683
+ try {
684
+ const existingResource = await this.getResourceById({ resourceId });
685
+ if (!existingResource) {
686
+ const newResource = {
687
+ id: resourceId,
688
+ workingMemory,
689
+ metadata: metadata || {},
690
+ createdAt: /* @__PURE__ */ new Date(),
691
+ updatedAt: /* @__PURE__ */ new Date()
692
+ };
693
+ return this.saveResource({ resource: newResource });
694
+ }
695
+ const updatedResource = {
696
+ ...existingResource,
697
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
698
+ metadata: {
699
+ ...existingResource.metadata,
700
+ ...metadata
701
+ },
702
+ updatedAt: /* @__PURE__ */ new Date()
703
+ };
704
+ await this.saveResource({ resource: updatedResource });
705
+ return updatedResource;
706
+ } catch (error) {
707
+ this.logger.error("Error updating resource:", error);
708
+ throw error;
709
+ }
710
+ }
711
+ async updateMessages(args) {
712
+ const { messages } = args;
713
+ if (messages.length === 0) return [];
714
+ try {
715
+ const messageIds = messages.map((m) => m.id);
716
+ const existingMessages = [];
717
+ const messageIdToKey = {};
718
+ for (const messageId of messageIds) {
719
+ const pattern = getMessageKey("*", messageId);
720
+ const keys = await this.db.scanKeys(pattern);
721
+ for (const key of keys) {
722
+ const data = await this.client.get(key);
723
+ if (!data) continue;
724
+ const message = JSON.parse(data);
725
+ if (message && message.id === messageId) {
726
+ existingMessages.push(message);
727
+ messageIdToKey[messageId] = key;
728
+ break;
729
+ }
730
+ }
731
+ }
732
+ if (existingMessages.length === 0) return [];
733
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
734
+ const multi = this.client.multi();
735
+ for (const existingMessage of existingMessages) {
736
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
737
+ if (!updatePayload) continue;
738
+ const { id, ...fieldsToUpdate } = updatePayload;
739
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
740
+ threadIdsToUpdate.add(existingMessage.threadId);
741
+ if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) threadIdsToUpdate.add(updatePayload.threadId);
742
+ const updatedMessage = { ...existingMessage };
743
+ if (fieldsToUpdate.content) {
744
+ const existingContent = existingMessage.content;
745
+ updatedMessage.content = {
746
+ ...existingContent,
747
+ ...fieldsToUpdate.content,
748
+ ...existingContent?.metadata && fieldsToUpdate.content.metadata ? { metadata: {
749
+ ...existingContent.metadata,
750
+ ...fieldsToUpdate.content.metadata
751
+ } } : {}
752
+ };
753
+ }
754
+ for (const key in fieldsToUpdate) if (Object.prototype.hasOwnProperty.call(fieldsToUpdate, key) && key !== "content") updatedMessage[key] = fieldsToUpdate[key];
755
+ const key = messageIdToKey[id];
756
+ if (!key) continue;
757
+ if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
758
+ multi.zRem(getThreadMessagesKey(existingMessage.threadId), id);
759
+ multi.del(key);
760
+ const newKey = getMessageKey(updatePayload.threadId, id);
761
+ multi.set(newKey, JSON.stringify(updatedMessage));
762
+ multi.set(getMessageIndexKey(id), updatePayload.threadId);
763
+ const score = getMessageScore(updatedMessage);
764
+ multi.zAdd(getThreadMessagesKey(updatePayload.threadId), {
765
+ score,
766
+ value: id
767
+ });
768
+ messageIdToKey[id] = newKey;
769
+ continue;
770
+ }
771
+ multi.set(key, JSON.stringify(updatedMessage));
772
+ }
773
+ const now = /* @__PURE__ */ new Date();
774
+ for (const threadId of threadIdsToUpdate) if (threadId) {
775
+ const threadKey = getKey(TABLE_THREADS, { id: threadId });
776
+ const existingThreadData = await this.client.get(threadKey);
777
+ if (existingThreadData) {
778
+ const updatedThread = {
779
+ ...JSON.parse(existingThreadData),
780
+ updatedAt: now
781
+ };
782
+ multi.set(threadKey, JSON.stringify(processRecord(TABLE_THREADS, updatedThread).processedRecord));
783
+ }
784
+ }
785
+ await multi.exec();
786
+ const updatedMessages = [];
787
+ for (const messageId of messageIds) {
788
+ const key = messageIdToKey[messageId];
789
+ if (key) {
790
+ const data = await this.client.get(key);
791
+ if (data) updatedMessages.push(JSON.parse(data));
792
+ }
793
+ }
794
+ return updatedMessages;
795
+ } catch (error) {
796
+ throw new MastraError({
797
+ id: createStorageErrorId("VALKEY", "UPDATE_MESSAGES", "FAILED"),
798
+ domain: ErrorDomain.STORAGE,
799
+ category: ErrorCategory.THIRD_PARTY,
800
+ details: { messageIds: messages.map((m) => m.id).join(",") }
801
+ }, error);
802
+ }
803
+ }
804
+ async deleteMessages(messageIds) {
805
+ if (!messageIds || messageIds.length === 0) return;
806
+ try {
807
+ const threadIds = /* @__PURE__ */ new Set();
808
+ const messageKeys = [];
809
+ const foundMessageIds = [];
810
+ const messageIdToThreadId = /* @__PURE__ */ new Map();
811
+ const indexKeys = messageIds.map((id) => getMessageIndexKey(id));
812
+ const indexResults = await this.client.mGet(indexKeys);
813
+ const indexedMessages = [];
814
+ const unindexedMessageIds = [];
815
+ messageIds.forEach((id, i) => {
816
+ const threadId = indexResults[i];
817
+ if (threadId) {
818
+ indexedMessages.push({
819
+ messageId: id,
820
+ threadId
821
+ });
822
+ return;
823
+ }
824
+ unindexedMessageIds.push(id);
825
+ });
826
+ for (const { messageId, threadId } of indexedMessages) {
827
+ messageKeys.push(getMessageKey(threadId, messageId));
828
+ foundMessageIds.push(messageId);
829
+ messageIdToThreadId.set(messageId, threadId);
830
+ threadIds.add(threadId);
831
+ }
832
+ for (const messageId of unindexedMessageIds) {
833
+ const pattern = getMessageKey("*", messageId);
834
+ const keys = await this.db.scanKeys(pattern);
835
+ for (const key of keys) {
836
+ const data = await this.client.get(key);
837
+ if (!data) continue;
838
+ const message = JSON.parse(data);
839
+ if (message && message.id === messageId) {
840
+ messageKeys.push(key);
841
+ foundMessageIds.push(messageId);
842
+ if (message.threadId) {
843
+ messageIdToThreadId.set(messageId, message.threadId);
844
+ threadIds.add(message.threadId);
845
+ }
846
+ break;
847
+ }
848
+ }
849
+ }
850
+ if (messageKeys.length === 0) return;
851
+ const multi = this.client.multi();
852
+ for (const key of messageKeys) multi.del(key);
853
+ for (const messageId of foundMessageIds) multi.del(getMessageIndexKey(messageId));
854
+ if (threadIds.size > 0) for (const threadId of threadIds) {
855
+ for (const [msgId, msgThreadId] of messageIdToThreadId) if (msgThreadId === threadId) multi.zRem(getThreadMessagesKey(threadId), msgId);
856
+ const threadKey = getKey(TABLE_THREADS, { id: threadId });
857
+ const threadData = await this.client.get(threadKey);
858
+ if (!threadData) continue;
859
+ const updatedThread = {
860
+ ...JSON.parse(threadData),
861
+ updatedAt: /* @__PURE__ */ new Date()
862
+ };
863
+ multi.set(threadKey, JSON.stringify(processRecord(TABLE_THREADS, updatedThread).processedRecord));
864
+ }
865
+ await multi.exec();
866
+ } catch (error) {
867
+ throw new MastraError({
868
+ id: createStorageErrorId("VALKEY", "DELETE_MESSAGES", "FAILED"),
869
+ domain: ErrorDomain.STORAGE,
870
+ category: ErrorCategory.THIRD_PARTY,
871
+ details: { messageIds: messageIds.join(", ") }
872
+ }, error);
873
+ }
874
+ }
875
+ sortThreads(threads, field, direction) {
876
+ return threads.sort((a, b) => {
877
+ const aValue = new Date(a[field]).getTime();
878
+ const bValue = new Date(b[field]).getTime();
879
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
880
+ });
881
+ }
882
+ async cloneThread(args) {
883
+ const { sourceThreadId, newThreadId: providedThreadId, resourceId, title, metadata, options } = args;
884
+ const sourceThread = await this.getThreadById({ threadId: sourceThreadId });
885
+ if (!sourceThread) throw new MastraError({
886
+ id: createStorageErrorId("VALKEY", "CLONE_THREAD", "SOURCE_NOT_FOUND"),
887
+ domain: ErrorDomain.STORAGE,
888
+ category: ErrorCategory.USER,
889
+ text: `Source thread with id ${sourceThreadId} not found`,
890
+ details: { sourceThreadId }
891
+ });
892
+ const newThreadId = providedThreadId || crypto.randomUUID();
893
+ if (await this.getThreadById({ threadId: newThreadId })) throw new MastraError({
894
+ id: createStorageErrorId("VALKEY", "CLONE_THREAD", "THREAD_EXISTS"),
895
+ domain: ErrorDomain.STORAGE,
896
+ category: ErrorCategory.USER,
897
+ text: `Thread with id ${newThreadId} already exists`,
898
+ details: { newThreadId }
899
+ });
900
+ try {
901
+ const threadMessagesKey = getThreadMessagesKey(sourceThreadId);
902
+ const messageKeys = (await this.client.zRange(threadMessagesKey, 0, -1)).map((mid) => getMessageKey(sourceThreadId, mid));
903
+ let sourceMessages = [];
904
+ if (messageKeys.length > 0) sourceMessages = (await this.client.mGet(messageKeys)).filter((data) => data !== null).map((data) => {
905
+ const msg = JSON.parse(data);
906
+ return {
907
+ ...msg,
908
+ createdAt: new Date(msg.createdAt)
909
+ };
910
+ });
911
+ if (options?.messageFilter?.startDate || options?.messageFilter?.endDate) sourceMessages = filterByDateRange(sourceMessages, (msg) => new Date(msg.createdAt), {
912
+ start: options.messageFilter?.startDate,
913
+ end: options.messageFilter?.endDate
914
+ });
915
+ if (options?.messageFilter?.messageIds && options.messageFilter.messageIds.length > 0) {
916
+ const messageIdSet = new Set(options.messageFilter.messageIds);
917
+ sourceMessages = sourceMessages.filter((msg) => messageIdSet.has(msg.id));
918
+ }
919
+ sourceMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
920
+ if (options?.messageLimit && options.messageLimit > 0 && sourceMessages.length > options.messageLimit) sourceMessages = sourceMessages.slice(-options.messageLimit);
921
+ const now = /* @__PURE__ */ new Date();
922
+ const lastMessageId = sourceMessages.length > 0 ? sourceMessages[sourceMessages.length - 1].id : void 0;
923
+ const cloneMetadata = {
924
+ sourceThreadId,
925
+ clonedAt: now,
926
+ ...lastMessageId && { lastMessageId }
927
+ };
928
+ const newThread = {
929
+ id: newThreadId,
930
+ resourceId: resourceId || sourceThread.resourceId,
931
+ title: title || (sourceThread.title ? `Clone of ${sourceThread.title}` : void 0),
932
+ metadata: {
933
+ ...metadata,
934
+ clone: cloneMetadata
935
+ },
936
+ createdAt: now,
937
+ updatedAt: now
938
+ };
939
+ const multi = this.client.multi();
940
+ const threadKey = getKey(TABLE_THREADS, { id: newThreadId });
941
+ multi.set(threadKey, JSON.stringify(processRecord(TABLE_THREADS, newThread).processedRecord));
942
+ const clonedMessages = [];
943
+ const targetResourceId = resourceId || sourceThread.resourceId;
944
+ const newThreadMessagesKey = getThreadMessagesKey(newThreadId);
945
+ for (let i = 0; i < sourceMessages.length; i++) {
946
+ const sourceMsg = sourceMessages[i];
947
+ const newMessageId = crypto.randomUUID();
948
+ const { _index, ...restMsg } = sourceMsg;
949
+ const newMessage = {
950
+ ...restMsg,
951
+ id: newMessageId,
952
+ threadId: newThreadId,
953
+ resourceId: targetResourceId
954
+ };
955
+ const messageKey = getMessageKey(newThreadId, newMessageId);
956
+ multi.set(messageKey, JSON.stringify(newMessage));
957
+ multi.set(getMessageIndexKey(newMessageId), newThreadId);
958
+ const score = getMessageScore({
959
+ createdAt: newMessage.createdAt,
960
+ _index: i
961
+ });
962
+ multi.zAdd(newThreadMessagesKey, {
963
+ score,
964
+ value: newMessageId
965
+ });
966
+ clonedMessages.push(newMessage);
967
+ }
968
+ await multi.exec();
969
+ return {
970
+ thread: newThread,
971
+ clonedMessages
972
+ };
973
+ } catch (error) {
974
+ if (error instanceof MastraError) throw error;
975
+ throw new MastraError({
976
+ id: createStorageErrorId("VALKEY", "CLONE_THREAD", "FAILED"),
977
+ domain: ErrorDomain.STORAGE,
978
+ category: ErrorCategory.THIRD_PARTY,
979
+ details: {
980
+ sourceThreadId,
981
+ newThreadId
982
+ }
983
+ }, error);
984
+ }
985
+ }
986
+ };
987
+ function getThreadMessagesKey(threadId) {
988
+ return `thread:${threadId}:messages`;
989
+ }
990
+ function getMessageKey(threadId, messageId) {
991
+ return getKey(TABLE_MESSAGES, {
992
+ threadId,
993
+ id: messageId
994
+ });
995
+ }
996
+ function getMessageIndexKey(messageId) {
997
+ return `msg-idx:${messageId}`;
998
+ }
999
+ function getMessageScore(message) {
1000
+ const createdAtScore = new Date(message.createdAt).getTime();
1001
+ const index = typeof message._index === "number" ? message._index : 0;
1002
+ return createdAtScore * 1e3 + index;
1003
+ }
1004
+ //#endregion
1005
+ //#region src/storage/domains/scores/index.ts
1006
+ /** Returns true when a row matches the multi-tenant scope filters (or none provided). */
1007
+ function matchesTenancy(row, filters) {
1008
+ if (filters?.organizationId !== void 0 && row.organizationId !== filters.organizationId) return false;
1009
+ if (filters?.projectId !== void 0 && row.projectId !== filters.projectId) return false;
1010
+ return true;
1011
+ }
1012
+ var ScoresValkey = class extends ScoresStorage {
1013
+ client;
1014
+ db;
1015
+ constructor(config) {
1016
+ super();
1017
+ this.client = config.client;
1018
+ this.db = new ValkeyDB({ client: config.client });
1019
+ }
1020
+ async dangerouslyClearAll() {
1021
+ await this.db.deleteData({ tableName: TABLE_SCORERS });
1022
+ }
1023
+ async getScoreById({ id }) {
1024
+ try {
1025
+ const data = await this.db.get({
1026
+ tableName: TABLE_SCORERS,
1027
+ keys: { id }
1028
+ });
1029
+ if (!data) return null;
1030
+ return transformScoreRow(data);
1031
+ } catch (error) {
1032
+ throw new MastraError({
1033
+ id: createStorageErrorId("VALKEY", "GET_SCORE_BY_ID", "FAILED"),
1034
+ domain: ErrorDomain.STORAGE,
1035
+ category: ErrorCategory.THIRD_PARTY,
1036
+ details: { ...id && { id } }
1037
+ }, error);
1038
+ }
1039
+ }
1040
+ async listScoresByScorerId({ scorerId, entityId, entityType, source, pagination = {
1041
+ page: 0,
1042
+ perPage: 20
1043
+ }, filters }) {
1044
+ return this.fetchAndFilterScores(pagination, (row) => {
1045
+ if (row.scorerId !== scorerId) return false;
1046
+ if (entityId && row.entityId !== entityId) return false;
1047
+ if (entityType && row.entityType !== entityType) return false;
1048
+ if (source && row.source !== source) return false;
1049
+ if (!matchesTenancy(row, filters)) return false;
1050
+ return true;
1051
+ });
1052
+ }
1053
+ async saveScore(score) {
1054
+ let validatedScore;
1055
+ try {
1056
+ validatedScore = saveScorePayloadSchema.parse(score);
1057
+ } catch (error) {
1058
+ throw new MastraError({
1059
+ id: createStorageErrorId("VALKEY", "SAVE_SCORE", "VALIDATION_FAILED"),
1060
+ domain: ErrorDomain.STORAGE,
1061
+ category: ErrorCategory.USER,
1062
+ details: {
1063
+ scorer: typeof score.scorer?.id === "string" ? score.scorer.id : String(score.scorer?.id ?? "unknown"),
1064
+ entityId: score.entityId ?? "unknown",
1065
+ entityType: score.entityType ?? "unknown",
1066
+ traceId: score.traceId ?? "",
1067
+ spanId: score.spanId ?? ""
1068
+ }
1069
+ }, error);
1070
+ }
1071
+ const now = /* @__PURE__ */ new Date();
1072
+ const id = crypto$1.randomUUID();
1073
+ const { key, processedRecord } = processRecord(TABLE_SCORERS, {
1074
+ ...validatedScore,
1075
+ id,
1076
+ createdAt: now,
1077
+ updatedAt: now
1078
+ });
1079
+ try {
1080
+ await this.client.set(key, JSON.stringify(processedRecord));
1081
+ return { score: {
1082
+ ...validatedScore,
1083
+ id,
1084
+ createdAt: now,
1085
+ updatedAt: now
1086
+ } };
1087
+ } catch (error) {
1088
+ throw new MastraError({
1089
+ id: createStorageErrorId("VALKEY", "SAVE_SCORE", "FAILED"),
1090
+ domain: ErrorDomain.STORAGE,
1091
+ category: ErrorCategory.THIRD_PARTY,
1092
+ details: { id }
1093
+ }, error);
1094
+ }
1095
+ }
1096
+ async listScoresByRunId({ runId, pagination = {
1097
+ page: 0,
1098
+ perPage: 20
1099
+ }, filters }) {
1100
+ return this.fetchAndFilterScores(pagination, (row) => row.runId === runId && matchesTenancy(row, filters));
1101
+ }
1102
+ async listScoresByEntityId({ entityId, entityType, pagination = {
1103
+ page: 0,
1104
+ perPage: 20
1105
+ }, filters }) {
1106
+ return this.fetchAndFilterScores(pagination, (row) => {
1107
+ if (row.entityId !== entityId) return false;
1108
+ if (entityType && row.entityType !== entityType) return false;
1109
+ if (!matchesTenancy(row, filters)) return false;
1110
+ return true;
1111
+ });
1112
+ }
1113
+ async listScoresBySpan({ traceId, spanId, pagination = {
1114
+ page: 0,
1115
+ perPage: 20
1116
+ }, filters }) {
1117
+ return this.fetchAndFilterScores(pagination, (row) => row.traceId === traceId && row.spanId === spanId && matchesTenancy(row, filters));
1118
+ }
1119
+ async fetchAndFilterScores(pagination, filterFn) {
1120
+ const { page, perPage: perPageInput } = pagination;
1121
+ const keys = await this.db.scanKeys(`${TABLE_SCORERS}:*`);
1122
+ if (keys.length === 0) return {
1123
+ scores: [],
1124
+ pagination: {
1125
+ total: 0,
1126
+ page,
1127
+ perPage: perPageInput,
1128
+ hasMore: false
1129
+ }
1130
+ };
1131
+ const filtered = (await this.client.mGet(keys)).map((data) => {
1132
+ if (!data) return null;
1133
+ try {
1134
+ return JSON.parse(data);
1135
+ } catch {
1136
+ return null;
1137
+ }
1138
+ }).filter((row) => !!row && typeof row === "object" && filterFn(row));
1139
+ const total = filtered.length;
1140
+ const perPage = normalizePerPage(perPageInput, 100);
1141
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1142
+ const end = perPageInput === false ? total : start + perPage;
1143
+ return {
1144
+ scores: filtered.slice(start, end).map((row) => transformScoreRow(row)),
1145
+ pagination: {
1146
+ total,
1147
+ page,
1148
+ perPage: perPageForResponse,
1149
+ hasMore: end < total
1150
+ }
1151
+ };
1152
+ }
1153
+ };
1154
+ //#endregion
1155
+ //#region src/storage/domains/workflows/index.ts
1156
+ function parseWorkflowRun(row) {
1157
+ let parsedSnapshot = row.snapshot;
1158
+ if (typeof parsedSnapshot === "string") try {
1159
+ parsedSnapshot = JSON.parse(row.snapshot);
1160
+ } catch (e) {
1161
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1162
+ }
1163
+ return {
1164
+ workflowName: row.workflow_name,
1165
+ runId: row.run_id,
1166
+ snapshot: parsedSnapshot,
1167
+ createdAt: ensureDate(row.createdAt),
1168
+ updatedAt: ensureDate(row.updatedAt),
1169
+ resourceId: row.resourceId
1170
+ };
1171
+ }
1172
+ var WorkflowsValkey = class extends WorkflowsStorage {
1173
+ client;
1174
+ db;
1175
+ constructor(config) {
1176
+ super();
1177
+ this.client = config.client;
1178
+ this.db = new ValkeyDB({ client: config.client });
1179
+ }
1180
+ supportsConcurrentUpdates() {
1181
+ return false;
1182
+ }
1183
+ async dangerouslyClearAll() {
1184
+ await this.db.deleteData({ tableName: TABLE_WORKFLOW_SNAPSHOT });
1185
+ }
1186
+ async updateWorkflowResults({ workflowName, runId, stepId, result, requestContext }) {
1187
+ try {
1188
+ const existingRecord = await this.db.get({
1189
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1190
+ keys: {
1191
+ namespace: "workflows",
1192
+ workflow_name: workflowName,
1193
+ run_id: runId
1194
+ }
1195
+ });
1196
+ let snapshot = existingRecord?.snapshot;
1197
+ if (!snapshot) snapshot = {
1198
+ context: {},
1199
+ activePaths: [],
1200
+ timestamp: Date.now(),
1201
+ suspendedPaths: {},
1202
+ activeStepsPath: {},
1203
+ resumeLabels: {},
1204
+ serializedStepGraph: [],
1205
+ status: "pending",
1206
+ value: {},
1207
+ waitingPaths: {},
1208
+ runId,
1209
+ requestContext: {}
1210
+ };
1211
+ snapshot.context[stepId] = result;
1212
+ snapshot.requestContext = {
1213
+ ...snapshot.requestContext,
1214
+ ...requestContext
1215
+ };
1216
+ await this.persistWorkflowSnapshot({
1217
+ namespace: "workflows",
1218
+ workflowName,
1219
+ runId,
1220
+ snapshot,
1221
+ createdAt: existingRecord?.createdAt ? ensureDate(existingRecord.createdAt) : void 0
1222
+ });
1223
+ return snapshot.context;
1224
+ } catch (error) {
1225
+ if (error instanceof MastraError) throw error;
1226
+ throw new MastraError({
1227
+ id: createStorageErrorId("VALKEY", "UPDATE_WORKFLOW_RESULTS", "FAILED"),
1228
+ domain: ErrorDomain.STORAGE,
1229
+ category: ErrorCategory.THIRD_PARTY,
1230
+ details: {
1231
+ workflowName,
1232
+ runId,
1233
+ stepId
1234
+ }
1235
+ }, error);
1236
+ }
1237
+ }
1238
+ async updateWorkflowState({ workflowName, runId, opts }) {
1239
+ try {
1240
+ const existingRecord = await this.db.get({
1241
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1242
+ keys: {
1243
+ namespace: "workflows",
1244
+ workflow_name: workflowName,
1245
+ run_id: runId
1246
+ }
1247
+ });
1248
+ const existingSnapshot = existingRecord?.snapshot;
1249
+ if (!existingSnapshot || !existingSnapshot.context) return;
1250
+ const { expectedStatus, ...state } = opts;
1251
+ if (!matchesExpectedWorkflowStatus(existingSnapshot.status, expectedStatus)) return;
1252
+ const updatedSnapshot = {
1253
+ ...existingSnapshot,
1254
+ ...state
1255
+ };
1256
+ await this.persistWorkflowSnapshot({
1257
+ namespace: "workflows",
1258
+ workflowName,
1259
+ runId,
1260
+ snapshot: updatedSnapshot,
1261
+ createdAt: existingRecord?.createdAt ? ensureDate(existingRecord.createdAt) : void 0
1262
+ });
1263
+ return updatedSnapshot;
1264
+ } catch (error) {
1265
+ if (error instanceof MastraError) throw error;
1266
+ throw new MastraError({
1267
+ id: createStorageErrorId("VALKEY", "UPDATE_WORKFLOW_STATE", "FAILED"),
1268
+ domain: ErrorDomain.STORAGE,
1269
+ category: ErrorCategory.THIRD_PARTY,
1270
+ details: {
1271
+ workflowName,
1272
+ runId
1273
+ }
1274
+ }, error);
1275
+ }
1276
+ }
1277
+ async persistWorkflowSnapshot(params) {
1278
+ const { namespace = "workflows", workflowName, runId, resourceId, snapshot, createdAt, updatedAt } = params;
1279
+ try {
1280
+ let finalCreatedAt = createdAt;
1281
+ if (!finalCreatedAt) {
1282
+ const existing = await this.db.get({
1283
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1284
+ keys: {
1285
+ namespace,
1286
+ workflow_name: workflowName,
1287
+ run_id: runId
1288
+ }
1289
+ });
1290
+ finalCreatedAt = existing?.createdAt ? ensureDate(existing.createdAt) : /* @__PURE__ */ new Date();
1291
+ }
1292
+ await this.db.insert({
1293
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1294
+ record: {
1295
+ namespace,
1296
+ workflow_name: workflowName,
1297
+ run_id: runId,
1298
+ resourceId,
1299
+ snapshot,
1300
+ createdAt: finalCreatedAt,
1301
+ updatedAt: updatedAt ?? /* @__PURE__ */ new Date()
1302
+ }
1303
+ });
1304
+ } catch (error) {
1305
+ throw new MastraError({
1306
+ id: createStorageErrorId("VALKEY", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1307
+ domain: ErrorDomain.STORAGE,
1308
+ category: ErrorCategory.THIRD_PARTY,
1309
+ details: {
1310
+ namespace,
1311
+ workflowName,
1312
+ runId
1313
+ }
1314
+ }, error);
1315
+ }
1316
+ }
1317
+ async loadWorkflowSnapshot(params) {
1318
+ const { namespace = "workflows", workflowName, runId } = params;
1319
+ const key = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1320
+ namespace,
1321
+ workflow_name: workflowName,
1322
+ run_id: runId
1323
+ });
1324
+ try {
1325
+ const data = await this.client.get(key);
1326
+ if (!data) return null;
1327
+ return JSON.parse(data).snapshot;
1328
+ } catch (error) {
1329
+ throw new MastraError({
1330
+ id: createStorageErrorId("VALKEY", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
1331
+ domain: ErrorDomain.STORAGE,
1332
+ category: ErrorCategory.THIRD_PARTY,
1333
+ details: {
1334
+ namespace,
1335
+ workflowName,
1336
+ runId
1337
+ }
1338
+ }, error);
1339
+ }
1340
+ }
1341
+ async getWorkflowRunById({ runId, workflowName }) {
1342
+ try {
1343
+ const key = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1344
+ namespace: "workflows",
1345
+ workflow_name: workflowName,
1346
+ run_id: runId
1347
+ }) + "*";
1348
+ const keys = await this.db.scanKeys(key);
1349
+ if (keys.length === 0) return null;
1350
+ const data = (await this.client.mGet(keys)).filter((data) => data !== null).map((data) => JSON.parse(data)).find((workflow) => {
1351
+ if (!workflow) return false;
1352
+ const runIdMatch = workflow.run_id === runId;
1353
+ if (workflowName) return runIdMatch && workflow.workflow_name === workflowName;
1354
+ return runIdMatch;
1355
+ });
1356
+ if (!data) return null;
1357
+ return parseWorkflowRun(data);
1358
+ } catch (error) {
1359
+ throw new MastraError({
1360
+ id: createStorageErrorId("VALKEY", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
1361
+ domain: ErrorDomain.STORAGE,
1362
+ category: ErrorCategory.THIRD_PARTY,
1363
+ details: {
1364
+ namespace: "workflows",
1365
+ runId,
1366
+ workflowName: workflowName || ""
1367
+ }
1368
+ }, error);
1369
+ }
1370
+ }
1371
+ async deleteWorkflowRunById({ runId, workflowName }) {
1372
+ const key = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1373
+ namespace: "workflows",
1374
+ workflow_name: workflowName,
1375
+ run_id: runId
1376
+ });
1377
+ try {
1378
+ await this.client.del(key);
1379
+ } catch (error) {
1380
+ throw new MastraError({
1381
+ id: createStorageErrorId("VALKEY", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
1382
+ domain: ErrorDomain.STORAGE,
1383
+ category: ErrorCategory.THIRD_PARTY,
1384
+ details: {
1385
+ namespace: "workflows",
1386
+ runId,
1387
+ workflowName
1388
+ }
1389
+ }, error);
1390
+ }
1391
+ }
1392
+ async listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId, status } = {}) {
1393
+ try {
1394
+ if (page !== void 0 && page < 0) throw new MastraError({
1395
+ id: createStorageErrorId("VALKEY", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
1396
+ domain: ErrorDomain.STORAGE,
1397
+ category: ErrorCategory.USER,
1398
+ details: { page }
1399
+ }, /* @__PURE__ */ new Error("page must be >= 0"));
1400
+ const normalizedFrom = fromDate ? ensureDate(fromDate) : void 0;
1401
+ const normalizedTo = toDate ? ensureDate(toDate) : void 0;
1402
+ let pattern = getKey(TABLE_WORKFLOW_SNAPSHOT, { namespace: "workflows" }) + ":*";
1403
+ if (workflowName && resourceId) pattern = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1404
+ namespace: "workflows",
1405
+ workflow_name: workflowName,
1406
+ run_id: "*",
1407
+ resourceId
1408
+ });
1409
+ else if (workflowName) pattern = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1410
+ namespace: "workflows",
1411
+ workflow_name: workflowName
1412
+ }) + ":*";
1413
+ else if (resourceId) pattern = getKey(TABLE_WORKFLOW_SNAPSHOT, {
1414
+ namespace: "workflows",
1415
+ workflow_name: "*",
1416
+ run_id: "*",
1417
+ resourceId
1418
+ });
1419
+ const keys = await this.db.scanKeys(pattern);
1420
+ if (keys.length === 0) return {
1421
+ runs: [],
1422
+ total: 0
1423
+ };
1424
+ let runs = (await this.client.mGet(keys)).filter((data) => data !== null).map((data) => JSON.parse(data)).filter((record) => record !== null && record !== void 0 && typeof record === "object" && "workflow_name" in record).filter((record) => !workflowName || record.workflow_name === workflowName).map((w) => parseWorkflowRun(w)).filter((w) => {
1425
+ if (normalizedFrom && w.createdAt < normalizedFrom) return false;
1426
+ if (normalizedTo && w.createdAt > normalizedTo) return false;
1427
+ if (status) {
1428
+ let snapshot = w.snapshot;
1429
+ if (typeof snapshot === "string") try {
1430
+ snapshot = JSON.parse(snapshot);
1431
+ } catch (e) {
1432
+ console.warn(`Failed to parse snapshot for workflow ${w.workflowName}: ${e}`);
1433
+ return false;
1434
+ }
1435
+ return snapshot.status === status;
1436
+ }
1437
+ return true;
1438
+ }).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1439
+ const total = runs.length;
1440
+ if (typeof perPage === "number" && typeof page === "number") {
1441
+ const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
1442
+ const offset = page * normalizedPerPage;
1443
+ runs = runs.slice(offset, offset + normalizedPerPage);
1444
+ }
1445
+ return {
1446
+ runs,
1447
+ total
1448
+ };
1449
+ } catch (error) {
1450
+ if (error instanceof MastraError) throw error;
1451
+ throw new MastraError({
1452
+ id: createStorageErrorId("VALKEY", "LIST_WORKFLOW_RUNS", "FAILED"),
1453
+ domain: ErrorDomain.STORAGE,
1454
+ category: ErrorCategory.THIRD_PARTY,
1455
+ details: {
1456
+ namespace: "workflows",
1457
+ workflowName: workflowName || "",
1458
+ resourceId: resourceId || ""
1459
+ }
1460
+ }, error);
1461
+ }
1462
+ }
1463
+ };
1464
+ //#endregion
1465
+ //#region src/client.ts
1466
+ const asString = (value) => {
1467
+ if (typeof value === "string") return value;
1468
+ if (Buffer.isBuffer(value)) return value.toString();
1469
+ return String(value);
1470
+ };
1471
+ const asNullableString = (value) => value === null ? null : asString(value);
1472
+ const asNumber = (value) => Number(value);
1473
+ var GlideMultiAdapter = class {
1474
+ getClient;
1475
+ batch = new Batch(true);
1476
+ constructor(getClient) {
1477
+ this.getClient = getClient;
1478
+ }
1479
+ del(key) {
1480
+ this.batch.customCommand(["DEL", key]);
1481
+ return this;
1482
+ }
1483
+ set(key, value) {
1484
+ this.batch.customCommand([
1485
+ "SET",
1486
+ key,
1487
+ value
1488
+ ]);
1489
+ return this;
1490
+ }
1491
+ zAdd(key, value) {
1492
+ this.batch.customCommand([
1493
+ "ZADD",
1494
+ key,
1495
+ String(value.score),
1496
+ value.value
1497
+ ]);
1498
+ return this;
1499
+ }
1500
+ zRem(key, value) {
1501
+ this.batch.customCommand([
1502
+ "ZREM",
1503
+ key,
1504
+ value
1505
+ ]);
1506
+ return this;
1507
+ }
1508
+ async exec() {
1509
+ return (await this.getClient()).exec(this.batch, true, { decoder: Decoder.String });
1510
+ }
1511
+ };
1512
+ var GlideValkeyClient = class {
1513
+ config;
1514
+ suppliedClient;
1515
+ clientPromise;
1516
+ constructor(config, suppliedClient) {
1517
+ this.config = config;
1518
+ this.suppliedClient = suppliedClient;
1519
+ }
1520
+ get isOpen() {
1521
+ return this.clientPromise !== void 0 || this.suppliedClient !== void 0;
1522
+ }
1523
+ connect() {
1524
+ return this.getClient().then(() => void 0);
1525
+ }
1526
+ async quit() {
1527
+ (await this.getClient()).close();
1528
+ }
1529
+ async get(key) {
1530
+ return asNullableString(await this.command(["GET", key]));
1531
+ }
1532
+ async set(key, value) {
1533
+ return this.command([
1534
+ "SET",
1535
+ key,
1536
+ value
1537
+ ]);
1538
+ }
1539
+ async mGet(keys) {
1540
+ if (keys.length === 0) return [];
1541
+ return (await this.command(["MGET", ...keys])).map(asNullableString);
1542
+ }
1543
+ async del(keys) {
1544
+ const values = Array.isArray(keys) ? keys : [keys];
1545
+ if (values.length === 0) return 0;
1546
+ return asNumber(await this.command(["DEL", ...values]));
1547
+ }
1548
+ async scan(cursor, options) {
1549
+ const result = await this.command([
1550
+ "SCAN",
1551
+ cursor,
1552
+ "MATCH",
1553
+ options.MATCH,
1554
+ "COUNT",
1555
+ String(options.COUNT)
1556
+ ]);
1557
+ return {
1558
+ cursor: asString(result[0]),
1559
+ keys: result[1].map(asString)
1560
+ };
1561
+ }
1562
+ async zRange(key, start, stop) {
1563
+ return (await this.command([
1564
+ "ZRANGE",
1565
+ key,
1566
+ String(start),
1567
+ String(stop)
1568
+ ])).map(asString);
1569
+ }
1570
+ async zRank(key, value) {
1571
+ const result = await this.command([
1572
+ "ZRANK",
1573
+ key,
1574
+ value
1575
+ ]);
1576
+ return result === null ? null : asNumber(result);
1577
+ }
1578
+ async zAdd(key, value) {
1579
+ return asNumber(await this.command([
1580
+ "ZADD",
1581
+ key,
1582
+ String(value.score),
1583
+ value.value
1584
+ ]));
1585
+ }
1586
+ async zRem(key, value) {
1587
+ return asNumber(await this.command([
1588
+ "ZREM",
1589
+ key,
1590
+ value
1591
+ ]));
1592
+ }
1593
+ multi() {
1594
+ return new GlideMultiAdapter(() => this.getClient());
1595
+ }
1596
+ getClient() {
1597
+ if (this.suppliedClient) return Promise.resolve(this.suppliedClient);
1598
+ this.clientPromise ??= GlideClient.createClient(this.config);
1599
+ return this.clientPromise;
1600
+ }
1601
+ async command(args) {
1602
+ return (await this.getClient()).customCommand(args, { decoder: Decoder.String });
1603
+ }
1604
+ };
1605
+ //#endregion
1606
+ //#region src/storage/store.ts
1607
+ /** GLIDE-backed Valkey storage adapter for Mastra. */
1608
+ var ValkeyStore = class extends MastraStorage {
1609
+ client;
1610
+ shouldManageConnection;
1611
+ stores;
1612
+ constructor(config) {
1613
+ super({
1614
+ id: config.id,
1615
+ name: "Valkey",
1616
+ disableInit: config.disableInit
1617
+ });
1618
+ if ("client" in config) {
1619
+ this.client = new GlideValkeyClient(void 0, config.client);
1620
+ this.shouldManageConnection = false;
1621
+ } else {
1622
+ const glideConfig = "config" in config ? config.config : {
1623
+ addresses: [{
1624
+ host: config.host,
1625
+ port: config.port ?? 6379
1626
+ }],
1627
+ databaseId: config.db ?? 0,
1628
+ credentials: config.password ? {
1629
+ username: config.username ?? "default",
1630
+ password: config.password
1631
+ } : void 0,
1632
+ useTLS: config.useTLS
1633
+ };
1634
+ this.client = new GlideValkeyClient(glideConfig);
1635
+ this.shouldManageConnection = true;
1636
+ }
1637
+ this.stores = {
1638
+ scores: new ScoresValkey({ client: this.client }),
1639
+ workflows: new WorkflowsValkey({ client: this.client }),
1640
+ memory: new StoreMemoryValkey({ client: this.client })
1641
+ };
1642
+ }
1643
+ async init() {
1644
+ if (this.shouldManageConnection) await this.client.connect();
1645
+ await super.init();
1646
+ }
1647
+ getClient() {
1648
+ return this.client;
1649
+ }
1650
+ async close() {
1651
+ if (this.shouldManageConnection) await this.client.quit();
1652
+ }
1653
+ };
1654
+ //#endregion
1655
+ //#region src/cache.ts
1656
+ const stringValue = (value) => Buffer.isBuffer(value) ? value.toString() : String(value);
1657
+ /** GLIDE-backed Valkey cache for Mastra server state. */
1658
+ var ValkeyServerCache = class extends MastraServerCache {
1659
+ client;
1660
+ keyPrefix;
1661
+ ttlSeconds;
1662
+ constructor(config, options = {}) {
1663
+ super({ name: "ValkeyServerCache" });
1664
+ this.client = config.client;
1665
+ this.keyPrefix = options.keyPrefix ?? "mastra:cache:";
1666
+ this.ttlSeconds = options.ttlSeconds ?? 300;
1667
+ }
1668
+ getKey(key) {
1669
+ return `${this.keyPrefix}${key}`;
1670
+ }
1671
+ async command(args) {
1672
+ return this.client.customCommand(args, { decoder: Decoder.String });
1673
+ }
1674
+ async get(key) {
1675
+ const value = await this.command(["GET", this.getKey(key)]);
1676
+ if (value === null) return null;
1677
+ const serialized = stringValue(value);
1678
+ try {
1679
+ return JSON.parse(serialized);
1680
+ } catch {
1681
+ return serialized;
1682
+ }
1683
+ }
1684
+ async set(key, value, ttlMs) {
1685
+ const args = [
1686
+ "SET",
1687
+ this.getKey(key),
1688
+ JSON.stringify(value)
1689
+ ];
1690
+ const seconds = ttlMs === void 0 ? this.ttlSeconds : Math.max(1, Math.ceil(ttlMs / 1e3));
1691
+ if (seconds > 0) args.push("EX", String(seconds));
1692
+ await this.command(args);
1693
+ }
1694
+ async listLength(key) {
1695
+ return Number(await this.command(["LLEN", this.getKey(key)]));
1696
+ }
1697
+ async listPush(key, value) {
1698
+ const fullKey = this.getKey(key);
1699
+ await this.command([
1700
+ "RPUSH",
1701
+ fullKey,
1702
+ JSON.stringify(value)
1703
+ ]);
1704
+ if (this.ttlSeconds > 0) await this.command([
1705
+ "EXPIRE",
1706
+ fullKey,
1707
+ String(this.ttlSeconds)
1708
+ ]);
1709
+ }
1710
+ async listFromTo(key, from, to = -1) {
1711
+ return (await this.command([
1712
+ "LRANGE",
1713
+ this.getKey(key),
1714
+ String(from),
1715
+ String(to)
1716
+ ])).map((value) => {
1717
+ const serialized = stringValue(value);
1718
+ try {
1719
+ return JSON.parse(serialized);
1720
+ } catch {
1721
+ return serialized;
1722
+ }
1723
+ });
1724
+ }
1725
+ async delete(key) {
1726
+ await this.command(["DEL", this.getKey(key)]);
1727
+ }
1728
+ async clear() {
1729
+ let cursor = "0";
1730
+ do {
1731
+ const result = await this.command([
1732
+ "SCAN",
1733
+ cursor,
1734
+ "MATCH",
1735
+ `${this.keyPrefix}*`,
1736
+ "COUNT",
1737
+ "100"
1738
+ ]);
1739
+ cursor = stringValue(result[0]);
1740
+ const keys = result[1].map(stringValue);
1741
+ if (keys.length > 0) await this.command(["DEL", ...keys]);
1742
+ } while (cursor !== "0");
1743
+ }
1744
+ async increment(key) {
1745
+ const fullKey = this.getKey(key);
1746
+ const value = Number(await this.command(["INCR", fullKey]));
1747
+ if (this.ttlSeconds > 0) await this.command([
1748
+ "EXPIRE",
1749
+ fullKey,
1750
+ String(this.ttlSeconds)
1751
+ ]);
1752
+ return value;
1753
+ }
1754
+ };
1755
+ //#endregion
1756
+ export { ScoresValkey, StoreMemoryValkey, ValkeyServerCache, ValkeyStore, WorkflowsValkey };
1757
+
1758
+ //# sourceMappingURL=index.js.map