@mastra/cloudflare-d1 1.2.0 → 1.3.0-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/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # @mastra/cloudflare-d1
2
2
 
3
+ ## 1.3.0-alpha.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed resource-scoped message includes across storage adapters so included context cannot cross resource boundaries. ([#20984](https://github.com/mastra-ai/mastra/pull/20984))
8
+
9
+ - Updated dependencies [[`6445eba`](https://github.com/mastra-ai/mastra/commit/6445eba6020abac681aba1cc9289f446cb400cbe), [`df31eb0`](https://github.com/mastra-ai/mastra/commit/df31eb0c7087d782a0d9346e467f9a4af4b0eef6), [`fcd0667`](https://github.com/mastra-ai/mastra/commit/fcd0667a4e378be35c9a1b1eb19cce78fbfd7282), [`bab06b1`](https://github.com/mastra-ai/mastra/commit/bab06b18923873a584bdfc71a6b4ec7fb4727fb7)]:
10
+ - @mastra/core@1.58.0-alpha.5
11
+
12
+ ## 1.3.0-alpha.0
13
+
14
+ ### Minor Changes
15
+
16
+ - Memory list reads now surface database errors instead of silently returning empty results. ([#17910](https://github.com/mastra-ai/mastra/pull/17910))
17
+
18
+ Previously, the paginated memory reads (`listThreads`, `listMessages`, `listMessagesByResourceId`, and `listMessagesById`) caught backend failures, logged them, and returned an empty payload like `{ threads: [], total: 0, hasMore: false }`. A transient outage (locked table, dropped connection) was therefore indistinguishable from a genuinely empty result, so an agent reading conversation history during a brief failure would treat it as "no history" and could overwrite real state. These methods now re-throw the failure as a `MastraError`. Validation (USER) errors and genuinely empty results are unchanged.
19
+
20
+ **Behavior change**
21
+
22
+ Callers that previously received an empty result on a backend failure will now receive a thrown `MastraError`. If you call these read methods directly (rather than through an agent, which already surfaces errors), wrap them so a transient outage doesn't crash the caller:
23
+
24
+ ```ts
25
+ try {
26
+ const { threads } = await storage.listThreads({ resourceId });
27
+ // ...use threads
28
+ } catch (error) {
29
+ // a real backend failure. Decide whether to retry, surface, or degrade.
30
+ // An empty thread list no longer hides here; it only means "no threads".
31
+ }
32
+ ```
33
+
34
+ ### Patch Changes
35
+
36
+ - Updated dependencies [[`e7109ee`](https://github.com/mastra-ai/mastra/commit/e7109ee6f731bacc79c885906f3c7dca8d8f013a), [`772c0c8`](https://github.com/mastra-ai/mastra/commit/772c0c897cec383258de2e6178147f8014767c7b), [`578bf2e`](https://github.com/mastra-ai/mastra/commit/578bf2e6a88e9d5b8bf502204e15a95dfbb679ae), [`06b2d87`](https://github.com/mastra-ai/mastra/commit/06b2d87e63bcdd0ed59215c6789692b9b12de376), [`ac01d63`](https://github.com/mastra-ai/mastra/commit/ac01d6355974aec73fdb8781449ed12bac582094), [`a810a05`](https://github.com/mastra-ai/mastra/commit/a810a058f62ad407cfc1701e0be36ae91145d7cf), [`f8da216`](https://github.com/mastra-ai/mastra/commit/f8da21633e7eb0e31c9ce0fc30567870d19416d3), [`6104347`](https://github.com/mastra-ai/mastra/commit/61043473ba6bfd0a25156824e853e13165562e6c), [`45bfb88`](https://github.com/mastra-ai/mastra/commit/45bfb88fd52f1dd3be20e2a38905777c96499c90), [`e3b9307`](https://github.com/mastra-ai/mastra/commit/e3b9307098daefbfae2a52ae2ef51bc9fc701190), [`d6834c5`](https://github.com/mastra-ai/mastra/commit/d6834c5a7866b16734d23900163c2414ed70d791), [`c52d346`](https://github.com/mastra-ai/mastra/commit/c52d3462ec831a5d95926ecd3d3373f5928ad2e5), [`0023e79`](https://github.com/mastra-ai/mastra/commit/0023e7919431078280abd11c89d1edeae35fcc69), [`c2ad51e`](https://github.com/mastra-ai/mastra/commit/c2ad51e2467f901eecba8c9f4a45e22a50bd7c18), [`3dc97ea`](https://github.com/mastra-ai/mastra/commit/3dc97ea415fad353b48a13095fad1835933cc12a), [`3d01cd3`](https://github.com/mastra-ai/mastra/commit/3d01cd387321b6f9c5cac31d487c84bf51b19c78), [`7bf3086`](https://github.com/mastra-ai/mastra/commit/7bf308663f0115ca74ad20554ade740f06640859), [`a8dd139`](https://github.com/mastra-ai/mastra/commit/a8dd1391a9fe9a6632c25809ef236980afa9a020), [`e5786be`](https://github.com/mastra-ai/mastra/commit/e5786be02bb903073082bd9d6da880ebaacc343f), [`2093fbd`](https://github.com/mastra-ai/mastra/commit/2093fbd53bb744bae19ec89f6d73db9a66fbe8a7), [`e7a5da4`](https://github.com/mastra-ai/mastra/commit/e7a5da4ef8e4dd452d2f232961b4e682a85ffe43), [`7b4393d`](https://github.com/mastra-ai/mastra/commit/7b4393d557411fdcf07b0e30e5acaf7cc85154ae)]:
37
+ - @mastra/core@1.58.0-alpha.1
38
+
3
39
  ## 1.2.0
4
40
 
5
41
  ### Minor Changes
@@ -3,7 +3,7 @@ name: mastra-cloudflare-d1
3
3
  description: Documentation for @mastra/cloudflare-d1. Use when working with @mastra/cloudflare-d1 APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/cloudflare-d1"
6
- version: "1.2.0"
6
+ version: "1.3.0-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.2.0",
2
+ "version": "1.3.0-alpha.1",
3
3
  "package": "@mastra/cloudflare-d1",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -61,11 +61,11 @@ export const mastra = new Mastra({
61
61
  })
62
62
  ```
63
63
 
64
- > **Note:** When using `import { env } from 'cloudflare:workers'`, `D1Store` must be initialized inline inside `new Mastra({...})` not extracted to a module-level variable. Alternatively, initialize `D1Store` inside the `fetch` handler after `env` is available. See [CloudflareDeployer reference](https://mastra.ai/reference/deployer/cloudflare) for details.
64
+ > **Note:** When using `import { env } from 'cloudflare:workers'`, `D1Store` must be initialized inline inside `new Mastra({...})`: not extracted to a module-level variable. Alternatively, initialize `D1Store` inside the `fetch` handler after `env` is available. See [CloudflareDeployer reference](https://mastra.ai/reference/deployer/cloudflare) for details.
65
65
 
66
66
  ### Using in a Cloudflare Worker without HTTP routes
67
67
 
68
- If you want to call Mastra directly in a Worker for example, to run an agent or trigger a workflow without serving HTTP routes, you don't need `CloudflareDeployer`. Access the D1 binding from the worker's `env` parameter and call Mastra programmatically.
68
+ If you want to call Mastra directly in a Worker (for example, to run an agent or trigger a workflow) without serving HTTP routes, you don't need `CloudflareDeployer`. Access the D1 binding from the worker's `env` parameter and call Mastra programmatically.
69
69
 
70
70
  ```typescript
71
71
  import { D1Store } from '@mastra/cloudflare-d1'
@@ -213,8 +213,8 @@ export default {
213
213
 
214
214
  ### Transactions & Consistency
215
215
 
216
- Cloudflare D1 provides transactional guarantees for single-row operations. This means that multiple operations can be executed as a single, all-or-nothing unit of work.
216
+ Cloudflare D1 provides transactional guarantees for single-row operations. Multiple operations can be executed as a single, all-or-nothing unit of work.
217
217
 
218
218
  ### Table Creation & Migrations
219
219
 
220
- Tables are created automatically when storage is initialized (and can be isolated per environment using the `tablePrefix` option), but advanced schema changes—such as adding columns, changing data types, or modifying indexes—require manual migration and careful planning to avoid data loss.
220
+ Tables are created automatically when storage is initialized (and can be isolated per environment using the `tablePrefix` option), but advanced schema changes require manual migration and careful planning. Examples include adding columns or changing data types and indexes to avoid data loss.
package/dist/index.cjs CHANGED
@@ -1229,13 +1229,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1229
1229
  }, error);
1230
1230
  this.logger?.error(mastraError.toString());
1231
1231
  this.logger?.trackException(mastraError);
1232
- return {
1233
- threads: [],
1234
- total: 0,
1235
- page,
1236
- perPage: perPageForResponse,
1237
- hasMore: false
1238
- };
1232
+ throw mastraError;
1239
1233
  }
1240
1234
  }
1241
1235
  async saveThread({ thread }) {
@@ -1396,15 +1390,23 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1396
1390
  return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1397
1391
  });
1398
1392
  }
1399
- async _getIncludedMessages(include) {
1393
+ /**
1394
+ * Fetches the messages named by `include` together with their surrounding context.
1395
+ *
1396
+ * @param include - Message ids to pin, each with an optional before/after window.
1397
+ * @param resourceId - When set, restricts both the pinned messages and their context
1398
+ * to that resource so an id from another resource returns nothing.
1399
+ */
1400
+ async _getIncludedMessages(include, resourceId) {
1400
1401
  if (!include || include.length === 0) return null;
1401
1402
  const tableName = this.#db.getTableName(_mastra_core_storage.TABLE_MESSAGES);
1403
+ const resourceCondition = resourceId ? ` AND resourceId = ?` : "";
1402
1404
  const targetIds = include.map((inc) => inc.id).filter(Boolean);
1403
1405
  if (targetIds.length === 0) return null;
1404
1406
  const idPlaceholders = targetIds.map(() => "?").join(", ");
1405
1407
  const targetResult = await this.#db.executeQuery({
1406
- sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE id IN (${idPlaceholders})`,
1407
- params: targetIds
1408
+ sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE id IN (${idPlaceholders})${resourceCondition}`,
1409
+ params: resourceId ? [...targetIds, resourceId] : targetIds
1408
1410
  });
1409
1411
  if (!Array.isArray(targetResult) || targetResult.length === 0) return null;
1410
1412
  const targetMap = new Map(targetResult.map((r) => [r.id, {
@@ -1436,21 +1438,25 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1436
1438
  SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1437
1439
  FROM ${tableName}
1438
1440
  WHERE thread_id = ?
1439
- AND createdAt <= ?
1441
+ AND createdAt <= ?${resourceCondition}
1440
1442
  ORDER BY createdAt DESC, id DESC
1441
1443
  LIMIT ?
1442
1444
  )`);
1443
- unionParams.push(target.threadId, target.createdAt, withPreviousMessages + 1);
1445
+ unionParams.push(target.threadId, target.createdAt);
1446
+ if (resourceId) unionParams.push(resourceId);
1447
+ unionParams.push(withPreviousMessages + 1);
1444
1448
  if (withNextMessages > 0) {
1445
1449
  unionQueries.push(`SELECT * FROM (
1446
1450
  SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1447
1451
  FROM ${tableName}
1448
1452
  WHERE thread_id = ?
1449
- AND createdAt > ?
1453
+ AND createdAt > ?${resourceCondition}
1450
1454
  ORDER BY createdAt ASC, id ASC
1451
1455
  LIMIT ?
1452
1456
  )`);
1453
- unionParams.push(target.threadId, target.createdAt, withNextMessages);
1457
+ unionParams.push(target.threadId, target.createdAt);
1458
+ if (resourceId) unionParams.push(resourceId);
1459
+ unionParams.push(withNextMessages);
1454
1460
  }
1455
1461
  }
1456
1462
  await flushBatch();
@@ -1569,7 +1575,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1569
1575
  hasMore: false
1570
1576
  };
1571
1577
  if (perPage === 0 && include && include.length > 0) {
1572
- const includeResult = await this._getIncludedMessages(include);
1578
+ const includeResult = await this._getIncludedMessages(include, resourceId);
1573
1579
  if (!Array.isArray(includeResult) || includeResult.length === 0) return {
1574
1580
  messages: [],
1575
1581
  total: 0,
@@ -1640,7 +1646,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1640
1646
  const messageIds = new Set(paginatedMessages.map((m) => m.id));
1641
1647
  let includeMessages = [];
1642
1648
  if (include && include.length > 0) {
1643
- const includeResult = await this._getIncludedMessages(include);
1649
+ const includeResult = await this._getIncludedMessages(include, resourceId);
1644
1650
  if (Array.isArray(includeResult)) {
1645
1651
  includeMessages = includeResult;
1646
1652
  for (const includeMsg of includeMessages) if (!messageIds.has(includeMsg.id)) {
@@ -1661,6 +1667,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1661
1667
  hasMore: metadataFilter ? perPageInput !== false && offset + paginatedCount < total : perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total
1662
1668
  };
1663
1669
  } catch (error) {
1670
+ if (error instanceof _mastra_core_error.MastraError && error.category === _mastra_core_error.ErrorCategory.USER) throw error;
1664
1671
  const mastraError = new _mastra_core_error.MastraError({
1665
1672
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "LIST_MESSAGES", "FAILED"),
1666
1673
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1673,13 +1680,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1673
1680
  }, error);
1674
1681
  this.logger?.error?.(mastraError.toString());
1675
1682
  this.logger?.trackException?.(mastraError);
1676
- return {
1677
- messages: [],
1678
- total: 0,
1679
- page,
1680
- perPage: perPageForResponse,
1681
- hasMore: false
1682
- };
1683
+ throw mastraError;
1683
1684
  }
1684
1685
  }
1685
1686
  async updateMessages(args) {