@mastra/cloudflare-d1 0.0.0-scorers-api-v2-20250801171841 → 0.0.0-scorers-ui-refactored-20250916094952

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.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './storage';
1
+ export * from './storage/index.js';
2
2
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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';
@@ -534,7 +534,6 @@ var MemoryStorageD1 = class extends MemoryStorage {
534
534
  keys: { id: threadId }
535
535
  });
536
536
  if (!thread) return null;
537
- console.log("thread", thread);
538
537
  try {
539
538
  return {
540
539
  ...thread,
@@ -803,6 +802,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
803
802
  }
804
803
  }
805
804
  async _getIncludedMessages(threadId, selectBy) {
805
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
806
806
  const include = selectBy?.include;
807
807
  if (!include) return null;
808
808
  const unionQueries = [];
@@ -861,17 +861,19 @@ var MemoryStorageD1 = class extends MemoryStorage {
861
861
  }
862
862
  async getMessages({
863
863
  threadId,
864
+ resourceId,
864
865
  selectBy,
865
866
  format
866
867
  }) {
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
868
  try {
869
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
870
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
871
+ const limit = resolveMessageLimit({
872
+ last: selectBy?.last,
873
+ defaultLimit: 40
874
+ });
875
+ const include = selectBy?.include || [];
876
+ const messages = [];
875
877
  if (include.length) {
876
878
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
877
879
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -911,7 +913,48 @@ var MemoryStorageD1 = class extends MemoryStorage {
911
913
  domain: ErrorDomain.STORAGE,
912
914
  category: ErrorCategory.THIRD_PARTY,
913
915
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
914
- details: { threadId }
916
+ details: { threadId, resourceId: resourceId ?? "" }
917
+ },
918
+ error
919
+ );
920
+ this.logger?.error(mastraError.toString());
921
+ this.logger?.trackException(mastraError);
922
+ throw mastraError;
923
+ }
924
+ }
925
+ async getMessagesById({
926
+ messageIds,
927
+ format
928
+ }) {
929
+ if (messageIds.length === 0) return [];
930
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
931
+ const messages = [];
932
+ try {
933
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
934
+ query.orderBy("createdAt", "DESC");
935
+ const { sql, params } = query.build();
936
+ const result = await this.operations.executeQuery({ sql, params });
937
+ if (Array.isArray(result)) messages.push(...result);
938
+ const processedMessages = messages.map((message) => {
939
+ const processedMsg = {};
940
+ for (const [key, value] of Object.entries(message)) {
941
+ if (key === `type` && value === `v2`) continue;
942
+ processedMsg[key] = deserializeValue(value);
943
+ }
944
+ return processedMsg;
945
+ });
946
+ this.logger.debug(`Retrieved ${messages.length} messages`);
947
+ const list = new MessageList().add(processedMessages, "memory");
948
+ if (format === `v1`) return list.get.all.v1();
949
+ return list.get.all.v2();
950
+ } catch (error) {
951
+ const mastraError = new MastraError(
952
+ {
953
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
954
+ domain: ErrorDomain.STORAGE,
955
+ category: ErrorCategory.THIRD_PARTY,
956
+ text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
957
+ details: { messageIds: JSON.stringify(messageIds) }
915
958
  },
916
959
  error
917
960
  );
@@ -922,6 +965,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
922
965
  }
923
966
  async getMessagesPaginated({
924
967
  threadId,
968
+ resourceId,
925
969
  selectBy,
926
970
  format
927
971
  }) {
@@ -931,6 +975,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
931
975
  const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
976
  const messages = [];
933
977
  try {
978
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
934
979
  if (selectBy?.include?.length) {
935
980
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
936
981
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -1019,7 +1064,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1019
1064
  domain: ErrorDomain.STORAGE,
1020
1065
  category: ErrorCategory.THIRD_PARTY,
1021
1066
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1022
- details: { threadId }
1067
+ details: { threadId, resourceId: resourceId ?? "" }
1023
1068
  },
1024
1069
  error
1025
1070
  );
@@ -1437,6 +1482,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1437
1482
  query.andWhere(`${key} = ?`, value);
1438
1483
  }
1439
1484
  }
1485
+ query.orderBy("createdAt", "DESC");
1440
1486
  query.limit(1);
1441
1487
  const { sql, params } = query.build();
1442
1488
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1521,20 +1567,19 @@ var StoreOperationsD1 = class extends StoreOperations {
1521
1567
  }
1522
1568
  };
1523
1569
  function transformScoreRow(row) {
1524
- let input = void 0;
1525
- if (row.input) {
1526
- try {
1527
- input = JSON.parse(row.input);
1528
- } catch {
1529
- input = row.input;
1530
- }
1531
- }
1532
- return {
1533
- ...row,
1534
- input,
1535
- createdAt: row.createdAtZ || row.createdAt,
1536
- updatedAt: row.updatedAtZ || row.updatedAt
1537
- };
1570
+ const deserialized = { ...row };
1571
+ deserialized.input = safelyParseJSON(row.input);
1572
+ deserialized.output = safelyParseJSON(row.output);
1573
+ deserialized.scorer = safelyParseJSON(row.scorer);
1574
+ deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1575
+ deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1576
+ deserialized.metadata = safelyParseJSON(row.metadata);
1577
+ deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1578
+ deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1579
+ deserialized.entity = safelyParseJSON(row.entity);
1580
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1581
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1582
+ return deserialized;
1538
1583
  }
1539
1584
  var ScoresStorageD1 = class extends ScoresStorage {
1540
1585
  operations;
@@ -1565,6 +1610,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1565
1610
  }
