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