@mastra/cloudflare-d1 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.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { MessageList } from '@mastra/core/agent';
2
+ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
3
  import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_TRACES, TABLE_EVALS } from '@mastra/core/storage';
3
4
  import Cloudflare from 'cloudflare';
4
5
  import { parseSqlIdentifier } from '@mastra/core/utils';
@@ -250,27 +251,39 @@ var D1Store = class extends MastraStorage {
250
251
  * @param config Configuration for D1 access (either REST API or Workers Binding API)
251
252
  */
252
253
  constructor(config) {
253
- super({ name: "D1" });
254
- if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
255
- throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
256
- }
257
- this.tablePrefix = config.tablePrefix || "";
258
- if ("binding" in config) {
259
- if (!config.binding) {
260
- throw new Error("D1 binding is required when using Workers Binding API");
254
+ try {
255
+ super({ name: "D1" });
256
+ if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
257
+ throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
261
258
  }
262
- this.binding = config.binding;
263
- this.logger.info("Using D1 Workers Binding API");
264
- } else {
265
- if (!config.accountId || !config.databaseId || !config.apiToken) {
266
- throw new Error("accountId, databaseId, and apiToken are required when using REST API");
259
+ this.tablePrefix = config.tablePrefix || "";
260
+ if ("binding" in config) {
261
+ if (!config.binding) {
262
+ throw new Error("D1 binding is required when using Workers Binding API");
263
+ }
264
+ this.binding = config.binding;
265
+ this.logger.info("Using D1 Workers Binding API");
266
+ } else {
267
+ if (!config.accountId || !config.databaseId || !config.apiToken) {
268
+ throw new Error("accountId, databaseId, and apiToken are required when using REST API");
269
+ }
270
+ this.accountId = config.accountId;
271
+ this.databaseId = config.databaseId;
272
+ this.client = new Cloudflare({
273
+ apiToken: config.apiToken
274
+ });
275
+ this.logger.info("Using D1 REST API");
267
276
  }
268
- this.accountId = config.accountId;
269
- this.databaseId = config.databaseId;
270
- this.client = new Cloudflare({
271
- apiToken: config.apiToken
272
- });
273
- this.logger.info("Using D1 REST API");
277
+ } catch (error) {
278
+ throw new MastraError(
279
+ {
280
+ id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
281
+ domain: ErrorDomain.STORAGE,
282
+ category: ErrorCategory.SYSTEM,
283
+ text: "Error initializing D1Store"
284
+ },
285
+ error
286
+ );
274
287
  }
275
288
  }
276
289
  // Helper method to get the full table name with prefix
@@ -462,16 +475,25 @@ var D1Store = class extends MastraStorage {
462
475
  if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
463
476
  tableConstraints.push("UNIQUE (workflow_name, run_id)");
464
477
  }
465
- const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
466
- const { sql, params } = query.build();
467
478
  try {
479
+ const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
480
+ const { sql, params } = query.build();
468
481
  await this.executeQuery({ sql, params });
469
482
  this.logger.debug(`Created table ${fullTableName}`);
470
483
  } catch (error) {
471
484
  this.logger.error(`Error creating table ${fullTableName}:`, {
472
485
  message: error instanceof Error ? error.message : String(error)
473
486
  });
474
- throw new Error(`Failed to create table ${fullTableName}: ${error}`);
487
+ throw new MastraError(
488
+ {
489
+ id: "CLOUDFLARE_D1_STORAGE_CREATE_TABLE_ERROR",
490
+ domain: ErrorDomain.STORAGE,
491
+ category: ErrorCategory.THIRD_PARTY,
492
+ text: `Failed to create table ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
493
+ details: { tableName }
494
+ },
495
+ error
496
+ );
475
497
  }
476
498
  }
477
499
  /**
@@ -501,10 +523,16 @@ var D1Store = class extends MastraStorage {
501
523
  }
502
524
  }
503
525
  } catch (error) {
504
- this.logger.error(`Error altering table ${fullTableName}:`, {
505
- message: error instanceof Error ? error.message : String(error)
506
- });
507
- throw new Error(`Failed to alter table ${fullTableName}: ${error}`);
526
+ throw new MastraError(
527
+ {
528
+ id: "CLOUDFLARE_D1_STORAGE_ALTER_TABLE_ERROR",
529
+ domain: ErrorDomain.STORAGE,
530
+ category: ErrorCategory.THIRD_PARTY,
531
+ text: `Failed to alter table ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
532
+ details: { tableName }
533
+ },
534
+ error
535
+ );
508
536
  }
509
537
  }
510
538
  async clearTable({ tableName }) {
@@ -515,10 +543,16 @@ var D1Store = class extends MastraStorage {
515
543
  await this.executeQuery({ sql, params });
516
544
  this.logger.debug(`Cleared table ${fullTableName}`);
517
545
  } catch (error) {
518
- this.logger.error(`Error clearing table ${fullTableName}:`, {
519
- message: error instanceof Error ? error.message : String(error)
520
- });
521
- throw new Error(`Failed to clear table ${fullTableName}: ${error}`);
546
+ throw new MastraError(
547
+ {
548
+ id: "CLOUDFLARE_D1_STORAGE_CLEAR_TABLE_ERROR",
549
+ domain: ErrorDomain.STORAGE,
550
+ category: ErrorCategory.THIRD_PARTY,
551
+ text: `Failed to clear table ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
552
+ details: { tableName }
553
+ },
554
+ error
555
+ );
522
556
  }
523
557
  }
524
558
  async processRecord(record) {
@@ -538,9 +572,16 @@ var D1Store = class extends MastraStorage {
538
572
  try {
539
573
  await this.executeQuery({ sql, params });
540
574
  } catch (error) {
541
- const message = error instanceof Error ? error.message : String(error);
542
- this.logger.error(`Error inserting into ${fullTableName}:`, { message });
543
- throw new Error(`Failed to insert into ${fullTableName}: ${error}`);
575
+ throw new MastraError(
576
+ {
577
+ id: "CLOUDFLARE_D1_STORAGE_INSERT_ERROR",
578
+ domain: ErrorDomain.STORAGE,
579
+ category: ErrorCategory.THIRD_PARTY,
580
+ text: `Failed to insert into ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
581
+ details: { tableName }
582
+ },
583
+ error
584
+ );
544
585
  }
545
586
  }
546
587
  async load({ tableName, keys }) {
@@ -566,10 +607,16 @@ var D1Store = class extends MastraStorage {
566
607
  }
567
608
  return processedResult;
568
609
  } catch (error) {
569
- this.logger.error(`Error loading from ${fullTableName}:`, {
570
- message: error instanceof Error ? error.message : String(error)
571
- });
572
- return null;
610
+ throw new MastraError(
611
+ {
612
+ id: "CLOUDFLARE_D1_STORAGE_LOAD_ERROR",
613
+ domain: ErrorDomain.STORAGE,
614
+ category: ErrorCategory.THIRD_PARTY,
615
+ text: `Failed to load from ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
616
+ details: { tableName }
617
+ },
618
+ error
619
+ );
573
620
  }
574
621
  }
575
622
  async getThreadById({ threadId }) {
@@ -586,9 +633,18 @@ var D1Store = class extends MastraStorage {
586
633
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
587
634
  };
588
635
  } catch (error) {
589
- this.logger.error(`Error processing thread ${threadId}:`, {
590
- message: error instanceof Error ? error.message : String(error)
591
- });
636
+ const mastraError = new MastraError(
637
+ {
638
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
639
+ domain: ErrorDomain.STORAGE,
640
+ category: ErrorCategory.THIRD_PARTY,
641
+ text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
642
+ details: { threadId }
643
+ },
644
+ error
645
+ );
646
+ this.logger?.error(mastraError.toString());
647
+ this.logger?.trackException(mastraError);
592
648
  return null;
593
649
  }
594
650
  }
@@ -608,9 +664,18 @@ var D1Store = class extends MastraStorage {
608
664
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
609
665
  }));
610
666
  } catch (error) {
611
- this.logger.error(`Error getting threads by resourceId ${resourceId}:`, {
612
- message: error instanceof Error ? error.message : String(error)
613
- });
667
+ const mastraError = new MastraError(
668
+ {
669
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
670
+ domain: ErrorDomain.STORAGE,
671
+ category: ErrorCategory.THIRD_PARTY,
672
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
673
+ details: { resourceId }
674
+ },
675
+ error
676
+ );
677
+ this.logger?.error(mastraError.toString());
678
+ this.logger?.trackException(mastraError);
614
679
  return [];
615
680
  }
616
681
  }
@@ -623,19 +688,41 @@ var D1Store = class extends MastraStorage {
623
688
  updatedAt: this.ensureDate(row.updatedAt),
624
689
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
625
690
  });
626
- const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
627
- const countResult = await this.executeQuery(countQuery.build());
628
- const total = Number(countResult?.[0]?.count ?? 0);
629
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
630
- const results = await this.executeQuery(selectQuery.build());
631
- const threads = results.map(mapRowToStorageThreadType);
632
- return {
633
- threads,
634
- total,
635
- page,
636
- perPage,
637
- hasMore: page * perPage + threads.length < total
638
- };
691
+ try {
692
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
693
+ const countResult = await this.executeQuery(countQuery.build());
694
+ const total = Number(countResult?.[0]?.count ?? 0);
695
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
696
+ const results = await this.executeQuery(selectQuery.build());
697
+ const threads = results.map(mapRowToStorageThreadType);
698
+ return {
699
+ threads,
700
+ total,
701
+ page,
702
+ perPage,
703
+ hasMore: page * perPage + threads.length < total
704
+ };
705
+ } catch (error) {
706
+ const mastraError = new MastraError(
707
+ {
708
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
709
+ domain: ErrorDomain.STORAGE,
710
+ category: ErrorCategory.THIRD_PARTY,
711
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
712
+ details: { resourceId }
713
+ },
714
+ error
715
+ );
716
+ this.logger?.error(mastraError.toString());
717
+ this.logger?.trackException(mastraError);
718
+ return {
719
+ threads: [],
720
+ total: 0,
721
+ page,
722
+ perPage,
723
+ hasMore: false
724
+ };
725
+ }
639
726
  }
640
727
  async saveThread({ thread }) {
641
728
  const fullTableName = this.getTableName(TABLE_THREADS);
@@ -663,9 +750,16 @@ var D1Store = class extends MastraStorage {
663
750
  await this.executeQuery({ sql, params });
664
751
  return thread;
665
752
  } catch (error) {
666
- const message = error instanceof Error ? error.message : String(error);
667
- this.logger.error(`Error saving thread to ${fullTableName}:`, { message });
668
- throw error;
753
+ throw new MastraError(
754
+ {
755
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
756
+ domain: ErrorDomain.STORAGE,
757
+ category: ErrorCategory.THIRD_PARTY,
758
+ text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
759
+ details: { threadId: thread.id }
760
+ },
761
+ error
762
+ );
669
763
  }
670
764
  }
671
765
  async updateThread({
@@ -674,19 +768,19 @@ var D1Store = class extends MastraStorage {
674
768
  metadata
675
769
  }) {
676
770
  const thread = await this.getThreadById({ threadId: id });
677
- if (!thread) {
678
- throw new Error(`Thread ${id} not found`);
679
- }
680
- const fullTableName = this.getTableName(TABLE_THREADS);
681
- const mergedMetadata = {
682
- ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
683
- ...metadata
684
- };
685
- const columns = ["title", "metadata", "updatedAt"];
686
- const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
687
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
688
- const { sql, params } = query.build();
689
771
  try {
772
+ if (!thread) {
773
+ throw new Error(`Thread ${id} not found`);
774
+ }
775
+ const fullTableName = this.getTableName(TABLE_THREADS);
776
+ const mergedMetadata = {
777
+ ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
778
+ ...metadata
779
+ };
780
+ const columns = ["title", "metadata", "updatedAt"];
781
+ const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
782
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
783
+ const { sql, params } = query.build();
690
784
  await this.executeQuery({ sql, params });
691
785
  return {
692
786
  ...thread,
@@ -698,9 +792,16 @@ var D1Store = class extends MastraStorage {
698
792
  updatedAt: /* @__PURE__ */ new Date()
699
793
  };
700
794
  } catch (error) {
701
- const message = error instanceof Error ? error.message : String(error);
702
- this.logger.error("Error updating thread:", { message });
703
- throw error;
795
+ throw new MastraError(
796
+ {
797
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
798
+ domain: ErrorDomain.STORAGE,
799
+ category: ErrorCategory.THIRD_PARTY,
800
+ text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
801
+ details: { threadId: id }
802
+ },
803
+ error
804
+ );
704
805
  }
705
806
  }
706
807
  async deleteThread({ threadId }) {
@@ -714,10 +815,16 @@ var D1Store = class extends MastraStorage {
714
815
  const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
715
816
  await this.executeQuery({ sql: messagesSql, params: messagesParams });
716
817
  } catch (error) {
717
- this.logger.error(`Error deleting thread ${threadId}:`, {
718
- message: error instanceof Error ? error.message : String(error)
719
- });
720
- throw new Error(`Failed to delete thread ${threadId}: ${error}`);
818
+ throw new MastraError(
819
+ {
820
+ id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
821
+ domain: ErrorDomain.STORAGE,
822
+ category: ErrorCategory.THIRD_PARTY,
823
+ text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
824
+ details: { threadId }
825
+ },
826
+ error
827
+ );
721
828
  }
722
829
  }
723
830
  async saveMessages(args) {
@@ -764,8 +871,15 @@ var D1Store = class extends MastraStorage {
764
871
  if (format === `v2`) return list.get.all.v2();
765
872
  return list.get.all.v1();
766
873
  } catch (error) {
767
- this.logger.error("Error saving messages:", { message: error instanceof Error ? error.message : String(error) });
768
- throw error;
874
+ throw new MastraError(
875
+ {
876
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
877
+ domain: ErrorDomain.STORAGE,
878
+ category: ErrorCategory.THIRD_PARTY,
879
+ text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
880
+ },
881
+ error
882
+ );
769
883
  }
770
884
  }
771
885
  async _getIncludedMessages(threadId, selectBy) {
@@ -820,7 +934,7 @@ var D1Store = class extends MastraStorage {
820
934
  format
821
935
  }) {
822
936
  const fullTableName = this.getTableName(TABLE_MESSAGES);
823
- const limit = typeof selectBy?.last === "number" ? selectBy.last : 40;
937
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
824
938
  const include = selectBy?.include || [];
825
939
  const messages = [];
826
940
  try {
@@ -857,11 +971,19 @@ var D1Store = class extends MastraStorage {
857
971
  if (format === `v2`) return list.get.all.v2();
858
972
  return list.get.all.v1();
859
973
  } catch (error) {
860
- this.logger.error("Error retrieving messages for thread", {
861
- threadId,
862
- message: error instanceof Error ? error.message : String(error)
863
- });
864
- return [];
974
+ const mastraError = new MastraError(
975
+ {
976
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
977
+ domain: ErrorDomain.STORAGE,
978
+ category: ErrorCategory.THIRD_PARTY,
979
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
980
+ details: { threadId }
981
+ },
982
+ error
983
+ );
984
+ this.logger?.error(mastraError.toString());
985
+ this.logger?.trackException(mastraError);
986
+ throw mastraError;
865
987
  }
866
988
  }
867
989
  async getMessagesPaginated({
@@ -873,37 +995,59 @@ var D1Store = class extends MastraStorage {
873
995
  const { start: fromDate, end: toDate } = dateRange || {};
874
996
  const fullTableName = this.getTableName(TABLE_MESSAGES);
875
997
  const messages = [];
876
- if (selectBy?.include?.length) {
877
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
878
- if (Array.isArray(includeResult)) messages.push(...includeResult);
879
- }
880
- const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
881
- if (fromDate) {
882
- countQuery.andWhere("createdAt >= ?", this.serializeDate(fromDate));
883
- }
884
- if (toDate) {
885
- countQuery.andWhere("createdAt <= ?", this.serializeDate(toDate));
886
- }
887
- const countResult = await this.executeQuery(countQuery.build());
888
- const total = Number(countResult[0]?.count ?? 0);
889
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
890
- if (fromDate) {
891
- query.andWhere("createdAt >= ?", this.serializeDate(fromDate));
892
- }
893
- if (toDate) {
894
- query.andWhere("createdAt <= ?", this.serializeDate(toDate));
998
+ try {
999
+ if (selectBy?.include?.length) {
1000
+ const includeResult = await this._getIncludedMessages(threadId, selectBy);
1001
+ if (Array.isArray(includeResult)) messages.push(...includeResult);
1002
+ }
1003
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
1004
+ if (fromDate) {
1005
+ countQuery.andWhere("createdAt >= ?", this.serializeDate(fromDate));
1006
+ }
1007
+ if (toDate) {
1008
+ countQuery.andWhere("createdAt <= ?", this.serializeDate(toDate));
1009
+ }
1010
+ const countResult = await this.executeQuery(countQuery.build());
1011
+ const total = Number(countResult[0]?.count ?? 0);
1012
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
1013
+ if (fromDate) {
1014
+ query.andWhere("createdAt >= ?", this.serializeDate(fromDate));
1015
+ }
1016
+ if (toDate) {
1017
+ query.andWhere("createdAt <= ?", this.serializeDate(toDate));
1018
+ }
1019
+ query.orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
1020
+ const results = await this.executeQuery(query.build());
1021
+ const list = new MessageList().add(results, "memory");
1022
+ messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
1023
+ return {
1024
+ messages,
1025
+ total,
1026
+ page,
1027
+ perPage,
1028
+ hasMore: page * perPage + messages.length < total
1029
+ };
1030
+ } catch (error) {
1031
+ const mastraError = new MastraError(
1032
+ {
1033
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
1034
+ domain: ErrorDomain.STORAGE,
1035
+ category: ErrorCategory.THIRD_PARTY,
1036
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1037
+ details: { threadId }
1038
+ },
1039
+ error
1040
+ );
1041
+ this.logger?.error(mastraError.toString());
1042
+ this.logger?.trackException(mastraError);
1043
+ return {
1044
+ messages: [],
1045
+ total: 0,
1046
+ page,
1047
+ perPage,
1048
+ hasMore: false
1049
+ };
895
1050
  }
896
- query.orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
897
- const results = await this.executeQuery(query.build());
898
- const list = new MessageList().add(results, "memory");
899
- messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
900
- return {
901
- messages,
902
- total,
903
- page,
904
- perPage,
905
- hasMore: page * perPage + messages.length < total
906
- };
907
1051
  }
908
1052
  async persistWorkflowSnapshot({
909
1053
  workflowName,
@@ -940,23 +1084,42 @@ var D1Store = class extends MastraStorage {
940
1084
  try {
941
1085
  await this.executeQuery({ sql, params });
942
1086
  } catch (error) {
943
- this.logger.error("Error persisting workflow snapshot:", {
944
- message: error instanceof Error ? error.message : String(error)
945
- });
946
- throw error;
1087
+ throw new MastraError(
1088
+ {
1089
+ id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1090
+ domain: ErrorDomain.STORAGE,
1091
+ category: ErrorCategory.THIRD_PARTY,
1092
+ text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1093
+ details: { workflowName, runId }
1094
+ },
1095
+ error
1096
+ );
947
1097
  }
948
1098
  }
949
1099
  async loadWorkflowSnapshot(params) {
950
1100
  const { workflowName, runId } = params;
951
1101
  this.logger.debug("Loading workflow snapshot", { workflowName, runId });
952
- const d = await this.load({
953
- tableName: TABLE_WORKFLOW_SNAPSHOT,
954
- keys: {
955
- workflow_name: workflowName,
956
- run_id: runId
957
- }
958
- });
959
- return d ? d.snapshot : null;
1102
+ try {
1103
+ const d = await this.load({
1104
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1105
+ keys: {
1106
+ workflow_name: workflowName,
1107
+ run_id: runId
1108
+ }
1109
+ });
1110
+ return d ? d.snapshot : null;
1111
+ } catch (error) {
1112
+ throw new MastraError(
1113
+ {
1114
+ id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1115
+ domain: ErrorDomain.STORAGE,
1116
+ category: ErrorCategory.THIRD_PARTY,
1117
+ text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1118
+ details: { workflowName, runId }
1119
+ },
1120
+ error
1121
+ );
1122
+ }
960
1123
  }
961
1124
  /**
962
1125
  * Insert multiple records in a batch operation
@@ -991,10 +1154,16 @@ var D1Store = class extends MastraStorage {
991
1154
  }
992
1155
  this.logger.debug(`Successfully batch inserted ${records.length} records into ${tableName}`);
993
1156
  } catch (error) {
994
- this.logger.error(`Error batch inserting into ${tableName}:`, {
995
- message: error instanceof Error ? error.message : String(error)
996
- });
997
- throw new Error(`Failed to batch insert into ${tableName}: ${error}`);
1157
+ throw new MastraError(
1158
+ {
1159
+ id: "CLOUDFLARE_D1_STORAGE_BATCH_INSERT_ERROR",
1160
+ domain: ErrorDomain.STORAGE,
1161
+ category: ErrorCategory.THIRD_PARTY,
1162
+ text: `Failed to batch insert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
1163
+ details: { tableName }
1164
+ },
1165
+ error
1166
+ );
998
1167
  }
999
1168
  }
