@mastra/cloudflare-d1 0.0.0-pg-pool-options-20250428183821 → 0.0.0-rag-chunk-extract-llm-option-20250926183645

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