@mastra/cloudflare-d1 0.0.0-pg-pool-options-20250428183821 → 0.0.0-playground-studio-cloud-20251031080052

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,9 +1,11 @@
1
- import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_TRACES, TABLE_EVALS } from '@mastra/core/storage';
1
+ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
+ import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, safelyParseJSON } from '@mastra/core/storage';
2
3
  import Cloudflare from 'cloudflare';
4
+ import { parseSqlIdentifier } from '@mastra/core/utils';
5
+ import { MessageList } from '@mastra/core/agent';
6
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
3
7
 
4
8
  // src/storage/index.ts
5
-
6
- // src/storage/sql-builder.ts
7
9
  var SqlBuilder = class {
8
10
  sql = "";
9
11
  params = [];
@@ -13,12 +15,15 @@ var SqlBuilder = class {
13
15
  if (!columns || Array.isArray(columns) && columns.length === 0) {
14
16
  this.sql = "SELECT *";
15
17
  } else {
16
- this.sql = `SELECT ${Array.isArray(columns) ? columns.join(", ") : columns}`;
18
+ const cols = Array.isArray(columns) ? columns : [columns];
19
+ const parsedCols = cols.map((col) => parseSelectIdentifier(col));
20
+ this.sql = `SELECT ${parsedCols.join(", ")}`;
17
21
  }
18
22
  return this;
19
23
  }
20
24
  from(table) {
21
- this.sql += ` FROM ${table}`;
25
+ const parsedTableName = parseSqlIdentifier(table, "table name");
26
+ this.sql += ` FROM ${parsedTableName}`;
22
27
  return this;
23
28
  }
24
29
  /**
@@ -55,7 +60,11 @@ var SqlBuilder = class {
55
60
  return this;
56
61
  }
57
62
  orderBy(column, direction = "ASC") {
58
- this.sql += ` ORDER BY ${column} ${direction}`;
63
+ const parsedColumn = parseSqlIdentifier(column, "column name");
64
+ if (!["ASC", "DESC"].includes(direction)) {
65
+ throw new Error(`Invalid sort direction: ${direction}`);
66
+ }
67
+ this.sql += ` ORDER BY ${parsedColumn} ${direction}`;
59
68
  return this;
60
69
  }
61
70
  limit(count) {
@@ -68,6 +77,10 @@ var SqlBuilder = class {
68
77
  this.params.push(count);
69
78
  return this;
70
79
  }
80
+ count() {
81
+ this.sql += "SELECT COUNT(*) AS count";
82
+ return this;
83
+ }
71
84
  /**
72
85
  * Insert a row, or update specific columns on conflict (upsert).
73
86
  * @param table Table name
@@ -77,27 +90,33 @@ var SqlBuilder = class {
77
90
  * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
78
91
  */
79
92
  insert(table, columns, values, conflictColumns, updateMap) {
80
- const placeholders = columns.map(() => "?").join(", ");
93
+ const parsedTableName = parseSqlIdentifier(table, "table name");
94
+ const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
95
+ const placeholders = parsedColumns.map(() => "?").join(", ");
81
96
  if (conflictColumns && updateMap) {
97
+ const parsedConflictColumns = conflictColumns.map((col) => parseSqlIdentifier(col, "column name"));
82
98
  const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
83
- this.sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
99
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
84
100
  this.params.push(...values);
85
101
  return this;
86
102
  }
87
- this.sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders})`;
103
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
88
104
  this.params.push(...values);
89
105
  return this;
90
106
  }
91
107
  // Update operations
92
108
  update(table, columns, values) {
93
- const setClause = columns.map((col) => `${col} = ?`).join(", ");
94
- this.sql = `UPDATE ${table} SET ${setClause}`;
109
+ const parsedTableName = parseSqlIdentifier(table, "table name");
110
+ const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
111
+ const setClause = parsedColumns.map((col) => `${col} = ?`).join(", ");
112
+ this.sql = `UPDATE ${parsedTableName} SET ${setClause}`;
95
113
  this.params.push(...values);
96
114
  return this;
97
115
  }
98
116
  // Delete operations
99
117
  delete(table) {
100
- this.sql = `DELETE FROM ${table}`;
118
+ const parsedTableName = parseSqlIdentifier(table, "table name");
119
+ this.sql = `DELETE FROM ${parsedTableName}`;
101
120
  return this;
102
121
  }
103
122
  /**
@@ -108,9 +127,16 @@ var SqlBuilder = class {
108
127
  * @returns The builder instance
109
128
  */
110
129
  createTable(table, columnDefinitions, tableConstraints) {
111
- const columns = columnDefinitions.join(", ");
130
+ const parsedTableName = parseSqlIdentifier(table, "table name");
131
+ const parsedColumnDefinitions = columnDefinitions.map((def) => {
132
+ const colName = def.split(/\s+/)[0];
133
+ if (!colName) throw new Error("Empty column name in definition");
134
+ parseSqlIdentifier(colName, "column name");
135
+ return def;
136
+ });
137
+ const columns = parsedColumnDefinitions.join(", ");
112
138
  const constraints = tableConstraints && tableConstraints.length > 0 ? ", " + tableConstraints.join(", ") : "";
113
- this.sql = `CREATE TABLE IF NOT EXISTS ${table} (${columns}${constraints})`;
139
+ this.sql = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns}${constraints})`;
114
140
  return this;
115
141
  }
116
142
  /**
@@ -133,13 +159,10 @@ var SqlBuilder = class {
133
159
  * @returns The builder instance
134
160
  */
135
161
  createIndex(indexName, tableName, columnName, indexType = "") {
136
- this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${indexName} ON ${tableName}(${columnName})`;
137
- return this;
138
- }
139
- // Raw SQL with params
140
- raw(sql, ...params) {
141
- this.sql = sql;
142
- this.params.push(...params);
162
+ const parsedIndexName = parseSqlIdentifier(indexName, "index name");
163
+ const parsedTableName = parseSqlIdentifier(tableName, "table name");
164
+ const parsedColumnName = parseSqlIdentifier(columnName, "column name");
165
+ this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${parsedIndexName} ON ${parsedTableName}(${parsedColumnName})`;
143
166
  return this;
144
167
  }
145
168
  /**
@@ -149,11 +172,12 @@ var SqlBuilder = class {
149
172
  * @param exact If true, will not add % wildcards
150
173
  */
