@mastra/cloudflare-d1 0.0.0-update-stores-peerDeps-20250723031338 → 0.0.0-usechat-duplicate-20251016110554

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,8 +1,9 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit } from '@mastra/core/storage';
2
+ import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, safelyParseJSON } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { parseSqlIdentifier } from '@mastra/core/utils';
5
5
  import { MessageList } from '@mastra/core/agent';
6
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
6
7
 
7
8
  // src/storage/index.ts
8
9
  var SqlBuilder = class {
@@ -534,7 +535,6 @@ var MemoryStorageD1 = class extends MemoryStorage {
534
535
  keys: { id: threadId }
535
536
  });
536
537
  if (!thread) return null;
537
- console.log("thread", thread);
538
538
  try {
539
539
  return {
540
540
  ...thread,
@@ -803,6 +803,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
803
803
  }
804
804
  }
805
805
  async _getIncludedMessages(threadId, selectBy) {
806
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
806
807
  const include = selectBy?.include;
807
808
  if (!include) return null;
808
809
  const unionQueries = [];
@@ -861,17 +862,19 @@ var MemoryStorageD1 = class extends MemoryStorage {
861
862
  }
862
863
  async getMessages({
863
864
  threadId,
865
+ resourceId,
864
866
  selectBy,
865
867
  format
866
868
  }) {
867
- const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
868
- const limit = resolveMessageLimit({
869
- last: selectBy?.last,
870
- defaultLimit: 40
871
- });
872
- const include = selectBy?.include || [];
873
- const messages = [];
874
869
  try {
870
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
871
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
872
+ const limit = resolveMessageLimit({
873
+ last: selectBy?.last,
874
+ defaultLimit: 40
875
+ });
876
+ const include = selectBy?.include || [];
877
+ const messages = [];
875
878
  if (include.length) {
876
879
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
877
880
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -911,7 +914,48 @@ var MemoryStorageD1 = class extends MemoryStorage {
911
914
  domain: ErrorDomain.STORAGE,
912
915
  category: ErrorCategory.THIRD_PARTY,
913
916
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
914
- details: { threadId }
917
+ details: { threadId, resourceId: resourceId ?? "" }
918
+ },
919
+ error
920
+ );
921
+ this.logger?.error(mastraError.toString());
922
+ this.logger?.trackException(mastraError);
923
+ throw mastraError;
924
+ }
925
+ }
926
+ async getMessagesById({
927
+ messageIds,
928
+ format
929
+ }) {
930
+ if (messageIds.length === 0) return [];
931
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
+ const messages = [];
933
+ try {
934
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
935
+ query.orderBy("createdAt", "DESC");
936
+ const { sql, params } = query.build();
937
+ const result = await this.operations.executeQuery({ sql, params });
938
+ if (Array.isArray(result)) messages.push(...result);
939
+ const processedMessages = messages.map((message) => {
940
+ const processedMsg = {};
941
+ for (const [key, value] of Object.entries(message)) {
942
+ if (key === `type` && value === `v2`) continue;
943
+ processedMsg[key] = deserializeValue(value);
944
+ }
945
+ return processedMsg;
946
+ });
947
+ this.logger.debug(`Retrieved ${messages.length} messages`);
948
+ const list = new MessageList().add(processedMessages, "memory");
949
+ if (format === `v1`) return list.get.all.v1();
950
+ return list.get.all.v2();
951
+ } catch (error) {
952
+ const mastraError = new MastraError(
953
+ {
954
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
955
+ domain: ErrorDomain.STORAGE,
956
+ category: ErrorCategory.THIRD_PARTY,
957
+ text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
958
+ details: { messageIds: JSON.stringify(messageIds) }
915
959
  },
916
960
  error
917
961
  );
@@ -922,6 +966,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
922
966
  }
923
967
  async getMessagesPaginated({
924
968
  threadId,
969
+ resourceId,
925
970
  selectBy,
926
971
  format
927
972
  }) {
@@ -931,6 +976,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
931
976
  const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
977
  const messages = [];
933
978
  try {
979
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
934
980
  if (selectBy?.include?.length) {
935
981
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
936
982
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -1019,7 +1065,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1019
1065
  domain: ErrorDomain.STORAGE,
1020
1066
  category: ErrorCategory.THIRD_PARTY,
1021
1067
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1022
- details: { threadId }
1068
+ details: { threadId, resourceId: resourceId ?? "" }
1023
1069
  },
1024
1070
  error
1025
1071
  );
@@ -1217,13 +1263,12 @@ var StoreOperationsD1 = class extends StoreOperations {
1217
1263
  sql,
1218
1264
  params: formattedParams
1219
1265
  });
1220
- if (!response.result) {
1221
- return first ? null : [];
1222
- }
1266
+ const result = response.result || [];
1267
+ const results = result.flatMap((r) => r.results || []);
1223
1268
  if (first) {
1224
- return response.result[0] || null;
1269
+ return results[0] || null;
1225
1270
  }
1226
- return response.result;
1271
+ return results;
1227
1272
  } catch (error) {
1228
1273
  throw new MastraError(
1229
1274
  {
@@ -1438,6 +1483,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1438
1483
  query.andWhere(`${key} = ?`, value);
1439
1484
  }
1440
1485
  }
1486
+ query.orderBy("createdAt", "DESC");
1441
1487
  query.limit(1);
1442
1488
  const { sql, params } = query.build();
1443
1489
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1522,20 +1568,19 @@ var StoreOperationsD1 = class extends StoreOperations {
1522
1568
  }
1523
1569
  };
1524
1570
  function transformScoreRow(row) {
1525
- let input = void 0;
1526
- if (row.input) {
1527
- try {
1528
- input = JSON.parse(row.input);
1529
- } catch {
1530
- input = row.input;
1531
- }
1532
- }
1533
- return {
1534
- ...row,
1535
- input,
1536
- createdAt: row.createdAtZ || row.createdAt,
1537
- updatedAt: row.updatedAtZ || row.updatedAt
1538
- };
1571
+ const deserialized = { ...row };
1572
+ deserialized.input = safelyParseJSON(row.input);
1573
+ deserialized.output = safelyParseJSON(row.output);
1574
+ deserialized.scorer = safelyParseJSON(row.scorer);
1575
+ deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1576
+ deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1577
+ deserialized.metadata = safelyParseJSON(row.metadata);
1578
+ deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1579
+ deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1580
+ deserialized.entity = safelyParseJSON(row.entity);
1581
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1582
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1583
+ return deserialized;
1539
1584
  }
1540
1585
  var ScoresStorageD1 = class extends ScoresStorage {
1541
1586
  operations;
@@ -1565,11 +1610,25 @@ var ScoresStorageD1 = class extends ScoresStorage {
1565
1610
  }
1566
1611
  }
1567
1612
  async saveScore(score) {
1613
+ let parsedScore;
1614
+ try {
1615
+ parsedScore = saveScorePayloadSchema.parse(score);
1616
+ } catch (error) {
1617
+ throw new MastraError(
1618
+ {
1619
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1620
+ domain: ErrorDomain.STORAGE,
1621
+ category: ErrorCategory.USER,
1622
+ details: { scoreId: score.id }
1623
+ },
1624
+ error
1625
+ );
1626
+ }
1568
1627
  try {
1628
+ const id = crypto.randomUUID();
1569
1629
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1570
- const { input, ...rest } = score;
1571
1630
  const serializedRecord = {};
1572
- for (const [key, value] of Object.entries(rest)) {
1631
+ for (const [key, value] of Object.entries(parsedScore)) {
1573
1632
  if (value !== null && value !== void 0) {
1574
1633
  if (typeof value === "object") {
1575
1634
  serializedRecord[key] = JSON.stringify(value);
@@ -1580,7 +1639,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1580
1639
  serializedRecord[key] = null;
1581
1640
  }
1582
1641
  }
1583
- serializedRecord.input = JSON.stringify(input);
1642
+ serializedRecord.id = id;
1584
1643
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1585
1644
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1586
1645
  const columns = Object.keys(serializedRecord);
@@ -1588,7 +1647,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1588
1647
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1589
1648
  const { sql, params } = query.build();
1590
1649
  await this.operations.executeQuery({ sql, params });
1591
- const scoreFromDb = await this.getScoreById({ id: score.id });
1650
+ const scoreFromDb = await this.getScoreById({ id });
1592
1651
  return { score: scoreFromDb };
1593
1652
  } catch (error) {
1594
1653
  throw new MastraError(
@@ -1603,11 +1662,23 @@ var ScoresStorageD1 = class extends ScoresStorage {
1603
1662
  }
1604
1663
  async getScoresByScorerId({
1605
1664
  scorerId,
1665
+ entityId,
1666
+ entityType,
1667
+ source,
1606
1668
  pagination
1607
1669
  }) {
1608
1670
  try {
1609
1671
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1610
1672
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1673
+ if (entityId) {
1674
+ countQuery.andWhere("entityId = ?", entityId);
1675
+ }
1676
+ if (entityType) {
1677
+ countQuery.andWhere("entityType = ?", entityType);
1678
+ }
1679
+ if (source) {
1680
+ countQuery.andWhere("source = ?", source);
1681
+ }
1611
1682
  const countResult = await this.operations.executeQuery(countQuery.build());
1612
1683
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1613
1684
  if (total === 0) {
@@ -1621,7 +1692,17 @@ var ScoresStorageD1 = class extends ScoresStorage {
1621
1692
  scores: []
1622
1693
  };
1623
1694
  }
1624
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1695
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1696
+ if (entityId) {
1697
+ selectQuery.andWhere("entityId = ?", entityId);
1698
+ }
1699
+ if (entityType) {
1700
+ selectQuery.andWhere("entityType = ?", entityType);
1701
+ }
1702
+ if (source) {
1703
+ selectQuery.andWhere("source = ?", source);
1704
+ }
1705
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1625
1706
  const { sql, params } = selectQuery.build();
1626
1707
  const results = await this.operations.executeQuery({ sql, params });
1627
1708
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
@@ -1734,6 +1815,53 @@ var ScoresStorageD1 = class extends ScoresStorage {
1734
1815
  );
1735
1816
  }
1736
1817
  }
1818
+ async getScoresBySpan({
1819
+ traceId,
1820
+ spanId,
1821
+ pagination
1822
+ }) {
1823
+ try {
1824
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1825
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1826
+ const countResult = await this.operations.executeQuery(countQuery.build());
1827
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1828
+ if (total === 0) {
1829
+ return {
1830
+ pagination: {
1831
+ total: 0,
1832
+ page: pagination.page,
1833
+ perPage: pagination.perPage,
1834
+ hasMore: false
1835
+ },
1836
+ scores: []
1837
+ };
1838
+ }
1839
+ const limit = pagination.perPage + 1;
1840
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1841
+ const { sql, params } = selectQuery.build();
1842
+ const results = await this.operations.executeQuery({ sql, params });
1843
+ const rows = Array.isArray(results) ? results : [];
1844
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1845
+ return {
1846
+ pagination: {
1847
+ total,
1848
+ page: pagination.page,
1849
+ perPage: pagination.perPage,
1850
+ hasMore: rows.length > pagination.perPage
1851
+ },
1852
+ scores
1853
+ };
1854
+ } catch (error) {
1855
+ throw new MastraError(
1856
+ {
1857
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1858
+ domain: ErrorDomain.STORAGE,
1859
+ category: ErrorCategory.THIRD_PARTY
1860
+ },
1861
+ error
1862
+ );
1863
+ }
1864
+ }
1737
1865
  };
1738
1866
  function isArrayOfRecords2(value) {
1739
1867
  return value && Array.isArray(value) && value.length > 0;
@@ -1811,7 +1939,7 @@ var TracesStorageD1 = class extends TracesStorage {
1811
1939
  const allDataResult = await this.operations.executeQuery(
1812
1940
  createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1813
1941
  );
1814
- console.log("allDataResult", allDataResult);
1942
+ console.info("allDataResult", allDataResult);
1815
1943
  const countResult = await this.operations.executeQuery(countQuery.build());
1816
1944
  const total = Number(countResult?.[0]?.count ?? 0);
1817
1945
  dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
@@ -1863,9 +1991,26 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1863
1991
  super();
1864
1992
  this.operations = operations;
1865
1993
  }
1994
+ updateWorkflowResults({
1995
+ // workflowName,
1996
+ // runId,
1997
+ // stepId,
1998
+ // result,
1999
+ // runtimeContext,
2000
+ }) {
2001
+ throw new Error("Method not implemented.");
2002
+ }
2003
+ updateWorkflowState({
2004
+ // workflowName,
2005
+ // runId,
2006
+ // opts,
2007
+ }) {
2008
+ throw new Error("Method not implemented.");
2009
+ }
1866
2010
  async persistWorkflowSnapshot({
1867
2011
  workflowName,
1868
2012
  runId,
2013
+ resourceId,
1869
2014
  snapshot
1870
2015
  }) {
1871
2016
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
@@ -1876,11 +2021,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1876
2021
  });
1877
2022
  const persisting = currentSnapshot ? {
1878
2023
  ...currentSnapshot,
2024
+ resourceId,
1879
2025
  snapshot: JSON.stringify(snapshot),
1880
2026
  updatedAt: now
1881
2027
  } : {
1882
2028
  workflow_name: workflowName,
1883
2029
  run_id: runId,
2030
+ resourceId,
1884
2031
  snapshot,
1885
2032
  createdAt: now,
1886
2033
  updatedAt: now
@@ -2145,7 +2292,9 @@ var D1Store = class extends MastraStorage {
2145
2292
  selectByIncludeResourceScope: true,
2146
2293
  resourceWorkingMemory: true,
2147
2294
  hasColumn: true,
2148
- createTable: true
2295
+ createTable: true,
2296
+ deleteMessages: false,
2297
+ getScoresBySpan: true
2149
2298
  };
2150
2299
  }
2151
2300
  async createTable({
@@ -2217,6 +2366,12 @@ var D1Store = class extends MastraStorage {
2217
2366
  }) {
2218
2367
  return this.stores.memory.getMessages({ threadId, selectBy, format });
2219
2368
  }
2369
+ async getMessagesById({
2370
+ messageIds,
2371
+ format
2372
+ }) {
2373
+ return this.stores.memory.getMessagesById({ messageIds, format });
2374
+ }
2220
2375
  async getMessagesPaginated({
2221
2376
  threadId,
2222
2377
  selectBy,
@@ -2224,12 +2379,29 @@ var D1Store = class extends MastraStorage {
2224
2379
  }) {
2225
2380
  return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2226
2381
  }
2382
+ async updateWorkflowResults({
2383
+ workflowName,
2384
+ runId,
2385
+ stepId,
2386
+ result,
2387
+ runtimeContext
2388
+ }) {
2389
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2390
+ }
2391
+ async updateWorkflowState({
2392
+ workflowName,
2393
+ runId,
2394
+ opts
2395
+ }) {
2396
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2397
+ }
2227
2398
  async persistWorkflowSnapshot({
2228
2399
  workflowName,
2229
2400
  runId,
2401
+ resourceId,
2230
2402
  snapshot
2231
2403
  }) {
2232
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2404
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2233
2405
  }
2234
2406
  async loadWorkflowSnapshot(params) {
2235
2407
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2316,10 +2488,20 @@ var D1Store = class extends MastraStorage {
2316
2488
  });
2317
2489
  }
2318
2490
  async getScoresByScorerId({
2319
- scorerId: _scorerId,
2320
- pagination: _pagination
2491
+ scorerId,
2492
+ pagination,
2493
+ entityId,
2494
+ entityType,
2495
+ source
2496
+ }) {
2497
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2498
+ }
2499
+ async getScoresBySpan({
2500
+ traceId,
2501
+ spanId,
2502
+ pagination
2321
2503
  }) {
2322
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2504
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2323
2505
  }
2324
2506
  /**
2325
2507
  * Close the database connection
@@ -2331,3 +2513,5 @@ var D1Store = class extends MastraStorage {
2331
2513
  };
2332
2514
 
2333
2515
  export { D1Store };
2516
+ //# sourceMappingURL=index.js.map
2517
+ //# sourceMappingURL=index.js.map