@mastra/cloudflare-d1 0.0.0-vector-query-sources-20250516172905 → 0.0.0-vector-query-tool-provider-options-20250828222356

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