@mastra/mongodb 0.11.0 → 0.11.1-alpha.1

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.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var error = require('@mastra/core/error');
3
4
  var vector = require('@mastra/core/vector');
4
5
  var mongodb = require('mongodb');
5
6
  var uuid = require('uuid');
@@ -118,28 +119,68 @@ var MongoDBVector = class extends vector.MastraVector {
118
119
  }
119
120
  // Public methods
120
121
  async connect() {
121
- await this.client.connect();
122
+ try {
123
+ await this.client.connect();
124
+ } catch (error$1) {
125
+ throw new error.MastraError(
126
+ {
127
+ id: "STORAGE_MONGODB_VECTOR_CONNECT_FAILED",
128
+ domain: error.ErrorDomain.STORAGE,
129
+ category: error.ErrorCategory.THIRD_PARTY
130
+ },
131
+ error$1
132
+ );
133
+ }
122
134
  }
123
135
  async disconnect() {
124
- await this.client.close();
136
+ try {
137
+ await this.client.close();
138
+ } catch (error$1) {
139
+ throw new error.MastraError(
140
+ {
141
+ id: "STORAGE_MONGODB_VECTOR_DISCONNECT_FAILED",
142
+ domain: error.ErrorDomain.STORAGE,
143
+ category: error.ErrorCategory.THIRD_PARTY
144
+ },
145
+ error$1
146
+ );
147
+ }
125
148
  }
