@mastra/cloudflare-d1 1.4.5-alpha.0 → 1.4.5-alpha.2

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.
@@ -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.4.5-alpha.0"
6
+ version: "1.4.5-alpha.2"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.4.5-alpha.0",
2
+ "version": "1.4.5-alpha.2",
3
3
  "package": "@mastra/cloudflare-d1",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let _mastra_core_error = require("@mastra/core/error");
25
24
  let _mastra_core_storage = require("@mastra/core/storage");
26
25
  let cloudflare = require("cloudflare");
@@ -29,7 +28,7 @@ let _mastra_core_base = require("@mastra/core/base");
29
28
  let _mastra_core_utils = require("@mastra/core/utils");
30
29
  let _mastra_core_agent = require("@mastra/core/agent");
31
30
  let _mastra_core_evals = require("@mastra/core/evals");
32
- //#region src/storage/domains/utils.ts
31
+ // src/storage/domains/utils.ts
33
32
  function isArrayOfRecords(value) {
34
33
  return value && Array.isArray(value) && value.length > 0;
35
34
  }
@@ -48,8 +47,7 @@ function deserializeValue(value, type) {
48
47
  }
49
48
  return value;
50
49
  }
51
- //#endregion
52
- //#region src/storage/sql-builder.ts
50
+ // src/storage/sql-builder.ts
53
51
  /**
54
52
  * SQL Builder class for constructing type-safe SQL queries
55
53
  * This helps create maintainable and secure SQL queries with proper parameter handling
@@ -278,8 +276,7 @@ function parseSelectIdentifier(column) {
278
276
  if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) throw new Error(`Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`);
279
277
  return column;
280
278
  }
281
- //#endregion
282
- //#region src/storage/db/run-fencing.ts
279
+ // src/storage/db/run-fencing.ts
283
280
  /**
284
281
  * Epoch milliseconds on the database clock. `julianday('now')` rather than
285
282
  * `unixepoch('subsec')`, which needs SQLite 3.42.
@@ -341,8 +338,7 @@ async function executeFenced(db, check, { sql, params }) {
341
338
  });
342
339
  if (Array.isArray(rows) && rows.length === 0) await assertRunFence(db, check);
343
340
  }
344
- //#endregion
345
- //#region src/storage/db/index.ts
341
+ // src/storage/db/index.ts
346
342
  /**
347
343
  * Resolves D1DomainConfig to D1DBConfig.
348
344
  * Handles creating a new D1 client if apiToken is provided.
@@ -734,8 +730,7 @@ var D1DB = class extends _mastra_core_base.MastraBase {
734
730
  }
735
731
  }
736
732
  };
737
- //#endregion
738
- //#region src/storage/domains/background-tasks/index.ts
733
+ // src/storage/domains/background-tasks/index.ts
739
734
  function serializeJson(v) {
740
735
  if (typeof v === "object" && v != null) return JSON.stringify(v);
741
736
  return v ?? null;
@@ -1055,8 +1050,7 @@ var BackgroundTasksStorageD1 = class extends _mastra_core_storage.BackgroundTask
1055
1050
  return Number(row?.count ?? 0);
1056
1051
  }
1057
1052
  };
1058
- //#endregion
1059
- //#region src/storage/domains/memory/index.ts
1053
+ // src/storage/domains/memory/index.ts
1060
1054
  function addSqliteMetadataFilter(conditions, params, metadataFilter) {
1061
1055
  if (!metadataFilter) return;
1062
1056
  for (const [key, value] of Object.entries(metadataFilter)) {
@@ -2043,8 +2037,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
2043
2037
  }
2044
2038
  }
2045
2039
  };
2046
- //#endregion
2047
- //#region src/storage/domains/scores/index.ts
2040
+ // src/storage/domains/scores/index.ts
2048
2041
  /** Applies multi-tenant scope conditions to a query builder. */
2049
2042
  function applyTenancyFilters(query, filters) {
2050
2043
  if (filters?.organizationId !== void 0) query.andWhere("organizationId = ?", filters.organizationId);
@@ -2352,8 +2345,7 @@ var ScoresStorageD1 = class extends _mastra_core_storage.ScoresStorage {
2352
2345
  }
2353
2346
  }
2354
2347
  };
2355
- //#endregion
2356
- //#region src/storage/domains/workflows/index.ts
2348
+ // src/storage/domains/workflows/index.ts
2357
2349
  const RUN_OWNER_COLUMNS = `generation, ownerId, leaseExpiresAt, ${DB_NOW_MS} AS nowMs`;
