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