126
149
  async createIndex({ indexName, dimension, metric = "cosine" }) {
127
- if (!Number.isInteger(dimension) || dimension <= 0) {
128
- throw new Error("Dimension must be a positive integer");
129
- }
130
- const mongoMetric = this.mongoMetricMap[metric];
131
- if (!mongoMetric) {
132
- throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
133
- }
134
- const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
135
- if (!collectionExists) {
136
- await this.db.createCollection(indexName);
150
+ let mongoMetric;
151
+ try {
152
+ if (!Number.isInteger(dimension) || dimension <= 0) {
153
+ throw new Error("Dimension must be a positive integer");
154
+ }
155
+ mongoMetric = this.mongoMetricMap[metric];
156
+ if (!mongoMetric) {
157
+ throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
158
+ }
159
+ } catch (error$1) {
160
+ throw new error.MastraError(
161
+ {
162
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_INVALID_ARGS",
163
+ domain: error.ErrorDomain.STORAGE,
164
+ category: error.ErrorCategory.USER,
165
+ details: {
166
+ indexName,
167
+ dimension,
168
+ metric
169
+ }
170
+ },
171
+ error$1
172
+ );
137
173
  }
138
- const collection = await this.getCollection(indexName);
139
- const indexNameInternal = `${indexName}_vector_index`;
140
- const embeddingField = this.embeddingFieldName;
141
- const numDimensions = dimension;
174
+ let collection;
142
175
  try {
176
+ const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
177
+ if (!collectionExists) {
178
+ await this.db.createCollection(indexName);
179
+ }
180
+ collection = await this.getCollection(indexName);
181
+ const indexNameInternal = `${indexName}_vector_index`;
182
+ const embeddingField = this.embeddingFieldName;
183
+ const numDimensions = dimension;
143
184
  await collection.createSearchIndex({
144
185
  definition: {
145
186
  fields: [
@@ -154,12 +195,33 @@ var MongoDBVector = class extends vector.MastraVector {
154
195
  name: indexNameInternal,
155
196
  type: "vectorSearch"
156
197
  });
157
- } catch (error) {
158
- if (error.codeName !== "IndexAlreadyExists") {
159
- throw error;
198
+ } catch (error$1) {
199
+ if (error$1.codeName !== "IndexAlreadyExists") {
200
+ throw new error.MastraError(
201
+ {
202
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED",
203
+ domain: error.ErrorDomain.STORAGE,
204
+ category: error.ErrorCategory.THIRD_PARTY
205
+ },
206
+ error$1
207
+ );
160
208
  }
161
209
  }
162
- await collection.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
210
+ try {
211
+ await collection?.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
212
+ } catch (error$1) {
213
+ throw new error.MastraError(
214
+ {
215
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED_STORE_METADATA",
216
+ domain: error.ErrorDomain.STORAGE,
217
+ category: error.ErrorCategory.THIRD_PARTY,
218
+ details: {
219
+ indexName
220
+ }
221
+ },
222
+ error$1
223
+ );
224
+ }
163
225
  }
164
226
  /**
165
227
  * Waits for the index to be ready.
@@ -189,40 +251,54 @@ var MongoDBVector = class extends vector.MastraVector {
189
251
  throw new Error(`Index "${indexNameInternal}" did not become ready within timeout`);
190
252
  }
191
253
  async upsert({ indexName, vectors, metadata, ids, documents }) {
192
- const collection = await this.getCollection(indexName);
193
- this.collectionForValidation = collection;
194
- const stats = await this.describeIndex({ indexName });
195
- await this.validateVectorDimensions(vectors, stats.dimension);
196
- const generatedIds = ids || vectors.map(() => uuid.v4());
197
- const operations = vectors.map((vector, idx) => {
198
- const id = generatedIds[idx];
199
- const meta = metadata?.[idx] || {};
200
- const doc = documents?.[idx];
201
- const normalizedMeta = Object.keys(meta).reduce(
202
- (acc, key) => {
203
- acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
204
- return acc;
254
+ try {
255
+ const collection = await this.getCollection(indexName);
256
+ this.collectionForValidation = collection;
257
+ const stats = await this.describeIndex({ indexName });
258
+ await this.validateVectorDimensions(vectors, stats.dimension);
259
+ const generatedIds = ids || vectors.map(() => uuid.v4());
260
+ const operations = vectors.map((vector, idx) => {
261
+ const id = generatedIds[idx];
262
+ const meta = metadata?.[idx] || {};
263
+ const doc = documents?.[idx];
264
+ const normalizedMeta = Object.keys(meta).reduce(
265
+ (acc, key) => {
266
+ acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
267
+ return acc;
268
+ },
269
+ {}
270
+ );
271
+ const updateDoc = {
272
+ [this.embeddingFieldName]: vector,
273
+ [this.metadataFieldName]: normalizedMeta
274
+ };
275
+ if (doc !== void 0) {
276
+ updateDoc[this.documentFieldName] = doc;
277
+ }
278
+ return {
279
+ updateOne: {
280
+ filter: { _id: id },
281
+ // '_id' is a string as per MongoDBDocument interface
282
+ update: { $set: updateDoc },
283
+ upsert: true
284
+ }
285
+ };
286
+ });
287
+ await collection.bulkWrite(operations);
288
+ return generatedIds;
289
+ } catch (error$1) {
290
+ throw new error.MastraError(
291
+ {
292
+ id: "STORAGE_MONGODB_VECTOR_UPSERT_FAILED",
293
+ domain: error.ErrorDomain.STORAGE,
294
+ category: error.ErrorCategory.THIRD_PARTY,
295
+ details: {
296
+ indexName
297
+ }
205
298
  },
206
- {}
299
+ error$1
207
300
  );
208
- const updateDoc = {
209
- [this.embeddingFieldName]: vector,
210
- [this.metadataFieldName]: normalizedMeta
211
- };
212
- if (doc !== void 0) {
213
- updateDoc[this.documentFieldName] = doc;
214
- }
215
- return {
216
- updateOne: {
217
- filter: { _id: id },
218
- // '_id' is a string as per MongoDBDocument interface
219
- update: { $set: updateDoc },
220
- upsert: true
221
- }
222
- };
223
- });
224
- await collection.bulkWrite(operations);
225
- return generatedIds;
301
+ }
226
302
  }
227
303
  async query({
228
304
  indexName,
@@ -232,44 +308,44 @@ var MongoDBVector = class extends vector.MastraVector {
232
308
  includeVector = false,
233
309
  documentFilter
234
310
  }) {
235
- const collection = await this.getCollection(indexName, true);
236
- const indexNameInternal = `${indexName}_vector_index`;
237
- const mongoFilter = this.transformFilter(filter);
238
- const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
239
- let combinedFilter = {};
240
- if (Object.keys(mongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
241
- combinedFilter = { $and: [mongoFilter, documentMongoFilter] };
242
- } else if (Object.keys(mongoFilter).length > 0) {
243
- combinedFilter = mongoFilter;
244
- } else if (Object.keys(documentMongoFilter).length > 0) {
245
- combinedFilter = documentMongoFilter;
246
- }
247
- const pipeline = [
248
- {
249
- $vectorSearch: {
250
- index: indexNameInternal,
251
- queryVector,
252
- path: this.embeddingFieldName,
253
- numCandidates: 100,
254
- limit: topK
255
- }
256
- },
257
- // Apply the filter using $match stage
258
- ...Object.keys(combinedFilter).length > 0 ? [{ $match: combinedFilter }] : [],
259
- {
260
- $set: { score: { $meta: "vectorSearchScore" } }
261
- },
262
- {
263
- $project: {
264
- _id: 1,
265
- score: 1,
266
- metadata: `$${this.metadataFieldName}`,
267
- document: `$${this.documentFieldName}`,
268
- ...includeVector && { vector: `$${this.embeddingFieldName}` }
269
- }
270
- }
271
- ];
272
311
  try {
312
+ const collection = await this.getCollection(indexName, true);
313
+ const indexNameInternal = `${indexName}_vector_index`;
314
+ const mongoFilter = this.transformFilter(filter);
315
+ const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
316
+ let combinedFilter = {};
317
+ if (Object.keys(mongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
318
+ combinedFilter = { $and: [mongoFilter, documentMongoFilter] };
319
+ } else if (Object.keys(mongoFilter).length > 0) {
320
+ combinedFilter = mongoFilter;
321
+ } else if (Object.keys(documentMongoFilter).length > 0) {
322
+ combinedFilter = documentMongoFilter;
323
+ }
324
+ const pipeline = [
325
+ {
326
+ $vectorSearch: {
327
+ index: indexNameInternal,
328
+ queryVector,
329
+ path: this.embeddingFieldName,
330
+ numCandidates: 100,
331
+ limit: topK
332
+ }
333
+ },
334
+ // Apply the filter using $match stage
335
+ ...Object.keys(combinedFilter).length > 0 ? [{ $match: combinedFilter }] : [],
336
+ {
337
+ $set: { score: { $meta: "vectorSearchScore" } }
338
+ },
339
+ {
340
+ $project: {
341
+ _id: 1,
342
+ score: 1,
343
+ metadata: `$${this.metadataFieldName}`,
344
+ document: `$${this.documentFieldName}`,
345
+ ...includeVector && { vector: `$${this.embeddingFieldName}` }
346
+ }
347
+ }
348
+ ];
273
349
  const results = await collection.aggregate(pipeline).toArray();
274
350
  return results.map((result) => ({
275
351
  id: result._id,
@@ -278,14 +354,34 @@ var MongoDBVector = class extends vector.MastraVector {
278
354
  vector: includeVector ? result.vector : void 0,
279
355
  document: result.document
280
356
  }));
281
- } catch (error) {
282
- console.error("Error during vector search:", error);
283
- throw error;
357
+ } catch (error$1) {
358
+ throw new error.MastraError(
359
+ {
360
+ id: "STORAGE_MONGODB_VECTOR_QUERY_FAILED",
361
+ domain: error.ErrorDomain.STORAGE,
362
+ category: error.ErrorCategory.THIRD_PARTY,
363
+ details: {
364
+ indexName
365
+ }
366
+ },
367
+ error$1
368
+ );
284
369
  }
285
370
  }
286
371
  async listIndexes() {
287
- const collections = await this.db.listCollections().toArray();
288
- return collections.map((col) => col.name);
372
+ try {
373
+ const collections = await this.db.listCollections().toArray();
374
+ return collections.map((col) => col.name);
375
+ } catch (error$1) {
376
+ throw new error.MastraError(
377
+ {
378
+ id: "STORAGE_MONGODB_VECTOR_LIST_INDEXES_FAILED",
379
+ domain: error.ErrorDomain.STORAGE,
380
+ category: error.ErrorCategory.THIRD_PARTY
381
+ },
382
+ error$1
383
+ );
384
+ }
289
385
  }
290
386
  /**
291
387
  * Retrieves statistics about a vector index.
@@ -294,24 +390,52 @@ var MongoDBVector = class extends vector.MastraVector {
294
390
  * @returns A promise that resolves to the index statistics including dimension, count and metric
295
391
  */
296
392
  async describeIndex({ indexName }) {
297
- const collection = await this.getCollection(indexName, true);
298
- const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
299
- const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
300
- const dimension = metadataDoc?.dimension || 0;
301
- const metric = metadataDoc?.metric || "cosine";
302
- return {
303
- dimension,
304
- count,
305
- metric
306
- };
393
+ try {
394
+ const collection = await this.getCollection(indexName, true);
395
+ const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
396
+ const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
397
+ const dimension = metadataDoc?.dimension || 0;
398
+ const metric = metadataDoc?.metric || "cosine";
399
+ return {
400
+ dimension,
401
+ count,
402
+ metric
403
+ };
404
+ } catch (error$1) {
405
+ throw new error.MastraError(
406
+ {
407
+ id: "STORAGE_MONGODB_VECTOR_DESCRIBE_INDEX_FAILED",
408
+ domain: error.ErrorDomain.STORAGE,
409
+ category: error.ErrorCategory.THIRD_PARTY,
410
+ details: {
411
+ indexName
412
+ }
413
+ },
414
+ error$1
415
+ );
416
+ }
307
417
  }
308
418
  async deleteIndex({ indexName }) {
309
419
  const collection = await this.getCollection(indexName, false);
310
- if (collection) {
311
- await collection.drop();
312
- this.collections.delete(indexName);
313
- } else {
314
- throw new Error(`Index (Collection) "${indexName}" does not exist`);
420
+ try {
421
+ if (collection) {
422
+ await collection.drop();
423
+ this.collections.delete(indexName);
424
+ } else {
425
+ throw new Error(`Index (Collection) "${indexName}" does not exist`);
426
+ }
427
+ } catch (error$1) {
428
+ throw new error.MastraError(
429
+ {
430
+ id: "STORAGE_MONGODB_VECTOR_DELETE_INDEX_FAILED",
431
+ domain: error.ErrorDomain.STORAGE,
432
+ category: error.ErrorCategory.THIRD_PARTY,
433
+ details: {
434
+ indexName
435
+ }
436
+ },
437
+ error$1
438
+ );
315
439
  }
316
440
  }
317
441
  /**
@@ -347,8 +471,19 @@ var MongoDBVector = class extends vector.MastraVector {
347
471
  updateDoc[this.metadataFieldName] = normalizedMeta;
348
472
  }
349
473
  await collection.findOneAndUpdate({ _id: id }, { $set: updateDoc });
350
- } catch (error) {
351
- throw new Error(`Failed to update vector by id: ${id} for index name: ${indexName}: ${error.message}`);
474
+ } catch (error$1) {
475
+ throw new error.MastraError(
476
+ {
477
+ id: "STORAGE_MONGODB_VECTOR_UPDATE_VECTOR_FAILED",
478
+ domain: error.ErrorDomain.STORAGE,
479
+ category: error.ErrorCategory.THIRD_PARTY,
480
+ details: {
481
+ indexName,
482
+ id
483
+ }
484
+ },
485
+ error$1
486
+ );
352
487
  }
353
488
  }
354
489
  /**
@@ -362,8 +497,19 @@ var MongoDBVector = class extends vector.MastraVector {
362
497
  try {
363
498
  const collection = await this.getCollection(indexName, true);
364
499
  await collection.deleteOne({ _id: id });
365
- } catch (error) {
366
- throw new Error(`Failed to delete vector by id: ${id} for index name: ${indexName}: ${error.message}`);
500
+ } catch (error$1) {
501
+ throw new error.MastraError(
502
+ {
503
+ id: "STORAGE_MONGODB_VECTOR_DELETE_VECTOR_FAILED",
504
+ domain: error.ErrorDomain.STORAGE,
505
+ category: error.ErrorCategory.THIRD_PARTY,
506
+ details: {
507
+ indexName,
508
+ id
509
+ }
510
+ },
511
+ error$1
512
+ );
367
513
  }
368
514
  }
369
515
  // Private methods
@@ -419,14 +565,26 @@ var MongoDBStore = class extends storage.MastraStorage {
419
565
  constructor(config) {
420
566
  super({ name: "MongoDBStore" });
421
567
  this.#isConnected = false;
422
- if (!config.url?.trim().length) {
423
- throw new Error(
424
- "MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
425
- );
426
- }
427
- if (!config.dbName?.trim().length) {
428
- throw new Error(
429
- "MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
568
+ try {
569
+ if (!config.url?.trim().length) {
570
+ throw new Error(
571
+ "MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
572
+ );
573
+ }
574
+ if (!config.dbName?.trim().length) {
575
+ throw new Error(
576
+ "MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
577
+ );
578
+ }
579
+ } catch (error$1) {
580
+ throw new error.MastraError(
581
+ {
582
+ id: "STORAGE_MONGODB_STORE_CONSTRUCTOR_FAILED",
583
+ domain: error.ErrorDomain.STORAGE,
584
+ category: error.ErrorCategory.USER,
585
+ details: { url: config.url, dbName: config.dbName }
586
+ },
587
+ error$1
430
588
  );
431
589
  }
432
590
  this.#dbName = config.dbName;
@@ -459,9 +617,19 @@ var MongoDBStore = class extends storage.MastraStorage {
459
617
  try {
460
618
  const collection = await this.getCollection(tableName);
461
619
  await collection.deleteMany({});
462
- } catch (error) {
463
- if (error instanceof Error) {
464
- this.logger.error(error.message);
620
+ } catch (error$1) {
621
+ if (error$1 instanceof Error) {
622
+ const matstraError = new error.MastraError(
623
+ {
624
+ id: "STORAGE_MONGODB_STORE_CLEAR_TABLE_FAILED",
625
+ domain: error.ErrorDomain.STORAGE,
626
+ category: error.ErrorCategory.THIRD_PARTY,
627
+ details: { tableName }
628
+ },
629
+ error$1
630
+ );
631
+ this.logger.error(matstraError.message);
632
+ this.logger?.trackException(matstraError);
465
633
  }
466
634
  }
467
635
  }
@@ -469,9 +637,20 @@ var MongoDBStore = class extends storage.MastraStorage {
469
637
  try {
470
638
  const collection = await this.getCollection(tableName);
471
639
  await collection.insertOne(record);
472
- } catch (error) {
473
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
474
- throw error;
640
+ } catch (error$1) {
641
+ if (error$1 instanceof Error) {
642
+ const matstraError = new error.MastraError(
643
+ {
644
+ id: "STORAGE_MONGODB_STORE_INSERT_FAILED",
645
+ domain: error.ErrorDomain.STORAGE,
646
+ category: error.ErrorCategory.THIRD_PARTY,
647
+ details: { tableName }
648
+ },
649
+ error$1
650
+ );
651
+ this.logger.error(matstraError.message);
652
+ this.logger?.trackException(matstraError);
653
+ }
475
654
  }
476
655
  }
477
656
  async batchInsert({ tableName, records }) {
@@ -481,9 +660,16 @@ var MongoDBStore = class extends storage.MastraStorage {
481
660
  try {
482
661
  const collection = await this.getCollection(tableName);
483
662
  await collection.insertMany(records);
484
- } catch (error) {
485
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
486
- throw error;
663
+ } catch (error$1) {
664
+ throw new error.MastraError(
665
+ {
666
+ id: "STORAGE_MONGODB_STORE_BATCH_INSERT_FAILED",
667
+ domain: error.ErrorDomain.STORAGE,
668
+ category: error.ErrorCategory.THIRD_PARTY,
669
+ details: { tableName }
670
+ },
671
+ error$1
672
+ );
487
673
  }
488
674
  }
489
675
  async load({ tableName, keys }) {
@@ -491,9 +677,16 @@ var MongoDBStore = class extends storage.MastraStorage {
491
677
  try {
492
678
  const collection = await this.getCollection(tableName);
493
679
  return await collection.find(keys).toArray();
494
- } catch (error) {
495
- this.logger.error(`Error loading ${tableName} with keys ${JSON.stringify(keys)}: ${error}`);
496
- throw error;
680
+ } catch (error$1) {
681
+ throw new error.MastraError(
682
+ {
683
+ id: "STORAGE_MONGODB_STORE_LOAD_FAILED",
684
+ domain: error.ErrorDomain.STORAGE,
685
+ category: error.ErrorCategory.THIRD_PARTY,
686
+ details: { tableName }
687
+ },
688
+ error$1
689
+ );
497
690
  }
498
691
  }
499
692
  async getThreadById({ threadId }) {
@@ -507,9 +700,16 @@ var MongoDBStore = class extends storage.MastraStorage {
507
700
  ...result,
508
701
  metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
509
702
  };
510
- } catch (error) {
511
- this.logger.error(`Error loading thread with ID ${threadId}: ${error}`);
512
- throw error;
703
+ } catch (error$1) {
704
+ throw new error.MastraError(
705
+ {
706
+ id: "STORAGE_MONGODB_STORE_GET_THREAD_BY_ID_FAILED",
707
+ domain: error.ErrorDomain.STORAGE,
708
+ category: error.ErrorCategory.THIRD_PARTY,
709
+ details: { threadId }
710
+ },
711
+ error$1
712
+ );
513
713
  }
514
714
  }
515
715
  async getThreadsByResourceId({ resourceId }) {
@@ -523,9 +723,16 @@ var MongoDBStore = class extends storage.MastraStorage {
523
723
  ...result,
524
724
  metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
525
725
  }));
526
- } catch (error) {
527
- this.logger.error(`Error loading threads by resourceId ${resourceId}: ${error}`);
528
- throw error;
726
+ } catch (error$1) {
727
+ throw new error.MastraError(
728
+ {
729
+ id: "STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
730
+ domain: error.ErrorDomain.STORAGE,
731
+ category: error.ErrorCategory.THIRD_PARTY,
732
+ details: { resourceId }
733
+ },
734
+ error$1
735
+ );
529
736
  }
530
737
  }
531
738
  async saveThread({ thread }) {
@@ -542,9 +749,16 @@ var MongoDBStore = class extends storage.MastraStorage {
542
749
  { upsert: true }
543
750
  );
544
751
  return thread;
545
- } catch (error) {
546
- this.logger.error(`Error saving thread ${thread.id}: ${error}`);
547
- throw error;
752
+ } catch (error$1) {
753
+ throw new error.MastraError(
754
+ {
755
+ id: "STORAGE_MONGODB_STORE_SAVE_THREAD_FAILED",
756
+ domain: error.ErrorDomain.STORAGE,
757
+ category: error.ErrorCategory.THIRD_PARTY,
758
+ details: { threadId: thread.id }
759
+ },
760
+ error$1
761
+ );
548
762
  }
549
763
  }
550
764
  async updateThread({
@@ -554,7 +768,13 @@ var MongoDBStore = class extends storage.MastraStorage {
554
768
  }) {
555
769
  const thread = await this.getThreadById({ threadId: id });
556
770
  if (!thread) {
557
- throw new Error(`Thread ${id} not found`);
771
+ throw new error.MastraError({
772
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_NOT_FOUND",
773
+ domain: error.ErrorDomain.STORAGE,
774
+ category: error.ErrorCategory.THIRD_PARTY,
775
+ details: { threadId: id },
776
+ text: `Thread ${id} not found`
777
+ });
558
778
  }
559
779
  const updatedThread = {
560
780
  ...thread,
@@ -575,9 +795,16 @@ var MongoDBStore = class extends storage.MastraStorage {
575
795
  }
576
796
  }
577
797
  );
578
- } catch (error) {
579
- this.logger.error(`Error updating thread ${id}:) ${error}`);
580
- throw error;
798
+ } catch (error$1) {
799
+ throw new error.MastraError(
800
+ {
801
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_FAILED",
802
+ domain: error.ErrorDomain.STORAGE,
803
+ category: error.ErrorCategory.THIRD_PARTY,
804
+ details: { threadId: id }
805
+ },
806
+ error$1
807
+ );
581
808
  }
582
809
  return updatedThread;
583
810
  }
@@ -587,9 +814,16 @@ var MongoDBStore = class extends storage.MastraStorage {
587
814
  await collectionMessages.deleteMany({ thread_id: threadId });
588
815
  const collectionThreads = await this.getCollection(storage.TABLE_THREADS);
589
816
  await collectionThreads.deleteOne({ id: threadId });
590
- } catch (error) {
591
- this.logger.error(`Error deleting thread ${threadId}: ${error}`);
592
- throw error;
817
+ } catch (error$1) {
818
+ throw new error.MastraError(
819
+ {
820
+ id: "STORAGE_MONGODB_STORE_DELETE_THREAD_FAILED",
821
+ domain: error.ErrorDomain.STORAGE,
822
+ category: error.ErrorCategory.THIRD_PARTY,
823
+ details: { threadId }
824
+ },
825
+ error$1
826
+ );
593
827
  }
594
828
  }
595
829
  async getMessages({
@@ -598,7 +832,7 @@ var MongoDBStore = class extends storage.MastraStorage {
598
832
  format
599
833
  }) {
600
834
  try {
601
- const limit = typeof selectBy?.last === "number" ? selectBy.last : 40;
835
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
602
836
  const include = selectBy?.include || [];
603
837
  let messages = [];
604
838
  let allMessages = [];
@@ -638,9 +872,16 @@ var MongoDBStore = class extends storage.MastraStorage {
638
872
  const list = new agent.MessageList().add(messages.slice(0, limit), "memory");
639
873
  if (format === `v2`) return list.get.all.v2();
640
874
  return list.get.all.v1();
641
- } catch (error) {
642
- this.logger.error("Error getting messages:", error);
643
- throw error;
875
+ } catch (error$1) {
876
+ throw new error.MastraError(
877
+ {
878
+ id: "STORAGE_MONGODB_STORE_GET_MESSAGES_FAILED",
879
+ domain: error.ErrorDomain.STORAGE,
880
+ category: error.ErrorCategory.THIRD_PARTY,
881
+ details: { threadId }
882
+ },
883
+ error$1
884
+ );
644
885
  }
645
886
  }
646
887
  async saveMessages({
@@ -712,26 +953,37 @@ var MongoDBStore = class extends storage.MastraStorage {
712
953
  query[key] = value;
713
954
  });
714
955
  }
715
- const collection = await this.getCollection(storage.TABLE_TRACES);
716
- const result = await collection.find(query, {
717
- sort: { startTime: -1 }
718
- }).limit(limit).skip(offset).toArray();
719
- return result.map((row) => ({
720
- id: row.id,
721
- parentSpanId: row.parentSpanId,
722
- traceId: row.traceId,
723
- name: row.name,
724
- scope: row.scope,
725
- kind: row.kind,
726
- status: safelyParseJSON(row.status),
727
- events: safelyParseJSON(row.events),
728
- links: safelyParseJSON(row.links),
729
- attributes: safelyParseJSON(row.attributes),
730
- startTime: row.startTime,
731
- endTime: row.endTime,
732
- other: safelyParseJSON(row.other),
733
- createdAt: row.createdAt
734
- }));
956
+ try {
957
+ const collection = await this.getCollection(storage.TABLE_TRACES);
958
+ const result = await collection.find(query, {
959
+ sort: { startTime: -1 }
960
+ }).limit(limit).skip(offset).toArray();
961
+ return result.map((row) => ({
962
+ id: row.id,
963
+ parentSpanId: row.parentSpanId,
964
+ traceId: row.traceId,
965
+ name: row.name,
966
+ scope: row.scope,
967
+ kind: row.kind,
968
+ status: safelyParseJSON(row.status),
969
+ events: safelyParseJSON(row.events),
970
+ links: safelyParseJSON(row.links),
971
+ attributes: safelyParseJSON(row.attributes),
972
+ startTime: row.startTime,
973
+ endTime: row.endTime,
974
+ other: safelyParseJSON(row.other),
975
+ createdAt: row.createdAt
976
+ }));
977
+ } catch (error$1) {
978
+ throw new error.MastraError(
979
+ {
980
+ id: "STORAGE_MONGODB_STORE_GET_TRACES_FAILED",
981
+ domain: error.ErrorDomain.STORAGE,
982
+ category: error.ErrorCategory.THIRD_PARTY
983
+ },
984
+ error$1
985
+ );
986
+ }
735
987
  }
736
988
  async getWorkflowRuns({
737
989
  workflowName,
@@ -753,37 +1005,48 @@ var MongoDBStore = class extends storage.MastraStorage {
753
1005
  query["createdAt"]["$lte"] = toDate;
754
1006
  }
755
1007
  }
756
- const collection = await this.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
757
- let total = 0;
758
- if (limit !== void 0 && offset !== void 0) {
759
- total = await collection.countDocuments(query);
760
- }
761
- const request = collection.find(query).sort({ createdAt: "desc" });
762
- if (limit) {
763
- request.limit(limit);
764
- }
765
- if (offset) {
766
- request.skip(offset);
767
- }
768
- const result = await request.toArray();
769
- const runs = result.map((row) => {
770
- let parsedSnapshot = row.snapshot;
771
- if (typeof parsedSnapshot === "string") {
772
- try {
773
- parsedSnapshot = JSON.parse(row.snapshot);
774
- } catch (e) {
775
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
776
- }
1008
+ try {
1009
+ const collection = await this.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
1010
+ let total = 0;
1011
+ if (limit !== void 0 && offset !== void 0) {
1012
+ total = await collection.countDocuments(query);
777
1013
  }
778
- return {
779
- workflowName: row.workflow_name,
780
- runId: row.run_id,
781
- snapshot: parsedSnapshot,
782
- createdAt: new Date(row.createdAt),
783
- updatedAt: new Date(row.updatedAt)
784
- };
785
- });
786
- return { runs, total: total || runs.length };
1014
+ const request = collection.find(query).sort({ createdAt: "desc" });
1015
+ if (limit) {
1016
+ request.limit(limit);
1017
+ }
1018
+ if (offset) {
1019
+ request.skip(offset);
1020
+ }
1021
+ const result = await request.toArray();
1022
+ const runs = result.map((row) => {
1023
+ let parsedSnapshot = row.snapshot;
1024
+ if (typeof parsedSnapshot === "string") {
1025
+ try {
1026
+ parsedSnapshot = JSON.parse(row.snapshot);
1027
+ } catch (e) {
1028
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1029
+ }
1030
+ }
1031
+ return {
1032
+ workflowName: row.workflow_name,
1033
+ runId: row.run_id,
1034
+ snapshot: parsedSnapshot,
1035
+ createdAt: new Date(row.createdAt),
1036
+ updatedAt: new Date(row.updatedAt)
1037
+ };
1038
+ });
1039
+ return { runs, total: total || runs.length };
1040
+ } catch (error$1) {
1041
+ throw new error.MastraError(
1042
+ {
1043
+ id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUNS_FAILED",
1044
+ domain: error.ErrorDomain.STORAGE,
1045
+ category: error.ErrorCategory.THIRD_PARTY
1046
+ },
1047
+ error$1
1048
+ );
1049
+ }
787
1050
  }
788
1051
  async getEvalsByAgentName(agentName, type) {
789
1052
  try {
@@ -808,12 +1071,19 @@ var MongoDBStore = class extends storage.MastraStorage {
808
1071
  }
809
1072
  return true;
810
1073
  });
811
- } catch (error) {
812
- if (error instanceof Error && error.message.includes("no such table")) {
1074
+ } catch (error$1) {
1075
+ if (error$1 instanceof Error && error$1.message.includes("no such table")) {
813
1076
  return [];
814
1077
  }
815
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
816
- throw error;
1078
+ throw new error.MastraError(
1079
+ {
1080
+ id: "STORAGE_MONGODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
1081
+ domain: error.ErrorDomain.STORAGE,
1082
+ category: error.ErrorCategory.THIRD_PARTY,
1083
+ details: { agentName }
1084
+ },
1085
+ error$1
1086
+ );
817
1087
  }
818
1088
  }
819
1089
  async persistWorkflowSnapshot({
@@ -837,9 +1107,16 @@ var MongoDBStore = class extends storage.MastraStorage {
837
1107
  },
838
1108
  { upsert: true }
839
1109
  );
840
- } catch (error) {
841
- this.logger.error(`Error persisting workflow snapshot: ${error}`);
842
- throw error;
1110
+ } catch (error$1) {
1111
+ throw new error.MastraError(
1112
+ {
1113
+ id: "STORAGE_MONGODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1114
+ domain: error.ErrorDomain.STORAGE,
1115
+ category: error.ErrorCategory.THIRD_PARTY,
1116
+ details: { workflowName, runId }
1117
+ },
1118
+ error$1
1119
+ );
843
1120
  }
844
1121
  }
845
1122
  async loadWorkflowSnapshot({
@@ -858,9 +1135,16 @@ var MongoDBStore = class extends storage.MastraStorage {
858
1135
  return null;
859
1136
  }
860
1137
  return JSON.parse(result[0].snapshot);
861
- } catch (error) {
862
- console.error("Error loading workflow snapshot:", error);
863
- throw error;
1138
+ } catch (error$1) {
1139
+ throw new error.MastraError(
1140
+ {
1141
+ id: "STORAGE_MONGODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1142
+ domain: error.ErrorDomain.STORAGE,
1143
+ category: error.ErrorCategory.THIRD_PARTY,
1144
+ details: { workflowName, runId }
1145
+ },
1146
+ error$1
1147
+ );
864
1148
  }
865
1149
  }
866
1150
  async getWorkflowRunById({
@@ -881,9 +1165,16 @@ var MongoDBStore = class extends storage.MastraStorage {
881
1165
  return null;
882
1166
  }
883
1167
  return this.parseWorkflowRun(result);
884
- } catch (error) {
885
- console.error("Error getting workflow run by ID:", error);
886
- throw error;
1168
+ } catch (error$1) {
1169
+ throw new error.MastraError(
1170
+ {
1171
+ id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1172
+ domain: error.ErrorDomain.STORAGE,
1173
+ category: error.ErrorCategory.THIRD_PARTY,
1174
+ details: { runId }
1175
+ },
1176
+ error$1
1177
+ );
887
1178
  }
888
1179
  }
889
1180
  parseWorkflowRun(row) {
@@ -943,16 +1234,46 @@ var MongoDBStore = class extends storage.MastraStorage {
943
1234
  };
944
1235
  }
945
1236
  async getTracesPaginated(_args) {
946
- throw new Error("Method not implemented.");
1237
+ throw new error.MastraError({
1238
+ id: "STORAGE_MONGODB_STORE_GET_TRACES_PAGINATED_FAILED",
1239
+ domain: error.ErrorDomain.STORAGE,
1240
+ category: error.ErrorCategory.THIRD_PARTY,
1241
+ text: "Method not implemented."
1242
+ });
947
1243
  }
948
1244
  async getThreadsByResourceIdPaginated(_args) {
949
- throw new Error("Method not implemented.");
1245
+ throw new error.MastraError({
1246
+ id: "STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1247
+ domain: error.ErrorDomain.STORAGE,
1248
+ category: error.ErrorCategory.THIRD_PARTY,
1249
+ text: "Method not implemented."
1250
+ });
950
1251
  }
951
1252
  async getMessagesPaginated(_args) {
952
- throw new Error("Method not implemented.");
1253
+ throw new error.MastraError({
1254
+ id: "STORAGE_MONGODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1255
+ domain: error.ErrorDomain.STORAGE,
1256
+ category: error.ErrorCategory.THIRD_PARTY,
1257
+ text: "Method not implemented."
1258
+ });
953
1259
  }
954
1260
  async close() {
955
- await this.#client.close();
1261
+ try {
1262
+ await this.#client.close();
1263
+ } catch (error$1) {
1264
+ throw new error.MastraError(
1265
+ {
1266
+ id: "STORAGE_MONGODB_STORE_CLOSE_FAILED",
1267
+ domain: error.ErrorDomain.STORAGE,
1268
+ category: error.ErrorCategory.USER
1269
+ },
1270
+ error$1
1271
+ );
1272
+ }
1273
+ }
1274
+ async updateMessages(_args) {
1275
+ this.logger.error("updateMessages is not yet implemented in MongoDBStore");
1276
+ throw new Error("Method not implemented");
956
1277
  }
957
1278
  };
958
1279