2358
2350
  /**
2359
2351
  * A run's first generation is the database clock, so a run claimed again after
@@ -2387,6 +2379,9 @@ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends _mastra_core_storage.W
2387
2379
  super();
2388
2380
  this.#db = new D1DB(resolveD1Config(config));
2389
2381
  }
2382
+ supportsGuardedSnapshotWrites() {
2383
+ return true;
2384
+ }
2390
2385
  supportsConcurrentUpdates() {
2391
2386
  return false;
2392
2387
  }
@@ -2563,7 +2558,7 @@ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends _mastra_core_storage.W
2563
2558
  async updateWorkflowState(_args) {
2564
2559
  throw new Error("updateWorkflowState is not implemented for Cloudflare D1 storage. D1 does not support atomic read-modify-write operations needed for concurrent workflow updates.");
2565
2560
  }
2566
- async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence }) {
2561
+ async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence, expectedStatus }) {
2567
2562
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT);
2568
2563
  const now = (/* @__PURE__ */ new Date()).toISOString();
2569
2564
  const check = this.#runFenceCheck(fence, runId, "persistWorkflowSnapshot");
@@ -2600,7 +2595,20 @@ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends _mastra_core_storage.W
2600
2595
  });
2601
2596
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap, runFenceGuard(check));
2602
2597
  try {
2603
- await executeFenced(this.#db, check, query.build());
2598
+ if (expectedStatus === void 0) {
2599
+ await executeFenced(this.#db, check, query.build());
2600
+ return true;
2601
+ }
2602
+ const expectedStatuses = Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus];
2603
+ const { sql, params } = query.build();
2604
+ const statusGuard = expectedStatuses.length === 0 ? " WHERE 0" : ` WHERE (CASE WHEN json_valid(${fullTableName}.snapshot) THEN json_extract(${fullTableName}.snapshot, '$.status') END) IN (${expectedStatuses.map(() => "?").join(", ")})`;
2605
+ const rows = await this.#db.executeQuery({
2606
+ sql: `${sql}${statusGuard} RETURNING 1 AS written`,
2607
+ params: [...params, ...expectedStatuses]
2608
+ });
2609
+ const written = Array.isArray(rows) && rows.length > 0;
2610
+ if (!written && check) await assertRunFence(this.#db, check);
2611
+ return written;
2604
2612
  } catch (error) {
2605
2613
  if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
2606
2614
  throw new _mastra_core_error.MastraError({
@@ -2615,6 +2623,26 @@ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends _mastra_core_storage.W
2615
2623
  }, error);
2616
2624
  }
2617
2625
  }
2626
+ async loadWorkflowRunStatus({ workflowName, runId }) {
2627
+ try {
2628
+ const row = await this.#db.executeQuery({
2629
+ sql: `SELECT CASE WHEN json_valid(snapshot) THEN json_extract(snapshot, '$.status') END AS status FROM ${this.#db.getTableName(_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT)} WHERE workflow_name = ? AND run_id = ?`,
2630
+ params: [workflowName, runId],
2631
+ first: true
2632
+ });
2633
+ return (row && !Array.isArray(row) ? row.status : void 0) ?? null;
2634
+ } catch (error) {
2635
+ throw new _mastra_core_error.MastraError({
2636
+ id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "LOAD_WORKFLOW_RUN_STATUS", "FAILED"),
2637
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2638
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2639
+ details: {
2640
+ workflowName,
2641
+ runId
2642
+ }
2643
+ }, error);
2644
+ }
2645
+ }
2618
2646
  async loadWorkflowSnapshot(params) {
2619
2647
  const { workflowName, runId } = params;
2620
2648
  this.logger.debug("Loading workflow snapshot", {
@@ -2779,8 +2807,7 @@ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends _mastra_core_storage.W
2779
2807
  }
2780
2808
  }
2781
2809
  };
2782
- //#endregion
2783
- //#region src/storage/index.ts
2810
+ // src/storage/index.ts
2784
2811
  /**
2785
2812
  * Cloudflare D1 storage adapter for Mastra.
2786
2813
  *
@@ -2883,7 +2910,6 @@ var D1Store = class extends _mastra_core_storage.MastraCompositeStore {
2883
2910
  this.logger.debug("Closing D1 connection");
2884
2911
  }
2885
2912
  };
2886
- //#endregion
2887
2913
  exports.BackgroundTasksStorageD1 = BackgroundTasksStorageD1;
2888
2914
  exports.D1Store = D1Store;
2889
2915
  exports.MemoryStorageD1 = MemoryStorageD1;