@mastra/cloudflare 1.6.0-alpha.0 → 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,2486 +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, validateStorageMetadataFilter, 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
- function addSqliteMetadataFilter(conditions, params, metadataFilter) {
949
- if (!metadataFilter) return;
950
- for (const [key, value] of Object.entries(metadataFilter)) {
951
- const path = `$.metadata.${key}`;
952
- conditions.push(`CASE WHEN json_valid(content) THEN json_type(content, ?) IS NOT NULL ELSE 0 END`);
953
- params.push(path);
954
- addSqliteMetadataValuePredicate(conditions, params, path, value);
955
- }
956
- }
957
- function addSqliteMetadataValuePredicate(conditions, params, path, value) {
958
- if (value === null) {
959
- conditions.push(`CASE WHEN json_valid(content) THEN json_type(content, ?) = 'null' ELSE 0 END`);
960
- params.push(path);
961
- return;
962
- }
963
- if (typeof value === "string") {
964
- conditions.push(
965
- `CASE WHEN json_valid(content) THEN json_type(content, ?) = 'text' AND json_extract(content, ?) = ? ELSE 0 END`
966
- );
967
- params.push(path, path, value);
968
- return;
969
- }
970
- if (typeof value === "number") {
971
- conditions.push(
972
- `CASE WHEN json_valid(content) THEN json_type(content, ?) IN ('integer', 'real') AND json_extract(content, ?) = ? ELSE 0 END`
973
- );
974
- params.push(path, path, value);
975
- return;
976
- }
977
- conditions.push(
978
- `CASE WHEN json_valid(content) THEN json_type(content, ?) = ? AND json_extract(content, ?) = ? ELSE 0 END`
979
- );
980
- params.push(path, value ? "true" : "false", path, value ? 1 : 0);
981
- }
982
- var MemoryStorageDO = class extends MemoryStorage {
983
- #db;
984
- constructor(config) {
985
- super();
986
- this.#db = new DODB(config);
987
- }
988
- async init() {
989
- await this.#db.createTable({ tableName: TABLE_THREADS, schema: TABLE_SCHEMAS[TABLE_THREADS] });
990
- await this.#db.createTable({ tableName: TABLE_MESSAGES, schema: TABLE_SCHEMAS[TABLE_MESSAGES] });
991
- await this.#db.createTable({ tableName: TABLE_RESOURCES, schema: TABLE_SCHEMAS[TABLE_RESOURCES] });
992
- await this.#db.alterTable({
993
- tableName: TABLE_MESSAGES,
994
- schema: TABLE_SCHEMAS[TABLE_MESSAGES],
995
- ifNotExists: ["resourceId"]
996
- });
997
- }
998
- async dangerouslyClearAll() {
999
- await this.#db.clearTable({ tableName: TABLE_MESSAGES });
1000
- await this.#db.clearTable({ tableName: TABLE_THREADS });
1001
- await this.#db.clearTable({ tableName: TABLE_RESOURCES });
1002
- }
1003
- async getResourceById({ resourceId }) {
1004
- const resource = await this.#db.load({
1005
- tableName: TABLE_RESOURCES,
1006
- keys: { id: resourceId }
1007
- });
1008
- if (!resource) return null;
1009
- try {
1010
- return {
1011
- ...resource,
1012
- createdAt: ensureDate(resource.createdAt),
1013
- updatedAt: ensureDate(resource.updatedAt),
1014
- metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
1015
- };
1016
- } catch (error) {
1017
- const mastraError = new MastraError(
1018
- {
1019
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_RESOURCE_BY_ID", "FAILED"),
1020
- domain: ErrorDomain.STORAGE,
1021
- category: ErrorCategory.THIRD_PARTY,
1022
- text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
1023
- details: { resourceId }
1024
- },
1025
- error
1026
- );
1027
- this.logger?.error(mastraError.toString());
1028
- this.logger?.trackException(mastraError);
1029
- return null;
1030
- }
1031
- }
1032
- async saveResource({ resource }) {
1033
- const fullTableName = this.#db.getTableName(TABLE_RESOURCES);
1034
- const resourceToSave = {
1035
- id: resource.id,
1036
- workingMemory: resource.workingMemory,
1037
- metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
1038
- createdAt: resource.createdAt,
1039
- updatedAt: resource.updatedAt
1040
- };
1041
- const processedRecord = await this.#db.processRecord(resourceToSave);
1042
- const columns = Object.keys(processedRecord);
1043
- const values = Object.values(processedRecord);
1044
- const updateMap = {
1045
- workingMemory: "excluded.workingMemory",
1046
- metadata: "excluded.metadata",
1047
- createdAt: "excluded.createdAt",
1048
- updatedAt: "excluded.updatedAt"
1049
- };
1050
- const query = createSqlBuilder().insert(
1051
- fullTableName,
1052
- columns,
1053
- values,
1054
- ["id"],
1055
- updateMap
1056
- );
1057
- const { sql, params } = query.build();
1058
- try {
1059
- await this.#db.executeQuery({ sql, params });
1060
- return resource;
1061
- } catch (error) {
1062
- throw new MastraError(
1063
- {
1064
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_RESOURCE", "FAILED"),
1065
- domain: ErrorDomain.STORAGE,
1066
- category: ErrorCategory.THIRD_PARTY,
1067
- text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
1068
- details: { resourceId: resource.id }
1069
- },
1070
- error
1071
- );
1072
- }
1073
- }
1074
- async updateResource({
1075
- resourceId,
1076
- workingMemory,
1077
- metadata
1078
- }) {
1079
- const existingResource = await this.getResourceById({ resourceId });
1080
- if (!existingResource) {
1081
- const newResource = {
1082
- id: resourceId,
1083
- workingMemory,
1084
- metadata: metadata || {},
1085
- createdAt: /* @__PURE__ */ new Date(),
1086
- updatedAt: /* @__PURE__ */ new Date()
1087
- };
1088
- return this.saveResource({ resource: newResource });
1089
- }
1090
- const updatedAt = /* @__PURE__ */ new Date();
1091
- const updatedResource = {
1092
- ...existingResource,
1093
- workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1094
- metadata: {
1095
- ...existingResource.metadata,
1096
- ...metadata
1097
- },
1098
- updatedAt
1099
- };
1100
- const fullTableName = this.#db.getTableName(TABLE_RESOURCES);
1101
- const columns = ["workingMemory", "metadata", "updatedAt"];
1102
- const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
1103
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
1104
- const { sql, params } = query.build();
1105
- try {
1106
- await this.#db.executeQuery({ sql, params });
1107
- return updatedResource;
1108
- } catch (error) {
1109
- throw new MastraError(
1110
- {
1111
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_RESOURCE", "FAILED"),
1112
- domain: ErrorDomain.STORAGE,
1113
- category: ErrorCategory.THIRD_PARTY,
1114
- text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
1115
- details: { resourceId }
1116
- },
1117
- error
1118
- );
1119
- }
1120
- }
1121
- async getThreadById({
1122
- threadId,
1123
- resourceId
1124
- }) {
1125
- const thread = await this.#db.load({
1126
- tableName: TABLE_THREADS,
1127
- keys: { id: threadId }
1128
- });
1129
- if (!thread || resourceId !== void 0 && thread.resourceId !== resourceId) return null;
1130
- try {
1131
- return {
1132
- ...thread,
1133
- createdAt: ensureDate(thread.createdAt),
1134
- updatedAt: ensureDate(thread.updatedAt),
1135
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
1136
- };
1137
- } catch (error) {
1138
- const mastraError = new MastraError(
1139
- {
1140
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_THREAD_BY_ID", "FAILED"),
1141
- domain: ErrorDomain.STORAGE,
1142
- category: ErrorCategory.THIRD_PARTY,
1143
- text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1144
- details: { threadId }
1145
- },
1146
- error
1147
- );
1148
- this.logger?.error(mastraError.toString());
1149
- this.logger?.trackException(mastraError);
1150
- return null;
1151
- }
1152
- }
1153
- async listThreads(args) {
1154
- const { page = 0, perPage: perPageInput, orderBy, filter } = args;
1155
- try {
1156
- this.validatePaginationInput(page, perPageInput ?? 100);
1157
- } catch (error) {
1158
- throw new MastraError(
1159
- {
1160
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_PAGE"),
1161
- domain: ErrorDomain.STORAGE,
1162
- category: ErrorCategory.USER,
1163
- details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
1164
- },
1165
- error instanceof Error ? error : new Error("Invalid pagination parameters")
1166
- );
1167
- }
1168
- const perPage = normalizePerPage(perPageInput, 100);
1169
- try {
1170
- this.validateMetadataKeys(filter?.metadata);
1171
- } catch (error) {
1172
- throw new MastraError(
1173
- {
1174
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_METADATA_KEY"),
1175
- domain: ErrorDomain.STORAGE,
1176
- category: ErrorCategory.USER,
1177
- details: { metadataKeys: filter?.metadata ? Object.keys(filter.metadata).join(", ") : "" }
1178
- },
1179
- error instanceof Error ? error : new Error("Invalid metadata key")
1180
- );
1181
- }
1182
- const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1183
- const { field, direction } = this.parseOrderBy(orderBy);
1184
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1185
- const mapRowToStorageThreadType = (row) => ({
1186
- ...row,
1187
- createdAt: ensureDate(row.createdAt),
1188
- updatedAt: ensureDate(row.updatedAt),
1189
- metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
1190
- });
1191
- try {
1192
- let countQuery = createSqlBuilder().count().from(fullTableName);
1193
- let selectQuery = createSqlBuilder().select("*").from(fullTableName);
1194
- if (filter?.resourceId) {
1195
- countQuery = countQuery.whereAnd("resourceId = ?", filter.resourceId);
1196
- selectQuery = selectQuery.whereAnd("resourceId = ?", filter.resourceId);
1197
- }
1198
- if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
1199
- for (const [key, value] of Object.entries(filter.metadata)) {
1200
- if (value !== null && typeof value === "object") {
1201
- throw new MastraError(
1202
- {
1203
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "INVALID_METADATA_VALUE"),
1204
- domain: ErrorDomain.STORAGE,
1205
- category: ErrorCategory.USER,
1206
- text: `Metadata filter value for key "${key}" must be a scalar type (string, number, boolean, or null), got ${Array.isArray(value) ? "array" : "object"}`,
1207
- details: { key, valueType: Array.isArray(value) ? "array" : "object" }
1208
- },
1209
- new Error("Invalid metadata filter value type")
1210
- );
1211
- }
1212
- if (value === null) {
1213
- const condition = `json_extract(metadata, '$.${key}') IS NULL`;
1214
- countQuery = countQuery.whereAnd(condition);
1215
- selectQuery = selectQuery.whereAnd(condition);
1216
- } else {
1217
- const condition = `json_extract(metadata, '$.${key}') = ?`;
1218
- const filterValue = value;
1219
- countQuery = countQuery.whereAnd(condition, filterValue);
1220
- selectQuery = selectQuery.whereAnd(condition, filterValue);
1221
- }
1222
- }
1223
- }
1224
- const countResult = await this.#db.executeQuery(countQuery.build());
1225
- const total = Number(countResult?.[0]?.count ?? 0);
1226
- if (total === 0) {
1227
- return {
1228
- threads: [],
1229
- total: 0,
1230
- page,
1231
- perPage: perPageForResponse,
1232
- hasMore: false
1233
- };
1234
- }
1235
- const limitValue = perPageInput === false ? total : perPage;
1236
- selectQuery = selectQuery.orderBy(field, direction).limit(limitValue).offset(offset);
1237
- const results = await this.#db.executeQuery(selectQuery.build());
1238
- const threads = results.map(mapRowToStorageThreadType);
1239
- return {
1240
- threads,
1241
- total,
1242
- page,
1243
- perPage: perPageForResponse,
1244
- hasMore: perPageInput === false ? false : offset + perPage < total
1245
- };
1246
- } catch (error) {
1247
- if (error instanceof MastraError && error.category === ErrorCategory.USER) {
1248
- throw error;
1249
- }
1250
- const mastraError = new MastraError(
1251
- {
1252
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_THREADS", "FAILED"),
1253
- domain: ErrorDomain.STORAGE,
1254
- category: ErrorCategory.THIRD_PARTY,
1255
- text: `Error listing threads: ${error instanceof Error ? error.message : String(error)}`,
1256
- details: {
1257
- ...filter?.resourceId && { resourceId: filter.resourceId },
1258
- hasMetadataFilter: !!filter?.metadata
1259
- }
1260
- },
1261
- error
1262
- );
1263
- this.logger?.error(mastraError.toString());
1264
- this.logger?.trackException(mastraError);
1265
- return {
1266
- threads: [],
1267
- total: 0,
1268
- page,
1269
- perPage: perPageForResponse,
1270
- hasMore: false
1271
- };
1272
- }
1273
- }
1274
- async saveThread({ thread }) {
1275
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1276
- const threadToSave = {
1277
- id: thread.id,
1278
- resourceId: thread.resourceId,
1279
- title: thread.title,
1280
- metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
1281
- createdAt: thread.createdAt.toISOString(),
1282
- updatedAt: thread.updatedAt.toISOString()
1283
- };
1284
- const processedRecord = await this.#db.processRecord(threadToSave);
1285
- const columns = Object.keys(processedRecord);
1286
- const values = Object.values(processedRecord);
1287
- const updateMap = {
1288
- resourceId: "excluded.resourceId",
1289
- title: "excluded.title",
1290
- metadata: "excluded.metadata",
1291
- createdAt: "excluded.createdAt",
1292
- updatedAt: "excluded.updatedAt"
1293
- };
1294
- const query = createSqlBuilder().insert(
1295
- fullTableName,
1296
- columns,
1297
- values,
1298
- ["id"],
1299
- updateMap
1300
- );
1301
- const { sql, params } = query.build();
1302
- try {
1303
- await this.#db.executeQuery({ sql, params });
1304
- return thread;
1305
- } catch (error) {
1306
- throw new MastraError(
1307
- {
1308
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_THREAD", "FAILED"),
1309
- domain: ErrorDomain.STORAGE,
1310
- category: ErrorCategory.THIRD_PARTY,
1311
- text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
1312
- details: { threadId: thread.id }
1313
- },
1314
- error
1315
- );
1316
- }
1317
- }
1318
- async updateThread({
1319
- id,
1320
- title,
1321
- metadata
1322
- }) {
1323
- const thread = await this.getThreadById({ threadId: id });
1324
- try {
1325
- if (!thread) {
1326
- throw new Error(`Thread ${id} not found`);
1327
- }
1328
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1329
- const mergedMetadata = {
1330
- ...thread.metadata,
1331
- ...metadata
1332
- };
1333
- const updatedAt = /* @__PURE__ */ new Date();
1334
- const columns = ["title", "metadata", "updatedAt"];
1335
- const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
1336
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
1337
- const { sql, params } = query.build();
1338
- await this.#db.executeQuery({ sql, params });
1339
- return {
1340
- ...thread,
1341
- title,
1342
- metadata: mergedMetadata,
1343
- updatedAt
1344
- };
1345
- } catch (error) {
1346
- throw new MastraError(
1347
- {
1348
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_THREAD", "FAILED"),
1349
- domain: ErrorDomain.STORAGE,
1350
- category: ErrorCategory.THIRD_PARTY,
1351
- text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
1352
- details: { threadId: id }
1353
- },
1354
- error
1355
- );
1356
- }
1357
- }
1358
- async deleteThread({ threadId }) {
1359
- const fullTableName = this.#db.getTableName(TABLE_THREADS);
1360
- try {
1361
- const messagesTableName = this.#db.getTableName(TABLE_MESSAGES);
1362
- const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
1363
- const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
1364
- await this.#db.executeQuery({ sql: messagesSql, params: messagesParams });
1365
- const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
1366
- const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
1367
- await this.#db.executeQuery({ sql: threadSql, params: threadParams });
1368
- } catch (error) {
1369
- throw new MastraError(
1370
- {
1371
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_THREAD", "FAILED"),
1372
- domain: ErrorDomain.STORAGE,
1373
- category: ErrorCategory.THIRD_PARTY,
1374
- text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1375
- details: { threadId }
1376
- },
1377
- error
1378
- );
1379
- }
1380
- }
1381
- async saveMessages(args) {
1382
- const { messages } = args;
1383
- if (messages.length === 0) return { messages: [] };
1384
- try {
1385
- const now = /* @__PURE__ */ new Date();
1386
- for (const [i, message] of messages.entries()) {
1387
- if (!message.id) throw new Error(`Message at index ${i} missing id`);
1388
- if (!message.threadId) {
1389
- throw new Error(`Message at index ${i} missing threadId`);
1390
- }
1391
- if (!message.content) {
1392
- throw new Error(`Message at index ${i} missing content`);
1393
- }
1394
- if (!message.role) {
1395
- throw new Error(`Message at index ${i} missing role`);
1396
- }
1397
- if (!message.resourceId) {
1398
- throw new Error(`Message at index ${i} missing resourceId`);
1399
- }
1400
- }
1401
- const uniqueThreadIds = [...new Set(messages.map((m) => m.threadId))];
1402
- const threads = await Promise.all(uniqueThreadIds.map((id) => this.getThreadById({ threadId: id })));
1403
- const missingThreadId = uniqueThreadIds.find((id, i) => !threads[i]);
1404
- if (missingThreadId) {
1405
- throw new Error(`Thread ${missingThreadId} not found`);
1406
- }
1407
- const messagesToInsert = messages.map((message) => {
1408
- const createdAt = message.createdAt ? new Date(message.createdAt) : now;
1409
- return {
1410
- id: message.id,
1411
- thread_id: message.threadId,
1412
- content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
1413
- createdAt: createdAt.toISOString(),
1414
- role: message.role,
1415
- type: message.type || "v2",
1416
- resourceId: message.resourceId
1417
- };
1418
- });
1419
- await Promise.all([
1420
- this.#db.batchUpsert({
1421
- tableName: TABLE_MESSAGES,
1422
- records: messagesToInsert
1423
- }),
1424
- // Update updatedAt timestamp for all affected threads
1425
- ...uniqueThreadIds.map(
1426
- (tid) => this.#db.executeQuery({
1427
- sql: `UPDATE ${this.#db.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
1428
- params: [now.toISOString(), tid]
1429
- })
1430
- )
1431
- ]);
1432
- this.logger.debug(`Saved ${messages.length} messages`);
1433
- const list = new MessageList().add(messages, "memory");
1434
- return { messages: list.get.all.db() };
1435
- } catch (error) {
1436
- throw new MastraError(
1437
- {
1438
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_MESSAGES", "FAILED"),
1439
- domain: ErrorDomain.STORAGE,
1440
- category: ErrorCategory.THIRD_PARTY,
1441
- text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
1442
- },
1443
- error
1444
- );
1445
- }
1446
- }
1447
- async _getIncludedMessages(include) {
1448
- if (!include || include.length === 0) return null;
1449
- const unionQueries = [];
1450
- const params = [];
1451
- let paramIdx = 1;
1452
- const tableName = this.#db.getTableName(TABLE_MESSAGES);
1453
- for (const inc of include) {
1454
- const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
1455
- unionQueries.push(`
1456
- SELECT * FROM (
1457
- WITH target_thread AS (
1458
- SELECT thread_id FROM ${tableName} WHERE id = ?
1459
- ),
1460
- ordered_messages AS (
1461
- SELECT
1462
- *,
1463
- ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
1464
- FROM ${tableName}
1465
- WHERE thread_id = (SELECT thread_id FROM target_thread)
1466
- )
1467
- SELECT
1468
- m.id,
1469
- m.content,
1470
- m.role,
1471
- m.type,
1472
- m.createdAt,
1473
- m.thread_id AS threadId,
1474
- m.resourceId
1475
- FROM ordered_messages m
1476
- WHERE m.id = ?
1477
- OR EXISTS (
1478
- SELECT 1 FROM ordered_messages target
1479
- WHERE target.id = ?
1480
- AND (
1481
- (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
1482
- OR
1483
- (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
1484
- )
1485
- )
1486
- ) AS query_${paramIdx}
1487
- `);
1488
- params.push(id, id, id, withNextMessages, withPreviousMessages);
1489
- paramIdx++;
1490
- }
1491
- const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
1492
- const messages = await this.#db.executeQuery({
1493
- sql: finalQuery,
1494
- params
1495
- });
1496
- if (!Array.isArray(messages)) {
1497
- return [];
1498
- }
1499
- const processedMessages = messages.map((message) => {
1500
- const processedMsg = {};
1501
- for (const [key, value] of Object.entries(message)) {
1502
- if (key === `type` && value === `v2`) continue;
1503
- processedMsg[key] = deserializeValue(value);
1504
- }
1505
- return processedMsg;
1506
- });
1507
- return processedMessages;
1508
- }
1509
- async listMessagesById({ messageIds }) {
1510
- if (messageIds.length === 0) return { messages: [] };
1511
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1512
- const messages = [];
1513
- try {
1514
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
1515
- query.orderBy("createdAt", "DESC");
1516
- const { sql, params } = query.build();
1517
- const result = await this.#db.executeQuery({ sql, params });
1518
- if (Array.isArray(result)) messages.push(...result);
1519
- const processedMessages = messages.map((message) => {
1520
- const processedMsg = {};
1521
- for (const [key, value] of Object.entries(message)) {
1522
- if (key === `type` && value === `v2`) continue;
1523
- processedMsg[key] = deserializeValue(value);
1524
- }
1525
- return processedMsg;
1526
- });
1527
- this.logger.debug(`Retrieved ${messages.length} messages`);
1528
- const list = new MessageList().add(processedMessages, "memory");
1529
- return { messages: list.get.all.db() };
1530
- } catch (error) {
1531
- const mastraError = new MastraError(
1532
- {
1533
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES_BY_ID", "FAILED"),
1534
- domain: ErrorDomain.STORAGE,
1535
- category: ErrorCategory.THIRD_PARTY,
1536
- text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
1537
- details: { messageIds: JSON.stringify(messageIds) }
1538
- },
1539
- error
1540
- );
1541
- this.logger?.error?.(mastraError.toString());
1542
- this.logger?.trackException?.(mastraError);
1543
- throw mastraError;
1544
- }
1545
- }
1546
- async listMessages(args) {
1547
- const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1548
- const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1549
- if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
1550
- throw new MastraError(
1551
- {
1552
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "INVALID_THREAD_ID"),
1553
- domain: ErrorDomain.STORAGE,
1554
- category: ErrorCategory.THIRD_PARTY,
1555
- details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
1556
- },
1557
- new Error("threadId must be a non-empty string or array of non-empty strings")
1558
- );
1559
- }
1560
- if (page < 0) {
1561
- throw new MastraError(
1562
- {
1563
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "INVALID_PAGE"),
1564
- domain: ErrorDomain.STORAGE,
1565
- category: ErrorCategory.USER,
1566
- details: { page }
1567
- },
1568
- new Error("page must be >= 0")
1569
- );
1570
- }
1571
- const perPage = normalizePerPage(perPageInput, 40);
1572
- const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1573
- const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
1574
- try {
1575
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1576
- const placeholders = threadIds.map(() => "?").join(", ");
1577
- let query = `
1578
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1579
- FROM ${fullTableName}
1580
- WHERE thread_id IN (${placeholders})
1581
- `;
1582
- const queryParams = [...threadIds];
1583
- if (resourceId) {
1584
- query += ` AND resourceId = ?`;
1585
- queryParams.push(resourceId);
1586
- }
1587
- const dateRange = filter?.dateRange;
1588
- if (dateRange?.start) {
1589
- const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
1590
- const startOp = dateRange.startExclusive ? ">" : ">=";
1591
- query += ` AND createdAt ${startOp} ?`;
1592
- queryParams.push(startDate);
1593
- }
1594
- if (dateRange?.end) {
1595
- const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
1596
- const endOp = dateRange.endExclusive ? "<" : "<=";
1597
- query += ` AND createdAt ${endOp} ?`;
1598
- queryParams.push(endDate);
1599
- }
1600
- const metadataConditions = [];
1601
- addSqliteMetadataFilter(metadataConditions, queryParams, metadataFilter);
1602
- if (metadataConditions.length > 0) {
1603
- query += ` AND ${metadataConditions.join(" AND ")}`;
1604
- }
1605
- const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1606
- query += ` ORDER BY "${field}" ${direction}`;
1607
- if (perPage !== Number.MAX_SAFE_INTEGER) {
1608
- query += ` LIMIT ? OFFSET ?`;
1609
- queryParams.push(perPage, offset);
1610
- }
1611
- const results = await this.#db.executeQuery({
1612
- sql: query,
1613
- params: queryParams
1614
- });
1615
- const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
1616
- const processedMsg = {};
1617
- for (const [key, value] of Object.entries(message)) {
1618
- if (key === `type` && value === `v2`) continue;
1619
- processedMsg[key] = deserializeValue(value);
1620
- }
1621
- return processedMsg;
1622
- });
1623
- const paginatedCount = paginatedMessages.length;
1624
- let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
1625
- const countParams = [threadId];
1626
- if (resourceId) {
1627
- countQuery += ` AND resourceId = ?`;
1628
- countParams.push(resourceId);
1629
- }
1630
- if (dateRange?.start) {
1631
- const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
1632
- const startOp = dateRange.startExclusive ? ">" : ">=";
1633
- countQuery += ` AND createdAt ${startOp} ?`;
1634
- countParams.push(startDate);
1635
- }
1636
- if (dateRange?.end) {
1637
- const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
1638
- const endOp = dateRange.endExclusive ? "<" : "<=";
1639
- countQuery += ` AND createdAt ${endOp} ?`;
1640
- countParams.push(endDate);
1641
- }
1642
- const countMetadataConditions = [];
1643
- addSqliteMetadataFilter(countMetadataConditions, countParams, metadataFilter);
1644
- if (countMetadataConditions.length > 0) {
1645
- countQuery += ` AND ${countMetadataConditions.join(" AND ")}`;
1646
- }
1647
- const countResult = await this.#db.executeQuery({
1648
- sql: countQuery,
1649
- params: countParams
1650
- });
1651
- const total = Number(countResult[0]?.count ?? 0);
1652
- if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
1653
- return {
1654
- messages: [],
1655
- total: 0,
1656
- page,
1657
- perPage: perPageForResponse,
1658
- hasMore: false
1659
- };
1660
- }
1661
- const messageIds = new Set(paginatedMessages.map((m) => m.id));
1662
- let includeMessages = [];
1663
- if (include && include.length > 0) {
1664
- const includeResult = await this._getIncludedMessages(include);
1665
- if (Array.isArray(includeResult)) {
1666
- includeMessages = includeResult;
1667
- for (const includeMsg of includeMessages) {
1668
- if (!messageIds.has(includeMsg.id)) {
1669
- paginatedMessages.push(includeMsg);
1670
- messageIds.add(includeMsg.id);
1671
- }
1672
- }
1673
- }
1674
- }
1675
- const list = new MessageList().add(paginatedMessages, "memory");
1676
- let finalMessages = list.get.all.db();
1677
- finalMessages = finalMessages.sort((a, b) => {
1678
- const isDateField = field === "createdAt" || field === "updatedAt";
1679
- const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
1680
- const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
1681
- if (aValue === bValue) {
1682
- return a.id.localeCompare(b.id);
1683
- }
1684
- if (typeof aValue === "number" && typeof bValue === "number") {
1685
- return direction === "ASC" ? aValue - bValue : bValue - aValue;
1686
- }
1687
- return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1688
- });
1689
- const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1690
- const hasMore = perPageInput !== false && (metadataFilter || returnedThreadMessageIds.size < total) && offset + paginatedCount < total;
1691
- return {
1692
- messages: finalMessages,
1693
- total,
1694
- page,
1695
- perPage: perPageForResponse,
1696
- hasMore
1697
- };
1698
- } catch (error) {
1699
- const mastraError = new MastraError(
1700
- {
1701
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_MESSAGES", "FAILED"),
1702
- domain: ErrorDomain.STORAGE,
1703
- category: ErrorCategory.THIRD_PARTY,
1704
- text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error instanceof Error ? error.message : String(error)}`,
1705
- details: {
1706
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1707
- resourceId: resourceId ?? ""
1708
- }
1709
- },
1710
- error
1711
- );
1712
- this.logger?.error?.(mastraError.toString());
1713
- this.logger?.trackException?.(mastraError);
1714
- return {
1715
- messages: [],
1716
- total: 0,
1717
- page,
1718
- perPage: perPageForResponse,
1719
- hasMore: false
1720
- };
1721
- }
1722
- }
1723
- async updateMessages(args) {
1724
- const { messages } = args;
1725
- this.logger.debug("Updating messages", { count: messages.length });
1726
- if (!messages.length) {
1727
- return [];
1728
- }
1729
- const messageIds = messages.map((m) => m.id);
1730
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1731
- const threadsTableName = this.#db.getTableName(TABLE_THREADS);
1732
- try {
1733
- const placeholders = messageIds.map(() => "?").join(",");
1734
- const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
1735
- const existingMessages = await this.#db.executeQuery({ sql: selectQuery, params: messageIds });
1736
- if (existingMessages.length === 0) {
1737
- return [];
1738
- }
1739
- const parsedExistingMessages = existingMessages.map((msg) => {
1740
- let parsedContent = msg.content;
1741
- if (typeof msg.content === "string") {
1742
- try {
1743
- parsedContent = JSON.parse(msg.content);
1744
- } catch {
1745
- }
1746
- }
1747
- return { ...msg, content: parsedContent };
1748
- });
1749
- const existingMessagesMap = new Map(parsedExistingMessages.map((msg) => [msg.id, msg]));
1750
- const updatedMessages = [];
1751
- const now = (/* @__PURE__ */ new Date()).toISOString();
1752
- for (const update of messages) {
1753
- const existing = existingMessagesMap.get(update.id);
1754
- if (!existing) continue;
1755
- let mergedContent = existing.content;
1756
- if (update.content) {
1757
- if (typeof mergedContent === "object" && mergedContent !== null) {
1758
- mergedContent = {
1759
- ...mergedContent,
1760
- ...update.content,
1761
- metadata: {
1762
- ...mergedContent.metadata,
1763
- ...update.content.metadata
1764
- }
1765
- };
1766
- } else {
1767
- mergedContent = update.content;
1768
- }
1769
- }
1770
- updatedMessages.push({
1771
- ...existing,
1772
- ...update,
1773
- content: mergedContent
1774
- });
1775
- }
1776
- for (const msg of updatedMessages) {
1777
- const contentStr = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1778
- const updateQuery = createSqlBuilder().update(fullTableName, ["content", "role", "type"], [contentStr, msg.role, msg.type]).where("id = ?", msg.id);
1779
- const { sql, params } = updateQuery.build();
1780
- await this.#db.executeQuery({ sql, params });
1781
- }
1782
- const threadIds = [...new Set(updatedMessages.map((m) => m.threadId))];
1783
- for (const tid of threadIds) {
1784
- await this.#db.executeQuery({
1785
- sql: `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id = ?`,
1786
- params: [now, tid]
1787
- });
1788
- }
1789
- const list = new MessageList().add(updatedMessages, "memory");
1790
- return list.get.all.db();
1791
- } catch (error) {
1792
- throw new MastraError(
1793
- {
1794
- id: createStorageErrorId("CLOUDFLARE_DO", "UPDATE_MESSAGES", "FAILED"),
1795
- domain: ErrorDomain.STORAGE,
1796
- category: ErrorCategory.THIRD_PARTY,
1797
- text: `Failed to update messages: ${error instanceof Error ? error.message : String(error)}`,
1798
- details: { messageIds: JSON.stringify(messageIds) }
1799
- },
1800
- error
1801
- );
1802
- }
1803
- }
1804
- async deleteMessages(messageIds) {
1805
- if (messageIds.length === 0) return;
1806
- const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1807
- try {
1808
- const placeholders = messageIds.map(() => "?").join(",");
1809
- const sql = `DELETE FROM ${fullTableName} WHERE id IN (${placeholders})`;
1810
- await this.#db.executeQuery({ sql, params: messageIds });
1811
- this.logger.debug(`Deleted ${messageIds.length} messages`);
1812
- } catch (error) {
1813
- throw new MastraError(
1814
- {
1815
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_MESSAGES", "FAILED"),
1816
- domain: ErrorDomain.STORAGE,
1817
- category: ErrorCategory.THIRD_PARTY,
1818
- text: `Failed to delete messages: ${error instanceof Error ? error.message : String(error)}`,
1819
- details: { messageIds: JSON.stringify(messageIds) }
1820
- },
1821
- error
1822
- );
1823
- }
1824
- }
1825
- };
1826
- function applyTenancyFilters(query, filters) {
1827
- if (filters?.organizationId !== void 0) {
1828
- query.andWhere("organizationId = ?", filters.organizationId);
1829
- }
1830
- if (filters?.projectId !== void 0) {
1831
- query.andWhere("projectId = ?", filters.projectId);
1832
- }
1833
- }
1834
- function transformScoreRow(row) {
1835
- return transformScoreRow$1(row, {
1836
- preferredTimestampFields: {
1837
- createdAt: "createdAtZ",
1838
- updatedAt: "updatedAtZ"
1839
- }
1840
- });
1841
- }
1842
- var ScoresStorageDO = class extends ScoresStorage {
1843
- #db;
1844
- constructor(config) {
1845
- super();
1846
- this.#db = new DODB(config);
1847
- }
1848
- async init() {
1849
- await this.#db.createTable({ tableName: TABLE_SCORERS, schema: TABLE_SCHEMAS[TABLE_SCORERS] });
1850
- }
1851
- async dangerouslyClearAll() {
1852
- await this.#db.clearTable({ tableName: TABLE_SCORERS });
1853
- }
1854
- async getScoreById({ id }) {
1855
- try {
1856
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1857
- const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
1858
- const { sql, params } = query.build();
1859
- const result = await this.#db.executeQuery({ sql, params, first: true });
1860
- if (!result) {
1861
- return null;
1862
- }
1863
- return transformScoreRow(result);
1864
- } catch (error) {
1865
- throw new MastraError(
1866
- {
1867
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORE_BY_ID", "FAILED"),
1868
- domain: ErrorDomain.STORAGE,
1869
- category: ErrorCategory.THIRD_PARTY
1870
- },
1871
- error
1872
- );
1873
- }
1874
- }
1875
- async saveScore(score) {
1876
- let parsedScore;
1877
- try {
1878
- parsedScore = saveScorePayloadSchema.parse(score);
1879
- } catch (error) {
1880
- const safeScore = score && typeof score === "object" ? score : {};
1881
- const safeScorer = safeScore.scorer && typeof safeScore.scorer === "object" ? safeScore.scorer : {};
1882
- throw new MastraError(
1883
- {
1884
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_SCORE", "VALIDATION_FAILED"),
1885
- domain: ErrorDomain.STORAGE,
1886
- category: ErrorCategory.USER,
1887
- details: {
1888
- scorer: typeof safeScorer.id === "string" ? safeScorer.id : String(safeScorer.id ?? "unknown"),
1889
- entityId: safeScore.entityId ?? "unknown",
1890
- entityType: safeScore.entityType ?? "unknown",
1891
- traceId: safeScore.traceId ?? "",
1892
- spanId: safeScore.spanId ?? ""
1893
- }
1894
- },
1895
- error
1896
- );
1897
- }
1898
- const id = crypto.randomUUID();
1899
- try {
1900
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1901
- const serializedRecord = {};
1902
- for (const [key, value] of Object.entries(parsedScore)) {
1903
- if (value !== null && value !== void 0) {
1904
- if (typeof value === "object") {
1905
- serializedRecord[key] = JSON.stringify(value);
1906
- } else {
1907
- serializedRecord[key] = value;
1908
- }
1909
- } else {
1910
- serializedRecord[key] = null;
1911
- }
1912
- }
1913
- const now = /* @__PURE__ */ new Date();
1914
- serializedRecord.id = id;
1915
- serializedRecord.createdAt = now.toISOString();
1916
- serializedRecord.updatedAt = now.toISOString();
1917
- const columns = Object.keys(serializedRecord);
1918
- const values = Object.values(serializedRecord);
1919
- const query = createSqlBuilder().insert(
1920
- fullTableName,
1921
- columns,
1922
- values
1923
- );
1924
- const { sql, params } = query.build();
1925
- await this.#db.executeQuery({ sql, params });
1926
- return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1927
- } catch (error) {
1928
- throw new MastraError(
1929
- {
1930
- id: createStorageErrorId("CLOUDFLARE_DO", "SAVE_SCORE", "FAILED"),
1931
- domain: ErrorDomain.STORAGE,
1932
- category: ErrorCategory.THIRD_PARTY,
1933
- details: { id }
1934
- },
1935
- error
1936
- );
1937
- }
1938
- }
1939
- async listScoresByScorerId({
1940
- scorerId,
1941
- entityId,
1942
- entityType,
1943
- source,
1944
- pagination,
1945
- filters
1946
- }) {
1947
- try {
1948
- const { page, perPage: perPageInput } = pagination;
1949
- const perPage = normalizePerPage(perPageInput, 100);
1950
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1951
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
1952
- const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1953
- if (entityId) {
1954
- countQuery.andWhere("entityId = ?", entityId);
1955
- }
1956
- if (entityType) {
1957
- countQuery.andWhere("entityType = ?", entityType);
1958
- }
1959
- if (source) {
1960
- countQuery.andWhere("source = ?", source);
1961
- }
1962
- applyTenancyFilters(countQuery, filters);
1963
- const countResult = await this.#db.executeQuery(countQuery.build());
1964
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1965
- if (total === 0) {
1966
- return {
1967
- pagination: {
1968
- total: 0,
1969
- page,
1970
- perPage: perPageForResponse,
1971
- hasMore: false
1972
- },
1973
- scores: []
1974
- };
1975
- }
1976
- const end = perPageInput === false ? total : start + perPage;
1977
- const limitValue = perPageInput === false ? total : perPage;
1978
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1979
- if (entityId) {
1980
- selectQuery.andWhere("entityId = ?", entityId);
1981
- }
1982
- if (entityType) {
1983
- selectQuery.andWhere("entityType = ?", entityType);
1984
- }
1985
- if (source) {
1986
- selectQuery.andWhere("source = ?", source);
1987
- }
1988
- applyTenancyFilters(selectQuery, filters);
1989
- selectQuery.limit(limitValue).offset(start);
1990
- const { sql, params } = selectQuery.build();
1991
- const results = await this.#db.executeQuery({ sql, params });
1992
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
1993
- return {
1994
- pagination: {
1995
- total,
1996
- page,
1997
- perPage: perPageForResponse,
1998
- hasMore: end < total
1999
- },
2000
- scores
2001
- };
2002
- } catch (error) {
2003
- throw new MastraError(
2004
- {
2005
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_SCORER_ID", "FAILED"),
2006
- domain: ErrorDomain.STORAGE,
2007
- category: ErrorCategory.THIRD_PARTY
2008
- },
2009
- error
2010
- );
2011
- }
2012
- }
2013
- async listScoresByRunId({
2014
- runId,
2015
- pagination,
2016
- filters
2017
- }) {
2018
- try {
2019
- const { page, perPage: perPageInput } = pagination;
2020
- const perPage = normalizePerPage(perPageInput, 100);
2021
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2022
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
2023
- const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
2024
- applyTenancyFilters(countQuery, filters);
2025
- const countResult = await this.#db.executeQuery(countQuery.build());
2026
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
2027
- if (total === 0) {
2028
- return {
2029
- pagination: {
2030
- total: 0,
2031
- page,
2032
- perPage: perPageForResponse,
2033
- hasMore: false
2034
- },
2035
- scores: []
2036
- };
2037
- }
2038
- const end = perPageInput === false ? total : start + perPage;
2039
- const limitValue = perPageInput === false ? total : perPage;
2040
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId);
2041
- applyTenancyFilters(selectQuery, filters);
2042
- selectQuery.limit(limitValue).offset(start);
2043
- const { sql, params } = selectQuery.build();
2044
- const results = await this.#db.executeQuery({ sql, params });
2045
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2046
- return {
2047
- pagination: {
2048
- total,
2049
- page,
2050
- perPage: perPageForResponse,
2051
- hasMore: end < total
2052
- },
2053
- scores
2054
- };
2055
- } catch (error) {
2056
- throw new MastraError(
2057
- {
2058
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_RUN_ID", "FAILED"),
2059
- domain: ErrorDomain.STORAGE,
2060
- category: ErrorCategory.THIRD_PARTY
2061
- },
2062
- error
2063
- );
2064
- }
2065
- }
2066
- async listScoresByEntityId({
2067
- entityId,
2068
- entityType,
2069
- pagination,
2070
- filters
2071
- }) {
2072
- try {
2073
- const { page, perPage: perPageInput } = pagination;
2074
- const perPage = normalizePerPage(perPageInput, 100);
2075
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2076
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
2077
- const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
2078
- applyTenancyFilters(countQuery, filters);
2079
- const countResult = await this.#db.executeQuery(countQuery.build());
2080
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
2081
- if (total === 0) {
2082
- return {
2083
- pagination: {
2084
- total: 0,
2085
- page,
2086
- perPage: perPageForResponse,
2087
- hasMore: false
2088
- },
2089
- scores: []
2090
- };
2091
- }
2092
- const end = perPageInput === false ? total : start + perPage;
2093
- const limitValue = perPageInput === false ? total : perPage;
2094
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
2095
- applyTenancyFilters(selectQuery, filters);
2096
- selectQuery.limit(limitValue).offset(start);
2097
- const { sql, params } = selectQuery.build();
2098
- const results = await this.#db.executeQuery({ sql, params });
2099
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2100
- return {
2101
- pagination: {
2102
- total,
2103
- page,
2104
- perPage: perPageForResponse,
2105
- hasMore: end < total
2106
- },
2107
- scores
2108
- };
2109
- } catch (error) {
2110
- throw new MastraError(
2111
- {
2112
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
2113
- domain: ErrorDomain.STORAGE,
2114
- category: ErrorCategory.THIRD_PARTY
2115
- },
2116
- error
2117
- );
2118
- }
2119
- }
2120
- async listScoresBySpan({
2121
- traceId,
2122
- spanId,
2123
- pagination,
2124
- filters
2125
- }) {
2126
- try {
2127
- const { page, perPage: perPageInput } = pagination;
2128
- const perPage = normalizePerPage(perPageInput, 100);
2129
- const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2130
- const fullTableName = this.#db.getTableName(TABLE_SCORERS);
2131
- const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
2132
- applyTenancyFilters(countQuery, filters);
2133
- const countResult = await this.#db.executeQuery(countQuery.build());
2134
- const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
2135
- if (total === 0) {
2136
- return {
2137
- pagination: {
2138
- total: 0,
2139
- page,
2140
- perPage: perPageForResponse,
2141
- hasMore: false
2142
- },
2143
- scores: []
2144
- };
2145
- }
2146
- const end = perPageInput === false ? total : start + perPage;
2147
- const limitValue = perPageInput === false ? total : perPage;
2148
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
2149
- applyTenancyFilters(selectQuery, filters);
2150
- selectQuery.orderBy("createdAt", "DESC").limit(limitValue).offset(start);
2151
- const { sql, params } = selectQuery.build();
2152
- const results = await this.#db.executeQuery({ sql, params });
2153
- const scores = Array.isArray(results) ? results.map((r) => transformScoreRow(r)) : [];
2154
- return {
2155
- pagination: {
2156
- total,
2157
- page,
2158
- perPage: perPageForResponse,
2159
- hasMore: end < total
2160
- },
2161
- scores
2162
- };
2163
- } catch (error) {
2164
- throw new MastraError(
2165
- {
2166
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_SCORES_BY_SPAN", "FAILED"),
2167
- domain: ErrorDomain.STORAGE,
2168
- category: ErrorCategory.THIRD_PARTY
2169
- },
2170
- error
2171
- );
2172
- }
2173
- }
2174
- };
2175
- var WorkflowsStorageDO = class extends WorkflowsStorage {
2176
- #db;
2177
- constructor(config) {
2178
- super();
2179
- this.#db = new DODB(config);
2180
- }
2181
- supportsConcurrentUpdates() {
2182
- return false;
2183
- }
2184
- async init() {
2185
- await this.#db.createTable({ tableName: TABLE_WORKFLOW_SNAPSHOT, schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT] });
2186
- }
2187
- async dangerouslyClearAll() {
2188
- await this.#db.clearTable({ tableName: TABLE_WORKFLOW_SNAPSHOT });
2189
- }
2190
- updateWorkflowResults({
2191
- // workflowName,
2192
- // runId,
2193
- // stepId,
2194
- // result,
2195
- // requestContext,
2196
- }) {
2197
- throw new Error("Method not implemented.");
2198
- }
2199
- updateWorkflowState({
2200
- // workflowName,
2201
- // runId,
2202
- // opts,
2203
- }) {
2204
- throw new Error("Method not implemented.");
2205
- }
2206
- async persistWorkflowSnapshot({
2207
- workflowName,
2208
- runId,
2209
- resourceId,
2210
- snapshot,
2211
- createdAt,
2212
- updatedAt
2213
- }) {
2214
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2215
- const now = (/* @__PURE__ */ new Date()).toISOString();
2216
- const currentSnapshot = await this.#db.load({
2217
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2218
- keys: { workflow_name: workflowName, run_id: runId }
2219
- });
2220
- const persisting = currentSnapshot ? {
2221
- ...currentSnapshot,
2222
- resourceId,
2223
- snapshot: JSON.stringify(snapshot),
2224
- updatedAt: updatedAt ? updatedAt.toISOString() : now
2225
- } : {
2226
- workflow_name: workflowName,
2227
- run_id: runId,
2228
- resourceId,
2229
- snapshot: JSON.stringify(snapshot),
2230
- createdAt: createdAt ? createdAt.toISOString() : now,
2231
- updatedAt: updatedAt ? updatedAt.toISOString() : now
2232
- };
2233
- const processedRecord = await this.#db.processRecord(persisting);
2234
- const columns = Object.keys(processedRecord);
2235
- const values = Object.values(processedRecord);
2236
- const updateMap = {
2237
- snapshot: "excluded.snapshot",
2238
- updatedAt: "excluded.updatedAt",
2239
- resourceId: `COALESCE(excluded.resourceId, ${fullTableName}.resourceId)`
2240
- };
2241
- this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2242
- const query = createSqlBuilder().insert(
2243
- fullTableName,
2244
- columns,
2245
- values,
2246
- ["workflow_name", "run_id"],
2247
- updateMap
2248
- );
2249
- const { sql, params } = query.build();
2250
- try {
2251
- await this.#db.executeQuery({ sql, params });
2252
- } catch (error) {
2253
- throw new MastraError(
2254
- {
2255
- id: createStorageErrorId("CLOUDFLARE_DO", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2256
- domain: ErrorDomain.STORAGE,
2257
- category: ErrorCategory.THIRD_PARTY,
2258
- text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
2259
- details: { workflowName, runId }
2260
- },
2261
- error
2262
- );
2263
- }
2264
- }
2265
- async loadWorkflowSnapshot(params) {
2266
- const { workflowName, runId } = params;
2267
- this.logger.debug("Loading workflow snapshot", { workflowName, runId });
2268
- try {
2269
- const d = await this.#db.load({
2270
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2271
- keys: {
2272
- workflow_name: workflowName,
2273
- run_id: runId
2274
- }
2275
- });
2276
- return d ? d.snapshot : null;
2277
- } catch (error) {
2278
- throw new MastraError(
2279
- {
2280
- id: createStorageErrorId("CLOUDFLARE_DO", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2281
- domain: ErrorDomain.STORAGE,
2282
- category: ErrorCategory.THIRD_PARTY,
2283
- text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
2284
- details: { workflowName, runId }
2285
- },
2286
- error
2287
- );
2288
- }
2289
- }
2290
- parseWorkflowRun(row) {
2291
- let parsedSnapshot = row.snapshot;
2292
- if (typeof parsedSnapshot === "string") {
2293
- try {
2294
- parsedSnapshot = JSON.parse(row.snapshot);
2295
- } catch (e) {
2296
- this.logger.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
2297
- }
2298
- }
2299
- return {
2300
- workflowName: row.workflow_name,
2301
- runId: row.run_id,
2302
- snapshot: parsedSnapshot,
2303
- createdAt: ensureDate(row.createdAt),
2304
- updatedAt: ensureDate(row.updatedAt),
2305
- resourceId: row.resourceId
2306
- };
2307
- }
2308
- async listWorkflowRuns({
2309
- workflowName,
2310
- fromDate,
2311
- toDate,
2312
- page,
2313
- perPage,
2314
- resourceId,
2315
- status
2316
- } = {}) {
2317
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2318
- try {
2319
- const builder = createSqlBuilder().select().from(fullTableName);
2320
- const countBuilder = createSqlBuilder().count().from(fullTableName);
2321
- if (workflowName) {
2322
- builder.whereAnd("workflow_name = ?", workflowName);
2323
- countBuilder.whereAnd("workflow_name = ?", workflowName);
2324
- }
2325
- if (status) {
2326
- builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
2327
- countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
2328
- }
2329
- if (resourceId) {
2330
- const hasResourceId = await this.#db.hasColumn(fullTableName, "resourceId");
2331
- if (hasResourceId) {
2332
- builder.whereAnd("resourceId = ?", resourceId);
2333
- countBuilder.whereAnd("resourceId = ?", resourceId);
2334
- } else {
2335
- this.logger.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
2336
- }
2337
- }
2338
- if (fromDate) {
2339
- builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
2340
- countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
2341
- }
2342
- if (toDate) {
2343
- builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2344
- countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2345
- }
2346
- builder.orderBy("createdAt", "DESC");
2347
- if (typeof perPage === "number" && typeof page === "number") {
2348
- const offset = page * perPage;
2349
- builder.limit(perPage);
2350
- builder.offset(offset);
2351
- }
2352
- const { sql, params } = builder.build();
2353
- let total = 0;
2354
- if (perPage !== void 0 && page !== void 0) {
2355
- const { sql: countSql, params: countParams } = countBuilder.build();
2356
- const countResult = await this.#db.executeQuery({
2357
- sql: countSql,
2358
- params: countParams,
2359
- first: true
2360
- });
2361
- total = Number(countResult?.count ?? 0);
2362
- }
2363
- const results = await this.#db.executeQuery({ sql, params });
2364
- const runs = (isArrayOfRecords(results) ? results : []).map(
2365
- (row) => this.parseWorkflowRun(row)
2366
- );
2367
- return { runs, total: total || runs.length };
2368
- } catch (error) {
2369
- throw new MastraError(
2370
- {
2371
- id: createStorageErrorId("CLOUDFLARE_DO", "LIST_WORKFLOW_RUNS", "FAILED"),
2372
- domain: ErrorDomain.STORAGE,
2373
- category: ErrorCategory.THIRD_PARTY,
2374
- text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
2375
- details: {
2376
- workflowName: workflowName ?? "",
2377
- resourceId: resourceId ?? ""
2378
- }
2379
- },
2380
- error
2381
- );
2382
- }
2383
- }
2384
- async getWorkflowRunById({
2385
- runId,
2386
- workflowName
2387
- }) {
2388
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2389
- try {
2390
- const conditions = [];
2391
- const params = [];
2392
- if (runId) {
2393
- conditions.push("run_id = ?");
2394
- params.push(runId);
2395
- }
2396
- if (workflowName) {
2397
- conditions.push("workflow_name = ?");
2398
- params.push(workflowName);
2399
- }
2400
- const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
2401
- const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
2402
- const result = await this.#db.executeQuery({ sql, params, first: true });
2403
- if (!result) return null;
2404
- return this.parseWorkflowRun(result);
2405
- } catch (error) {
2406
- throw new MastraError(
2407
- {
2408
- id: createStorageErrorId("CLOUDFLARE_DO", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2409
- domain: ErrorDomain.STORAGE,
2410
- category: ErrorCategory.THIRD_PARTY,
2411
- text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2412
- details: { runId, workflowName: workflowName ?? "" }
2413
- },
2414
- error
2415
- );
2416
- }
2417
- }
2418
- async deleteWorkflowRunById({ runId, workflowName }) {
2419
- const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2420
- try {
2421
- const sql = `DELETE FROM ${fullTableName} WHERE workflow_name = ? AND run_id = ?`;
2422
- const params = [workflowName, runId];
2423
- await this.#db.executeQuery({ sql, params });
2424
- } catch (error) {
2425
- throw new MastraError(
2426
- {
2427
- id: createStorageErrorId("CLOUDFLARE_DO", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2428
- domain: ErrorDomain.STORAGE,
2429
- category: ErrorCategory.THIRD_PARTY,
2430
- text: `Failed to delete workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2431
- details: { runId, workflowName }
2432
- },
2433
- error
2434
- );
2435
- }
2436
- }
2437
- };
2438
-
2439
- // src/do/index.ts
2440
- var CloudflareDOStorage = class extends MastraCompositeStore {
2441
- stores;
2442
- /**
2443
- * Creates a new CloudflareDOStorage instance
2444
- * @param config Configuration for Durable Objects SqlStorage access
2445
- */
2446
- constructor(config) {
2447
- try {
2448
- super({ id: "do-store", name: "DO", disableInit: config.disableInit });
2449
- if (config.tablePrefix && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(config.tablePrefix)) {
2450
- throw new Error(
2451
- "Invalid tablePrefix: must start with a letter or underscore and contain only letters, numbers, and underscores."
2452
- );
2453
- }
2454
- const domainConfig = { sql: config.sql, tablePrefix: config.tablePrefix };
2455
- this.stores = {
2456
- memory: new MemoryStorageDO(domainConfig),
2457
- workflows: new WorkflowsStorageDO(domainConfig),
2458
- scores: new ScoresStorageDO(domainConfig),
2459
- backgroundTasks: new BackgroundTasksStorageDO(domainConfig)
2460
- };
2461
- this.logger.info("Using Durable Objects SqlStorage");
2462
- } catch (error) {
2463
- throw new MastraError(
2464
- {
2465
- id: createStorageErrorId("CLOUDFLARE_DO", "INITIALIZATION", "FAILED"),
2466
- domain: ErrorDomain.STORAGE,
2467
- category: ErrorCategory.SYSTEM,
2468
- text: "Error initializing CloudflareDOStorage"
2469
- },
2470
- error
2471
- );
2472
- }
2473
- }
2474
- /**
2475
- * Close the database connection
2476
- * No explicit cleanup needed for DO storage
2477
- */
2478
- async close() {
2479
- this.logger.debug("Closing DO connection");
2480
- }
2481
- };
2482
- var DOStore = CloudflareDOStorage;
2483
-
2484
- export { BackgroundTasksStorageDO, CloudflareDOStorage, DODB, DOStore, MemoryStorageDO, ScoresStorageDO, WorkflowsStorageDO };
2485
- //# sourceMappingURL=chunk-YLGT7WTC.js.map
2486
- //# sourceMappingURL=chunk-YLGT7WTC.js.map