@mastra/cloudflare-d1 0.0.0-remove-unused-import-20250909212718 → 0.0.0-remove-ai-peer-dep-from-evals-20260105220639

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