@mastra/cloudflare-d1 1.0.0-beta.9 → 1.0.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 CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ensureDate, createStorageErrorId, normalizePerPage, calculatePagination, serializeDate, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraStorage, getSqlType, getDefaultValue, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
2
+ import { MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ensureDate, createStorageErrorId, normalizePerPage, calculatePagination, serializeDate, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, getSqlType, getDefaultValue, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { MessageList } from '@mastra/core/agent';
5
5
  import { MastraBase } from '@mastra/core/base';
@@ -840,18 +840,33 @@ var MemoryStorageD1 = class extends MemoryStorage {
840
840
  return null;
841
841
  }
842
842
  }
843
- async listThreadsByResourceId(args) {
844
- const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
843
+ async listThreads(args) {
844
+ const { page = 0, perPage: perPageInput, orderBy, filter } = args;
845
+ try {
846
+ this.validatePaginationInput(page, perPageInput ?? 100);
847
+ } catch (error) {
848
+ throw new MastraError(
849
+ {
850
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS", "INVALID_PAGE"),
851
+ domain: ErrorDomain.STORAGE,
852
+ category: ErrorCategory.USER,
853
+ details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
854
+ },
855
+ error instanceof Error ? error : new Error("Invalid pagination parameters")
856
+ );
857
+ }
845
858
  const perPage = normalizePerPage(perPageInput, 100);
846
- if (page < 0) {
859
+ try {
860
+ this.validateMetadataKeys(filter?.metadata);
861
+ } catch (error) {
847
862
  throw new MastraError(
848
863
  {
849
- id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
864
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS", "INVALID_METADATA_KEY"),
850
865
  domain: ErrorDomain.STORAGE,
851
866
  category: ErrorCategory.USER,
852
- details: { page }
867
+ details: { metadataKeys: filter?.metadata ? Object.keys(filter.metadata).join(", ") : "" }
853
868
  },
854
- new Error("page must be >= 0")
869
+ error instanceof Error ? error : new Error("Invalid metadata key")
855
870
  );
856
871
  }
857
872
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
@@ -864,11 +879,51 @@ var MemoryStorageD1 = class extends MemoryStorage {
864
879
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
865
880
  });
866
881
  try {
867
- const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
882
+ let countQuery = createSqlBuilder().count().from(fullTableName);
883
+ let selectQuery = createSqlBuilder().select("*").from(fullTableName);
884
+ if (filter?.resourceId) {
885
+ countQuery = countQuery.whereAnd("resourceId = ?", filter.resourceId);
886
+ selectQuery = selectQuery.whereAnd("resourceId = ?", filter.resourceId);
887
+ }
888
+ if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
889
+ for (const [key, value] of Object.entries(filter.metadata)) {
890
+ if (value !== null && typeof value === "object") {
891
+ throw new MastraError(
892
+ {
893
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS", "INVALID_METADATA_VALUE"),
894
+ domain: ErrorDomain.STORAGE,
895
+ category: ErrorCategory.USER,
896
+ text: `Metadata filter value for key "${key}" must be a scalar type (string, number, boolean, or null), got ${Array.isArray(value) ? "array" : "object"}`,
897
+ details: { key, valueType: Array.isArray(value) ? "array" : "object" }
898
+ },
899
+ new Error("Invalid metadata filter value type")
900
+ );
901
+ }
902
+ if (value === null) {
903
+ const condition = `json_extract(metadata, '$.${key}') IS NULL`;
904
+ countQuery = countQuery.whereAnd(condition);
905
+ selectQuery = selectQuery.whereAnd(condition);
906
+ } else {
907
+ const condition = `json_extract(metadata, '$.${key}') = ?`;
908
+ const filterValue = value;
909
+ countQuery = countQuery.whereAnd(condition, filterValue);
910
+ selectQuery = selectQuery.whereAnd(condition, filterValue);
911
+ }
912
+ }
913
+ }
868
914
  const countResult = await this.#db.executeQuery(countQuery.build());
869
915
  const total = Number(countResult?.[0]?.count ?? 0);
916
+ if (total === 0) {
917
+ return {
918
+ threads: [],
919
+ total: 0,
920
+ page,
921
+ perPage: perPageForResponse,
922
+ hasMore: false
923
+ };
924
+ }
870
925
  const limitValue = perPageInput === false ? total : perPage;
871
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy(field, direction).limit(limitValue).offset(offset);
926
+ selectQuery = selectQuery.orderBy(field, direction).limit(limitValue).offset(offset);
872
927
  const results = await this.#db.executeQuery(selectQuery.build());
873
928
  const threads = results.map(mapRowToStorageThreadType);
874
929
  return {
@@ -879,13 +934,19 @@ var MemoryStorageD1 = class extends MemoryStorage {
879
934
  hasMore: perPageInput === false ? false : offset + perPage < total
880
935
  };
881
936
  } catch (error) {
937
+ if (error instanceof MastraError && error.category === ErrorCategory.USER) {
938
+ throw error;
939
+ }
882
940
  const mastraError = new MastraError(
883
941
  {
884
- id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
942
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS", "FAILED"),
885
943
  domain: ErrorDomain.STORAGE,
886
944
  category: ErrorCategory.THIRD_PARTY,
887
- text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
888
- details: { resourceId }
945
+ text: `Error listing threads: ${error instanceof Error ? error.message : String(error)}`,
946
+ details: {
947
+ ...filter?.resourceId && { resourceId: filter.resourceId },
948
+ hasMetadataFilter: !!filter?.metadata
949
+ }
889
950
  },
890
951
  error
891
952
  );
@@ -1885,7 +1946,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1885
1946
  try {
1886
1947
  parsedSnapshot = JSON.parse(row.snapshot);
1887
1948
  } catch (e) {
1888
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1949
+ this.logger.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1889
1950
  }
1890
1951
  }
1891
1952
  return {
@@ -1921,7 +1982,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1921
1982
  builder.whereAnd("resourceId = ?", resourceId);
1922
1983
  countBuilder.whereAnd("resourceId = ?", resourceId);
1923
1984
  } else {
1924
- console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
1985
+ this.logger.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
1925
1986
  }
1926
1987
  }
1927
1988
  if (fromDate) {
@@ -2024,7 +2085,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2024
2085
  };
2025
2086
 
2026
2087
  // src/storage/index.ts
2027
- var D1Store = class extends MastraStorage {
2088
+ var D1Store = class extends MastraCompositeStore {
2028
2089
  client;
2029
2090
  binding;
2030
2091
  tablePrefix;