@mastra/cloudflare 1.5.1 → 1.6.0

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.
@@ -1,2442 +0,0 @@
1
- import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { createStorageErrorId, getSqlType, getDefaultValue, BackgroundTasksStorage, TABLE_SCHEMAS, TABLE_BACKGROUND_TASKS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ensureDate, normalizePerPage, calculatePagination, serializeDate, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
- import { MastraBase } from '@mastra/core/base';
4
- import { parseSqlIdentifier } from '@mastra/core/utils';
5
- import { MessageList } from '@mastra/core/agent';
6
- import { saveScorePayloadSchema } from '@mastra/core/evals';
7
-
8
- // src/do/index.ts
9
-
10
- // src/do/storage/domains/utils.ts
11
- function isArrayOfRecords(value) {
12
- return value !== null && value !== void 0 && Array.isArray(value);
13
- }
14
- function deserializeValue(value, type) {
15
- if (value === null || value === void 0) return null;
16
- if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
17
- try {
18
- return JSON.parse(value);
19
- } catch {
20
- return value;
21
- }
22
- }
23
- return value;
24
- }
25
- var SqlBuilder = class {
26
- sql = "";
27
- params = [];
28
- whereAdded = false;
29
- // Basic query building
30
- select(columns) {
31
- if (!columns || Array.isArray(columns) && columns.length === 0) {
32
- this.sql = "SELECT *";
33
- } else {
34
- const cols = Array.isArray(columns) ? columns : [columns];
35
- const parsedCols = cols.map((col) => parseSelectIdentifier(col));
36
- this.sql = `SELECT ${parsedCols.join(", ")}`;
37
- }
38
- return this;
39
- }
40
- from(table) {
41
- const parsedTableName = parseSqlIdentifier(table, "table name");
42
- this.sql += ` FROM ${parsedTableName}`;
43
- return this;
44
- }
45
- /**
46
- * Add a WHERE clause to the query
47
- * @param condition The condition to add
48
- * @param params Parameters to bind to the condition
49
- */
50
- where(condition, ...params) {
51
- this.sql += ` WHERE ${condition}`;
52
- this.params.push(...params);
53
- this.whereAdded = true;
54
- return this;
55
- }
56
- /**
57
- * Add a WHERE clause if it hasn't been added yet, otherwise add an AND clause
58
- * @param condition The condition to add
59
- * @param params Parameters to bind to the condition
60
- */
61
- whereAnd(condition, ...params) {
62
- if (this.whereAdded) {
63
- return this.andWhere(condition, ...params);
64
- } else {
65
- return this.where(condition, ...params);
66
- }
67
- }
68
- andWhere(condition, ...params) {
69
- this.sql += ` AND ${condition}`;
70
- this.params.push(...params);
71
- return this;
72
- }
73
- orWhere(condition, ...params) {
74
- this.sql += ` OR ${condition}`;
75
- this.params.push(...params);
76
- return this;
77
- }
78
- orderBy(column, direction = "ASC") {
79
- const parsedColumn = parseSqlIdentifier(column, "column name");
80
- if (!["ASC", "DESC"].includes(direction)) {
81
- throw new Error(`Invalid sort direction: ${direction}`);
82
- }
83
- this.sql += ` ORDER BY ${parsedColumn} ${direction}`;
84
- return this;
85
- }
86
- limit(count) {
87
- this.sql += ` LIMIT ?`;
88
- this.params.push(count);
89
- return this;
90
- }
91
- offset(count) {
92
- this.sql += ` OFFSET ?`;
93
- this.params.push(count);
94
- return this;
95
- }
96
- count() {
97
- this.sql += "SELECT COUNT(*) AS count";
98
- return this;
99
- }
100
- /**
101
- * Insert a row, or update specific columns on conflict (upsert).
102
- * @param table Table name
103
- * @param columns Columns to insert
104
- * @param values Values to insert
105
- * @param conflictColumns Columns to check for conflict (usually PK or UNIQUE)
106
- * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
107
- */
108
- insert(table, columns, values, conflictColumns, updateMap) {
109
- const parsedTableName = parseSqlIdentifier(table, "table name");
110
- const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
111
- const placeholders = parsedColumns.map(() => "?").join(", ");
112
- if (conflictColumns && updateMap) {
113
- const parsedConflictColumns = conflictColumns.map((col) => parseSqlIdentifier(col, "column name"));
114
- const excludedPattern = /^excluded\.[a-zA-Z_][a-zA-Z0-9_]*$/;
115
- const coalescePattern = /^COALESCE\(excluded\.[a-zA-Z_][a-zA-Z0-9_]*,\s*[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*\)$/;
116
- const updateClause = Object.entries(updateMap).map(([col, expr]) => {
117
- const parsedCol = parseSqlIdentifier(col, "update column name");
118
- if (!excludedPattern.test(expr) && !coalescePattern.test(expr)) {
119
- throw new Error(
120
- `Invalid update expression for column ${col}: must be 'excluded.<column>' or 'COALESCE(excluded.<column>, <table>.<column>)' pattern`
121
- );
122
- }
123
- return `${parsedCol} = ${expr}`;
124
- }).join(", ");
125
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
126
- this.params.push(...values);
127
- return this;
128
- }
129
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
130
- this.params.push(...values);
131
- return this;
132
- }
133
- // Update operations
134
- update(table, columns, values) {
135
- const parsedTableName = parseSqlIdentifier(table, "table name");
136
- const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
137
- const setClause = parsedColumns.map((col) => `${col} = ?`).join(", ");
138
- this.sql = `UPDATE ${parsedTableName} SET ${setClause}`;
139
- this.params.push(...values);
140
- return this;
141
- }
142
- // Delete operations
143
- delete(table) {
144
- const parsedTableName = parseSqlIdentifier(table, "table name");
145
- this.sql = `DELETE FROM ${parsedTableName}`;
146
- return this;
147
- }
148
- /**
149
- * Create a table if it doesn't exist
150
- * @param table The table name
151
- * @param columnDefinitions The column definitions as an array of strings
152
- * @param tableConstraints Optional constraints for the table
153
- * @returns The builder instance
154
- */
155
- createTable(table, columnDefinitions, tableConstraints) {
156
- const parsedTableName = parseSqlIdentifier(table, "table name");
157
- const parsedColumnDefinitions = columnDefinitions.map((def) => {
158
- const colName = def.split(/\s+/)[0];
159
- if (!colName) throw new Error("Empty column name in definition");
160
- parseSqlIdentifier(colName, "column name");
161
- return def;
162
- });
163
- const columns = parsedColumnDefinitions.join(", ");
164
- let constraints = "";
165
- if (tableConstraints && tableConstraints.length > 0) {
166
- const constraintPattern = /^(PRIMARY\s+KEY|UNIQUE|FOREIGN\s+KEY|CHECK)\s*\([a-zA-Z0-9_,\s]+\)$/i;
167
- for (const constraint of tableConstraints) {
168
- if (!constraintPattern.test(constraint.trim())) {
169
- throw new Error(`Invalid table constraint: ${constraint}`);
170
- }
171
- }
172
- constraints = ", " + tableConstraints.join(", ");
173
- }
174
- this.sql = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns}${constraints})`;
175
- return this;
176
- }
177
- /**
178
- * Check if an index exists in the database
179
- * @param indexName The name of the index to check
180
- * @param tableName The table the index is on
181
- * @returns The builder instance
182
- */
183
- checkIndexExists(indexName, tableName) {
184
- this.sql = `SELECT name FROM sqlite_master WHERE type='index' AND name=? AND tbl_name=?`;
185
- this.params.push(indexName, tableName);
186
- return this;
187
- }
188
- /**
189
- * Create an index if it doesn't exist
190
- * @param indexName The name of the index to create
191
- * @param tableName The table to create the index on
192
- * @param columnName The column to index
193
- * @param indexType Optional index type (e.g., 'UNIQUE')
194
- * @returns The builder instance
195
- */
196
- createIndex(indexName, tableName, columnName, indexType = "") {
197
- const parsedIndexName = parseSqlIdentifier(indexName, "index name");
198
- const parsedTableName = parseSqlIdentifier(tableName, "table name");
199
- const parsedColumnName = parseSqlIdentifier(columnName, "column name");
200
- const allowedIndexTypes = ["", "UNIQUE"];
201
- const normalizedIndexType = indexType.toUpperCase().trim();
202
- if (!allowedIndexTypes.includes(normalizedIndexType)) {
203
- throw new Error(
204
- `Invalid index type: ${indexType}. Allowed values: ${allowedIndexTypes.filter((t) => t).join(", ")}`
205
- );
206
- }
207
- this.sql = `CREATE ${normalizedIndexType ? normalizedIndexType + " " : ""}INDEX IF NOT EXISTS ${parsedIndexName} ON ${parsedTableName}(${parsedColumnName})`;
208
- return this;
209
- }
210
- /**
211
- * Add a LIKE condition to the query
212
- * @param column The column to check
213
- * @param value The value to match (will be wrapped with % for LIKE)
214
- * @param exact If true, will not add % wildcards
215
- */
216
- like(column, value, exact = false) {
217
- const parsedColumnName = parseSqlIdentifier(column, "column name");
218
- const likeValue = exact ? value : `%${value}%`;
219
- if (this.whereAdded) {
220
- this.sql += ` AND ${parsedColumnName} LIKE ?`;
221
- } else {
222
- this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
223
- this.whereAdded = true;
224
- }
225
- this.params.push(likeValue);
226
- return this;
227
- }
228
- /**
229
- * Add a JSON LIKE condition for searching in JSON fields
230
- * @param column The JSON column to search in
231
- * @param key The JSON key to match
232
- * @param value The value to match
233
- */
234
- jsonLike(column, key, value) {
235
- const parsedColumnName = parseSqlIdentifier(column, "column name");
236
- const parsedKey = parseSqlIdentifier(key, "key name");
237
- const jsonPattern = `%"${parsedKey}":"${value}"%`;
238
- if (this.whereAdded) {
239
- this.sql += ` AND ${parsedColumnName} LIKE ?`;
240
- } else {
241
- this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
242
- this.whereAdded = true;
243
- }
244
- this.params.push(jsonPattern);
245
- return this;
246
- }
247
- /**
248
- * Get the built query
249
- * @returns Object containing the SQL string and parameters array
250
- */
251
- build() {
252
- return {
253
- sql: this.sql,
254
- params: this.params
255
- };
256
- }
257
- /**
258
- * Reset the builder for reuse
259
- * @returns The reset builder instance
260
- */
261
- reset() {
262
- this.sql = "";
263
- this.params = [];
264
- this.whereAdded = false;
265
- return this;
266
- }
267
- };
268
- function createSqlBuilder() {
269
- return new SqlBuilder();
270
- }
271
- var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_]+(\s+AS\s+[a-zA-Z0-9_]+)?$/;
272
- function parseSelectIdentifier(column) {
273
- if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) {
274
- throw new Error(
275
- `Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`
276
- );
277
- }
278
- return column;
279
- }
280
-
281
- // src/do/storage/db/index.ts
282
- var DODB = class extends MastraBase {
283
- sql;
284
- tablePrefix;
285
- constructor(config) {
286
- super({
287
- component: "STORAGE",
288
- name: "DO_DB"
289
- });
290
- this.sql = config.sql;
291
- this.tablePrefix = config.tablePrefix || "";
292
- }
293
- async hasColumn(table, column) {
294
- const identifierPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
295
- if (!identifierPattern.test(table)) {
296
- throw new Error(`Invalid table name: ${table}`);
297
- }
298
- if (!identifierPattern.test(column)) {
299
- throw new Error(`Invalid column name: ${column}`);
300
- }
301
- if (this.tablePrefix && !identifierPattern.test(this.tablePrefix)) {
302
- throw new Error(`Invalid table prefix: ${this.tablePrefix}`);
303
- }
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);
315
- }
316
- /**
317
- * Execute a SQL query using Durable Objects SqlStorage.
318
- * SqlStorage.exec() is synchronous but we wrap in Promise for interface compatibility.
319
- */
320
- async executeQuery(options) {
321
- const { sql, params = [], first = false } = options;
322
- try {
323
- const formattedParams = this.formatSqlParams(params);
324
- const cursor = this.sql.exec(sql, ...formattedParams);
325
- if (first) {
326
- const rows = cursor.toArray();
327
- return rows[0] || null;
328
- }
329
- return cursor.toArray();
330
- } catch (error) {
331
- throw new MastraError(
332
- {
333
- id: createStorageErrorId("CLOUDFLARE_DO", "QUERY", "FAILED"),
334
- domain: ErrorDomain.STORAGE,
335
- category: ErrorCategory.THIRD_PARTY,
336
- details: { sql }
337
- },
338
- error
339
- );
340
- }
341
- }
342
- async getTableColumns(tableName) {
343
- const identifierPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
344
- if (!identifierPattern.test(tableName)) {
345
- this.logger.warn(`Invalid table name in getTableColumns: ${tableName}`);
346
- return [];
347
- }
348
- try {
349
- const sql = `PRAGMA table_info(${tableName})`;
350
- const result = await this.executeQuery({ sql });
351
- if (!result || !Array.isArray(result)) {
352
- return [];
353
- }
354
- return result.map((row) => ({
355
- name: row.name,
356
- type: row.type
357
- }));
358
- } catch (error) {
359
- this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
360
- return [];
361
- }
362
- }
363
- serializeValue(value) {
364
- if (value === null || value === void 0) {
365
- return null;
366
- }
367
- if (value instanceof Date) {
368
- return value.toISOString();
369
- }
370
- if (typeof value === "object") {
371
- return JSON.stringify(value);
372
- }
373
- return value;
374
- }
375
- getSqlType(type) {
376
- switch (type) {
377
- case "bigint":
378
- return "INTEGER";
379
- // SQLite uses INTEGER for all integer sizes
380
- case "jsonb":
381
- return "TEXT";
382
- // Store JSON as TEXT in SQLite
383
- case "boolean":
384
- return "INTEGER";
385
- // SQLite uses 0/1 for booleans
386
- default:
387
- return getSqlType(type);
388
- }
389
- }
390
- getDefaultValue(type) {
391
- return getDefaultValue(type);
392
- }
393
- async createTable({
394
- tableName,
395
- schema
396
- }) {
397
- try {
398
- const fullTableName = this.getTableName(tableName);
399
- const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
400
- const type = this.getSqlType(colDef.type);
401
- const nullable = colDef.nullable === false ? "NOT NULL" : "";
402
- const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
403
- return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
404
- });
405
- const tableConstraints = [];
406
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
407
- tableConstraints.push("UNIQUE (workflow_name, run_id)");
408
- }
409
- const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
410
- const { sql, params } = query.build();
411
- await this.executeQuery({ sql, params });
412
- this.logger.debug(`Created table ${fullTableName}`);
413
- } catch (error) {
414
- throw new MastraError(
415
- {
416
- id: createStorageErrorId("CLOUDFLARE_DO", "CREATE_TABLE", "FAILED"),
417
- domain: ErrorDomain.STORAGE,
418
- category: ErrorCategory.THIRD_PARTY,
419
- details: { tableName }
420
- },
421
- error
422
- );
423
- }
424
- }
425
- async clearTable({ tableName }) {
426
- try {
427
- const fullTableName = this.getTableName(tableName);
428
- const query = createSqlBuilder().delete(fullTableName);
429
- const { sql, params } = query.build();
430
- await this.executeQuery({ sql, params });
431
- this.logger.debug(`Cleared table ${fullTableName}`);
432
- } catch (error) {
433
- throw new MastraError(
434
- {
435
- id: createStorageErrorId("CLOUDFLARE_DO", "CLEAR_TABLE", "FAILED"),
436
- domain: ErrorDomain.STORAGE,
437
- category: ErrorCategory.THIRD_PARTY,
438
- details: { tableName }
439
- },
440
- error
441
- );
442
- }
443
- }
444
- async dropTable({ tableName }) {
445
- try {
446
- const fullTableName = this.getTableName(tableName);
447
- const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
448
- await this.executeQuery({ sql });
449
- this.logger.debug(`Dropped table ${fullTableName}`);
450
- } catch (error) {
451
- throw new MastraError(
452
- {
453
- id: createStorageErrorId("CLOUDFLARE_DO", "DROP_TABLE", "FAILED"),
454
- domain: ErrorDomain.STORAGE,
455
- category: ErrorCategory.THIRD_PARTY,
456
- details: { tableName }
457
- },
458
- error
459
- );
460
- }
461
- }
462
- async alterTable(args) {
463
- const identifierPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
464
- try {
465
- const fullTableName = this.getTableName(args.tableName);
466
- if (!identifierPattern.test(fullTableName)) {
467
- throw new Error(`Invalid table name: ${fullTableName}`);
468
- }
469
- const existingColumns = await this.getTableColumns(fullTableName);
470
- const existingColumnNames = new Set(existingColumns.map((col) => col.name));
471
- for (const [columnName, column] of Object.entries(args.schema)) {
472
- if (!identifierPattern.test(columnName)) {
473
- throw new Error(`Invalid column name: ${columnName}`);
474
- }
475
- if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
476
- const sqlType = this.getSqlType(column.type);
477
- const defaultValue = this.getDefaultValue(column.type);
478
- const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
479
- await this.executeQuery({ sql });
480
- this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
481
- }
482
- }
483
- } catch (error) {
484
- throw new MastraError(
485
- {
486
- id: createStorageErrorId("CLOUDFLARE_DO", "ALTER_TABLE", "FAILED"),
487
- domain: ErrorDomain.STORAGE,
488
- category: ErrorCategory.THIRD_PARTY,
489
- details: { tableName: args.tableName }
490
- },
491
- error
492
- );
493
- }
494
- }
495
- async insert({ tableName, record }) {
496
- try {
497
- const fullTableName = this.getTableName(tableName);
498
- const processedRecord = await this.processRecord(record);
499
- const columns = Object.keys(processedRecord);
500
- const values = Object.values(processedRecord);
501
- const query = createSqlBuilder().insert(fullTableName, columns, values);
502
- const { sql, params } = query.build();
503
- await this.executeQuery({ sql, params });
504
- } catch (error) {
505
- throw new MastraError(
506
- {
507
- id: createStorageErrorId("CLOUDFLARE_DO", "INSERT", "FAILED"),
508
- domain: ErrorDomain.STORAGE,
509
- category: ErrorCategory.THIRD_PARTY,
510
- details: { tableName }
511
- },
512
- error
513
- );
514
- }
515
- }
516
- async batchInsert({
517
- tableName,
518
- records
519
- }) {
520
- try {
521
- if (records.length === 0) return;
522
- const fullTableName = this.getTableName(tableName);
523
- const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
524
- const columns = Object.keys(processedRecords[0] || {});
525
- for (const record of processedRecords) {
526
- const values = Object.values(record);
527
- const query = createSqlBuilder().insert(fullTableName, columns, values);
528
- const { sql, params } = query.build();
529
- await this.executeQuery({ sql, params });
530
- }
531
- } catch (error) {
532
- throw new MastraError(
533
- {
534
- id: createStorageErrorId("CLOUDFLARE_DO", "BATCH_INSERT", "FAILED"),
535
- domain: ErrorDomain.STORAGE,
536
- category: ErrorCategory.THIRD_PARTY,
537
- details: { tableName }
538
- },
539
- error
540
- );
541
- }
542
- }
543
- async load({
544
- tableName,
545
- keys,
546
- orderBy
547
- }) {
548
- try {
549
- const fullTableName = this.getTableName(tableName);
550
- const query = createSqlBuilder().select("*").from(fullTableName);
551
- let firstKey = true;
552
- for (const [key, value] of Object.entries(keys)) {
553
- if (firstKey) {
554
- query.where(`${key} = ?`, value);
555
- firstKey = false;
556
- } else {
557
- query.andWhere(`${key} = ?`, value);
558
- }
559
- }
560
- if (orderBy) {
561
- query.orderBy(orderBy.column, orderBy.direction);
562
- }
563
- query.limit(1);
564
- const { sql, params } = query.build();
565
- const result = await this.executeQuery({ sql, params, first: true });
566
- if (!result) {
567
- return null;
568
- }
569
- const deserializedResult = {};
570
- for (const [key, value] of Object.entries(result)) {
571
- deserializedResult[key] = deserializeValue(value);
572
- }
573
- return deserializedResult;
574
- } catch (error) {
575
- throw new MastraError(
576
- {
577
- id: createStorageErrorId("CLOUDFLARE_DO", "LOAD", "FAILED"),
578
- domain: ErrorDomain.STORAGE,
579
- category: ErrorCategory.THIRD_PARTY,
580
- details: { tableName }
581
- },
582
- error
583
- );
584
- }
585
- }
586
- async processRecord(record) {
587
- const processed = {};
588
- for (const [key, value] of Object.entries(record)) {
589
- processed[key] = this.serializeValue(value);
590
- }
591
- return processed;
592
- }
593
- /**
594
- * Upsert multiple records in a batch operation
595
- * @param tableName The table to insert into
596
- * @param records The records to insert
597
- * @param conflictKeys The columns to use for conflict detection (defaults to ['id'])
598
- */
599
- async batchUpsert({
600
- tableName,
601
- records,
602
- conflictKeys = ["id"]
603
- }) {
604
- if (records.length === 0) return;
605
- const fullTableName = this.getTableName(tableName);
606
- try {
607
- const batchSize = 50;
608
- for (let i = 0; i < records.length; i += batchSize) {
609
- const batch = records.slice(i, i + batchSize);
610
- const recordsToInsert = batch;
611
- if (recordsToInsert.length > 0) {
612
- const firstRecord = recordsToInsert[0];
613
- const columns = Object.keys(firstRecord || {});
614
- for (const record of recordsToInsert) {
615
- const values = columns.map((col) => {
616
- if (!record) return null;
617
- const value = typeof col === "string" ? record[col] : null;
618
- return this.serializeValue(value);
619
- });
620
- const recordToUpsert = columns.reduce(
621
- (acc, col) => {
622
- if (col !== "createdAt" && !conflictKeys.includes(col)) {
623
- acc[col] = `excluded.${col}`;
624
- }
625
- return acc;
626
- },
627
- {}
628
- );
629
- const query = createSqlBuilder().insert(
630
- fullTableName,
631
- columns,
632
- values,
633
- conflictKeys,
634
- recordToUpsert
635
- );
636
- const { sql, params } = query.build();
637
- await this.executeQuery({ sql, params });
638
- }
639
- }
640
- this.logger.debug(
641
- `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
642
- );
643
- }
644
- this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
645
- } catch (error) {
646
- throw new MastraError(
647
- {
648
- id: createStorageErrorId("CLOUDFLARE_DO", "BATCH_UPSERT", "FAILED"),
649
- domain: ErrorDomain.STORAGE,
650
- category: ErrorCategory.THIRD_PARTY,
651
- text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
652
- details: { tableName }
653
- },
654
- error
655
- );
656
- }
657
- }
658
- };
659
-
660
- // src/do/storage/domains/background-tasks/index.ts
661
- function serializeJson(v) {
662
- if (typeof v === "object" && v != null) return JSON.stringify(v);
663
- return v ?? void 0;
664
- }
665
- function rowToTask(row) {
666
- const parseJson = (v) => {
667
- if (v == null) return void 0;
668
- if (typeof v === "string") {
669
- try {
670
- return JSON.parse(v);
671
- } catch {
672
- return v;
673
- }
674
- }
675
- return v;
676
- };
677
- const asDate = (v) => v ? new Date(String(v)) : void 0;
678
- return {
679
- id: String(row.id),
680
- status: String(row.status),
681
- toolName: String(row.tool_name),
682
- toolCallId: String(row.tool_call_id),
683
- args: parseJson(row.args) ?? {},
684
- agentId: String(row.agent_id),
685
- threadId: row.thread_id != null ? String(row.thread_id) : void 0,
686
- resourceId: row.resource_id != null ? String(row.resource_id) : void 0,
687
- runId: String(row.run_id),
688
- result: parseJson(row.result),
689
- error: parseJson(row.error),
690
- suspendPayload: parseJson(row.suspend_payload),
691
- retryCount: Number(row.retry_count ?? 0),
692
- maxRetries: Number(row.max_retries ?? 0),
693
- timeoutMs: Number(row.timeout_ms ?? 3e5),
694
- createdAt: asDate(row.createdAt) ?? /* @__PURE__ */ new Date(),
695
- startedAt: asDate(row.startedAt),
696
- suspendedAt: asDate(row.suspendedAt),
697
- completedAt: asDate(row.completedAt)
698
- };
699
- }
700
- function dateColumnName(col) {
701
- return col;
702
- }
703
- var BackgroundTasksStorageDO = class extends BackgroundTasksStorage {
704
- #db;
705
- constructor(config) {
706
- super();
707
- this.#db = new DODB(config);
708
- }
709
- async init() {
710
- await this.#db.createTable({
711
- tableName: TABLE_BACKGROUND_TASKS,
712
- schema: TABLE_SCHEMAS[TABLE_BACKGROUND_TASKS]
713
- });
714
- await this.#db.alterTable({
715
- tableName: TABLE_BACKGROUND_TASKS,
716
- schema: TABLE_SCHEMAS[TABLE_BACKGROUND_TASKS],
717
- ifNotExists: ["suspend_payload", "suspendedAt"]
718
- });
719
- }
720
- async dangerouslyClearAll() {
721
- await this.#db.clearTable({ tableName: TABLE_BACKGROUND_TASKS });
722
- }
723
- async createTask(task) {
724
- try {
725
- await this.#db.insert({
726
- tableName: TABLE_BACKGROUND_TASKS,
727
- record: {
728
- id: task.id,
729
- tool_call_id: task.toolCallId,
730
- tool_name: task.toolName,
731
- agent_id: task.agentId,
732
- thread_id: task.threadId ?? null,
733
- resource_id: task.resourceId ?? null,
734
- run_id: task.runId,
735
- status: task.status,
736
- args: serializeJson(task.args),
737
- result: serializeJson(task.result),
738
- error: serializeJson(task.error),
739
- suspend_payload: serializeJson(task.suspendPayload),
740
- retry_count: task.retryCount,
741
- max_retries: task.maxRetries,
742
- timeout_ms: task.timeoutMs,
743
- createdAt: task.createdAt.toISOString(),
744
- startedAt: task.startedAt?.toISOString() ?? null,
745
- suspendedAt: task.suspendedAt?.toISOString() ?? null,
746
- completedAt: task.completedAt?.toISOString() ?? null
747
- }
748
- });
749
- } catch (error) {
750
- throw new MastraError(
751
- {
752
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_CREATE", "FAILED"),
753
- domain: ErrorDomain.STORAGE,
754
- category: ErrorCategory.THIRD_PARTY
755
- },
756
- error
757
- );
758
- }
759
- }
760
- async updateTask(taskId, update) {
761
- const columns = [];
762
- const values = [];
763
- if ("status" in update) {
764
- columns.push("status");
765
- values.push(update.status);
766
- }
767
- if ("result" in update) {
768
- columns.push("result");
769
- values.push(serializeJson(update.result));
770
- }
771
- if ("error" in update) {
772
- columns.push("error");
773
- values.push(serializeJson(update.error));
774
- }
775
- if ("suspendPayload" in update) {
776
- columns.push("suspend_payload");
777
- values.push(serializeJson(update.suspendPayload));
778
- }
779
- if ("retryCount" in update) {
780
- columns.push("retry_count");
781
- values.push(update.retryCount);
782
- }
783
- if ("startedAt" in update) {
784
- columns.push("startedAt");
785
- values.push(update.startedAt?.toISOString() ?? null);
786
- }
787
- if ("suspendedAt" in update) {
788
- columns.push("suspendedAt");
789
- values.push(update.suspendedAt?.toISOString() ?? null);
790
- }
791
- if ("completedAt" in update) {
792
- columns.push("completedAt");
793
- values.push(update.completedAt?.toISOString() ?? null);
794
- }
795
- if (columns.length === 0) return;
796
- try {
797
- const fullTableName = this.#db.getTableName(TABLE_BACKGROUND_TASKS);
798
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", taskId);
799
- const { sql, params } = query.build();
800
- await this.#db.executeQuery({ sql, params });
801
- } catch (error) {
802
- throw new MastraError(
803
- {
804
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_UPDATE", "FAILED"),
805
- domain: ErrorDomain.STORAGE,
806
- category: ErrorCategory.THIRD_PARTY
807
- },
808
- error
809
- );
810
- }
811
- }
812
- async getTask(taskId) {
813
- try {
814
- const fullTableName = this.#db.getTableName(TABLE_BACKGROUND_TASKS);
815
- const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", taskId);
816
- const { sql, params } = query.build();
817
- const result = await this.#db.executeQuery({ sql, params, first: true });
818
- if (!result) return null;
819
- const deserialized = {};
820
- for (const [k, v] of Object.entries(result)) {
821
- deserialized[k] = deserializeValue(v);
822
- }
823
- return rowToTask(deserialized);
824
- } catch (error) {
825
- throw new MastraError(
826
- {
827
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_GET", "FAILED"),
828
- domain: ErrorDomain.STORAGE,
829
- category: ErrorCategory.THIRD_PARTY
830
- },
831
- error
832
- );
833
- }
834
- }
835
- async listTasks(filter) {
836
- try {
837
- const fullTableName = this.#db.getTableName(TABLE_BACKGROUND_TASKS);
838
- const applyConditions = (builder) => {
839
- if (filter.status) {
840
- const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
841
- const placeholders = statuses.map(() => "?").join(", ");
842
- builder.whereAnd(`status IN (${placeholders})`, ...statuses);
843
- }
844
- if (filter.agentId) builder.whereAnd("agent_id = ?", filter.agentId);
845
- if (filter.threadId) builder.whereAnd("thread_id = ?", filter.threadId);
846
- if (filter.resourceId) builder.whereAnd("resource_id = ?", filter.resourceId);
847
- if (filter.toolName) builder.whereAnd("tool_name = ?", filter.toolName);
848
- if (filter.toolCallId) builder.whereAnd("tool_call_id = ?", filter.toolCallId);
849
- if (filter.runId) builder.whereAnd("run_id = ?", filter.runId);
850
- const dateCol = dateColumnName(filter.dateFilterBy ?? "createdAt");
851
- if (filter.fromDate) builder.whereAnd(`${dateCol} >= ?`, filter.fromDate.toISOString());
852
- if (filter.toDate) builder.whereAnd(`${dateCol} < ?`, filter.toDate.toISOString());
853
- };
854
- const countQuery = createSqlBuilder().count().from(fullTableName);
855
- applyConditions(countQuery);
856
- const { sql: countSql, params: countParams } = countQuery.build();
857
- const countResult = await this.#db.executeQuery({ sql: countSql, params: countParams, first: true });
858
- const total = Number(countResult?.count ?? 0);
859
- const dataQuery = createSqlBuilder().select("*").from(fullTableName);
860
- applyConditions(dataQuery);
861
- const orderBy = dateColumnName(filter.orderBy ?? "createdAt");
862
- const direction = filter.orderDirection === "desc" ? "DESC" : "ASC";
863
- dataQuery.orderBy(orderBy, direction);
864
- if (filter.perPage != null) {
865
- dataQuery.limit(filter.perPage);
866
- if (filter.page != null) {
867
- dataQuery.offset(filter.page * filter.perPage);
868
- }
869
- }
870
- const { sql, params } = dataQuery.build();
871
- const rows = await this.#db.executeQuery({ sql, params });
872
- const tasks = (rows ?? []).map((row) => {
873
- const deserialized = {};
874
- for (const [k, v] of Object.entries(row)) {
875
- deserialized[k] = deserializeValue(v);
876
- }
877
- return rowToTask(deserialized);
878
- });
879
- return { tasks, total };
880
- } catch (error) {
881
- throw new MastraError(
882
- {
883
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_LIST", "FAILED"),
884
- domain: ErrorDomain.STORAGE,
885
- category: ErrorCategory.THIRD_PARTY
886
- },
887
- error
888
- );
889
- }
890
- }
891
- async deleteTask(taskId) {
892
- try {
893
- const fullTableName = this.#db.getTableName(TABLE_BACKGROUND_TASKS);
894
- const query = createSqlBuilder().delete(fullTableName).where("id = ?", taskId);
895
- const { sql, params } = query.build();
896
- await this.#db.executeQuery({ sql, params });
897
- } catch (error) {
898
- throw new MastraError(
899
- {
900
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_DELETE", "FAILED"),
901
- domain: ErrorDomain.STORAGE,
902
- category: ErrorCategory.THIRD_PARTY
903
- },
904
- error
905
- );
906
- }
907
- }
908
- async deleteTasks(filter) {
909
- try {
910
- const fullTableName = this.#db.getTableName(TABLE_BACKGROUND_TASKS);
911
- const query = createSqlBuilder().delete(fullTableName);
912
- if (filter.status) {
913
- const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
914
- const placeholders = statuses.map(() => "?").join(", ");
915
- query.whereAnd(`status IN (${placeholders})`, ...statuses);
916
- }
917
- if (filter.agentId) query.whereAnd("agent_id = ?", filter.agentId);
918
- if (filter.threadId) query.whereAnd("thread_id = ?", filter.threadId);
919
- if (filter.resourceId) query.whereAnd("resource_id = ?", filter.resourceId);
920
- if (filter.toolName) query.whereAnd("tool_name = ?", filter.toolName);
921
- if (filter.toolCallId) query.whereAnd("tool_call_id = ?", filter.toolCallId);
922
- if (filter.runId) query.whereAnd("run_id = ?", filter.runId);
923
- const dateCol = dateColumnName(filter.dateFilterBy ?? "createdAt");
924
- if (filter.fromDate) query.whereAnd(`${dateCol} >= ?`, filter.fromDate.toISOString());
925
- if (filter.toDate) query.whereAnd(`${dateCol} < ?`, filter.toDate.toISOString());
926
- const { sql, params } = query.build();
927
- await this.#db.executeQuery({ sql, params });
928
- } catch (error) {
929
- throw new MastraError(
930
- {
931
- id: createStorageErrorId("CLOUDFLARE_DO", "BACKGROUND_TASKS_DELETE_MANY", "FAILED"),
932
- domain: ErrorDomain.STORAGE,
933
- category: ErrorCategory.THIRD_PARTY
934
- },
935
- error
936
- );
937
- }
938
- }
939
- async getRunningCount() {
940
- const { total } = await this.listTasks({ status: "running" });
941
- return total;
942
- }
943
- async getRunningCountByAgent(agentId) {
944
- const { total } = await this.listTasks({ status: "running", agentId });
945
- return total;
946
- }
947
- };
948
- var MemoryStorageDO = class extends MemoryStorage {
949
- #db;
950
- constructor(config) {
951
- super();
952
- this.#db = new DODB(config);
953
- }
954
- async init() {
955
- await this.#db.createTable({ tableName: TABLE_THREADS, schema: TABLE_SCHEMAS[TABLE_THREADS] });
956
- await this.#db.createTable({ tableName: TABLE_MESSAGES, schema: TABLE_SCHEMAS[TABLE_MESSAGES] });
957
- await this.#db.createTable({ tableName: TABLE_RESOURCES, schema: TABLE_SCHEMAS[TABLE_RESOURCES] });
958
- await this.#db.alterTable({
959
- tableName: TABLE_MESSAGES,
960
- schema: TABLE_SCHEMAS[TABLE_MESSAGES],
961
- ifNotExists: ["resourceId"]
962
- });
963
- }
964
- async dangerouslyClearAll() {
965
- await this.#db.clearTable({ tableName: TABLE_MESSAGES });
966
- await this.#db.clearTable({ tableName: TABLE_THREADS });
967
- await this.#db.clearTable({ tableName: TABLE_RESOURCES });
968
- }
969
- async getResourceById({ resourceId }) {
970
- const resource = await this.#db.load({
971
- tableName: TABLE_RESOURCES,
972
- keys: { id: resourceId }
973
- });
974
- if (!resource) return null;
975
- try {
976
- return {
977
- ...resource,
978
- createdAt: ensureDate(resource.createdAt),
979
- updatedAt: ensureDate(resource.updatedAt),
980
- metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
981
- };
982
- } catch (error) {
983
- const mastraError = new MastraError(
984
- {
985
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_RESOURCE_BY_ID", "FAILED"),
986
- domain: ErrorDomain.STORAGE,
987
- category: ErrorCategory.THIRD_PARTY,
988
- text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
989
- details: { resourceId }
990
- },
991
- error
992
- );
993
- this.logger?.error(mastraError.toString());
994
- this.logger?.trackException(mastraError);
995
- return null;
996
- }
997
- }
998
- async saveResource({ resource }) {
999
- const fullTableName = this.#db.getTableName(TABLE_RESOURCES);
1000
- const resourceToSave = {
1001
- id: resource.id,
1002
- workingMemory: resource.workingMemory,
1003
- metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
1004
- createdAt: resource.createdAt,
1005
- updatedAt: resource.updatedAt
1006
- };
1007
- const processedRecord = await this.#db.processRecord(resourceToSave);
1008
- const columns = Object.keys(processedRecord);
1009
- const values = Object.values(processedRecord);
1010
- const updateMap = {
1011
- workingMemory: "excluded.workingMemory",
1012
- metadata: "excluded.metadata",
1013
- createdAt: "excluded.createdAt",
1014
- updatedAt: "excluded.updatedAt"
1015
- };
1016
- const query = createSqlBuilder().insert(
1017
- fullTableName,
1018
- columns,
1019
- values,
1020
- ["id"],
1021
- updateMap
1022
- );
1023
- const { sql, params } = query.build();
1024
- try {
1025
- await this.#db.executeQuery({ sql, params });
1026
- return resource;
1027
- } catch (error) {
1028
- throw new MastraError(
1029
- {
1030
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_RESOURCE", "FAILED"),
1031
- domain: ErrorDomain.STORAGE,
1032
- category: ErrorCategory.THIRD_PARTY,
1033
- text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
1034
- details: { resourceId: resource.id }
1035
- },
1036
- error
1037
- );
1038
- }
1039
- }
1040
- async updateResource({
1041
- resourceId,
1042
- workingMemory,
1043
- metadata
1044
- }) {
1045
- const existingResource = await this.getResourceById({ resourceId });
1046
- if (!existingResource) {
1047
- const newResource = {
1048
- id: resourceId,
1049
- workingMemory,
1050
- metadata: metadata || {},
1051
- createdAt: /* @__PURE__ */ new Date(),
1052
- updatedAt: /* @__PURE__ */ new Date()
1053
- };
1054
- return this.saveResource({ resource: newResource });
1055
- }
1056
- const updatedAt = /* @__PURE__ */ new Date();
1057
- const updatedResource = {
1058
- ...existingResource,
1059
- workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1060
- metadata: {
1061
- ...existingResource.metadata,
1062
- ...metadata
1063
- },
1064
- updatedAt
1065
- };
1066
- const fullTableName = this.#db.getTableName(TABLE_RESOURCES);
1067
- const columns = ["workingMemory", "metadata", "updatedAt"];
1068
- const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
1069
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
1070
- const { sql, params } = query.build();
1071
- try {
1072
- await this.#db.executeQuery({ sql, params });
1073
- return updatedResource;
1074
- } catch (error) {
1075
- throw new MastraError(
1076
- {
1077
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_RESOURCE", "FAILED"),
1078
- domain: ErrorDomain.STORAGE,
1079
- category: ErrorCategory.THIRD_PARTY,
1080
- text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
1081
- details: { resourceId }
1082
- },
1083
- error
1084
- );
1085
- }
1086
- }
1087
- async getThreadById({
1088
- threadId,
1089
- resourceId
1090
- }) {
1091
- const thread = await this.#db.load({
1092
- tableName: TABLE_THREADS,
1093
- keys: { id: threadId }
1094
- });
1095
- if (!thread || resourceId !== void 0 && thread.resourceId !== resourceId) return null;
1096
- try {
1097
- return {
1098
- ...thread,
1099
- createdAt: ensureDate(thread.createdAt),
1100
- updatedAt: ensureDate(thread.updatedAt),
1101
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
1102
- };
1103
- } catch (error) {
1104
- const mastraError = new MastraError(
1105
- {
1106
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_THREAD_BY_ID", "FAILED"),
1107
- domain: ErrorDomain.STORAGE,
1108
- category: ErrorCategory.THIRD_PARTY,
1109
- text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1110
- details: { threadId }
1111
- },
1112
- error
1113
- );
1114
- this.logger?.error(mastraError.toString());
1115
- this.logger?.trackException(mastraError);
1116
- return null;
1117
- }
1118
- }
1119
- async listThreads(args) {
1120
- const { page = 0, perPage: perPageInput, orderBy, filter } = args;
1121
- try {
1122
- this.validatePaginationInput(page, perPageInput ?? 100);
1123
- } catch (error) {
1124
- throw new MastraError(
1125
- {
1126
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_PAGE"),
1127
- domain: ErrorDomain.STORAGE,
1128
- category: ErrorCategory.USER,
1129
- details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
1130
- },
1131
- error instanceof Error ? error : new Error("Invalid pagination parameters")
1132
- );
1133
- }
1134
- const perPage = normalizePerPage(perPageInput, 100);
1135
- try {
1136
- this.validateMetadataKeys(filter?.metadata);
1137
- } catch (error) {
1138
- throw new MastraError(
1139
- {
1140
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_METADATA_KEY"),
1141
- domain: ErrorDomain.STORAGE,
1142
- category: ErrorCategory.USER,
1143
- details: { metadataKeys: filter?.metadata ? Object.keys(filter.metadata).join(", ") : "" }
1144
- },
1145
- error instanceof Error ? error : new Error("Invalid metadata key")
1146
- );
1147
- }
1148
- const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1149
- const { field, direction } = this.parseOrderBy(orderBy);
1150
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1151
- const mapRowToStorageThreadType = (row) => ({
1152
- ...row,
1153
- createdAt: ensureDate(row.createdAt),
1154
- updatedAt: ensureDate(row.updatedAt),
1155
- metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
1156
- });
1157
- try {
1158
- let countQuery = createSqlBuilder().count().from(fullTableName);
1159
- let selectQuery = createSqlBuilder().select("*").from(fullTableName);
1160
- if (filter?.resourceId) {
1161
- countQuery = countQuery.whereAnd("resourceId = ?", filter.resourceId);
1162
- selectQuery = selectQuery.whereAnd("resourceId = ?", filter.resourceId);
1163
- }
1164
- if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
1165
- for (const [key, value] of Object.entries(filter.metadata)) {
1166
- if (value !== null && typeof value === "object") {
1167
- throw new MastraError(
1168
- {
1169
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_METADATA_VALUE"),
1170
- domain: ErrorDomain.STORAGE,
1171
- category: ErrorCategory.USER,
1172
- text: `Metadata filter value for key "${key}" must be a scalar type (string, number, boolean, or null), got ${Array.isArray(value) ? "array" : "object"}`,
1173
- details: { key, valueType: Array.isArray(value) ? "array" : "object" }
1174
- },
1175
- new Error("Invalid metadata filter value type")
1176
- );
1177
- }
1178
- if (value === null) {
1179
- const condition = `json_extract(metadata, '$.${key}') IS NULL`;
1180
- countQuery = countQuery.whereAnd(condition);
1181
- selectQuery = selectQuery.whereAnd(condition);
1182
- } else {
1183
- const condition = `json_extract(metadata, '$.${key}') = ?`;
1184
- const filterValue = value;
1185
- countQuery = countQuery.whereAnd(condition, filterValue);
1186
- selectQuery = selectQuery.whereAnd(condition, filterValue);
1187
- }
1188
- }
1189
- }
1190
- const countResult = await this.#db.executeQuery(countQuery.build());
1191
- const total = Number(countResult?.[0]?.count ?? 0);
1192
- if (total === 0) {
1193
- return {
1194
- threads: [],
1195
- total: 0,
1196
- page,
1197
- perPage: perPageForResponse,
1198
- hasMore: false
1199
- };
1200
- }
1201
- const limitValue = perPageInput === false ? total : perPage;
1202
- selectQuery = selectQuery.orderBy(field, direction).limit(limitValue).offset(offset);
1203
- const results = await this.#db.executeQuery(selectQuery.build());
1204
- const threads = results.map(mapRowToStorageThreadType);
1205
- return {
1206
- threads,
1207
- total,
1208
- page,
1209
- perPage: perPageForResponse,
1210
- hasMore: perPageInput === false ? false : offset + perPage < total
1211
- };
1212
- } catch (error) {
1213
- if (error instanceof MastraError && error.category === ErrorCategory.USER) {
1214
- throw error;
1215
- }
1216
- const mastraError = new MastraError(
1217
- {
1218
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "FAILED"),
1219
- domain: ErrorDomain.STORAGE,
1220
- category: ErrorCategory.THIRD_PARTY,
1221
- text: `Error listing threads: ${error instanceof Error ? error.message : String(error)}`,
1222
- details: {
1223
- ...filter?.resourceId && { resourceId: filter.resourceId },
1224
- hasMetadataFilter: !!filter?.metadata
1225
- }
1226
- },
1227
- error
1228
- );
1229
- this.logger?.error(mastraError.toString());
1230
- this.logger?.trackException(mastraError);
1231
- return {
1232
- threads: [],
1233
- total: 0,
1234
- page,
1235
- perPage: perPageForResponse,
1236
- hasMore: false
1237
- };
1238
- }
1239
- }
1240
- async saveThread({ thread }) {
1241
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1242
- const threadToSave = {
1243
- id: thread.id,
1244
- resourceId: thread.resourceId,
1245
- title: thread.title,
1246
- metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
1247
- createdAt: thread.createdAt.toISOString(),
1248
- updatedAt: thread.updatedAt.toISOString()
1249
- };
1250
- const processedRecord = await this.#db.processRecord(threadToSave);
1251
- const columns = Object.keys(processedRecord);
1252
- const values = Object.values(processedRecord);
1253
- const updateMap = {
1254
- resourceId: "excluded.resourceId",
1255
- title: "excluded.title",
1256
- metadata: "excluded.metadata",
1257
- createdAt: "excluded.createdAt",
1258
- updatedAt: "excluded.updatedAt"
1259
- };
1260
- const query = createSqlBuilder().insert(
1261
- fullTableName,
1262
- columns,
1263
- values,
1264
- ["id"],
1265
- updateMap
1266
- );
1267
- const { sql, params } = query.build();
1268
- try {
1269
- await this.#db.executeQuery({ sql, params });
1270
- return thread;
1271
- } catch (error) {
1272
- throw new MastraError(
1273
- {
1274
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_THREAD", "FAILED"),
1275
- domain: ErrorDomain.STORAGE,
1276
- category: ErrorCategory.THIRD_PARTY,
1277
- text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
1278
- details: { threadId: thread.id }
1279
- },
1280
- error
1281
- );
1282
- }
1283
- }
1284
- async updateThread({
1285
- id,
1286
- title,
1287
- metadata
1288
- }) {
1289
- const thread = await this.getThreadById({ threadId: id });
1290
- try {
1291
- if (!thread) {
1292
- throw new Error(`Thread ${id} not found`);
1293
- }
1294
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1295
- const mergedMetadata = {
1296
- ...thread.metadata,
1297
- ...metadata
1298
- };
1299
- const updatedAt = /* @__PURE__ */ new Date();
1300
- const columns = ["title", "metadata", "updatedAt"];
1301
- const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
1302
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
1303
- const { sql, params } = query.build();
1304
- await this.#db.executeQuery({ sql, params });
1305
- return {
1306
- ...thread,
1307
- title,
1308
- metadata: mergedMetadata,
1309
- updatedAt
1310
- };
1311
- } catch (error) {
1312
- throw new MastraError(
1313
- {
1314
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_THREAD", "FAILED"),
1315
- domain: ErrorDomain.STORAGE,
1316
- category: ErrorCategory.THIRD_PARTY,
1317
- text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
1318
- details: { threadId: id }
1319
- },
1320
- error
1321
- );
1322
- }
1323
- }
1324
- async deleteThread({ threadId }) {
1325
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1326
- try {
1327
- const messagesTableName = this.#db.getTableName(TABLE_MESSAGES);
1328
- const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
1329
- const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
1330
- await this.#db.executeQuery({ sql: messagesSql, params: messagesParams });
1331
- const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
1332
- const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
1333
- await this.#db.executeQuery({ sql: threadSql, params: threadParams });
1334
- } catch (error) {
1335
- throw new MastraError(
1336
- {
1337
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_THREAD", "FAILED"),
1338
- domain: ErrorDomain.STORAGE,
1339
- category: ErrorCategory.THIRD_PARTY,
1340
- text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1341
- details: { threadId }
1342
- },
1343
- error
1344
- );
1345
- }
1346
- }
1347
- async saveMessages(args) {
1348
- const { messages } = args;
1349
- if (messages.length === 0) return { messages: [] };
1350
- try {
1351
- const now = /* @__PURE__ */ new Date();
1352
- for (const [i, message] of messages.entries()) {
1353
- if (!message.id) throw new Error(`Message at index ${i} missing id`);
1354
- if (!message.threadId) {
1355
- throw new Error(`Message at index ${i} missing threadId`);
1356
- }
1357
- if (!message.content) {
1358
- throw new Error(`Message at index ${i} missing content`);
1359
- }
1360
- if (!message.role) {
1361
- throw new Error(`Message at index ${i} missing role`);
1362
- }
1363
- if (!message.resourceId) {
1364
- throw new Error(`Message at index ${i} missing resourceId`);
1365
- }
1366
- }
1367
- const uniqueThreadIds = [...new Set(messages.map((m) => m.threadId))];
1368
- const threads = await Promise.all(uniqueThreadIds.map((id) => this.getThreadById({ threadId: id })));
1369
- const missingThreadId = uniqueThreadIds.find((id, i) => !threads[i]);
1370
- if (missingThreadId) {
1371
- throw new Error(`Thread ${missingThreadId} not found`);
1372
- }
1373
- const messagesToInsert = messages.map((message) => {
1374
- const createdAt = message.createdAt ? new Date(message.createdAt) : now;
1375
- return {
1376
- id: message.id,
1377
- thread_id: message.threadId,
1378
- content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
1379
- createdAt: createdAt.toISOString(),
1380
- role: message.role,
1381
- type: message.type || "v2",
1382
- resourceId: message.resourceId
1383
- };
1384
- });
1385
- await Promise.all([
1386
- this.#db.batchUpsert({
1387
- tableName: TABLE_MESSAGES,
1388
- records: messagesToInsert
1389
- }),
1390
- // Update updatedAt timestamp for all affected threads
1391
- ...uniqueThreadIds.map(
1392
- (tid) => this.#db.executeQuery({
1393
- sql: `UPDATE ${this.#db.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
1394
- params: [now.toISOString(), tid]
1395
- })
1396
- )
1397
- ]);
1398
- this.logger.debug(`Saved ${messages.length} messages`);
1399
- const list = new MessageList().add(messages, "memory");
1400
- return { messages: list.get.all.db() };
1401
- } catch (error) {
1402
- throw new MastraError(
1403
- {
1404
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_MESSAGES", "FAILED"),
1405
- domain: ErrorDomain.STORAGE,
1406
- category: ErrorCategory.THIRD_PARTY,
1407
- text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
1408
- },
1409
- error
1410
- );
1411
- }
1412
- }
1413
- async _getIncludedMessages(include) {
1414
- if (!include || include.length === 0) return null;
1415
- const unionQueries = [];
1416
- const params = [];
1417
- let paramIdx = 1;
1418
- const tableName = this.#db.getTableName(TABLE_MESSAGES);
1419
- for (const inc of include) {
1420
- const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
1421
- unionQueries.push(`
1422
- SELECT * FROM (
1423
- WITH target_thread AS (
1424
- SELECT thread_id FROM ${tableName} WHERE id = ?
1425
- ),
1426
- ordered_messages AS (
1427
- SELECT
1428
- *,
1429
- ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
1430
- FROM ${tableName}
1431
- WHERE thread_id = (SELECT thread_id FROM target_thread)
1432
- )
1433
- SELECT
1434
- m.id,
1435
- m.content,
1436
- m.role,
1437
- m.type,
1438
- m.createdAt,
1439
- m.thread_id AS threadId,
1440
- m.resourceId
1441
- FROM ordered_messages m
1442
- WHERE m.id = ?
1443
- OR EXISTS (
1444
- SELECT 1 FROM ordered_messages target
1445
- WHERE target.id = ?
1446
- AND (
1447
- (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
1448
- OR
1449
- (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
1450
- )
1451
- )
1452
- ) AS query_${paramIdx}
1453
- `);
1454
- params.push(id, id, id, withNextMessages, withPreviousMessages);
1455
- paramIdx++;
1456
- }
1457
- const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
1458
- const messages = await this.#db.executeQuery({
1459
- sql: finalQuery,
1460
- params
1461
- });
1462
- if (!Array.isArray(messages)) {
1463
- return [];
1464
- }
1465
- const processedMessages = messages.map((message) => {
1466
- const processedMsg = {};
1467
- for (const [key, value] of Object.entries(message)) {
1468
- if (key === `type` && value === `v2`) continue;
1469
- processedMsg[key] = deserializeValue(value);
1470
- }
1471
- return processedMsg;
1472
- });
1473
- return processedMessages;
1474
- }
1475
- async listMessagesById({ messageIds }) {
1476
- if (messageIds.length === 0) return { messages: [] };
1477
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1478
- const messages = [];
1479
- try {
1480
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
1481
- query.orderBy("createdAt", "DESC");
1482
- const { sql, params } = query.build();
1483
- const result = await this.#db.executeQuery({ sql, params });
1484
- if (Array.isArray(result)) messages.push(...result);
1485
- const processedMessages = messages.map((message) => {
1486
- const processedMsg = {};
1487
- for (const [key, value] of Object.entries(message)) {
1488
- if (key === `type` && value === `v2`) continue;
1489
- processedMsg[key] = deserializeValue(value);
1490
- }
1491
- return processedMsg;
1492
- });
1493
- this.logger.debug(`Retrieved ${messages.length} messages`);
1494
- const list = new MessageList().add(processedMessages, "memory");
1495
- return { messages: list.get.all.db() };
1496
- } catch (error) {
1497
- const mastraError = new MastraError(
1498
- {
1499
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES_BY_ID", "FAILED"),
1500
- domain: ErrorDomain.STORAGE,
1501
- category: ErrorCategory.THIRD_PARTY,
1502
- text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
1503
- details: { messageIds: JSON.stringify(messageIds) }
1504
- },
1505
- error
1506
- );
1507
- this.logger?.error?.(mastraError.toString());
1508
- this.logger?.trackException?.(mastraError);
1509
- throw mastraError;
1510
- }
1511
- }
1512
- async listMessages(args) {
1513
- const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1514
- const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1515
- if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
1516
- throw new MastraError(
1517
- {
1518
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "INVALID_THREAD_ID"),
1519
- domain: ErrorDomain.STORAGE,
1520
- category: ErrorCategory.THIRD_PARTY,
1521
- details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
1522
- },
1523
- new Error("threadId must be a non-empty string or array of non-empty strings")
1524
- );
1525
- }
1526
- if (page < 0) {
1527
- throw new MastraError(
1528
- {
1529
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "INVALID_PAGE"),
1530
- domain: ErrorDomain.STORAGE,
1531
- category: ErrorCategory.USER,
1532
- details: { page }
1533
- },
1534
- new Error("page must be >= 0")
1535
- );
1536
- }
1537
- const perPage = normalizePerPage(perPageInput, 40);
1538
- const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1539
- try {
1540
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1541
- const placeholders = threadIds.map(() => "?").join(", ");
1542
- let query = `
1543
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1544
- FROM ${fullTableName}
1545
- WHERE thread_id IN (${placeholders})
1546
- `;
1547
- const queryParams = [...threadIds];
1548
- if (resourceId) {
1549
- query += ` AND resourceId = ?`;
1550
- queryParams.push(resourceId);
1551
- }
1552
- const dateRange = filter?.dateRange;
1553
- if (dateRange?.start) {
1554
- const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
1555
- const startOp = dateRange.startExclusive ? ">" : ">=";
1556
- query += ` AND createdAt ${startOp} ?`;
1557
- queryParams.push(startDate);
1558
- }
1559
- if (dateRange?.end) {
1560
- const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
1561
- const endOp = dateRange.endExclusive ? "<" : "<=";
1562
- query += ` AND createdAt ${endOp} ?`;
1563
- queryParams.push(endDate);
1564
- }
1565
- const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1566
- query += ` ORDER BY "${field}" ${direction}`;
1567
- if (perPage !== Number.MAX_SAFE_INTEGER) {
1568
- query += ` LIMIT ? OFFSET ?`;
1569
- queryParams.push(perPage, offset);
1570
- }
1571
- const results = await this.#db.executeQuery({
1572
- sql: query,
1573
- params: queryParams
1574
- });
1575
- const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
1576
- const processedMsg = {};
1577
- for (const [key, value] of Object.entries(message)) {
1578
- if (key === `type` && value === `v2`) continue;
1579
- processedMsg[key] = deserializeValue(value);
1580
- }
1581
- return processedMsg;
1582
- });
1583
- const paginatedCount = paginatedMessages.length;
1584
- let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
1585
- const countParams = [threadId];
1586
- if (resourceId) {
1587
- countQuery += ` AND resourceId = ?`;
1588
- countParams.push(resourceId);
1589
- }
1590
- if (dateRange?.start) {
1591
- const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
1592
- const startOp = dateRange.startExclusive ? ">" : ">=";
1593
- countQuery += ` AND createdAt ${startOp} ?`;
1594
- countParams.push(startDate);
1595
- }
1596
- if (dateRange?.end) {
1597
- const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
1598
- const endOp = dateRange.endExclusive ? "<" : "<=";
1599
- countQuery += ` AND createdAt ${endOp} ?`;
1600
- countParams.push(endDate);
1601
- }
1602
- const countResult = await this.#db.executeQuery({
1603
- sql: countQuery,
1604
- params: countParams
1605
- });
1606
- const total = Number(countResult[0]?.count ?? 0);
1607
- if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
1608
- return {
1609
- messages: [],
1610
- total: 0,
1611
- page,
1612
- perPage: perPageForResponse,
1613
- hasMore: false
1614
- };
1615
- }
1616
- const messageIds = new Set(paginatedMessages.map((m) => m.id));
1617
- let includeMessages = [];
1618
- if (include && include.length > 0) {
1619
- const includeResult = await this._getIncludedMessages(include);
1620
- if (Array.isArray(includeResult)) {
1621
- includeMessages = includeResult;
1622
- for (const includeMsg of includeMessages) {
1623
- if (!messageIds.has(includeMsg.id)) {
1624
- paginatedMessages.push(includeMsg);
1625
- messageIds.add(includeMsg.id);
1626
- }
1627
- }
1628
- }
1629
- }
1630
- const list = new MessageList().add(paginatedMessages, "memory");
1631
- let finalMessages = list.get.all.db();
1632
- finalMessages = finalMessages.sort((a, b) => {
1633
- const isDateField = field === "createdAt" || field === "updatedAt";
1634
- const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
1635
- const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
1636
- if (aValue === bValue) {
1637
- return a.id.localeCompare(b.id);
1638
- }
1639
- if (typeof aValue === "number" && typeof bValue === "number") {
1640
- return direction === "ASC" ? aValue - bValue : bValue - aValue;
1641
- }
1642
- return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1643
- });
1644
- const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1645
- const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1646
- const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
1647
- return {
1648
- messages: finalMessages,
1649
- total,
1650
- page,
1651
- perPage: perPageForResponse,
1652
- hasMore
1653
- };
1654
- } catch (error) {
1655
- const mastraError = new MastraError(
1656
- {
1657
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "FAILED"),
1658
- domain: ErrorDomain.STORAGE,
1659
- category: ErrorCategory.THIRD_PARTY,
1660
- text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error instanceof Error ? error.message : String(error)}`,
1661
- details: {
1662
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1663
- resourceId: resourceId ?? ""
1664
- }
1665
- },
1666
- error
1667
- );
1668
- this.logger?.error?.(mastraError.toString());
1669
- this.logger?.trackException?.(mastraError);
1670
- return {
1671
- messages: [],
1672
- total: 0,
1673
- page,
1674
- perPage: perPageForResponse,
1675
- hasMore: false
1676
- };
1677
- }
1678
- }
1679
- async updateMessages(args) {
1680
- const { messages } = args;
1681
- this.logger.debug("Updating messages", { count: messages.length });
1682
- if (!messages.length) {
1683
- return [];
1684
- }
1685
- const messageIds = messages.map((m) => m.id);
1686
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1687
- const threadsTableName = this.#db.getTableName(TABLE_THREADS);
1688
- try {
1689
- const placeholders = messageIds.map(() => "?").join(",");
1690
- const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
1691
- const existingMessages = await this.#db.executeQuery({ sql: selectQuery, params: messageIds });
1692
- if (existingMessages.length === 0) {
1693
- return [];
1694
- }
1695
- const parsedExistingMessages = existingMessages.map((msg) => {
1696
- let parsedContent = msg.content;
1697
- if (typeof msg.content === "string") {
1698
- try {
1699
- parsedContent = JSON.parse(msg.content);
1700
- } catch {
1701
- }
1702
- }
1703
- return { ...msg, content: parsedContent };
1704
- });
1705
- const existingMessagesMap = new Map(parsedExistingMessages.map((msg) => [msg.id, msg]));
1706
- const updatedMessages = [];
1707
- const now = (/* @__PURE__ */ new Date()).toISOString();
1708
- for (const update of messages) {
1709
- const existing = existingMessagesMap.get(update.id);
1710
- if (!existing) continue;
1711
- let mergedContent = existing.content;
1712
- if (update.content) {
1713
- if (typeof mergedContent === "object" && mergedContent !== null) {
1714
- mergedContent = {
1715
- ...mergedContent,
1716
- ...update.content,
1717
- metadata: {
1718
- ...mergedContent.metadata,
1719
- ...update.content.metadata
1720
- }
1721
- };
1722
- } else {
1723
- mergedContent = update.content;
1724
- }
1725
- }
1726
- updatedMessages.push({
1727
- ...existing,
1728
- ...update,
1729
- content: mergedContent
1730
- });
1731
- }
1732
- for (const msg of updatedMessages) {
1733
- const contentStr = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1734
- const updateQuery = createSqlBuilder().update(fullTableName, ["content", "role", "type"], [contentStr, msg.role, msg.type]).where("id = ?", msg.id);
1735
- const { sql, params } = updateQuery.build();
1736
- await this.#db.executeQuery({ sql, params });
1737
- }
1738
- const threadIds = [...new Set(updatedMessages.map((m) => m.threadId))];
1739
- for (const tid of threadIds) {
1740
- await this.#db.executeQuery({
1741
- sql: `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id = ?`,
1742
- params: [now, tid]
1743
- });
1744
- }
1745
- const list = new MessageList().add(updatedMessages, "memory");
1746
- return list.get.all.db();
1747
- } catch (error) {
1748
- throw new MastraError(
1749
- {
1750
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_MESSAGES", "FAILED"),
1751
- domain: ErrorDomain.STORAGE,
1752
- category: ErrorCategory.THIRD_PARTY,
1753
- text: `Failed to update messages: ${error instanceof Error ? error.message : String(error)}`,
1754
- details: { messageIds: JSON.stringify(messageIds) }
1755
- },
1756
- error
1757
- );
1758
- }
1759
- }
1760
- async deleteMessages(messageIds) {
1761
- if (messageIds.length === 0) return;
1762
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1763
- try {
1764
- const placeholders = messageIds.map(() => "?").join(",");
1765
- const sql = `DELETE FROM ${fullTableName} WHERE id IN (${placeholders})`;
1766
- await this.#db.executeQuery({ sql, params: messageIds });
1767
- this.logger.debug(`Deleted ${messageIds.length} messages`);
1768
- } catch (error) {
1769
- throw new MastraError(
1770
- {
1771
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_MESSAGES", "FAILED"),
1772
- domain: ErrorDomain.STORAGE,
1773
- category: ErrorCategory.THIRD_PARTY,
1774
- text: `Failed to delete messages: ${error instanceof Error ? error.message : String(error)}`,
1775
- details: { messageIds: JSON.stringify(messageIds) }
1776
- },
1777
- error
1778
- );
1779
- }
1780
- }
1781
- };
1782
- function applyTenancyFilters(query, filters) {
1783
- if (filters?.organizationId !== void 0) {
1784
- query.andWhere("organizationId = ?", filters.organizationId);
1785
- }
1786
- if (filters?.projectId !== void 0) {
1787
- query.andWhere("projectId = ?", filters.projectId);
1788
- }
1789
- }
1790
- function transformScoreRow(row) {
1791
- return transformScoreRow$1(row, {
1792
- preferredTimestampFields: {
1793
- createdAt: "createdAtZ",
1794
- updatedAt: "updatedAtZ"
1795
- }
1796
- });
1797
- }
1798
- var ScoresStorageDO = class extends ScoresStorage {
1799
- #db;
1800
- constructor(config) {
1801
- super();
1802
- this.#db = new DODB(config);
1803
- }
1804
- async init() {
1805
- await this.#db.createTable({ tableName: TABLE_SCORERS, schema: TABLE_SCHEMAS[TABLE_SCORERS] });
1806
- }
1807
- async dangerouslyClearAll() {
1808
- await this.#db.clearTable({ tableName: TABLE_SCORERS });
1809
- }
1810
- async getScoreById({ id }) {
1811
- try {
1812
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1813
- const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
1814
- const { sql, params } = query.build();
1815
- const result = await this.#db.executeQuery({ sql, params, first: true });
1816
- if (!result) {
1817
- return null;
1818
- }
1819
- return transformScoreRow(result);
1820
- } catch (error) {
1821
- throw new MastraError(
1822
- {
1823
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORE_BY_ID", "FAILED"),
1824
- domain: ErrorDomain.STORAGE,
1825
- category: ErrorCategory.THIRD_PARTY
1826
- },
1827
- error
1828
- );
1829
- }
1830
- }
1831
- async saveScore(score) {
1832
- let parsedScore;
1833
- try {
1834
- parsedScore = saveScorePayloadSchema.parse(score);
1835
- } catch (error) {
1836
- const safeScore = score && typeof score === "object" ? score : {};
1837
- const safeScorer = safeScore.scorer && typeof safeScore.scorer === "object" ? safeScore.scorer : {};
1838
- throw new MastraError(
1839
- {
1840
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_SCORE", "VALIDATION_FAILED"),
1841
- domain: ErrorDomain.STORAGE,
1842
- category: ErrorCategory.USER,
1843
- details: {
1844
- scorer: typeof safeScorer.id === "string" ? safeScorer.id : String(safeScorer.id ?? "unknown"),
1845
- entityId: safeScore.entityId ?? "unknown",
1846
- entityType: safeScore.entityType ?? "unknown",
1847
- traceId: safeScore.traceId ?? "",
1848
- spanId: safeScore.spanId ?? ""
1849
- }
1850
- },
1851
- error
1852
- );
1853
- }
1854
- const id = crypto.randomUUID();
1855
- try {
1856
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1857
- const serializedRecord = {};
1858
- for (const [key, value] of Object.entries(parsedScore)) {
1859
- if (value !== null && value !== void 0) {
1860
- if (typeof value === "object") {
1861
- serializedRecord[key] = JSON.stringify(value);
1862
- } else {
1863
- serializedRecord[key] = value;
1864
- }
1865
- } else {
1866
- serializedRecord[key] = null;
1867
- }
1868
- }
1869
- const now = /* @__PURE__ */ new Date();
1870
- serializedRecord.id = id;
1871
- serializedRecord.createdAt = now.toISOString();
1872
- serializedRecord.updatedAt = now.toISOString();
1873
- const columns = Object.keys(serializedRecord);
1874
- const values = Object.values(serializedRecord);
1875
- const query = createSqlBuilder().insert(
1876
- fullTableName,
1877
- columns,
1878
- values
1879
- );
1880
- const { sql, params } = query.build();
1881
- await this.#db.executeQuery({ sql, params });
1882
- return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1883
- } catch (error) {
1884
- throw new MastraError(
1885
- {
1886
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_SCORE", "FAILED"),
1887
- domain: ErrorDomain.STORAGE,
1888
- category: ErrorCategory.THIRD_PARTY,
1889
- details: { id }
1890
- },
1891
- error
1892
- );
1893
- }
1894
- }
1895
- async listScoresByScorerId({
1896
- scorerId,
1897
- entityId,
1898
- entityType,
1899
- source,
1900
- pagination,
1901
- filters
1902
- }) {
1903
- try {
1904
- const { page, perPage: perPageInput } = pagination;
1905
- const perPage = normalizePerPage(perPageInput, 100);
1906
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1907
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1908
- const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1909
- if (entityId) {
1910
- countQuery.andWhere("entityId = ?", entityId);
1911
- }
1912
- if (entityType) {
1913
- countQuery.andWhere("entityType = ?", entityType);
1914
- }
1915
- if (source) {
1916
- countQuery.andWhere("source = ?", source);
1917
- }
1918
- applyTenancyFilters(countQuery, filters);
1919
- const countResult = await this.#db.executeQuery(countQuery.build());
1920
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1921
- if (total === 0) {
1922
- return {
1923
- pagination: {
1924
- total: 0,
1925
- page,
1926
- perPage: perPageForResponse,
1927
- hasMore: false
1928
- },
1929
- scores: []
1930
- };
1931
- }
1932
- const end = perPageInput === false ? total : start + perPage;
1933
- const limitValue = perPageInput === false ? total : perPage;
1934
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1935
- if (entityId) {
1936
- selectQuery.andWhere("entityId = ?", entityId);
1937
- }
1938
- if (entityType) {
1939
- selectQuery.andWhere("entityType = ?", entityType);
1940
- }
1941
- if (source) {
1942
- selectQuery.andWhere("source = ?", source);
1943
- }
1944
- applyTenancyFilters(selectQuery, filters);
1945
- selectQuery.limit(limitValue).offset(start);
1946
- const { sql, params } = selectQuery.build();
1947
- const results = await this.#db.executeQuery({ sql, params });
1948
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
1949
- return {
1950
- pagination: {
1951
- total,
1952
- page,
1953
- perPage: perPageForResponse,
1954
- hasMore: end < total
1955
- },
1956
- scores
1957
- };
1958
- } catch (error) {
1959
- throw new MastraError(
1960
- {
1961
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1962
- domain: ErrorDomain.STORAGE,
1963
- category: ErrorCategory.THIRD_PARTY
1964
- },
1965
- error
1966
- );
1967
- }
1968
- }
1969
- async listScoresByRunId({
1970
- runId,
1971
- pagination,
1972
- filters
1973
- }) {
1974
- try {
1975
- const { page, perPage: perPageInput } = pagination;
1976
- const perPage = normalizePerPage(perPageInput, 100);
1977
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1978
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1979
- const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1980
- applyTenancyFilters(countQuery, filters);
1981
- const countResult = await this.#db.executeQuery(countQuery.build());
1982
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1983
- if (total === 0) {
1984
- return {
1985
- pagination: {
1986
- total: 0,
1987
- page,
1988
- perPage: perPageForResponse,
1989
- hasMore: false
1990
- },
1991
- scores: []
1992
- };
1993
- }
1994
- const end = perPageInput === false ? total : start + perPage;
1995
- const limitValue = perPageInput === false ? total : perPage;
1996
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId);
1997
- applyTenancyFilters(selectQuery, filters);
1998
- selectQuery.limit(limitValue).offset(start);
1999
- const { sql, params } = selectQuery.build();
2000
- const results = await this.#db.executeQuery({ sql, params });
2001
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2002
- return {
2003
- pagination: {
2004
- total,
2005
- page,
2006
- perPage: perPageForResponse,
2007
- hasMore: end < total
2008
- },
2009
- scores
2010
- };
2011
- } catch (error) {
2012
- throw new MastraError(
2013
- {
2014
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_RUN_ID", "FAILED"),
2015
- domain: ErrorDomain.STORAGE,
2016
- category: ErrorCategory.THIRD_PARTY
2017
- },
2018
- error
2019
- );
2020
- }
2021
- }
2022
- async listScoresByEntityId({
2023
- entityId,
2024
- entityType,
2025
- pagination,
2026
- filters
2027
- }) {
2028
- try {
2029
- const { page, perPage: perPageInput } = pagination;
2030
- const perPage = normalizePerPage(perPageInput, 100);
2031
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2032
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
2033
- const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
2034
- applyTenancyFilters(countQuery, filters);
2035
- const countResult = await this.#db.executeQuery(countQuery.build());
2036
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
2037
- if (total === 0) {
2038
- return {
2039
- pagination: {
2040
- total: 0,
2041
- page,
2042
- perPage: perPageForResponse,
2043
- hasMore: false
2044
- },
2045
- scores: []
2046
- };
2047
- }
2048
- const end = perPageInput === false ? total : start + perPage;
2049
- const limitValue = perPageInput === false ? total : perPage;
2050
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
2051
- applyTenancyFilters(selectQuery, filters);
2052
- selectQuery.limit(limitValue).offset(start);
2053
- const { sql, params } = selectQuery.build();
2054
- const results = await this.#db.executeQuery({ sql, params });
2055
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2056
- return {
2057
- pagination: {
2058
- total,
2059
- page,
2060
- perPage: perPageForResponse,
2061
- hasMore: end < total
2062
- },
2063
- scores
2064
- };
2065
- } catch (error) {
2066
- throw new MastraError(
2067
- {
2068
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
2069
- domain: ErrorDomain.STORAGE,
2070
- category: ErrorCategory.THIRD_PARTY
2071
- },
2072
- error
2073
- );
2074
- }
2075
- }
2076
- async listScoresBySpan({
2077
- traceId,
2078
- spanId,
2079
- pagination,
2080
- filters
2081
- }) {
2082
- try {
2083
- const { page, perPage: perPageInput } = pagination;
2084
- const perPage = normalizePerPage(perPageInput, 100);
2085
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2086
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
2087
- const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
2088
- applyTenancyFilters(countQuery, filters);
2089
- const countResult = await this.#db.executeQuery(countQuery.build());
2090
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
2091
- if (total === 0) {
2092
- return {
2093
- pagination: {
2094
- total: 0,
2095
- page,
2096
- perPage: perPageForResponse,
2097
- hasMore: false
2098
- },
2099
- scores: []
2100
- };
2101
- }
2102
- const end = perPageInput === false ? total : start + perPage;
2103
- const limitValue = perPageInput === false ? total : perPage;
2104
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
2105
- applyTenancyFilters(selectQuery, filters);
2106
- selectQuery.orderBy("createdAt", "DESC").limit(limitValue).offset(start);
2107
- const { sql, params } = selectQuery.build();
2108
- const results = await this.#db.executeQuery({ sql, params });
2109
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2110
- return {
2111
- pagination: {
2112
- total,
2113
- page,
2114
- perPage: perPageForResponse,
2115
- hasMore: end < total
2116
- },
2117
- scores
2118
- };
2119
- } catch (error) {
2120
- throw new MastraError(
2121
- {
2122
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_SPAN", "FAILED"),
2123
- domain: ErrorDomain.STORAGE,
2124
- category: ErrorCategory.THIRD_PARTY
2125
- },
2126
- error
2127
- );
2128
- }
2129
- }
2130
- };
2131
- var WorkflowsStorageDO = class extends WorkflowsStorage {
2132
- #db;
2133
- constructor(config) {
2134
- super();
2135
- this.#db = new DODB(config);
2136
- }
2137
- supportsConcurrentUpdates() {
2138
- return false;
2139
- }
2140
- async init() {
2141
- await this.#db.createTable({ tableName: TABLE_WORKFLOW_SNAPSHOT, schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT] });
2142
- }
2143
- async dangerouslyClearAll() {
2144
- await this.#db.clearTable({ tableName: TABLE_WORKFLOW_SNAPSHOT });
2145
- }
2146
- updateWorkflowResults({
2147
- // workflowName,
2148
- // runId,
2149
- // stepId,
2150
- // result,
2151
- // requestContext,
2152
- }) {
2153
- throw new Error("Method not implemented.");
2154
- }
2155
- updateWorkflowState({
2156
- // workflowName,
2157
- // runId,
2158
- // opts,
2159
- }) {
2160
- throw new Error("Method not implemented.");
2161
- }
2162
- async persistWorkflowSnapshot({
2163
- workflowName,
2164
- runId,
2165
- resourceId,
2166
- snapshot,
2167
- createdAt,
2168
- updatedAt
2169
- }) {
2170
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2171
- const now = (/* @__PURE__ */ new Date()).toISOString();
2172
- const currentSnapshot = await this.#db.load({
2173
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2174
- keys: { workflow_name: workflowName, run_id: runId }
2175
- });
2176
- const persisting = currentSnapshot ? {
2177
- ...currentSnapshot,
2178
- resourceId,
2179
- snapshot: JSON.stringify(snapshot),
2180
- updatedAt: updatedAt ? updatedAt.toISOString() : now
2181
- } : {
2182
- workflow_name: workflowName,
2183
- run_id: runId,
2184
- resourceId,
2185
- snapshot: JSON.stringify(snapshot),
2186
- createdAt: createdAt ? createdAt.toISOString() : now,
2187
- updatedAt: updatedAt ? updatedAt.toISOString() : now
2188
- };
2189
- const processedRecord = await this.#db.processRecord(persisting);
2190
- const columns = Object.keys(processedRecord);
2191
- const values = Object.values(processedRecord);
2192
- const updateMap = {
2193
- snapshot: "excluded.snapshot",
2194
- updatedAt: "excluded.updatedAt",
2195
- resourceId: `COALESCE(excluded.resourceId, ${fullTableName}.resourceId)`
2196
- };
2197
- this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2198
- const query = createSqlBuilder().insert(
2199
- fullTableName,
2200
- columns,
2201
- values,
2202
- ["workflow_name", "run_id"],
2203
- updateMap
2204
- );
2205
- const { sql, params } = query.build();
2206
- try {
2207
- await this.#db.executeQuery({ sql, params });
2208
- } catch (error) {
2209
- throw new MastraError(
2210
- {
2211
- id: createStorageErrorId("CLOUDFLARE_DO", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2212
- domain: ErrorDomain.STORAGE,
2213
- category: ErrorCategory.THIRD_PARTY,
2214
- text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
2215
- details: { workflowName, runId }
2216
- },
2217
- error
2218
- );
2219
- }
2220
- }
2221
- async loadWorkflowSnapshot(params) {
2222
- const { workflowName, runId } = params;
2223
- this.logger.debug("Loading workflow snapshot", { workflowName, runId });
2224
- try {
2225
- const d = await this.#db.load({
2226
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2227
- keys: {
2228
- workflow_name: workflowName,
2229
- run_id: runId
2230
- }
2231
- });
2232
- return d ? d.snapshot : null;
2233
- } catch (error) {
2234
- throw new MastraError(
2235
- {
2236
- id: createStorageErrorId("CLOUDFLARE_DO", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2237
- domain: ErrorDomain.STORAGE,
2238
- category: ErrorCategory.THIRD_PARTY,
2239
- text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
2240
- details: { workflowName, runId }
2241
- },
2242
- error
2243
- );
2244
- }
2245
- }
2246
- parseWorkflowRun(row) {
2247
- let parsedSnapshot = row.snapshot;
2248
- if (typeof parsedSnapshot === "string") {
2249
- try {
2250
- parsedSnapshot = JSON.parse(row.snapshot);
2251
- } catch (e) {
2252
- this.logger.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
2253
- }
2254
- }
2255
- return {
2256
- workflowName: row.workflow_name,
2257
- runId: row.run_id,
2258
- snapshot: parsedSnapshot,
2259
- createdAt: ensureDate(row.createdAt),
2260
- updatedAt: ensureDate(row.updatedAt),
2261
- resourceId: row.resourceId
2262
- };
2263
- }
2264
- async listWorkflowRuns({
2265
- workflowName,
2266
- fromDate,
2267
- toDate,
2268
- page,
2269
- perPage,
2270
- resourceId,
2271
- status
2272
- } = {}) {
2273
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2274
- try {
2275
- const builder = createSqlBuilder().select().from(fullTableName);
2276
- const countBuilder = createSqlBuilder().count().from(fullTableName);
2277
- if (workflowName) {
2278
- builder.whereAnd("workflow_name = ?", workflowName);
2279
- countBuilder.whereAnd("workflow_name = ?", workflowName);
2280
- }
2281
- if (status) {
2282
- builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
2283
- countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
2284
- }
2285
- if (resourceId) {
2286
- const hasResourceId = await this.#db.hasColumn(fullTableName, "resourceId");
2287
- if (hasResourceId) {
2288
- builder.whereAnd("resourceId = ?", resourceId);
2289
- countBuilder.whereAnd("resourceId = ?", resourceId);
2290
- } else {
2291
- this.logger.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
2292
- }
2293
- }
2294
- if (fromDate) {
2295
- builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
2296
- countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
2297
- }
2298
- if (toDate) {
2299
- builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2300
- countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2301
- }
2302
- builder.orderBy("createdAt", "DESC");
2303
- if (typeof perPage === "number" && typeof page === "number") {
2304
- const offset = page * perPage;
2305
- builder.limit(perPage);
2306
- builder.offset(offset);
2307
- }
2308
- const { sql, params } = builder.build();
2309
- let total = 0;
2310
- if (perPage !== void 0 && page !== void 0) {
2311
- const { sql: countSql, params: countParams } = countBuilder.build();
2312
- const countResult = await this.#db.executeQuery({
2313
- sql: countSql,
2314
- params: countParams,
2315
- first: true
2316
- });
2317
- total = Number(countResult?.count ?? 0);
2318
- }
2319
- const results = await this.#db.executeQuery({ sql, params });
2320
- const runs = (isArrayOfRecords(results) ? results : []).map(
2321
- (row) => this.parseWorkflowRun(row)
2322
- );
2323
- return { runs, total: total || runs.length };
2324
- } catch (error) {
2325
- throw new MastraError(
2326
- {
2327
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_WORKFLOW_RUNS", "FAILED"),
2328
- domain: ErrorDomain.STORAGE,
2329
- category: ErrorCategory.THIRD_PARTY,
2330
- text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
2331
- details: {
2332
- workflowName: workflowName ?? "",
2333
- resourceId: resourceId ?? ""
2334
- }
2335
- },
2336
- error
2337
- );
2338
- }
2339
- }
2340
- async getWorkflowRunById({
2341
- runId,
2342
- workflowName
2343
- }) {
2344
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2345
- try {
2346
- const conditions = [];
2347
- const params = [];
2348
- if (runId) {
2349
- conditions.push("run_id = ?");
2350
- params.push(runId);
2351
- }
2352
- if (workflowName) {
2353
- conditions.push("workflow_name = ?");
2354
- params.push(workflowName);
2355
- }
2356
- const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
2357
- const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
2358
- const result = await this.#db.executeQuery({ sql, params, first: true });
2359
- if (!result) return null;
2360
- return this.parseWorkflowRun(result);
2361
- } catch (error) {
2362
- throw new MastraError(
2363
- {
2364
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2365
- domain: ErrorDomain.STORAGE,
2366
- category: ErrorCategory.THIRD_PARTY,
2367
- text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2368
- details: { runId, workflowName: workflowName ?? "" }
2369
- },
2370
- error
2371
- );
2372
- }
2373
- }
2374
- async deleteWorkflowRunById({ runId, workflowName }) {
2375
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2376
- try {
2377
- const sql = `DELETE FROM ${fullTableName} WHERE workflow_name = ? AND run_id = ?`;
2378
- const params = [workflowName, runId];
2379
- await this.#db.executeQuery({ sql, params });
2380
- } catch (error) {
2381
- throw new MastraError(
2382
- {
2383
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2384
- domain: ErrorDomain.STORAGE,
2385
- category: ErrorCategory.THIRD_PARTY,
2386
- text: `Failed to delete workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2387
- details: { runId, workflowName }
2388
- },
2389
- error
2390
- );
2391
- }
2392
- }
2393
- };
2394
-
2395
- // src/do/index.ts
2396
- var CloudflareDOStorage = class extends MastraCompositeStore {
2397
- stores;
2398
- /**
2399
- * Creates a new CloudflareDOStorage instance
2400
- * @param config Configuration for Durable Objects SqlStorage access
2401
- */
2402
- constructor(config) {
2403
- try {
2404
- super({ id: "do-store", name: "DO", disableInit: config.disableInit });
2405
- if (config.tablePrefix && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(config.tablePrefix)) {
2406
- throw new Error(
2407
- "Invalid tablePrefix: must start with a letter or underscore and contain only letters, numbers, and underscores."
2408
- );
2409
- }
2410
- const domainConfig = { sql: config.sql, tablePrefix: config.tablePrefix };
2411
- this.stores = {
2412
- memory: new MemoryStorageDO(domainConfig),
2413
- workflows: new WorkflowsStorageDO(domainConfig),
2414
- scores: new ScoresStorageDO(domainConfig),
2415
- backgroundTasks: new BackgroundTasksStorageDO(domainConfig)
2416
- };
2417
- this.logger.info("Using Durable Objects SqlStorage");
2418
- } catch (error) {
2419
- throw new MastraError(
2420
- {
2421
- id: createStorageErrorId("CLOUDFLARE_DO", "INITIALIZATION", "FAILED"),
2422
- domain: ErrorDomain.STORAGE,
2423
- category: ErrorCategory.SYSTEM,
2424
- text: "Error initializing CloudflareDOStorage"
2425
- },
2426
- error
2427
- );
2428
- }
2429
- }
2430
- /**
2431
- * Close the database connection
2432
- * No explicit cleanup needed for DO storage
2433
- */
2434
- async close() {
2435
- this.logger.debug("Closing DO connection");
2436
- }
2437
- };
2438
- var DOStore = CloudflareDOStorage;
2439
-
2440
- export { BackgroundTasksStorageDO, CloudflareDOStorage, DODB, DOStore, MemoryStorageDO, ScoresStorageDO, WorkflowsStorageDO };
2441
- //# sourceMappingURL=chunk-OMTTR37Z.js.map
2442
- //# sourceMappingURL=chunk-OMTTR37Z.js.map