1566
1611
  async saveScore(score) {
1567
1612
  try {
1613
+ const id = crypto.randomUUID();
1568
1614
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1569
1615
  const { input, ...rest } = score;
1570
1616
  const serializedRecord = {};
@@ -1579,6 +1625,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1579
1625
  serializedRecord[key] = null;
1580
1626
  }
1581
1627
  }
1628
+ serializedRecord.id = id;
1582
1629
  serializedRecord.input = JSON.stringify(input);
1583
1630
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1584
1631
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -1587,7 +1634,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1587
1634
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1588
1635
  const { sql, params } = query.build();
1589
1636
  await this.operations.executeQuery({ sql, params });
1590
- const scoreFromDb = await this.getScoreById({ id: score.id });
1637
+ const scoreFromDb = await this.getScoreById({ id });
1591
1638
  return { score: scoreFromDb };
1592
1639
  } catch (error) {
1593
1640
  throw new MastraError(
@@ -1602,11 +1649,23 @@ var ScoresStorageD1 = class extends ScoresStorage {
1602
1649
  }
1603
1650
  async getScoresByScorerId({
1604
1651
  scorerId,
1652
+ entityId,
1653
+ entityType,
1654
+ source,
1605
1655
  pagination
1606
1656
  }) {
1607
1657
  try {
1608
1658
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1609
1659
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1660
+ if (entityId) {
1661
+ countQuery.andWhere("entityId = ?", entityId);
1662
+ }
1663
+ if (entityType) {
1664
+ countQuery.andWhere("entityType = ?", entityType);
1665
+ }
1666
+ if (source) {
1667
+ countQuery.andWhere("source = ?", source);
1668
+ }
1610
1669
  const countResult = await this.operations.executeQuery(countQuery.build());
1611
1670
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1612
1671
  if (total === 0) {
@@ -1620,7 +1679,17 @@ var ScoresStorageD1 = class extends ScoresStorage {
1620
1679
  scores: []
1621
1680
  };
1622
1681
  }
1623
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1682
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1683
+ if (entityId) {
1684
+ selectQuery.andWhere("entityId = ?", entityId);
1685
+ }
1686
+ if (entityType) {
1687
+ selectQuery.andWhere("entityType = ?", entityType);
1688
+ }
1689
+ if (source) {
1690
+ selectQuery.andWhere("source = ?", source);
1691
+ }
1692
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1624
1693
  const { sql, params } = selectQuery.build();
1625
1694
  const results = await this.operations.executeQuery({ sql, params });
1626
1695
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
@@ -1862,9 +1931,26 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1862
1931
  super();
1863
1932
  this.operations = operations;
1864
1933
  }
1934
+ updateWorkflowResults({
1935
+ // workflowName,
1936
+ // runId,
1937
+ // stepId,
1938
+ // result,
1939
+ // runtimeContext,
1940
+ }) {
1941
+ throw new Error("Method not implemented.");
1942
+ }
1943
+ updateWorkflowState({
1944
+ // workflowName,
1945
+ // runId,
1946
+ // opts,
1947
+ }) {
1948
+ throw new Error("Method not implemented.");
1949
+ }
1865
1950
  async persistWorkflowSnapshot({
1866
1951
  workflowName,
1867
1952
  runId,
1953
+ resourceId,
1868
1954
  snapshot
1869
1955
  }) {
1870
1956
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
@@ -1875,11 +1961,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1875
1961
  });
1876
1962
  const persisting = currentSnapshot ? {
1877
1963
  ...currentSnapshot,
1964
+ resourceId,
1878
1965
  snapshot: JSON.stringify(snapshot),
1879
1966
  updatedAt: now
1880
1967
  } : {
1881
1968
  workflow_name: workflowName,
1882
1969
  run_id: runId,
1970
+ resourceId,
1883
1971
  snapshot,
1884
1972
  createdAt: now,
1885
1973
  updatedAt: now
@@ -2217,6 +2305,12 @@ var D1Store = class extends MastraStorage {
2217
2305
  }) {
2218
2306
  return this.stores.memory.getMessages({ threadId, selectBy, format });
2219
2307
  }
2308
+ async getMessagesById({
2309
+ messageIds,
2310
+ format
2311
+ }) {
2312
+ return this.stores.memory.getMessagesById({ messageIds, format });
2313
+ }
2220
2314
  async getMessagesPaginated({
2221
2315
  threadId,
2222
2316
  selectBy,
@@ -2224,12 +2318,29 @@ var D1Store = class extends MastraStorage {
2224
2318
  }) {
2225
2319
  return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2226
2320
  }
2321
+ async updateWorkflowResults({
2322
+ workflowName,
2323
+ runId,
2324
+ stepId,
2325
+ result,
2326
+ runtimeContext
2327
+ }) {
2328
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2329
+ }
2330
+ async updateWorkflowState({
2331
+ workflowName,
2332
+ runId,
2333
+ opts
2334
+ }) {
2335
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2336
+ }
2227
2337
  async persistWorkflowSnapshot({
2228
2338
  workflowName,
2229
2339
  runId,
2340
+ resourceId,
2230
2341
  snapshot
2231
2342
  }) {
2232
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2343
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2233
2344
  }
2234
2345
  async loadWorkflowSnapshot(params) {
2235
2346
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2316,10 +2427,13 @@ var D1Store = class extends MastraStorage {
2316
2427
  });
2317
2428
  }
2318
2429
  async getScoresByScorerId({
2319
- scorerId: _scorerId,
2320
- pagination: _pagination
2430
+ scorerId,
2431
+ pagination,
2432
+ entityId,
2433
+ entityType,
2434
+ source
2321
2435
  }) {
2322
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2436
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2323
2437
  }
2324
2438
  /**
2325
2439
  * Close the database connection