@mastra/cloudflare-d1 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-scorers-api-v2-20250801171841

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