@mastra/cloudflare-d1 0.0.0-tsconfig-compile-20250703214351 → 0.0.0-unified-sidebar-20251010130811

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