151
174
  like(column, value, exact = false) {
175
+ const parsedColumnName = parseSqlIdentifier(column, "column name");
152
176
  const likeValue = exact ? value : `%${value}%`;
153
177
  if (this.whereAdded) {
154
- this.sql += ` AND ${column} LIKE ?`;
178
+ this.sql += ` AND ${parsedColumnName} LIKE ?`;
155
179
  } else {
156
- this.sql += ` WHERE ${column} LIKE ?`;
180
+ this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
157
181
  this.whereAdded = true;
158
182
  }
159
183
  this.params.push(likeValue);
@@ -166,11 +190,13 @@ var SqlBuilder = class {
166
190
  * @param value The value to match
167
191
  */
168
192
  jsonLike(column, key, value) {
169
- const jsonPattern = `%"${key}":"${value}"%`;
193
+ const parsedColumnName = parseSqlIdentifier(column, "column name");
194
+ const parsedKey = parseSqlIdentifier(key, "key name");
195
+ const jsonPattern = `%"${parsedKey}":"${value}"%`;
170
196
  if (this.whereAdded) {
171
- this.sql += ` AND ${column} LIKE ?`;
197
+ this.sql += ` AND ${parsedColumnName} LIKE ?`;
172
198
  } else {
173
- this.sql += ` WHERE ${column} LIKE ?`;
199
+ this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
174
200
  this.whereAdded = true;
175
201
  }
176
202
  this.params.push(jsonPattern);
@@ -200,331 +226,301 @@ var SqlBuilder = class {
200
226
  function createSqlBuilder() {
201
227
  return new SqlBuilder();
202
228
  }
229
+ var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_]+(\s+AS\s+[a-zA-Z0-9_]+)?$/;
230
+ function parseSelectIdentifier(column) {
231
+ if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) {
232
+ throw new Error(
233
+ `Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`
234
+ );
235
+ }
236
+ return column;
237
+ }
203
238
 
204
- // src/storage/index.ts
239
+ // src/storage/domains/utils.ts
205
240
  function isArrayOfRecords(value) {
206
241
  return value && Array.isArray(value) && value.length > 0;
207
242
  }
208
- var D1Store = class extends MastraStorage {
209
- client;
210
- accountId;
211
- databaseId;
212
- binding;
213
- // D1Database binding
214
- tablePrefix;
215
- /**
216
- * Creates a new D1Store instance
217
- * @param config Configuration for D1 access (either REST API or Workers Binding API)
218
- */
219
- constructor(config) {
220
- super({ name: "D1" });
221
- this.tablePrefix = config.tablePrefix || "";
222
- if ("binding" in config) {
223
- if (!config.binding) {
224
- throw new Error("D1 binding is required when using Workers Binding API");
225
- }
226
- this.binding = config.binding;
227
- this.logger.info("Using D1 Workers Binding API");
228
- } else {
229
- if (!config.accountId || !config.databaseId || !config.apiToken) {
230
- throw new Error("accountId, databaseId, and apiToken are required when using REST API");
231
- }
232
- this.accountId = config.accountId;
233
- this.databaseId = config.databaseId;
234
- this.client = new Cloudflare({
235
- apiToken: config.apiToken
236
- });
237
- this.logger.info("Using D1 REST API");
243
+ function deserializeValue(value, type) {
244
+ if (value === null || value === void 0) return null;
245
+ if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
246
+ try {
247
+ return JSON.parse(value);
248
+ } catch {
249
+ return value;
238
250
  }
239
251
  }
240
- // Helper method to get the full table name with prefix
241
- getTableName(tableName) {
242
- return `${this.tablePrefix}${tableName}`;
243
- }
244
- formatSqlParams(params) {
245
- return params.map((p) => p === void 0 || p === null ? null : p);
252
+ return value;
253
+ }
254
+
255
+ // src/storage/domains/legacy-evals/index.ts
256
+ var LegacyEvalsStorageD1 = class extends LegacyEvalsStorage {
257
+ operations;
258
+ constructor({ operations }) {
259
+ super();
260
+ this.operations = operations;
246
261
  }
247
- // Helper method to create SQL indexes for better query performance
248
- async createIndexIfNotExists(tableName, columnName, indexType = "") {
249
- const fullTableName = this.getTableName(tableName);
250
- const indexName = `idx_${tableName}_${columnName}`;
251
- try {
252
- const checkQuery = createSqlBuilder().checkIndexExists(indexName, fullTableName);
253
- const { sql: checkSql, params: checkParams } = checkQuery.build();
254
- const indexExists = await this.executeQuery({
255
- sql: checkSql,
256
- params: checkParams,
257
- first: true
258
- });
259
- if (!indexExists) {
260
- const createQuery = createSqlBuilder().createIndex(indexName, fullTableName, columnName, indexType);
261
- const { sql: createSql, params: createParams } = createQuery.build();
262
- await this.executeQuery({ sql: createSql, params: createParams });
263
- this.logger.debug(`Created index ${indexName} on ${fullTableName}(${columnName})`);
264
- }
265
- } catch (error) {
266
- this.logger.error(`Error creating index on ${fullTableName}(${columnName}):`, {
267
- message: error instanceof Error ? error.message : String(error)
268
- });
262
+ async getEvals(options) {
263
+ const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
264
+ const fullTableName = this.operations.getTableName(TABLE_EVALS);
265
+ const conditions = [];
266
+ const queryParams = [];
267
+ if (agentName) {
268
+ conditions.push(`agent_name = ?`);
269
+ queryParams.push(agentName);
269
270
  }
270
- }
271
- async executeWorkersBindingQuery({
272
- sql,
273
- params = [],
274
- first = false
275
- }) {
276
- if (!this.binding) {
277
- throw new Error("Workers binding is not configured");
271
+ if (type === "test") {
272
+ conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
273
+ } else if (type === "live") {
274
+ conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
278
275
  }
279
- try {
280
- const statement = this.binding.prepare(sql);
281
- const formattedParams = this.formatSqlParams(params);
282
- let result;
283
- if (formattedParams.length > 0) {
284
- if (first) {
285
- result = await statement.bind(...formattedParams).first();
286
- if (!result) return null;
287
- return result;
288
- } else {
289
- result = await statement.bind(...formattedParams).all();
290
- const results = result.results || [];
291
- if (result.meta) {
292
- this.logger.debug("Query metadata", { meta: result.meta });
293
- }
294
- return results;
295
- }
296
- } else {
297
- if (first) {
298
- result = await statement.first();
299
- if (!result) return null;
300
- return result;
301
- } else {
302
- result = await statement.all();
303
- const results = result.results || [];
304
- if (result.meta) {
305
- this.logger.debug("Query metadata", { meta: result.meta });
306
- }
307
- return results;
308
- }
309
- }
310
- } catch (workerError) {
311
- this.logger.error("Workers Binding API error", {
312
- message: workerError instanceof Error ? workerError.message : String(workerError),
313
- sql
314
- });
315
- throw new Error(`D1 Workers API error: ${workerError.message}`);
276
+ if (dateRange?.start) {
277
+ conditions.push(`created_at >= ?`);
278
+ queryParams.push(serializeDate(dateRange.start));
316
279
  }
317
- }
318
- async executeRestQuery({
319
- sql,
320
- params = [],
321
- first = false
322
- }) {
323
- if (!this.client || !this.accountId || !this.databaseId) {
324
- throw new Error("Missing required REST API configuration");
280
+ if (dateRange?.end) {
281
+ conditions.push(`created_at <= ?`);
282
+ queryParams.push(serializeDate(dateRange.end));
283
+ }
284
+ const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
285
+ if (conditions.length > 0) {
286
+ countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
325
287
  }
288
+ const { sql: countSql, params: countParams } = countQueryBuilder.build();
326
289
  try {
327
- const response = await this.client.d1.database.query(this.databaseId, {
328
- account_id: this.accountId,
329
- sql,
330
- params: this.formatSqlParams(params)
290
+ const countResult = await this.operations.executeQuery({
291
+ sql: countSql,
292
+ params: countParams,
293
+ first: true
331
294
  });
332
- const result = response.result || [];
333
- const results = result.flatMap((r) => r.results || []);
334
- if (first) {
335
- const firstResult = isArrayOfRecords(results) && results.length > 0 ? results[0] : null;
336
- if (!firstResult) return null;
337
- return firstResult;
295
+ const total = Number(countResult?.count || 0);
296
+ const currentOffset = page * perPage;
297
+ if (total === 0) {
298
+ return {
299
+ evals: [],
300
+ total: 0,
301
+ page,
302
+ perPage,
303
+ hasMore: false
304
+ };
338
305
  }
339
- return results;
340
- } catch (restError) {
341
- this.logger.error("REST API error", {
342
- message: restError instanceof Error ? restError.message : String(restError),
343
- sql
306
+ const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
307
+ if (conditions.length > 0) {
308
+ dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
309
+ }
310
+ dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
311
+ const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
312
+ const rows = await this.operations.executeQuery({
313
+ sql: dataSql,
314
+ params: dataParams
315
+ });
316
+ const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
317
+ const result = deserializeValue(row.result);
318
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
319
+ if (!result || typeof result !== "object" || !("score" in result)) {
320
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
321
+ }
322
+ return {
323
+ input: row.input,
324
+ output: row.output,
325
+ result,
326
+ agentName: row.agent_name,
327
+ metricName: row.metric_name,
328
+ instructions: row.instructions,
329
+ testInfo,
330
+ globalRunId: row.global_run_id,
331
+ runId: row.run_id,
332
+ createdAt: row.created_at
333
+ };
344
334
  });
345
- throw new Error(`D1 REST API error: ${restError.message}`);
335
+ const hasMore = currentOffset + evals.length < total;
336
+ return {
337
+ evals,
338
+ total,
339
+ page,
340
+ perPage,
341
+ hasMore
342
+ };
343
+ } catch (error) {
344
+ throw new MastraError(
345
+ {
346
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
347
+ domain: ErrorDomain.STORAGE,
348
+ category: ErrorCategory.THIRD_PARTY,
349
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
350
+ details: { agentName: agentName ?? "", type: type ?? "" }
351
+ },
352
+ error
353
+ );
346
354
  }
347
355
  }
348
356
  /**
349
- * Execute a SQL query against the D1 database
350
- * @param options Query options including SQL, parameters, and whether to return only the first result
351
- * @returns Query results as an array or a single object if first=true
357
+ * @deprecated use getEvals instead
352
358
  */
353
- async executeQuery(options) {
354
- const { sql, params = [], first = false } = options;
359
+ async getEvalsByAgentName(agentName, type) {
360
+ const fullTableName = this.operations.getTableName(TABLE_EVALS);
355
361
  try {
356
- this.logger.debug("Executing SQL query", { sql, params, first });
357
- if (this.binding) {
358
- return this.executeWorkersBindingQuery({ sql, params, first });
359
- } else if (this.client && this.accountId && this.databaseId) {
360
- return this.executeRestQuery({ sql, params, first });
361
- } else {
362
- throw new Error("No valid D1 configuration provided");
362
+ let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
363
+ if (type === "test") {
364
+ query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
365
+ } else if (type === "live") {
366
+ query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
363
367
  }
368
+ query.orderBy("created_at", "DESC");
369
+ const { sql, params } = query.build();
370
+ const results = await this.operations.executeQuery({ sql, params });
371
+ return isArrayOfRecords(results) ? results.map((row) => {
372
+ const result = deserializeValue(row.result);
373
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
374
+ return {
375
+ input: row.input || "",
376
+ output: row.output || "",
377
+ result,
378
+ agentName: row.agent_name || "",
379
+ metricName: row.metric_name || "",
380
+ instructions: row.instructions || "",
381
+ runId: row.run_id || "",
382
+ globalRunId: row.global_run_id || "",
383
+ createdAt: row.created_at || "",
384
+ testInfo
385
+ };
386
+ }) : [];
364
387
  } catch (error) {
365
- this.logger.error("Error executing SQL query", {
366
- message: error instanceof Error ? error.message : String(error),
367
- sql,
368
- params,
369
- first
370
- });
371
- throw new Error(`D1 query error: ${error.message}`);
372
- }
373
- }
374
- // Helper to convert storage type to SQL type
375
- getSqlType(type) {
376
- switch (type) {
377
- case "text":
378
- return "TEXT";
379
- case "timestamp":
380
- return "TIMESTAMP";
381
- case "integer":
382
- return "INTEGER";
383
- case "bigint":
384
- return "INTEGER";
385
- // SQLite doesn't have a separate BIGINT type
386
- case "jsonb":
387
- return "TEXT";
388
- // Store JSON as TEXT in SQLite
389
- default:
390
- return "TEXT";
391
- }
392
- }
393
- ensureDate(date) {
394
- if (!date) return void 0;
395
- return date instanceof Date ? date : new Date(date);
396
- }
397
- serializeDate(date) {
398
- if (!date) return void 0;
399
- const dateObj = this.ensureDate(date);
400
- return dateObj?.toISOString();
401
- }
402
- // Helper to serialize objects to JSON strings
403
- serializeValue(value) {
404
- if (value === null || value === void 0) return null;
405
- if (value instanceof Date) {
406
- return this.serializeDate(value);
407
- }
408
- if (typeof value === "object") {
409
- return JSON.stringify(value);
388
+ const mastraError = new MastraError(
389
+ {
390
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
391
+ domain: ErrorDomain.STORAGE,
392
+ category: ErrorCategory.THIRD_PARTY,
393
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
394
+ details: { agentName }
395
+ },
396
+ error
397
+ );
398
+ this.logger?.error(mastraError.toString());
399
+ this.logger?.trackException(mastraError);
400
+ return [];
410
401
  }
411
- return value;
412
402
  }
413
- // Helper to deserialize JSON strings to objects
414
- deserializeValue(value, type) {
415
- if (value === null || value === void 0) return null;
416
- if (type === "date" && typeof value === "string") {
417
- return new Date(value);
418
- }
419
- if (type === "jsonb" && typeof value === "string") {
420
- try {
421
- return JSON.parse(value);
422
- } catch {
423
- return value;
424
- }
425
- }
426
- if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
427
- try {
428
- return JSON.parse(value);
429
- } catch {
430
- return value;
431
- }
432
- }
433
- return value;
403
+ };
404
+ var MemoryStorageD1 = class extends MemoryStorage {
405
+ operations;
406
+ constructor({ operations }) {
407
+ super();
408
+ this.operations = operations;
434
409
  }
435
- async createTable({
436
- tableName,
437
- schema
438
- }) {
439
- const fullTableName = this.getTableName(tableName);
440
- const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
441
- const type = this.getSqlType(colDef.type);
442
- const nullable = colDef.nullable === false ? "NOT NULL" : "";
443
- const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
444
- return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
410
+ async getResourceById({ resourceId }) {
411
+ const resource = await this.operations.load({
412
+ tableName: TABLE_RESOURCES,
413
+ keys: { id: resourceId }
445
414
  });
446
- const tableConstraints = [];
447
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
448
- tableConstraints.push("UNIQUE (workflow_name, run_id)");
449
- }
450
- const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
451
- const { sql, params } = query.build();
452
- try {
453
- await this.executeQuery({ sql, params });
454
- this.logger.debug(`Created table ${fullTableName}`);
455
- } catch (error) {
456
- this.logger.error(`Error creating table ${fullTableName}:`, {
457
- message: error instanceof Error ? error.message : String(error)
458
- });
459
- throw new Error(`Failed to create table ${fullTableName}: ${error}`);
460
- }
461
- }
462
- async clearTable({ tableName }) {
463
- const fullTableName = this.getTableName(tableName);
415
+ if (!resource) return null;
464
416
  try {
465
- const query = createSqlBuilder().delete(fullTableName);
466
- const { sql, params } = query.build();
467
- await this.executeQuery({ sql, params });
468
- this.logger.debug(`Cleared table ${fullTableName}`);
417
+ return {
418
+ ...resource,
419
+ createdAt: ensureDate(resource.createdAt),
420
+ updatedAt: ensureDate(resource.updatedAt),
421
+ metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
422
+ };
469
423
  } catch (error) {
470
- this.logger.error(`Error clearing table ${fullTableName}:`, {
471
- message: error instanceof Error ? error.message : String(error)
472
- });
473
- throw new Error(`Failed to clear table ${fullTableName}: ${error}`);
474
- }
475
- }
476
- async processRecord(record) {
477
- const processedRecord = {};
478
- for (const [key, value] of Object.entries(record)) {
479
- processedRecord[key] = this.serializeValue(value);
424
+ const mastraError = new MastraError(
425
+ {
426
+ id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
427
+ domain: ErrorDomain.STORAGE,
428
+ category: ErrorCategory.THIRD_PARTY,
429
+ text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
430
+ details: { resourceId }
431
+ },
432
+ error
433
+ );
434
+ this.logger?.error(mastraError.toString());
435
+ this.logger?.trackException(mastraError);
436
+ return null;
480
437
  }
481
- return processedRecord;
482
438
  }
483
- async insert({ tableName, record }) {
484
- const fullTableName = this.getTableName(tableName);
485
- const processedRecord = await this.processRecord(record);
439
+ async saveResource({ resource }) {
440
+ const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
441
+ const resourceToSave = {
442
+ id: resource.id,
443
+ workingMemory: resource.workingMemory,
444
+ metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
445
+ createdAt: resource.createdAt,
446
+ updatedAt: resource.updatedAt
447
+ };
448
+ const processedRecord = await this.operations.processRecord(resourceToSave);
486
449
  const columns = Object.keys(processedRecord);
487
450
  const values = Object.values(processedRecord);
488
- const query = createSqlBuilder().insert(fullTableName, columns, values);
451
+ const updateMap = {
452
+ workingMemory: "excluded.workingMemory",
453
+ metadata: "excluded.metadata",
454
+ createdAt: "excluded.createdAt",
455
+ updatedAt: "excluded.updatedAt"
456
+ };
457
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
489
458
  const { sql, params } = query.build();
490
459
  try {
491
- await this.executeQuery({ sql, params });
460
+ await this.operations.executeQuery({ sql, params });
461
+ return resource;
492
462
  } catch (error) {
493
- this.logger.error(`Error inserting into ${fullTableName}:`, { error });
494
- throw new Error(`Failed to insert into ${fullTableName}: ${error}`);
463
+ throw new MastraError(
464
+ {
465
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
466
+ domain: ErrorDomain.STORAGE,
467
+ category: ErrorCategory.THIRD_PARTY,
468
+ text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
469
+ details: { resourceId: resource.id }
470
+ },
471
+ error
472
+ );
495
473
  }
496
474
  }
497
- async load({ tableName, keys }) {
498
- const fullTableName = this.getTableName(tableName);
499
- const query = createSqlBuilder().select("*").from(fullTableName);
500
- let firstKey = true;
501
- for (const [key, value] of Object.entries(keys)) {
502
- if (firstKey) {
503
- query.where(`${key} = ?`, value);
504
- firstKey = false;
505
- } else {
506
- query.andWhere(`${key} = ?`, value);
507
- }
475
+ async updateResource({
476
+ resourceId,
477
+ workingMemory,
478
+ metadata
479
+ }) {
480
+ const existingResource = await this.getResourceById({ resourceId });
481
+ if (!existingResource) {
482
+ const newResource = {
483
+ id: resourceId,
484
+ workingMemory,
485
+ metadata: metadata || {},
486
+ createdAt: /* @__PURE__ */ new Date(),
487
+ updatedAt: /* @__PURE__ */ new Date()
488
+ };
489
+ return this.saveResource({ resource: newResource });
508
490
  }
509
- query.limit(1);
491
+ const updatedAt = /* @__PURE__ */ new Date();
492
+ const updatedResource = {
493
+ ...existingResource,
494
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
495
+ metadata: {
496
+ ...existingResource.metadata,
497
+ ...metadata
498
+ },
499
+ updatedAt
500
+ };
501
+ const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
502
+ const columns = ["workingMemory", "metadata", "updatedAt"];
503
+ const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
504
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
510
505
  const { sql, params } = query.build();
511
506
  try {
512
- const result = await this.executeQuery({ sql, params, first: true });
513
- if (!result) return null;
514
- const processedResult = {};
515
- for (const [key, value] of Object.entries(result)) {
516
- processedResult[key] = this.deserializeValue(value);
517
- }
518
- return processedResult;
507
+ await this.operations.executeQuery({ sql, params });
508
+ return updatedResource;
519
509
  } catch (error) {
520
- this.logger.error(`Error loading from ${fullTableName}:`, {
521
- message: error instanceof Error ? error.message : String(error)
522
- });
523
- return null;
510
+ throw new MastraError(
511
+ {
512
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
513
+ domain: ErrorDomain.STORAGE,
514
+ category: ErrorCategory.THIRD_PARTY,
515
+ text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
516
+ details: { resourceId }
517
+ },
518
+ error
519
+ );
524
520
  }
525
521
  }
526
522
  async getThreadById({ threadId }) {
527
- const thread = await this.load({
523
+ const thread = await this.operations.load({
528
524
  tableName: TABLE_THREADS,
529
525
  keys: { id: threadId }
530
526
  });
@@ -532,47 +528,113 @@ var D1Store = class extends MastraStorage {
532
528
  try {
533
529
  return {
534
530
  ...thread,
535
- createdAt: this.ensureDate(thread.createdAt),
536
- updatedAt: this.ensureDate(thread.updatedAt),
531
+ createdAt: ensureDate(thread.createdAt),
532
+ updatedAt: ensureDate(thread.updatedAt),
537
533
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
538
534
  };
539
535
  } catch (error) {
540
- this.logger.error(`Error processing thread ${threadId}:`, {
541
- message: error instanceof Error ? error.message : String(error)
542
- });
536
+ const mastraError = new MastraError(
537
+ {
538
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
539
+ domain: ErrorDomain.STORAGE,
540
+ category: ErrorCategory.THIRD_PARTY,
541
+ text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
542
+ details: { threadId }
543
+ },
544
+ error
545
+ );
546
+ this.logger?.error(mastraError.toString());
547
+ this.logger?.trackException(mastraError);
543
548
  return null;
544
549
  }
545
550
  }
551
+ /**
552
+ * @deprecated use getThreadsByResourceIdPaginated instead
553
+ */
546
554
  async getThreadsByResourceId({ resourceId }) {
547
- const fullTableName = this.getTableName(TABLE_THREADS);
555
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
548
556
  try {
549
557
  const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
550
558
  const { sql, params } = query.build();
551
- const results = await this.executeQuery({ sql, params });
559
+ const results = await this.operations.executeQuery({ sql, params });
552
560
  return (isArrayOfRecords(results) ? results : []).map((thread) => ({
553
561
  ...thread,
554
- createdAt: this.ensureDate(thread.createdAt),
555
- updatedAt: this.ensureDate(thread.updatedAt),
562
+ createdAt: ensureDate(thread.createdAt),
563
+ updatedAt: ensureDate(thread.updatedAt),
556
564
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
557
565
  }));
558
566
  } catch (error) {
559
- this.logger.error(`Error getting threads by resourceId ${resourceId}:`, {
560
- message: error instanceof Error ? error.message : String(error)
561
- });
567
+ const mastraError = new MastraError(
568
+ {
569
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
570
+ domain: ErrorDomain.STORAGE,
571
+ category: ErrorCategory.THIRD_PARTY,
572
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
573
+ details: { resourceId }
574
+ },
575
+ error
576
+ );
577
+ this.logger?.error(mastraError.toString());
578
+ this.logger?.trackException(mastraError);
562
579
  return [];
563
580
  }
564
581
  }
582
+ async getThreadsByResourceIdPaginated(args) {
583
+ const { resourceId, page, perPage } = args;
584
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
585
+ const mapRowToStorageThreadType = (row) => ({
586
+ ...row,
587
+ createdAt: ensureDate(row.createdAt),
588
+ updatedAt: ensureDate(row.updatedAt),
589
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
590
+ });
591
+ try {
592
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
593
+ const countResult = await this.operations.executeQuery(countQuery.build());
594
+ const total = Number(countResult?.[0]?.count ?? 0);
595
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
596
+ const results = await this.operations.executeQuery(selectQuery.build());
597
+ const threads = results.map(mapRowToStorageThreadType);
598
+ return {
599
+ threads,
600
+ total,
601
+ page,
602
+ perPage,
603
+ hasMore: page * perPage + threads.length < total
604
+ };
605
+ } catch (error) {
606
+ const mastraError = new MastraError(
607
+ {
608
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
609
+ domain: ErrorDomain.STORAGE,
610
+ category: ErrorCategory.THIRD_PARTY,
611
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
612
+ details: { resourceId }
613
+ },
614
+ error
615
+ );
616
+ this.logger?.error(mastraError.toString());
617
+ this.logger?.trackException(mastraError);
618
+ return {
619
+ threads: [],
620
+ total: 0,
621
+ page,
622
+ perPage,
623
+ hasMore: false
624
+ };
625
+ }
626
+ }
565
627
  async saveThread({ thread }) {
566
- const fullTableName = this.getTableName(TABLE_THREADS);
628
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
567
629
  const threadToSave = {
568
630
  id: thread.id,
569
631
  resourceId: thread.resourceId,
570
632
  title: thread.title,
571
633
  metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
572
- createdAt: thread.createdAt,
573
- updatedAt: thread.updatedAt
634
+ createdAt: thread.createdAt.toISOString(),
635
+ updatedAt: thread.updatedAt.toISOString()
574
636
  };
575
- const processedRecord = await this.processRecord(threadToSave);
637
+ const processedRecord = await this.operations.processRecord(threadToSave);
576
638
  const columns = Object.keys(processedRecord);
577
639
  const values = Object.values(processedRecord);
578
640
  const updateMap = {
@@ -585,11 +647,19 @@ var D1Store = class extends MastraStorage {
585
647
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
586
648
  const { sql, params } = query.build();
587
649
  try {
588
- await this.executeQuery({ sql, params });
650
+ await this.operations.executeQuery({ sql, params });
589
651
  return thread;
590
652
  } catch (error) {
591
- this.logger.error(`Error saving thread to ${fullTableName}:`, { error });
592
- throw error;
653
+ throw new MastraError(
654
+ {
655
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
656
+ domain: ErrorDomain.STORAGE,
657
+ category: ErrorCategory.THIRD_PARTY,
658
+ text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
659
+ details: { threadId: thread.id }
660
+ },
661
+ error
662
+ );
593
663
  }
594
664
  }
595
665
  async updateThread({
@@ -598,20 +668,21 @@ var D1Store = class extends MastraStorage {
598
668
  metadata
599
669
  }) {
600
670
  const thread = await this.getThreadById({ threadId: id });
601
- if (!thread) {
602
- throw new Error(`Thread ${id} not found`);
603
- }
604
- const fullTableName = this.getTableName(TABLE_THREADS);
605
- const mergedMetadata = {
606
- ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
607
- ...metadata
608
- };
609
- const columns = ["title", "metadata", "updatedAt"];
610
- const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
611
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
612
- const { sql, params } = query.build();
613
671
  try {
614
- await this.executeQuery({ sql, params });
672
+ if (!thread) {
673
+ throw new Error(`Thread ${id} not found`);
674
+ }
675
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
676
+ const mergedMetadata = {
677
+ ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
678
+ ...metadata
679
+ };
680
+ const updatedAt = /* @__PURE__ */ new Date();
681
+ const columns = ["title", "metadata", "updatedAt"];
682
+ const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
683
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
684
+ const { sql, params } = query.build();
685
+ await this.operations.executeQuery({ sql, params });
615
686
  return {
616
687
  ...thread,
617
688
  title,
@@ -619,40 +690,64 @@ var D1Store = class extends MastraStorage {
619
690
  ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
620
691
  ...metadata
621
692
  },
622
- updatedAt: /* @__PURE__ */ new Date()
693
+ updatedAt
623
694
  };
624
695
  } catch (error) {
625
- this.logger.error("Error updating thread:", { error });
626
- throw error;
696
+ throw new MastraError(
697
+ {
698
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
699
+ domain: ErrorDomain.STORAGE,
700
+ category: ErrorCategory.THIRD_PARTY,
701
+ text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
702
+ details: { threadId: id }
703
+ },
704
+ error
705
+ );
627
706
  }
628
707
  }
629
708
  async deleteThread({ threadId }) {
630
- const fullTableName = this.getTableName(TABLE_THREADS);
709
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
631
710
  try {
632
711
  const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
633
712
  const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
634
- await this.executeQuery({ sql: threadSql, params: threadParams });
635
- const messagesTableName = this.getTableName(TABLE_MESSAGES);
713
+ await this.operations.executeQuery({ sql: threadSql, params: threadParams });
714
+ const messagesTableName = this.operations.getTableName(TABLE_MESSAGES);
636
715
  const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
637
716
  const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
638
- await this.executeQuery({ sql: messagesSql, params: messagesParams });
717
+ await this.operations.executeQuery({ sql: messagesSql, params: messagesParams });
639
718
  } catch (error) {
640
- this.logger.error(`Error deleting thread ${threadId}:`, {
641
- message: error instanceof Error ? error.message : String(error)
642
- });
643
- throw new Error(`Failed to delete thread ${threadId}: ${error}`);
719
+ throw new MastraError(
720
+ {
721
+ id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
722
+ domain: ErrorDomain.STORAGE,
723
+ category: ErrorCategory.THIRD_PARTY,
724
+ text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
725
+ details: { threadId }
726
+ },
727
+ error
728
+ );
644
729
  }
645
730
  }
646
- // Thread and message management methods
647
- async saveMessages({ messages }) {
731
+ async saveMessages(args) {
732
+ const { messages, format = "v1" } = args;
648
733
  if (messages.length === 0) return [];
649
734
  try {
650
735
  const now = /* @__PURE__ */ new Date();
736
+ const threadId = messages[0]?.threadId;
651
737
  for (const [i, message] of messages.entries()) {
652
738
  if (!message.id) throw new Error(`Message at index ${i} missing id`);
653
- if (!message.threadId) throw new Error(`Message at index ${i} missing threadId`);
654
- if (!message.content) throw new Error(`Message at index ${i} missing content`);
655
- if (!message.role) throw new Error(`Message at index ${i} missing role`);
739
+ if (!message.threadId) {
740
+ throw new Error(`Message at index ${i} missing threadId`);
741
+ }
742
+ if (!message.content) {
743
+ throw new Error(`Message at index ${i} missing content`);
744
+ }
745
+ if (!message.role) {
746
+ throw new Error(`Message at index ${i} missing role`);
747
+ }
748
+ if (!message.resourceId) {
749
+ throw new Error(`Message at index ${i} missing resourceId`);
750
+ }
656
751
  const thread = await this.getThreadById({ threadId: message.threadId });
657
752
  if (!thread) {
658
753
  throw new Error(`Thread ${message.threadId} not found`);
@@ -666,122 +761,1146 @@ var D1Store = class extends MastraStorage {
666
761
  content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
667
762
  createdAt: createdAt.toISOString(),
668
763
  role: message.role,
669
- type: message.type
764
+ type: message.type || "v2",
765
+ resourceId: message.resourceId
670
766
  };
671
767
  });
672
- await this.batchInsert({
673
- tableName: TABLE_MESSAGES,
674
- records: messagesToInsert
675
- });
768
+ await Promise.all([
769
+ this.operations.batchUpsert({
770
+ tableName: TABLE_MESSAGES,
771
+ records: messagesToInsert
772
+ }),
773
+ // Update thread's updatedAt timestamp
774
+ this.operations.executeQuery({
775
+ sql: `UPDATE ${this.operations.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
776
+ params: [now.toISOString(), threadId]
777
+ })
778
+ ]);
676
779
  this.logger.debug(`Saved ${messages.length} messages`);
677
- return messages;
780
+ const list = new MessageList().add(messages, "memory");
781
+ if (format === `v2`) return list.get.all.v2();
782
+ return list.get.all.v1();
678
783
  } catch (error) {
679
- this.logger.error("Error saving messages:", { message: error instanceof Error ? error.message : String(error) });
680
- throw error;
784
+ throw new MastraError(
785
+ {
786
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
787
+ domain: ErrorDomain.STORAGE,
788
+ category: ErrorCategory.THIRD_PARTY,
789
+ text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
790
+ },
791
+ error
792
+ );
681
793
  }
682
794
  }
683
- async getMessages({ threadId, selectBy }) {
684
- const fullTableName = this.getTableName(TABLE_MESSAGES);
685
- const limit = typeof selectBy?.last === "number" ? selectBy.last : 40;
686
- const include = selectBy?.include || [];
687
- const messages = [];
688
- try {
689
- if (include.length) {
690
- const prevMax = Math.max(...include.map((i) => i.withPreviousMessages || 0));
691
- const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
692
- const includeIds = include.map((i) => i.id);
693
- const sql2 = `
694
- WITH ordered_messages AS (
695
- SELECT
696
- *,
697
- ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
698
- FROM ${fullTableName}
699
- WHERE thread_id = ?
700
- )
701
- SELECT
702
- m.id,
703
- m.content,
704
- m.role,
705
- m.type,
706
- m.createdAt,
707
- m.thread_id AS "threadId"
708
- FROM ordered_messages m
709
- WHERE m.id IN (${includeIds.map(() => "?").join(",")})
710
- OR EXISTS (
711
- SELECT 1 FROM ordered_messages target
712
- WHERE target.id IN (${includeIds.map(() => "?").join(",")})
713
- AND (
714
- (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
715
- OR
716
- (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
717
- )
718
- )
719
- ORDER BY m.createdAt DESC
720
- `;
721
- const params2 = [
722
- threadId,
723
- ...includeIds,
724
- // for m.id IN (...)
725
- ...includeIds,
726
- // for target.id IN (...)
727
- prevMax,
728
- nextMax
729
- ];
730
- const includeResult = await this.executeQuery({ sql: sql2, params: params2 });
795
+ async _getIncludedMessages(threadId, selectBy) {
796
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
797
+ const include = selectBy?.include;
798
+ if (!include) return null;
799
+ const unionQueries = [];
800
+ const params = [];
801
+ let paramIdx = 1;
802
+ for (const inc of include) {
803
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
804
+ const searchId = inc.threadId || threadId;
805
+ unionQueries.push(`
806
+ SELECT * FROM (
807
+ WITH ordered_messages AS (
808
+ SELECT
809
+ *,
810
+ ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
811
+ FROM ${this.operations.getTableName(TABLE_MESSAGES)}
812
+ WHERE thread_id = ?
813
+ )
814
+ SELECT
815
+ m.id,
816
+ m.content,
817
+ m.role,
818
+ m.type,
819
+ m.createdAt,
820
+ m.thread_id AS threadId,
821
+ m.resourceId
822
+ FROM ordered_messages m
823
+ WHERE m.id = ?
824
+ OR EXISTS (
825
+ SELECT 1 FROM ordered_messages target
826
+ WHERE target.id = ?
827
+ AND (
828
+ (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
829
+ OR
830
+ (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
831
+ )
832
+ )
833
+ ) AS query_${paramIdx}
834
+ `);
835
+ params.push(searchId, id, id, withNextMessages, withPreviousMessages);
836
+ paramIdx++;
837
+ }
838
+ const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
839
+ const messages = await this.operations.executeQuery({ sql: finalQuery, params });
840
+ if (!Array.isArray(messages)) {
841
+ return [];
842
+ }
843
+ const processedMessages = messages.map((message) => {
844
+ const processedMsg = {};
845
+ for (const [key, value] of Object.entries(message)) {
846
+ if (key === `type` && value === `v2`) continue;
847
+ processedMsg[key] = deserializeValue(value);
848
+ }
849
+ return processedMsg;
850
+ });
851
+ return processedMessages;
852
+ }
853
+ async getMessages({
854
+ threadId,
855
+ resourceId,
856
+ selectBy,
857
+ format
858
+ }) {
859
+ try {
860
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
861
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
862
+ const limit = resolveMessageLimit({
863
+ last: selectBy?.last,
864
+ defaultLimit: 40
865
+ });
866
+ const include = selectBy?.include || [];
867
+ const messages = [];
868
+ if (include.length) {
869
+ const includeResult = await this._getIncludedMessages(threadId, selectBy);
870
+ if (Array.isArray(includeResult)) messages.push(...includeResult);
871
+ }
872
+ const excludeIds = messages.map((m) => m.id);
873
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
874
+ if (excludeIds.length > 0) {
875
+ query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
876
+ }
877
+ query.orderBy("createdAt", "DESC").limit(limit);
878
+ const { sql, params } = query.build();
879
+ const result = await this.operations.executeQuery({ sql, params });
880
+ if (Array.isArray(result)) messages.push(...result);
881
+ messages.sort((a, b) => {
882
+ const aRecord = a;
883
+ const bRecord = b;
884
+ const timeA = new Date(aRecord.createdAt).getTime();
885
+ const timeB = new Date(bRecord.createdAt).getTime();
886
+ return timeA - timeB;
887
+ });
888
+ const processedMessages = messages.map((message) => {
889
+ const processedMsg = {};
890
+ for (const [key, value] of Object.entries(message)) {
891
+ if (key === `type` && value === `v2`) continue;
892
+ processedMsg[key] = deserializeValue(value);
893
+ }
894
+ return processedMsg;
895
+ });
896
+ this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
897
+ const list = new MessageList().add(processedMessages, "memory");
898
+ if (format === `v2`) return list.get.all.v2();
899
+ return list.get.all.v1();
900
+ } catch (error) {
901
+ const mastraError = new MastraError(
902
+ {
903
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
904
+ domain: ErrorDomain.STORAGE,
905
+ category: ErrorCategory.THIRD_PARTY,
906
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
907
+ details: { threadId, resourceId: resourceId ?? "" }
908
+ },
909
+ error
910
+ );
911
+ this.logger?.error(mastraError.toString());
912
+ this.logger?.trackException(mastraError);
913
+ throw mastraError;
914
+ }
915
+ }
916
+ async getMessagesById({
917
+ messageIds,
918
+ format
919
+ }) {
920
+ if (messageIds.length === 0) return [];
921
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
922
+ const messages = [];
923
+ try {
924
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
925
+ query.orderBy("createdAt", "DESC");
926
+ const { sql, params } = query.build();
927
+ const result = await this.operations.executeQuery({ sql, params });
928
+ if (Array.isArray(result)) messages.push(...result);
929
+ const processedMessages = messages.map((message) => {
930
+ const processedMsg = {};
931
+ for (const [key, value] of Object.entries(message)) {
932
+ if (key === `type` && value === `v2`) continue;
933
+ processedMsg[key] = deserializeValue(value);
934
+ }
935
+ return processedMsg;
936
+ });
937
+ this.logger.debug(`Retrieved ${messages.length} messages`);
938
+ const list = new MessageList().add(processedMessages, "memory");
939
+ if (format === `v1`) return list.get.all.v1();
940
+ return list.get.all.v2();
941
+ } catch (error) {
942
+ const mastraError = new MastraError(
943
+ {
944
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
945
+ domain: ErrorDomain.STORAGE,
946
+ category: ErrorCategory.THIRD_PARTY,
947
+ text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
948
+ details: { messageIds: JSON.stringify(messageIds) }
949
+ },
950
+ error
951
+ );
952
+ this.logger?.error(mastraError.toString());
953
+ this.logger?.trackException(mastraError);
954
+ throw mastraError;
955
+ }
956
+ }
957
+ async getMessagesPaginated({
958
+ threadId,
959
+ resourceId,
960
+ selectBy,
961
+ format
962
+ }) {
963
+ const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
964
+ const { start: fromDate, end: toDate } = dateRange || {};
965
+ const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
966
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
967
+ const messages = [];
968
+ try {
969
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
970
+ if (selectBy?.include?.length) {
971
+ const includeResult = await this._getIncludedMessages(threadId, selectBy);
731
972
  if (Array.isArray(includeResult)) messages.push(...includeResult);
732
973
  }
733
- const excludeIds = messages.map((m) => m.id);
734
- let query = createSqlBuilder().select(["id", "content", "role", "type", '"createdAt"', 'thread_id AS "threadId"']).from(fullTableName).where("thread_id = ?", threadId).andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds).orderBy("createdAt", "DESC").limit(limit);
735
- const { sql, params } = query.build();
736
- const result = await this.executeQuery({ sql, params });
737
- if (Array.isArray(result)) messages.push(...result);
738
- messages.sort((a, b) => {
739
- const aRecord = a;
740
- const bRecord = b;
741
- const timeA = new Date(aRecord.createdAt).getTime();
742
- const timeB = new Date(bRecord.createdAt).getTime();
743
- return timeA - timeB;
744
- });
745
- const processedMessages = messages.map((message) => {
746
- const processedMsg = {};
747
- for (const [key, value] of Object.entries(message)) {
748
- processedMsg[key] = this.deserializeValue(value);
749
- }
750
- return processedMsg;
751
- });
752
- this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
753
- return processedMessages;
974
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
975
+ if (fromDate) {
976
+ countQuery.andWhere("createdAt >= ?", serializeDate(fromDate));
977
+ }
978
+ if (toDate) {
979
+ countQuery.andWhere("createdAt <= ?", serializeDate(toDate));
980
+ }
981
+ const countResult = await this.operations.executeQuery(countQuery.build());
982
+ const total = Number(countResult[0]?.count ?? 0);
983
+ if (total === 0 && messages.length === 0) {
984
+ return {
985
+ messages: [],
986
+ total: 0,
987
+ page,
988
+ perPage,
989
+ hasMore: false
990
+ };
991
+ }
992
+ const excludeIds = messages.map((m) => m.id);
993
+ const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
994
+ let query;
995
+ let queryParams = [threadId];
996
+ if (fromDate) {
997
+ queryParams.push(serializeDate(fromDate));
998
+ }
999
+ if (toDate) {
1000
+ queryParams.push(serializeDate(toDate));
1001
+ }
1002
+ if (excludeIds.length > 0) {
1003
+ queryParams.push(...excludeIds);
1004
+ }
1005
+ if (selectBy?.last && selectBy.last > 0) {
1006
+ query = `
1007
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1008
+ FROM ${fullTableName}
1009
+ WHERE thread_id = ?
1010
+ ${fromDate ? "AND createdAt >= ?" : ""}
1011
+ ${toDate ? "AND createdAt <= ?" : ""}
1012
+ ${excludeCondition}
1013
+ ORDER BY createdAt DESC
1014
+ LIMIT ?
1015
+ `;
1016
+ queryParams.push(selectBy.last);
1017
+ } else {
1018
+ query = `
1019
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1020
+ FROM ${fullTableName}
1021
+ WHERE thread_id = ?
1022
+ ${fromDate ? "AND createdAt >= ?" : ""}
1023
+ ${toDate ? "AND createdAt <= ?" : ""}
1024
+ ${excludeCondition}
1025
+ ORDER BY createdAt DESC
1026
+ LIMIT ? OFFSET ?
1027
+ `;
1028
+ queryParams.push(perPage, page * perPage);
1029
+ }
1030
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
1031
+ const processedMessages = results.map((message) => {
1032
+ const processedMsg = {};
1033
+ for (const [key, value] of Object.entries(message)) {
1034
+ if (key === `type` && value === `v2`) continue;
1035
+ processedMsg[key] = deserializeValue(value);
1036
+ }
1037
+ return processedMsg;
1038
+ });
1039
+ if (selectBy?.last) {
1040
+ processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1041
+ }
1042
+ const list = new MessageList().add(processedMessages, "memory");
1043
+ messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
1044
+ return {
1045
+ messages,
1046
+ total,
1047
+ page,
1048
+ perPage,
1049
+ hasMore: selectBy?.last ? false : page * perPage + messages.length < total
1050
+ };
1051
+ } catch (error) {
1052
+ const mastraError = new MastraError(
1053
+ {
1054
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
1055
+ domain: ErrorDomain.STORAGE,
1056
+ category: ErrorCategory.THIRD_PARTY,
1057
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1058
+ details: { threadId, resourceId: resourceId ?? "" }
1059
+ },
1060
+ error
1061
+ );
1062
+ this.logger?.error(mastraError.toString());
1063
+ this.logger?.trackException(mastraError);
1064
+ return {
1065
+ messages: [],
1066
+ total: 0,
1067
+ page,
1068
+ perPage,
1069
+ hasMore: false
1070
+ };
1071
+ }
1072
+ }
1073
+ async updateMessages(args) {
1074
+ const { messages } = args;
1075
+ this.logger.debug("Updating messages", { count: messages.length });
1076
+ if (!messages.length) {
1077
+ return [];
1078
+ }
1079
+ const messageIds = messages.map((m) => m.id);
1080
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
1081
+ const threadsTableName = this.operations.getTableName(TABLE_THREADS);
1082
+ try {
1083
+ const placeholders = messageIds.map(() => "?").join(",");
1084
+ const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
1085
+ const existingMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1086
+ if (existingMessages.length === 0) {
1087
+ return [];
1088
+ }
1089
+ const parsedExistingMessages = existingMessages.map((msg) => {
1090
+ if (typeof msg.content === "string") {
1091
+ try {
1092
+ msg.content = JSON.parse(msg.content);
1093
+ } catch {
1094
+ }
1095
+ }
1096
+ return msg;
1097
+ });
1098
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
1099
+ const updateQueries = [];
1100
+ for (const existingMessage of parsedExistingMessages) {
1101
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
1102
+ if (!updatePayload) continue;
1103
+ const { id, ...fieldsToUpdate } = updatePayload;
1104
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
1105
+ threadIdsToUpdate.add(existingMessage.threadId);
1106
+ if ("threadId" in updatePayload && updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
1107
+ threadIdsToUpdate.add(updatePayload.threadId);
1108
+ }
1109
+ const setClauses = [];
1110
+ const values = [];
1111
+ const updatableFields = { ...fieldsToUpdate };
1112
+ if (updatableFields.content) {
1113
+ const existingContent = existingMessage.content || {};
1114
+ const newContent = {
1115
+ ...existingContent,
1116
+ ...updatableFields.content,
1117
+ // Deep merge metadata if it exists on both
1118
+ ...existingContent?.metadata && updatableFields.content.metadata ? {
1119
+ metadata: {
1120
+ ...existingContent.metadata,
1121
+ ...updatableFields.content.metadata
1122
+ }
1123
+ } : {}
1124
+ };
1125
+ setClauses.push(`content = ?`);
1126
+ values.push(JSON.stringify(newContent));
1127
+ delete updatableFields.content;
1128
+ }
1129
+ for (const key in updatableFields) {
1130
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
1131
+ const dbColumn = key === "threadId" ? "thread_id" : key;
1132
+ setClauses.push(`${dbColumn} = ?`);
1133
+ values.push(updatableFields[key]);
1134
+ }
1135
+ }
1136
+ if (setClauses.length > 0) {
1137
+ values.push(id);
1138
+ const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
1139
+ updateQueries.push({ sql: updateQuery, params: values });
1140
+ }
1141
+ }
1142
+ for (const query of updateQueries) {
1143
+ await this.operations.executeQuery(query);
1144
+ }
1145
+ if (threadIdsToUpdate.size > 0) {
1146
+ const threadPlaceholders = Array.from(threadIdsToUpdate).map(() => "?").join(",");
1147
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadPlaceholders})`;
1148
+ const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
1149
+ await this.operations.executeQuery({ sql: threadUpdateQuery, params: threadUpdateParams });
1150
+ }
1151
+ const updatedMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1152
+ return updatedMessages.map((message) => {
1153
+ if (typeof message.content === "string") {
1154
+ try {
1155
+ message.content = JSON.parse(message.content);
1156
+ } catch {
1157
+ }
1158
+ }
1159
+ return message;
1160
+ });
1161
+ } catch (error) {
1162
+ throw new MastraError(
1163
+ {
1164
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
1165
+ domain: ErrorDomain.STORAGE,
1166
+ category: ErrorCategory.THIRD_PARTY,
1167
+ details: { count: messages.length }
1168
+ },
1169
+ error
1170
+ );
1171
+ }
1172
+ }
1173
+ };
1174
+ var StoreOperationsD1 = class extends StoreOperations {
1175
+ client;
1176
+ binding;
1177
+ tablePrefix;
1178
+ constructor(config) {
1179
+ super();
1180
+ this.client = config.client;
1181
+ this.binding = config.binding;
1182
+ this.tablePrefix = config.tablePrefix || "";
1183
+ }
1184
+ async hasColumn(table, column) {
1185
+ const fullTableName = table.startsWith(this.tablePrefix) ? table : `${this.tablePrefix}${table}`;
1186
+ const sql = `PRAGMA table_info(${fullTableName});`;
1187
+ const result = await this.executeQuery({ sql, params: [] });
1188
+ if (!result || !Array.isArray(result)) return false;
1189
+ return result.some((col) => col.name === column || col.name === column.toLowerCase());
1190
+ }
1191
+ getTableName(tableName) {
1192
+ return `${this.tablePrefix}${tableName}`;
1193
+ }
1194
+ formatSqlParams(params) {
1195
+ return params.map((p) => p === void 0 || p === null ? null : p);
1196
+ }
1197
+ async executeWorkersBindingQuery({
1198
+ sql,
1199
+ params = [],
1200
+ first = false
1201
+ }) {
1202
+ if (!this.binding) {
1203
+ throw new Error("Workers binding is not configured");
1204
+ }
1205
+ try {
1206
+ const statement = this.binding.prepare(sql);
1207
+ const formattedParams = this.formatSqlParams(params);
1208
+ let result;
1209
+ if (formattedParams.length > 0) {
1210
+ if (first) {
1211
+ result = await statement.bind(...formattedParams).first();
1212
+ if (!result) return null;
1213
+ return result;
1214
+ } else {
1215
+ result = await statement.bind(...formattedParams).all();
1216
+ const results = result.results || [];
1217
+ return results;
1218
+ }
1219
+ } else {
1220
+ if (first) {
1221
+ result = await statement.first();
1222
+ if (!result) return null;
1223
+ return result;
1224
+ } else {
1225
+ result = await statement.all();
1226
+ const results = result.results || [];
1227
+ return results;
1228
+ }
1229
+ }
1230
+ } catch (error) {
1231
+ throw new MastraError(
1232
+ {
1233
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1234
+ domain: ErrorDomain.STORAGE,
1235
+ category: ErrorCategory.THIRD_PARTY,
1236
+ details: { sql }
1237
+ },
1238
+ error
1239
+ );
1240
+ }
1241
+ }
1242
+ async executeRestQuery({
1243
+ sql,
1244
+ params = [],
1245
+ first = false
1246
+ }) {
1247
+ if (!this.client) {
1248
+ throw new Error("D1 client is not configured");
1249
+ }
1250
+ try {
1251
+ const formattedParams = this.formatSqlParams(params);
1252
+ const response = await this.client.query({
1253
+ sql,
1254
+ params: formattedParams
1255
+ });
1256
+ const result = response.result || [];
1257
+ const results = result.flatMap((r) => r.results || []);
1258
+ if (first) {
1259
+ return results[0] || null;
1260
+ }
1261
+ return results;
1262
+ } catch (error) {
1263
+ throw new MastraError(
1264
+ {
1265
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1266
+ domain: ErrorDomain.STORAGE,
1267
+ category: ErrorCategory.THIRD_PARTY,
1268
+ details: { sql }
1269
+ },
1270
+ error
1271
+ );
1272
+ }
1273
+ }
1274
+ async executeQuery(options) {
1275
+ if (this.binding) {
1276
+ return this.executeWorkersBindingQuery(options);
1277
+ } else if (this.client) {
1278
+ return this.executeRestQuery(options);
1279
+ } else {
1280
+ throw new Error("Neither binding nor client is configured");
1281
+ }
1282
+ }
1283
+ async getTableColumns(tableName) {
1284
+ try {
1285
+ const sql = `PRAGMA table_info(${tableName})`;
1286
+ const result = await this.executeQuery({ sql });
1287
+ if (!result || !Array.isArray(result)) {
1288
+ return [];
1289
+ }
1290
+ return result.map((row) => ({
1291
+ name: row.name,
1292
+ type: row.type
1293
+ }));
1294
+ } catch (error) {
1295
+ this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
1296
+ return [];
1297
+ }
1298
+ }
1299
+ serializeValue(value) {
1300
+ if (value === null || value === void 0) {
1301
+ return null;
1302
+ }
1303
+ if (value instanceof Date) {
1304
+ return value.toISOString();
1305
+ }
1306
+ if (typeof value === "object") {
1307
+ return JSON.stringify(value);
1308
+ }
1309
+ return value;
1310
+ }
1311
+ getSqlType(type) {
1312
+ switch (type) {
1313
+ case "bigint":
1314
+ return "INTEGER";
1315
+ // SQLite uses INTEGER for all integer sizes
1316
+ case "jsonb":
1317
+ return "TEXT";
1318
+ // Store JSON as TEXT in SQLite
1319
+ default:
1320
+ return super.getSqlType(type);
1321
+ }
1322
+ }
1323
+ async createTable({
1324
+ tableName,
1325
+ schema
1326
+ }) {
1327
+ try {
1328
+ const fullTableName = this.getTableName(tableName);
1329
+ const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
1330
+ const type = this.getSqlType(colDef.type);
1331
+ const nullable = colDef.nullable === false ? "NOT NULL" : "";
1332
+ const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
1333
+ return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
1334
+ });
1335
+ const tableConstraints = [];
1336
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1337
+ tableConstraints.push("UNIQUE (workflow_name, run_id)");
1338
+ }
1339
+ const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
1340
+ const { sql, params } = query.build();
1341
+ await this.executeQuery({ sql, params });
1342
+ this.logger.debug(`Created table ${fullTableName}`);
1343
+ } catch (error) {
1344
+ throw new MastraError(
1345
+ {
1346
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1347
+ domain: ErrorDomain.STORAGE,
1348
+ category: ErrorCategory.THIRD_PARTY,
1349
+ details: { tableName }
1350
+ },
1351
+ error
1352
+ );
1353
+ }
1354
+ }
1355
+ async clearTable({ tableName }) {
1356
+ try {
1357
+ const fullTableName = this.getTableName(tableName);
1358
+ const query = createSqlBuilder().delete(fullTableName);
1359
+ const { sql, params } = query.build();
1360
+ await this.executeQuery({ sql, params });
1361
+ this.logger.debug(`Cleared table ${fullTableName}`);
1362
+ } catch (error) {
1363
+ throw new MastraError(
1364
+ {
1365
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1366
+ domain: ErrorDomain.STORAGE,
1367
+ category: ErrorCategory.THIRD_PARTY,
1368
+ details: { tableName }
1369
+ },
1370
+ error
1371
+ );
1372
+ }
1373
+ }
1374
+ async dropTable({ tableName }) {
1375
+ try {
1376
+ const fullTableName = this.getTableName(tableName);
1377
+ const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
1378
+ await this.executeQuery({ sql });
1379
+ this.logger.debug(`Dropped table ${fullTableName}`);
1380
+ } catch (error) {
1381
+ throw new MastraError(
1382
+ {
1383
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1384
+ domain: ErrorDomain.STORAGE,
1385
+ category: ErrorCategory.THIRD_PARTY,
1386
+ details: { tableName }
1387
+ },
1388
+ error
1389
+ );
1390
+ }
1391
+ }
1392
+ async alterTable(args) {
1393
+ try {
1394
+ const fullTableName = this.getTableName(args.tableName);
1395
+ const existingColumns = await this.getTableColumns(fullTableName);
1396
+ const existingColumnNames = new Set(existingColumns.map((col) => col.name));
1397
+ for (const [columnName, column] of Object.entries(args.schema)) {
1398
+ if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
1399
+ const sqlType = this.getSqlType(column.type);
1400
+ const defaultValue = this.getDefaultValue(column.type);
1401
+ const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
1402
+ await this.executeQuery({ sql });
1403
+ this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
1404
+ }
1405
+ }
1406
+ } catch (error) {
1407
+ throw new MastraError(
1408
+ {
1409
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1410
+ domain: ErrorDomain.STORAGE,
1411
+ category: ErrorCategory.THIRD_PARTY,
1412
+ details: { tableName: args.tableName }
1413
+ },
1414
+ error
1415
+ );
1416
+ }
1417
+ }
1418
+ async insert({ tableName, record }) {
1419
+ try {
1420
+ const fullTableName = this.getTableName(tableName);
1421
+ const processedRecord = await this.processRecord(record);
1422
+ const columns = Object.keys(processedRecord);
1423
+ const values = Object.values(processedRecord);
1424
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1425
+ const { sql, params } = query.build();
1426
+ await this.executeQuery({ sql, params });
1427
+ } catch (error) {
1428
+ throw new MastraError(
1429
+ {
1430
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1431
+ domain: ErrorDomain.STORAGE,
1432
+ category: ErrorCategory.THIRD_PARTY,
1433
+ details: { tableName }
1434
+ },
1435
+ error
1436
+ );
1437
+ }
1438
+ }
1439
+ async batchInsert({ tableName, records }) {
1440
+ try {
1441
+ if (records.length === 0) return;
1442
+ const fullTableName = this.getTableName(tableName);
1443
+ const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
1444
+ const columns = Object.keys(processedRecords[0] || {});
1445
+ for (const record of processedRecords) {
1446
+ const values = Object.values(record);
1447
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1448
+ const { sql, params } = query.build();
1449
+ await this.executeQuery({ sql, params });
1450
+ }
1451
+ } catch (error) {
1452
+ throw new MastraError(
1453
+ {
1454
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1455
+ domain: ErrorDomain.STORAGE,
1456
+ category: ErrorCategory.THIRD_PARTY,
1457
+ details: { tableName }
1458
+ },
1459
+ error
1460
+ );
1461
+ }
1462
+ }
1463
+ async load({ tableName, keys }) {
1464
+ try {
1465
+ const fullTableName = this.getTableName(tableName);
1466
+ const query = createSqlBuilder().select("*").from(fullTableName);
1467
+ let firstKey = true;
1468
+ for (const [key, value] of Object.entries(keys)) {
1469
+ if (firstKey) {
1470
+ query.where(`${key} = ?`, value);
1471
+ firstKey = false;
1472
+ } else {
1473
+ query.andWhere(`${key} = ?`, value);
1474
+ }
1475
+ }
1476
+ query.orderBy("createdAt", "DESC");
1477
+ query.limit(1);
1478
+ const { sql, params } = query.build();
1479
+ const result = await this.executeQuery({ sql, params, first: true });
1480
+ if (!result) {
1481
+ return null;
1482
+ }
1483
+ const deserializedResult = {};
1484
+ for (const [key, value] of Object.entries(result)) {
1485
+ deserializedResult[key] = deserializeValue(value);
1486
+ }
1487
+ return deserializedResult;
1488
+ } catch (error) {
1489
+ throw new MastraError(
1490
+ {
1491
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1492
+ domain: ErrorDomain.STORAGE,
1493
+ category: ErrorCategory.THIRD_PARTY,
1494
+ details: { tableName }
1495
+ },
1496
+ error
1497
+ );
1498
+ }
1499
+ }
1500
+ async processRecord(record) {
1501
+ const processed = {};
1502
+ for (const [key, value] of Object.entries(record)) {
1503
+ processed[key] = this.serializeValue(value);
1504
+ }
1505
+ return processed;
1506
+ }
1507
+ /**
1508
+ * Upsert multiple records in a batch operation
1509
+ * @param tableName The table to insert into
1510
+ * @param records The records to insert
1511
+ */
1512
+ async batchUpsert({ tableName, records }) {
1513
+ if (records.length === 0) return;
1514
+ const fullTableName = this.getTableName(tableName);
1515
+ try {
1516
+ const batchSize = 50;
1517
+ for (let i = 0; i < records.length; i += batchSize) {
1518
+ const batch = records.slice(i, i + batchSize);
1519
+ const recordsToInsert = batch;
1520
+ if (recordsToInsert.length > 0) {
1521
+ const firstRecord = recordsToInsert[0];
1522
+ const columns = Object.keys(firstRecord || {});
1523
+ for (const record of recordsToInsert) {
1524
+ const values = columns.map((col) => {
1525
+ if (!record) return null;
1526
+ const value = typeof col === "string" ? record[col] : null;
1527
+ return this.serializeValue(value);
1528
+ });
1529
+ const recordToUpsert = columns.reduce(
1530
+ (acc, col) => {
1531
+ if (col !== "createdAt") acc[col] = `excluded.${col}`;
1532
+ return acc;
1533
+ },
1534
+ {}
1535
+ );
1536
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert);
1537
+ const { sql, params } = query.build();
1538
+ await this.executeQuery({ sql, params });
1539
+ }
1540
+ }
1541
+ this.logger.debug(
1542
+ `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
1543
+ );
1544
+ }
1545
+ this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
1546
+ } catch (error) {
1547
+ throw new MastraError(
1548
+ {
1549
+ id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
1550
+ domain: ErrorDomain.STORAGE,
1551
+ category: ErrorCategory.THIRD_PARTY,
1552
+ text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
1553
+ details: { tableName }
1554
+ },
1555
+ error
1556
+ );
1557
+ }
1558
+ }
1559
+ };
1560
+ function transformScoreRow(row) {
1561
+ const deserialized = { ...row };
1562
+ deserialized.input = safelyParseJSON(row.input);
1563
+ deserialized.output = safelyParseJSON(row.output);
1564
+ deserialized.scorer = safelyParseJSON(row.scorer);
1565
+ deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1566
+ deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1567
+ deserialized.metadata = safelyParseJSON(row.metadata);
1568
+ deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1569
+ deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1570
+ deserialized.entity = safelyParseJSON(row.entity);
1571
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1572
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1573
+ return deserialized;
1574
+ }
1575
+ var ScoresStorageD1 = class extends ScoresStorage {
1576
+ operations;
1577
+ constructor({ operations }) {
1578
+ super();
1579
+ this.operations = operations;
1580
+ }
1581
+ async getScoreById({ id }) {
1582
+ try {
1583
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1584
+ const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
1585
+ const { sql, params } = query.build();
1586
+ const result = await this.operations.executeQuery({ sql, params, first: true });
1587
+ if (!result) {
1588
+ return null;
1589
+ }
1590
+ return transformScoreRow(result);
1591
+ } catch (error) {
1592
+ throw new MastraError(
1593
+ {
1594
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1595
+ domain: ErrorDomain.STORAGE,
1596
+ category: ErrorCategory.THIRD_PARTY
1597
+ },
1598
+ error
1599
+ );
1600
+ }
1601
+ }
1602
+ async saveScore(score) {
1603
+ let parsedScore;
1604
+ try {
1605
+ parsedScore = saveScorePayloadSchema.parse(score);
1606
+ } catch (error) {
1607
+ throw new MastraError(
1608
+ {
1609
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1610
+ domain: ErrorDomain.STORAGE,
1611
+ category: ErrorCategory.USER,
1612
+ details: { scoreId: score.id }
1613
+ },
1614
+ error
1615
+ );
1616
+ }
1617
+ try {
1618
+ const id = crypto.randomUUID();
1619
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1620
+ const serializedRecord = {};
1621
+ for (const [key, value] of Object.entries(parsedScore)) {
1622
+ if (value !== null && value !== void 0) {
1623
+ if (typeof value === "object") {
1624
+ serializedRecord[key] = JSON.stringify(value);
1625
+ } else {
1626
+ serializedRecord[key] = value;
1627
+ }
1628
+ } else {
1629
+ serializedRecord[key] = null;
1630
+ }
1631
+ }
1632
+ serializedRecord.id = id;
1633
+ serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1634
+ serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1635
+ const columns = Object.keys(serializedRecord);
1636
+ const values = Object.values(serializedRecord);
1637
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1638
+ const { sql, params } = query.build();
1639
+ await this.operations.executeQuery({ sql, params });
1640
+ const scoreFromDb = await this.getScoreById({ id });
1641
+ return { score: scoreFromDb };
1642
+ } catch (error) {
1643
+ throw new MastraError(
1644
+ {
1645
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1646
+ domain: ErrorDomain.STORAGE,
1647
+ category: ErrorCategory.THIRD_PARTY
1648
+ },
1649
+ error
1650
+ );
1651
+ }
1652
+ }
1653
+ async getScoresByScorerId({
1654
+ scorerId,
1655
+ entityId,
1656
+ entityType,
1657
+ source,
1658
+ pagination
1659
+ }) {
1660
+ try {
1661
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1662
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1663
+ if (entityId) {
1664
+ countQuery.andWhere("entityId = ?", entityId);
1665
+ }
1666
+ if (entityType) {
1667
+ countQuery.andWhere("entityType = ?", entityType);
1668
+ }
1669
+ if (source) {
1670
+ countQuery.andWhere("source = ?", source);
1671
+ }
1672
+ const countResult = await this.operations.executeQuery(countQuery.build());
1673
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1674
+ if (total === 0) {
1675
+ return {
1676
+ pagination: {
1677
+ total: 0,
1678
+ page: pagination.page,
1679
+ perPage: pagination.perPage,
1680
+ hasMore: false
1681
+ },
1682
+ scores: []
1683
+ };
1684
+ }
1685
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1686
+ if (entityId) {
1687
+ selectQuery.andWhere("entityId = ?", entityId);
1688
+ }
1689
+ if (entityType) {
1690
+ selectQuery.andWhere("entityType = ?", entityType);
1691
+ }
1692
+ if (source) {
1693
+ selectQuery.andWhere("source = ?", source);
1694
+ }
1695
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1696
+ const { sql, params } = selectQuery.build();
1697
+ const results = await this.operations.executeQuery({ sql, params });
1698
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1699
+ return {
1700
+ pagination: {
1701
+ total,
1702
+ page: pagination.page,
1703
+ perPage: pagination.perPage,
1704
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1705
+ },
1706
+ scores
1707
+ };
1708
+ } catch (error) {
1709
+ throw new MastraError(
1710
+ {
1711
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1712
+ domain: ErrorDomain.STORAGE,
1713
+ category: ErrorCategory.THIRD_PARTY
1714
+ },
1715
+ error
1716
+ );
1717
+ }
1718
+ }
1719
+ async getScoresByRunId({
1720
+ runId,
1721
+ pagination
1722
+ }) {
1723
+ try {
1724
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1725
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1726
+ const countResult = await this.operations.executeQuery(countQuery.build());
1727
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1728
+ if (total === 0) {
1729
+ return {
1730
+ pagination: {
1731
+ total: 0,
1732
+ page: pagination.page,
1733
+ perPage: pagination.perPage,
1734
+ hasMore: false
1735
+ },
1736
+ scores: []
1737
+ };
1738
+ }
1739
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1740
+ const { sql, params } = selectQuery.build();
1741
+ const results = await this.operations.executeQuery({ sql, params });
1742
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1743
+ return {
1744
+ pagination: {
1745
+ total,
1746
+ page: pagination.page,
1747
+ perPage: pagination.perPage,
1748
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1749
+ },
1750
+ scores
1751
+ };
1752
+ } catch (error) {
1753
+ throw new MastraError(
1754
+ {
1755
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1756
+ domain: ErrorDomain.STORAGE,
1757
+ category: ErrorCategory.THIRD_PARTY
1758
+ },
1759
+ error
1760
+ );
1761
+ }
1762
+ }
1763
+ async getScoresByEntityId({
1764
+ entityId,
1765
+ entityType,
1766
+ pagination
1767
+ }) {
1768
+ try {
1769
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1770
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1771
+ const countResult = await this.operations.executeQuery(countQuery.build());
1772
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1773
+ if (total === 0) {
1774
+ return {
1775
+ pagination: {
1776
+ total: 0,
1777
+ page: pagination.page,
1778
+ perPage: pagination.perPage,
1779
+ hasMore: false
1780
+ },
1781
+ scores: []
1782
+ };
1783
+ }
1784
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1785
+ const { sql, params } = selectQuery.build();
1786
+ const results = await this.operations.executeQuery({ sql, params });
1787
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1788
+ return {
1789
+ pagination: {
1790
+ total,
1791
+ page: pagination.page,
1792
+ perPage: pagination.perPage,
1793
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1794
+ },
1795
+ scores
1796
+ };
754
1797
  } catch (error) {
755
- this.logger.error("Error retrieving messages for thread", {
756
- threadId,
757
- message: error instanceof Error ? error.message : String(error)
758
- });
759
- return [];
1798
+ throw new MastraError(
1799
+ {
1800
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1801
+ domain: ErrorDomain.STORAGE,
1802
+ category: ErrorCategory.THIRD_PARTY
1803
+ },
1804
+ error
1805
+ );
760
1806
  }
761
1807
  }
1808
+ async getScoresBySpan({
1809
+ traceId,
1810
+ spanId,
1811
+ pagination
1812
+ }) {
1813
+ try {
1814
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1815
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1816
+ const countResult = await this.operations.executeQuery(countQuery.build());
1817
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1818
+ if (total === 0) {
1819
+ return {
1820
+ pagination: {
1821
+ total: 0,
1822
+ page: pagination.page,
1823
+ perPage: pagination.perPage,
1824
+ hasMore: false
1825
+ },
1826
+ scores: []
1827
+ };
1828
+ }
1829
+ const limit = pagination.perPage + 1;
1830
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1831
+ const { sql, params } = selectQuery.build();
1832
+ const results = await this.operations.executeQuery({ sql, params });
1833
+ const rows = Array.isArray(results) ? results : [];
1834
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1835
+ return {
1836
+ pagination: {
1837
+ total,
1838
+ page: pagination.page,
1839
+ perPage: pagination.perPage,
1840
+ hasMore: rows.length > pagination.perPage
1841
+ },
1842
+ scores
1843
+ };
1844
+ } catch (error) {
1845
+ throw new MastraError(
1846
+ {
1847
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1848
+ domain: ErrorDomain.STORAGE,
1849
+ category: ErrorCategory.THIRD_PARTY
1850
+ },
1851
+ error
1852
+ );
1853
+ }
1854
+ }
1855
+ };
1856
+ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1857
+ operations;
1858
+ constructor({ operations }) {
1859
+ super();
1860
+ this.operations = operations;
1861
+ }
1862
+ updateWorkflowResults({
1863
+ // workflowName,
1864
+ // runId,
1865
+ // stepId,
1866
+ // result,
1867
+ // runtimeContext,
1868
+ }) {
1869
+ throw new Error("Method not implemented.");
1870
+ }
1871
+ updateWorkflowState({
1872
+ // workflowName,
1873
+ // runId,
1874
+ // opts,
1875
+ }) {
1876
+ throw new Error("Method not implemented.");
1877
+ }
762
1878
  async persistWorkflowSnapshot({
763
1879
  workflowName,
764
1880
  runId,
1881
+ resourceId,
765
1882
  snapshot
766
1883
  }) {
767
- const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1884
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
768
1885
  const now = (/* @__PURE__ */ new Date()).toISOString();
769
- const currentSnapshot = await this.load({
1886
+ const currentSnapshot = await this.operations.load({
770
1887
  tableName: TABLE_WORKFLOW_SNAPSHOT,
771
1888
  keys: { workflow_name: workflowName, run_id: runId }
772
1889
  });
773
1890
  const persisting = currentSnapshot ? {
774
1891
  ...currentSnapshot,
1892
+ resourceId,
775
1893
  snapshot: JSON.stringify(snapshot),
776
1894
  updatedAt: now
777
1895
  } : {
778
1896
  workflow_name: workflowName,
779
1897
  run_id: runId,
1898
+ resourceId,
780
1899
  snapshot,
781
1900
  createdAt: now,
782
1901
  updatedAt: now
783
1902
  };
784
- const processedRecord = await this.processRecord(persisting);
1903
+ const processedRecord = await this.operations.processRecord(persisting);
785
1904
  const columns = Object.keys(processedRecord);
786
1905
  const values = Object.values(processedRecord);
787
1906
  const updateMap = {
@@ -792,139 +1911,452 @@ var D1Store = class extends MastraStorage {
792
1911
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
793
1912
  const { sql, params } = query.build();
794
1913
  try {
795
- await this.executeQuery({ sql, params });
1914
+ await this.operations.executeQuery({ sql, params });
796
1915
  } catch (error) {
797
- this.logger.error("Error persisting workflow snapshot:", {
798
- message: error instanceof Error ? error.message : String(error)
799
- });
800
- throw error;
1916
+ throw new MastraError(
1917
+ {
1918
+ id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1919
+ domain: ErrorDomain.STORAGE,
1920
+ category: ErrorCategory.THIRD_PARTY,
1921
+ text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1922
+ details: { workflowName, runId }
1923
+ },
1924
+ error
1925
+ );
801
1926
  }
802
1927
  }
803
1928
  async loadWorkflowSnapshot(params) {
804
1929
  const { workflowName, runId } = params;
805
1930
  this.logger.debug("Loading workflow snapshot", { workflowName, runId });
806
- const d = await this.load({
807
- tableName: TABLE_WORKFLOW_SNAPSHOT,
808
- keys: {
809
- workflow_name: workflowName,
810
- run_id: runId
1931
+ try {
1932
+ const d = await this.operations.load({
1933
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1934
+ keys: {
1935
+ workflow_name: workflowName,
1936
+ run_id: runId
1937
+ }
1938
+ });
1939
+ return d ? d.snapshot : null;
1940
+ } catch (error) {
1941
+ throw new MastraError(
1942
+ {
1943
+ id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1944
+ domain: ErrorDomain.STORAGE,
1945
+ category: ErrorCategory.THIRD_PARTY,
1946
+ text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1947
+ details: { workflowName, runId }
1948
+ },
1949
+ error
1950
+ );
1951
+ }
1952
+ }
1953
+ parseWorkflowRun(row) {
1954
+ let parsedSnapshot = row.snapshot;
1955
+ if (typeof parsedSnapshot === "string") {
1956
+ try {
1957
+ parsedSnapshot = JSON.parse(row.snapshot);
1958
+ } catch (e) {
1959
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
811
1960
  }
812
- });
813
- return d ? d.snapshot : null;
1961
+ }
1962
+ return {
1963
+ workflowName: row.workflow_name,
1964
+ runId: row.run_id,
1965
+ snapshot: parsedSnapshot,
1966
+ createdAt: ensureDate(row.createdAt),
1967
+ updatedAt: ensureDate(row.updatedAt),
1968
+ resourceId: row.resourceId
1969
+ };
814
1970
  }
815
- /**
816
- * Insert multiple records in a batch operation
817
- * @param tableName The table to insert into
818
- * @param records The records to insert
819
- */
820
- async batchInsert({ tableName, records }) {
821
- if (records.length === 0) return;
822
- const fullTableName = this.getTableName(tableName);
1971
+ async getWorkflowRuns({
1972
+ workflowName,
1973
+ fromDate,
1974
+ toDate,
1975
+ limit,
1976
+ offset,
1977
+ resourceId
1978
+ } = {}) {
1979
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
823
1980
  try {
824
- const batchSize = 50;
825
- for (let i = 0; i < records.length; i += batchSize) {
826
- const batch = records.slice(i, i + batchSize);
827
- const recordsToInsert = batch;
828
- if (recordsToInsert.length > 0) {
829
- const firstRecord = recordsToInsert[0];
830
- const columns = Object.keys(firstRecord || {});
831
- for (const record of recordsToInsert) {
832
- const values = columns.map((col) => {
833
- if (!record) return null;
834
- const value = typeof col === "string" ? record[col] : null;
835
- return this.serializeValue(value);
836
- });
837
- const query = createSqlBuilder().insert(fullTableName, columns, values);
838
- const { sql, params } = query.build();
839
- await this.executeQuery({ sql, params });
840
- }
1981
+ const builder = createSqlBuilder().select().from(fullTableName);
1982
+ const countBuilder = createSqlBuilder().count().from(fullTableName);
1983
+ if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
1984
+ if (resourceId) {
1985
+ const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
1986
+ if (hasResourceId) {
1987
+ builder.whereAnd("resourceId = ?", resourceId);
1988
+ countBuilder.whereAnd("resourceId = ?", resourceId);
1989
+ } else {
1990
+ console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
841
1991
  }
842
- this.logger.debug(
843
- `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
844
- );
845
1992
  }
846
- this.logger.debug(`Successfully batch inserted ${records.length} records into ${tableName}`);
1993
+ if (fromDate) {
1994
+ builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
1995
+ countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
1996
+ }
1997
+ if (toDate) {
1998
+ builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
1999
+ countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2000
+ }
2001
+ builder.orderBy("createdAt", "DESC");
2002
+ if (typeof limit === "number") builder.limit(limit);
2003
+ if (typeof offset === "number") builder.offset(offset);
2004
+ const { sql, params } = builder.build();
2005
+ let total = 0;
2006
+ if (limit !== void 0 && offset !== void 0) {
2007
+ const { sql: countSql, params: countParams } = countBuilder.build();
2008
+ const countResult = await this.operations.executeQuery({
2009
+ sql: countSql,
2010
+ params: countParams,
2011
+ first: true
2012
+ });
2013
+ total = Number(countResult?.count ?? 0);
2014
+ }
2015
+ const results = await this.operations.executeQuery({ sql, params });
2016
+ const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
2017
+ return { runs, total: total || runs.length };
847
2018
  } catch (error) {
848
- this.logger.error(`Error batch inserting into ${tableName}:`, {
849
- message: error instanceof Error ? error.message : String(error)
850
- });
851
- throw new Error(`Failed to batch insert into ${tableName}: ${error}`);
2019
+ throw new MastraError(
2020
+ {
2021
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
2022
+ domain: ErrorDomain.STORAGE,
2023
+ category: ErrorCategory.THIRD_PARTY,
2024
+ text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
2025
+ details: {
2026
+ workflowName: workflowName ?? "",
2027
+ resourceId: resourceId ?? ""
2028
+ }
2029
+ },
2030
+ error
2031
+ );
852
2032
  }
853
2033
  }
854
- async getTraces({
855
- name,
856
- scope,
857
- page,
858
- perPage,
859
- attributes
2034
+ async getWorkflowRunById({
2035
+ runId,
2036
+ workflowName
860
2037
  }) {
861
- const fullTableName = this.getTableName(TABLE_TRACES);
2038
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
862
2039
  try {
863
- const query = createSqlBuilder().select("*").from(fullTableName).where("1=1");
864
- if (name) {
865
- query.andWhere("name LIKE ?", `%${name}%`);
2040
+ const conditions = [];
2041
+ const params = [];
2042
+ if (runId) {
2043
+ conditions.push("run_id = ?");
2044
+ params.push(runId);
866
2045
  }
867
- if (scope) {
868
- query.andWhere("scope = ?", scope);
2046
+ if (workflowName) {
2047
+ conditions.push("workflow_name = ?");
2048
+ params.push(workflowName);
869
2049
  }
870
- if (attributes && Object.keys(attributes).length > 0) {
871
- for (const [key, value] of Object.entries(attributes)) {
872
- query.jsonLike("attributes", key, value);
873
- }
874
- }
875
- query.orderBy("startTime", "DESC").limit(perPage).offset((page - 1) * perPage);
876
- const { sql, params } = query.build();
877
- const results = await this.executeQuery({ sql, params });
878
- return isArrayOfRecords(results) ? results.map((trace) => ({
879
- ...trace,
880
- attributes: this.deserializeValue(trace.attributes, "jsonb"),
881
- status: this.deserializeValue(trace.status, "jsonb"),
882
- events: this.deserializeValue(trace.events, "jsonb"),
883
- links: this.deserializeValue(trace.links, "jsonb"),
884
- other: this.deserializeValue(trace.other, "jsonb")
885
- })) : [];
886
- } catch (error) {
887
- this.logger.error("Error getting traces:", { message: error instanceof Error ? error.message : String(error) });
888
- return [];
2050
+ const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
2051
+ const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
2052
+ const result = await this.operations.executeQuery({ sql, params, first: true });
2053
+ if (!result) return null;
2054
+ return this.parseWorkflowRun(result);
2055
+ } catch (error) {
2056
+ throw new MastraError(
2057
+ {
2058
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
2059
+ domain: ErrorDomain.STORAGE,
2060
+ category: ErrorCategory.THIRD_PARTY,
2061
+ text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2062
+ details: { runId, workflowName: workflowName ?? "" }
2063
+ },
2064
+ error
2065
+ );
889
2066
  }
890
2067
  }
891
- async getEvalsByAgentName(agentName, type) {
892
- const fullTableName = this.getTableName(TABLE_EVALS);
2068
+ };
2069
+
2070
+ // src/storage/index.ts
2071
+ var D1Store = class extends MastraStorage {
2072
+ client;
2073
+ binding;
2074
+ // D1Database binding
2075
+ tablePrefix;
2076
+ stores;
2077
+ /**
2078
+ * Creates a new D1Store instance
2079
+ * @param config Configuration for D1 access (either REST API or Workers Binding API)
2080
+ */
2081
+ constructor(config) {
893
2082
  try {
894
- let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
895
- if (type === "test") {
896
- query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
897
- } else if (type === "live") {
898
- query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
2083
+ super({ name: "D1" });
2084
+ if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2085
+ throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
899
2086
  }
900
- query.orderBy("created_at", "DESC");
901
- const { sql, params } = query.build();
902
- const results = await this.executeQuery({ sql, params });
903
- return isArrayOfRecords(results) ? results.map((row) => {
904
- const result = this.deserializeValue(row.result);
905
- const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
906
- return {
907
- input: row.input || "",
908
- output: row.output || "",
909
- result,
910
- agentName: row.agent_name || "",
911
- metricName: row.metric_name || "",
912
- instructions: row.instructions || "",
913
- runId: row.run_id || "",
914
- globalRunId: row.global_run_id || "",
915
- createdAt: row.created_at || "",
916
- testInfo
2087
+ this.tablePrefix = config.tablePrefix || "";
2088
+ if ("binding" in config) {
2089
+ if (!config.binding) {
2090
+ throw new Error("D1 binding is required when using Workers Binding API");
2091
+ }
2092
+ this.binding = config.binding;
2093
+ this.logger.info("Using D1 Workers Binding API");
2094
+ } else if ("client" in config) {
2095
+ if (!config.client) {
2096
+ throw new Error("D1 client is required when using D1ClientConfig");
2097
+ }
2098
+ this.client = config.client;
2099
+ this.logger.info("Using D1 Client");
2100
+ } else {
2101
+ if (!config.accountId || !config.databaseId || !config.apiToken) {
2102
+ throw new Error("accountId, databaseId, and apiToken are required when using REST API");
2103
+ }
2104
+ const cfClient = new Cloudflare({
2105
+ apiToken: config.apiToken
2106
+ });
2107
+ this.client = {
2108
+ query: ({ sql, params }) => {
2109
+ return cfClient.d1.database.query(config.databaseId, {
2110
+ account_id: config.accountId,
2111
+ sql,
2112
+ params
2113
+ });
2114
+ }
917
2115
  };
918
- }) : [];
2116
+ this.logger.info("Using D1 REST API");
2117
+ }
919
2118
  } catch (error) {
920
- this.logger.error(`Error getting evals for agent ${agentName}:`, {
921
- message: error instanceof Error ? error.message : String(error)
922
- });
923
- return [];
2119
+ throw new MastraError(
2120
+ {
2121
+ id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
2122
+ domain: ErrorDomain.STORAGE,
2123
+ category: ErrorCategory.SYSTEM,
2124
+ text: "Error initializing D1Store"
2125
+ },
2126
+ error
2127
+ );
924
2128
  }
2129
+ const operations = new StoreOperationsD1({
2130
+ client: this.client,
2131
+ binding: this.binding,
2132
+ tablePrefix: this.tablePrefix
2133
+ });
2134
+ const scores = new ScoresStorageD1({
2135
+ operations
2136
+ });
2137
+ const legacyEvals = new LegacyEvalsStorageD1({
2138
+ operations
2139
+ });
2140
+ const workflows = new WorkflowsStorageD1({
2141
+ operations
2142
+ });
2143
+ const memory = new MemoryStorageD1({
2144
+ operations
2145
+ });
2146
+ this.stores = {
2147
+ operations,
2148
+ scores,
2149
+ legacyEvals,
2150
+ workflows,
2151
+ memory
2152
+ };
925
2153
  }
926
- getWorkflowRuns(_args) {
927
- throw new Error("Method not implemented.");
2154
+ get supports() {
2155
+ return {
2156
+ selectByIncludeResourceScope: true,
2157
+ resourceWorkingMemory: true,
2158
+ hasColumn: true,
2159
+ createTable: true,
2160
+ deleteMessages: false,
2161
+ getScoresBySpan: true
2162
+ };
2163
+ }
2164
+ async createTable({
2165
+ tableName,
2166
+ schema
2167
+ }) {
2168
+ return this.stores.operations.createTable({ tableName, schema });
2169
+ }
2170
+ /**
2171
+ * Alters table schema to add columns if they don't exist
2172
+ * @param tableName Name of the table
2173
+ * @param schema Schema of the table
2174
+ * @param ifNotExists Array of column names to add if they don't exist
2175
+ */
2176
+ async alterTable({
2177
+ tableName,
2178
+ schema,
2179
+ ifNotExists
2180
+ }) {
2181
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2182
+ }
2183
+ async clearTable({ tableName }) {
2184
+ return this.stores.operations.clearTable({ tableName });
2185
+ }
2186
+ async dropTable({ tableName }) {
2187
+ return this.stores.operations.dropTable({ tableName });
2188
+ }
2189
+ async hasColumn(table, column) {
2190
+ return this.stores.operations.hasColumn(table, column);
2191
+ }
2192
+ async insert({ tableName, record }) {
2193
+ return this.stores.operations.insert({ tableName, record });
2194
+ }
2195
+ async load({ tableName, keys }) {
2196
+ return this.stores.operations.load({ tableName, keys });
2197
+ }
2198
+ async getThreadById({ threadId }) {
2199
+ return this.stores.memory.getThreadById({ threadId });
2200
+ }
2201
+ /**
2202
+ * @deprecated use getThreadsByResourceIdPaginated instead
2203
+ */
2204
+ async getThreadsByResourceId({ resourceId }) {
2205
+ return this.stores.memory.getThreadsByResourceId({ resourceId });
2206
+ }
2207
+ async getThreadsByResourceIdPaginated(args) {
2208
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2209
+ }
2210
+ async saveThread({ thread }) {
2211
+ return this.stores.memory.saveThread({ thread });
2212
+ }
2213
+ async updateThread({
2214
+ id,
2215
+ title,
2216
+ metadata
2217
+ }) {
2218
+ return this.stores.memory.updateThread({ id, title, metadata });
2219
+ }
2220
+ async deleteThread({ threadId }) {
2221
+ return this.stores.memory.deleteThread({ threadId });
2222
+ }
2223
+ async saveMessages(args) {
2224
+ return this.stores.memory.saveMessages(args);
2225
+ }
2226
+ async getMessages({
2227
+ threadId,
2228
+ selectBy,
2229
+ format
2230
+ }) {
2231
+ return this.stores.memory.getMessages({ threadId, selectBy, format });
2232
+ }
2233
+ async getMessagesById({
2234
+ messageIds,
2235
+ format
2236
+ }) {
2237
+ return this.stores.memory.getMessagesById({ messageIds, format });
2238
+ }
2239
+ async getMessagesPaginated({
2240
+ threadId,
2241
+ selectBy,
2242
+ format
2243
+ }) {
2244
+ return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2245
+ }
2246
+ async updateWorkflowResults({
2247
+ workflowName,
2248
+ runId,
2249
+ stepId,
2250
+ result,
2251
+ runtimeContext
2252
+ }) {
2253
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2254
+ }
2255
+ async updateWorkflowState({
2256
+ workflowName,
2257
+ runId,
2258
+ opts
2259
+ }) {
2260
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2261
+ }
2262
+ async persistWorkflowSnapshot({
2263
+ workflowName,
2264
+ runId,
2265
+ resourceId,
2266
+ snapshot
2267
+ }) {
2268
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2269
+ }
2270
+ async loadWorkflowSnapshot(params) {
2271
+ return this.stores.workflows.loadWorkflowSnapshot(params);
2272
+ }
2273
+ async getWorkflowRuns({
2274
+ workflowName,
2275
+ fromDate,
2276
+ toDate,
2277
+ limit,
2278
+ offset,
2279
+ resourceId
2280
+ } = {}) {
2281
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2282
+ }
2283
+ async getWorkflowRunById({
2284
+ runId,
2285
+ workflowName
2286
+ }) {
2287
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2288
+ }
2289
+ /**
2290
+ * Insert multiple records in a batch operation
2291
+ * @param tableName The table to insert into
2292
+ * @param records The records to insert
2293
+ */
2294
+ async batchInsert({ tableName, records }) {
2295
+ return this.stores.operations.batchInsert({ tableName, records });
2296
+ }
2297
+ /**
2298
+ * @deprecated use getEvals instead
2299
+ */
2300
+ async getEvalsByAgentName(agentName, type) {
2301
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2302
+ }
2303
+ async getEvals(options) {
2304
+ return this.stores.legacyEvals.getEvals(options);
2305
+ }
2306
+ async updateMessages(_args) {
2307
+ return this.stores.memory.updateMessages(_args);
2308
+ }
2309
+ async getResourceById({ resourceId }) {
2310
+ return this.stores.memory.getResourceById({ resourceId });
2311
+ }
2312
+ async saveResource({ resource }) {
2313
+ return this.stores.memory.saveResource({ resource });
2314
+ }
2315
+ async updateResource({
2316
+ resourceId,
2317
+ workingMemory,
2318
+ metadata
2319
+ }) {
2320
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2321
+ }
2322
+ async getScoreById({ id: _id }) {
2323
+ return this.stores.scores.getScoreById({ id: _id });
2324
+ }
2325
+ async saveScore(_score) {
2326
+ return this.stores.scores.saveScore(_score);
2327
+ }
2328
+ async getScoresByRunId({
2329
+ runId: _runId,
2330
+ pagination: _pagination
2331
+ }) {
2332
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2333
+ }
2334
+ async getScoresByEntityId({
2335
+ entityId: _entityId,
2336
+ entityType: _entityType,
2337
+ pagination: _pagination
2338
+ }) {
2339
+ return this.stores.scores.getScoresByEntityId({
2340
+ entityId: _entityId,
2341
+ entityType: _entityType,
2342
+ pagination: _pagination
2343
+ });
2344
+ }
2345
+ async getScoresByScorerId({
2346
+ scorerId,
2347
+ pagination,
2348
+ entityId,
2349
+ entityType,
2350
+ source
2351
+ }) {
2352
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2353
+ }
2354
+ async getScoresBySpan({
2355
+ traceId,
2356
+ spanId,
2357
+ pagination
2358
+ }) {
2359
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
928
2360
  }
929
2361
  /**
930
2362
  * Close the database connection
@@ -936,3 +2368,5 @@ var D1Store = class extends MastraStorage {
936
2368
  };
937
2369
 
938
2370
  export { D1Store };
2371
+ //# sourceMappingURL=index.js.map
2372
+ //# sourceMappingURL=index.js.map