@mastra/cloudflare-d1 0.0.0-vnext-inngest-20250508131921 → 0.0.0-vnext-20251104230439

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