1000
1169
  /**
@@ -1043,7 +1212,21 @@ var D1Store = class extends MastraStorage {
1043
1212
  })
1044
1213
  ) : [];
1045
1214
  } catch (error) {
1046
- this.logger.error("Error getting traces:", { message: error instanceof Error ? error.message : String(error) });
1215
+ const mastraError = new MastraError(
1216
+ {
1217
+ id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1218
+ domain: ErrorDomain.STORAGE,
1219
+ category: ErrorCategory.THIRD_PARTY,
1220
+ text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1221
+ details: {
1222
+ name: name ?? "",
1223
+ scope: scope ?? ""
1224
+ }
1225
+ },
1226
+ error
1227
+ );
1228
+ this.logger?.error(mastraError.toString());
1229
+ this.logger?.trackException(mastraError);
1047
1230
  return [];
1048
1231
  }
1049
1232
  }
@@ -1099,7 +1282,18 @@ var D1Store = class extends MastraStorage {
1099
1282
  hasMore: page * perPage + traces.length < total
1100
1283
  };
1101
1284
  } catch (error) {
1102
- this.logger.error("Error getting traces:", { message: error instanceof Error ? error.message : String(error) });
1285
+ const mastraError = new MastraError(
1286
+ {
1287
+ id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1288
+ domain: ErrorDomain.STORAGE,
1289
+ category: ErrorCategory.THIRD_PARTY,
1290
+ text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1291
+ details: { name: name ?? "", scope: scope ?? "" }
1292
+ },
1293
+ error
1294
+ );
1295
+ this.logger?.error(mastraError.toString());
1296
+ this.logger?.trackException(mastraError);
1103
1297
  return { traces: [], total: 0, page, perPage, hasMore: false };
1104
1298
  }
1105
1299
  }
@@ -1135,9 +1329,18 @@ var D1Store = class extends MastraStorage {
1135
1329
  };
1136
1330
  }) : [];
1137
1331
  } catch (error) {
1138
- this.logger.error(`Error getting evals for agent ${agentName}:`, {
1139
- message: error instanceof Error ? error.message : String(error)
1140
- });
1332
+ const mastraError = new MastraError(
1333
+ {
1334
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
1335
+ domain: ErrorDomain.STORAGE,
1336
+ category: ErrorCategory.THIRD_PARTY,
1337
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
1338
+ details: { agentName }
1339
+ },
1340
+ error
1341
+ );
1342
+ this.logger?.error(mastraError.toString());
1343
+ this.logger?.trackException(mastraError);
1141
1344
  return [];
1142
1345
  }
1143
1346
  }
@@ -1168,52 +1371,65 @@ var D1Store = class extends MastraStorage {
1168
1371
  countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
1169
1372
  }
1170
1373
  const { sql: countSql, params: countParams } = countQueryBuilder.build();
1171
- const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
1172
- const total = Number(countResult?.count || 0);
1173
- const currentOffset = page * perPage;
1174
- if (total === 0) {
1374
+ try {
1375
+ const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
1376
+ const total = Number(countResult?.count || 0);
1377
+ const currentOffset = page * perPage;
1378
+ if (total === 0) {
1379
+ return {
1380
+ evals: [],
1381
+ total: 0,
1382
+ page,
1383
+ perPage,
1384
+ hasMore: false
1385
+ };
1386
+ }
1387
+ const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
1388
+ if (conditions.length > 0) {
1389
+ dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
1390
+ }
1391
+ dataQueryBuilder.orderBy("createdAt", "DESC").limit(perPage).offset(currentOffset);
1392
+ const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
1393
+ const rows = await this.executeQuery({ sql: dataSql, params: dataParams });
1394
+ const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
1395
+ const result = this.deserializeValue(row.result);
1396
+ const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
1397
+ if (!result || typeof result !== "object" || !("score" in result)) {
1398
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
1399
+ }
1400
+ return {
1401
+ input: row.input,
1402
+ output: row.output,
1403
+ result,
1404
+ agentName: row.agent_name,
1405
+ metricName: row.metric_name,
1406
+ instructions: row.instructions,
1407
+ testInfo,
1408
+ globalRunId: row.global_run_id,
1409
+ runId: row.run_id,
1410
+ createdAt: row.createdAt
1411
+ };
1412
+ });
1413
+ const hasMore = currentOffset + evals.length < total;
1175
1414
  return {
1176
- evals: [],
1177
- total: 0,
1415
+ evals,
1416
+ total,
1178
1417
  page,
1179
1418
  perPage,
1180
- hasMore: false
1419
+ hasMore
1181
1420
  };
1421
+ } catch (error) {
1422
+ throw new MastraError(
1423
+ {
1424
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
1425
+ domain: ErrorDomain.STORAGE,
1426
+ category: ErrorCategory.THIRD_PARTY,
1427
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
1428
+ details: { agentName: agentName ?? "", type: type ?? "" }
1429
+ },
1430
+ error
1431
+ );
1182
1432
  }
1183
- const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
1184
- if (conditions.length > 0) {
1185
- dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
1186
- }
1187
- dataQueryBuilder.orderBy("createdAt", "DESC").limit(perPage).offset(currentOffset);
1188
- const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
1189
- const rows = await this.executeQuery({ sql: dataSql, params: dataParams });
1190
- const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
1191
- const result = this.deserializeValue(row.result);
1192
- const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
1193
- if (!result || typeof result !== "object" || !("score" in result)) {
1194
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
1195
- }
1196
- return {
1197
- input: row.input,
1198
- output: row.output,
1199
- result,
1200
- agentName: row.agent_name,
1201
- metricName: row.metric_name,
1202
- instructions: row.instructions,
1203
- testInfo,
1204
- globalRunId: row.global_run_id,
1205
- runId: row.run_id,
1206
- createdAt: row.createdAt
1207
- };
1208
- });
1209
- const hasMore = currentOffset + evals.length < total;
1210
- return {
1211
- evals,
1212
- total,
1213
- page,
1214
- perPage,
1215
- hasMore
1216
- };
1217
1433
  }
1218
1434
  parseWorkflowRun(row) {
1219
1435
  let parsedSnapshot = row.snapshot;
@@ -1283,10 +1499,16 @@ var D1Store = class extends MastraStorage {
1283
1499
  const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
1284
1500
  return { runs, total: total || runs.length };
1285
1501
  } catch (error) {
1286
- this.logger.error("Error getting workflow runs:", {
1287
- message: error instanceof Error ? error.message : String(error)
1288
- });
1289
- throw error;
1502
+ throw new MastraError(
1503
+ {
1504
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
1505
+ domain: ErrorDomain.STORAGE,
1506
+ category: ErrorCategory.THIRD_PARTY,
1507
+ text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
1508
+ details: { workflowName: workflowName ?? "", resourceId: resourceId ?? "" }
1509
+ },
1510
+ error
1511
+ );
1290
1512
  }
1291
1513
  }
1292
1514
  async getWorkflowRunById({
@@ -1311,10 +1533,16 @@ var D1Store = class extends MastraStorage {
1311
1533
  if (!result) return null;
1312
1534
  return this.parseWorkflowRun(result);
1313
1535
  } catch (error) {
1314
- this.logger.error("Error getting workflow run by ID:", {
1315
- message: error instanceof Error ? error.message : String(error)
1316
- });
1317
- throw error;
1536
+ throw new MastraError(
1537
+ {
1538
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
1539
+ domain: ErrorDomain.STORAGE,
1540
+ category: ErrorCategory.THIRD_PARTY,
1541
+ text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
1542
+ details: { runId, workflowName: workflowName ?? "" }
1543
+ },
1544
+ error
1545
+ );
1318
1546
  }
1319
1547
  }
1320
1548
  /**
@@ -1324,6 +1552,10 @@ var D1Store = class extends MastraStorage {
1324
1552
  async close() {
1325
1553
  this.logger.debug("Closing D1 connection");
1326
1554
  }
1555
+ async updateMessages(_args) {
1556
+ this.logger.error("updateMessages is not yet implemented in CloudflareD1Store");
1557
+ throw new Error("Method not implemented");
1558
+ }
1327
1559
  };
1328
1560
 
1329
1561
  export { D1Store };