@mastra/cloudflare-d1 0.1.5-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,46 @@
1
+ # Elastic License 2.0 (ELv2)
2
+
3
+ Copyright (c) 2025 Mastra AI, Inc.
4
+
5
+ **Acceptance**
6
+ By using the software, you agree to all of the terms and conditions below.
7
+
8
+ **Copyright License**
9
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
10
+
11
+ **Limitations**
12
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
13
+
14
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
15
+
16
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
17
+
18
+ **Patents**
19
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
20
+
21
+ **Notices**
22
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
23
+
24
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
25
+
26
+ **No Other Rights**
27
+ These terms do not imply any licenses other than those expressly granted in these terms.
28
+
29
+ **Termination**
30
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
31
+
32
+ **No Liability**
33
+ As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
34
+
35
+ **Definitions**
36
+ The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
37
+
38
+ _you_ refers to the individual or entity agreeing to these terms.
39
+
40
+ _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
41
+
42
+ _your licenses_ are all the licenses granted to you for the software under these terms.
43
+
44
+ _use_ means anything you do with the software requiring one of your licenses.
45
+
46
+ _trademark_ means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # @mastra/cloudflare-d1
2
+
3
+ A Mastra store for Cloudflare D1 SQL databases, supporting threads, messages, workflows, evaluations, and traces with robust SQL features.
4
+
5
+ ## Features
6
+
7
+ - Thread and message storage using SQL tables
8
+ - True sorted order and filtering via SQL queries
9
+ - Rich metadata support (JSON-encoded)
10
+ - Timestamp tracking for all records
11
+ - Workflow snapshot persistence
12
+ - Trace and evaluation storage
13
+ - Efficient batch operations (with prepared statements)
14
+ - Automatic JSON serialization/deserialization for metadata and custom fields
15
+ - Error handling and logging for all operations
16
+ - Supports both Cloudflare Workers D1 Binding and REST API
17
+
18
+ ## Prerequisites
19
+
20
+ - Access to a Cloudflare account with D1 enabled
21
+ - D1 database created and configured
22
+ - For Workers binding: Worker configured with D1 binding
23
+ - For REST API: Cloudflare API Token with D1 permissions
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ pnpm add @mastra/cloudflare-d1
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ### With Workers D1 Binding
34
+
35
+ ```typescript
36
+ import { D1Store } from '@mastra/cloudflare-d1';
37
+
38
+ const store = new D1Store({
39
+ binding: env.DB, // D1Database binding from Worker environment
40
+ tablePrefix: 'mastra_', // optional
41
+ });
42
+ ```
43
+
44
+ ### With REST API
45
+
46
+ ```typescript
47
+ import { D1Store } from '@mastra/cloudflare-d1';
48
+
49
+ const store = new D1Store({
50
+ accountId: '<your-account-id>',
51
+ databaseId: '<your-d1-database-id>',
52
+ apiToken: '<your-api-token>',
53
+ tablePrefix: 'mastra_', // optional
54
+ });
55
+ ```
56
+
57
+ ## Supported Methods
58
+
59
+ ### Thread Operations
60
+
61
+ - `saveThread(thread)`: Create or update a thread
62
+ - `getThreadById({ threadId })`: Get a thread by ID
63
+ - `getThreadsByResourceId({ resourceId })`: Fetch all threads associated with a resource.
64
+ - `updateThread({ id, title, metadata })`: Update the title and/or metadata of a thread.
65
+ - `deleteThread({ threadId })`: Delete a thread and all its messages.
66
+
67
+ ### Message Operations
68
+
69
+ - `saveMessages({ messages })`: Save multiple messages in a batch operation (uses prepared statements).
70
+ - `getMessages({ threadId, selectBy? })`: Retrieve messages for a thread, with optional filtering (e.g., last N, include surrounding messages).
71
+
72
+ ### Workflow Operations
73
+
74
+ - `persistWorkflowSnapshot({ workflowName, runId, snapshot })`: Save workflow state for a given workflow/run.
75
+ - `loadWorkflowSnapshot({ workflowName, runId })`: Load persisted workflow state.
76
+
77
+ ### Trace/Evaluation Operations
78
+
79
+ - `getTraces({ name?, scope?, page, perPage, attributes? })`: Query trace records with optional filters and pagination.
80
+ - `getEvalsByAgentName({ agentName, type? })`: Query evaluation results by agent name.
81
+
82
+ ### Utility
83
+
84
+ - `clearTable({ tableName })`: Remove all records from a logical table.
85
+ - `batchInsert({ tableName, records })`: Batch insert multiple records.
86
+ - `insert({ tableName, record })`: Insert a single record into a table.
87
+
88
+ ---
89
+
90
+ ## Data Types
91
+
92
+ The D1 store supports the following data types:
93
+
94
+ - `text`: String
95
+ - `timestamp`: ISO8601 string (converted to/from Date)
96
+ - `uuid`: String
97
+ - `jsonb`: JSON-encoded object
98
+ - `integer`: Integer (for internal counters, etc)
99
+
100
+ All metadata and custom fields are automatically serialized/deserialized as JSON.
101
+
102
+ ---
103
+
104
+ ## Configuration Reference
105
+
106
+ | Option | Type | Description |
107
+ | ----------- | ---------- | ------------------------------------ |
108
+ | binding | D1Database | D1 Workers binding (for Workers) |
109
+ | accountId | string | Cloudflare Account ID (for REST API) |
110
+ | databaseId | string | D1 Database ID (for REST API) |
111
+ | apiToken | string | Cloudflare API Token (for REST API) |
112
+ | tablePrefix | string | Optional prefix for all table names |
113
+
114
+ ---
115
+
116
+ ## Table/Namespace Mapping
117
+
118
+ Each logical Mastra table maps to a SQL table in D1 (with optional prefix):
119
+
120
+ - `mastra_threads` — stores threads
121
+ - `mastra_messages` — stores messages
122
+ - `mastra_workflow_snapshot` — stores workflow snapshots
123
+ - `mastra_evals` — stores evaluations
124
+ - `mastra_traces` — stores traces
125
+
126
+ (The prefix is configurable via `tablePrefix`.)
127
+
128
+ ---
129
+
130
+ ## Limitations
131
+
132
+ - No multi-statement transactions (D1 currently supports single statements per query)
133
+ - No advanced SQL joins (D1 is SQLite-based, but some features may be limited)
134
+ - Batch operations are processed in chunks, not truly atomic
135
+ - Some REST API operations may be slower than Workers binding
136
+ - D1 is in beta and may have evolving limitations
137
+ - No vector search capabilities
138
+ - Note: D1 has specific limitations and behaviors, please refer to the official Cloudflare D1 documentation for more information.
139
+
140
+ ## Cleanup / Disconnect
141
+
142
+ No explicit cleanup is required. Connections are managed by the platform.
@@ -0,0 +1,313 @@
1
+ import type { D1Database as D1Database_2 } from '@cloudflare/workers-types';
2
+ import type { EvalRow } from '@mastra/core/storage';
3
+ import { MastraStorage } from '@mastra/core/storage';
4
+ import type { MessageType } from '@mastra/core/memory';
5
+ import type { StorageColumn } from '@mastra/core/storage';
6
+ import type { StorageGetMessagesArg } from '@mastra/core/storage';
7
+ import type { StorageThreadType } from '@mastra/core/memory';
8
+ import type { TABLE_NAMES } from '@mastra/core/storage';
9
+ import type { WorkflowRuns } from '@mastra/core/storage';
10
+ import type { WorkflowRunState } from '@mastra/core/workflows';
11
+ import type { WorkflowRunState as WorkflowRunState_2 } from '@mastra/core';
12
+
13
+ export declare const createSampleMessage: (threadId: string) => any;
14
+
15
+ export declare const createSampleThread: () => {
16
+ id: string;
17
+ resourceId: string;
18
+ title: string;
19
+ createdAt: Date;
20
+ updatedAt: Date;
21
+ metadata: {
22
+ key: string;
23
+ };
24
+ };
25
+
26
+ export declare const createSampleThreadWithParams: (threadId: string, resourceId: string, createdAt: Date, updatedAt: Date) => {
27
+ id: string;
28
+ resourceId: string;
29
+ title: string;
30
+ createdAt: Date;
31
+ updatedAt: Date;
32
+ metadata: {
33
+ key: string;
34
+ };
35
+ };
36
+
37
+ export declare const createSampleTrace: (name: string, scope?: string, attributes?: Record<string, string>) => {
38
+ id: string;
39
+ parentSpanId: string;
40
+ traceId: string;
41
+ name: string;
42
+ scope: string | undefined;
43
+ kind: string;
44
+ status: string;
45
+ events: string;
46
+ links: string;
47
+ attributes: string | undefined;
48
+ startTime: string;
49
+ endTime: string;
50
+ other: string;
51
+ createdAt: string;
52
+ };
53
+
54
+ export declare const createSampleWorkflowSnapshot: (threadId: string) => WorkflowRunState_2;
55
+
56
+ export declare function createSqlBuilder(): SqlBuilder;
57
+
58
+ /**
59
+ * Configuration for D1 using the REST API
60
+ */
61
+ declare interface D1Config {
62
+ /** Cloudflare account ID */
63
+ accountId: string;
64
+ /** Cloudflare API token with D1 access */
65
+ apiToken: string;
66
+ /** D1 database ID */
67
+ databaseId: string;
68
+ /** Optional prefix for table names */
69
+ tablePrefix?: string;
70
+ }
71
+ export { D1Config }
72
+ export { D1Config as D1Config_alias_1 }
73
+
74
+ declare class D1Store extends MastraStorage {
75
+ private client?;
76
+ private accountId?;
77
+ private databaseId?;
78
+ private binding?;
79
+ private tablePrefix;
80
+ /**
81
+ * Creates a new D1Store instance
82
+ * @param config Configuration for D1 access (either REST API or Workers Binding API)
83
+ */
84
+ constructor(config: D1StoreConfig);
85
+ private getTableName;
86
+ private formatSqlParams;
87
+ private createIndexIfNotExists;
88
+ private executeWorkersBindingQuery;
89
+ private executeRestQuery;
90
+ /**
91
+ * Execute a SQL query against the D1 database
92
+ * @param options Query options including SQL, parameters, and whether to return only the first result
93
+ * @returns Query results as an array or a single object if first=true
94
+ */
95
+ private executeQuery;
96
+ private getSqlType;
97
+ private ensureDate;
98
+ private serializeDate;
99
+ private serializeValue;
100
+ private deserializeValue;
101
+ createTable({ tableName, schema, }: {
102
+ tableName: TABLE_NAMES;
103
+ schema: Record<string, StorageColumn>;
104
+ }): Promise<void>;
105
+ clearTable({ tableName }: {
106
+ tableName: TABLE_NAMES;
107
+ }): Promise<void>;
108
+ private processRecord;
109
+ insert({ tableName, record }: {
110
+ tableName: TABLE_NAMES;
111
+ record: Record<string, any>;
112
+ }): Promise<void>;
113
+ load<R>({ tableName, keys }: {
114
+ tableName: TABLE_NAMES;
115
+ keys: Record<string, string>;
116
+ }): Promise<R | null>;
117
+ getThreadById({ threadId }: {
118
+ threadId: string;
119
+ }): Promise<StorageThreadType | null>;
120
+ getThreadsByResourceId({ resourceId }: {
121
+ resourceId: string;
122
+ }): Promise<StorageThreadType[]>;
123
+ saveThread({ thread }: {
124
+ thread: StorageThreadType;
125
+ }): Promise<StorageThreadType>;
126
+ updateThread({ id, title, metadata, }: {
127
+ id: string;
128
+ title: string;
129
+ metadata: Record<string, unknown>;
130
+ }): Promise<StorageThreadType>;
131
+ deleteThread({ threadId }: {
132
+ threadId: string;
133
+ }): Promise<void>;
134
+ saveMessages({ messages }: {
135
+ messages: MessageType[];
136
+ }): Promise<MessageType[]>;
137
+ getMessages<T = MessageType>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T[]>;
138
+ persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
139
+ workflowName: string;
140
+ runId: string;
141
+ snapshot: WorkflowRunState;
142
+ }): Promise<void>;
143
+ loadWorkflowSnapshot(params: {
144
+ workflowName: string;
145
+ runId: string;
146
+ }): Promise<WorkflowRunState | null>;
147
+ /**
148
+ * Insert multiple records in a batch operation
149
+ * @param tableName The table to insert into
150
+ * @param records The records to insert
151
+ */
152
+ batchInsert({ tableName, records }: {
153
+ tableName: TABLE_NAMES;
154
+ records: Record<string, any>[];
155
+ }): Promise<void>;
156
+ getTraces({ name, scope, page, perPage, attributes, }: {
157
+ name?: string;
158
+ scope?: string;
159
+ page: number;
160
+ perPage: number;
161
+ attributes?: Record<string, string>;
162
+ }): Promise<Record<string, any>[]>;
163
+ getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
164
+ getWorkflowRuns(_args?: {
165
+ workflowName?: string;
166
+ fromDate?: Date;
167
+ toDate?: Date;
168
+ limit?: number;
169
+ offset?: number;
170
+ }): Promise<WorkflowRuns>;
171
+ /**
172
+ * Close the database connection
173
+ * No explicit cleanup needed for D1 in either REST or Workers Binding mode
174
+ */
175
+ close(): Promise<void>;
176
+ }
177
+ export { D1Store }
178
+ export { D1Store as D1Store_alias_1 }
179
+
180
+ /**
181
+ * Combined configuration type supporting both REST API and Workers Binding API
182
+ */
183
+ declare type D1StoreConfig = D1Config | D1WorkersConfig;
184
+ export { D1StoreConfig }
185
+ export { D1StoreConfig as D1StoreConfig_alias_1 }
186
+
187
+ /**
188
+ * Configuration for D1 using the Workers Binding API
189
+ */
190
+ declare interface D1WorkersConfig {
191
+ /** D1 database binding from Workers environment */
192
+ binding: D1Database_2;
193
+ /** Optional prefix for table names */
194
+ tablePrefix?: string;
195
+ }
196
+ export { D1WorkersConfig }
197
+ export { D1WorkersConfig as D1WorkersConfig_alias_1 }
198
+
199
+ export declare const retryUntil: <T>(fn: () => Promise<T>, condition: (result: T) => boolean, timeout?: number, // REST API needs longer timeout due to higher latency
200
+ interval?: number) => Promise<T>;
201
+
202
+ /**
203
+ * SQL Builder class for constructing type-safe SQL queries
204
+ * This helps create maintainable and secure SQL queries with proper parameter handling
205
+ */
206
+ export declare class SqlBuilder {
207
+ private sql;
208
+ private params;
209
+ private whereAdded;
210
+ select(columns?: string | string[]): SqlBuilder;
211
+ from(table: string): SqlBuilder;
212
+ /**
213
+ * Add a WHERE clause to the query
214
+ * @param condition The condition to add
215
+ * @param params Parameters to bind to the condition
216
+ */
217
+ where(condition: string, ...params: SqlParam[]): SqlBuilder;
218
+ /**
219
+ * Add a WHERE clause if it hasn't been added yet, otherwise add an AND clause
220
+ * @param condition The condition to add
221
+ * @param params Parameters to bind to the condition
222
+ */
223
+ whereAnd(condition: string, ...params: SqlParam[]): SqlBuilder;
224
+ andWhere(condition: string, ...params: SqlParam[]): SqlBuilder;
225
+ orWhere(condition: string, ...params: SqlParam[]): SqlBuilder;
226
+ orderBy(column: string, direction?: 'ASC' | 'DESC'): SqlBuilder;
227
+ limit(count: number): SqlBuilder;
228
+ offset(count: number): SqlBuilder;
229
+ /**
230
+ * Insert a row, or update specific columns on conflict (upsert).
231
+ * @param table Table name
232
+ * @param columns Columns to insert
233
+ * @param values Values to insert
234
+ * @param conflictColumns Columns to check for conflict (usually PK or UNIQUE)
235
+ * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
236
+ */
237
+ insert(table: string, columns: string[], values: SqlParam[], conflictColumns?: string[], updateMap?: Record<string, string>): SqlBuilder;
238
+ update(table: string, columns: string[], values: SqlParam[]): SqlBuilder;
239
+ delete(table: string): SqlBuilder;
240
+ /**
241
+ * Create a table if it doesn't exist
242
+ * @param table The table name
243
+ * @param columnDefinitions The column definitions as an array of strings
244
+ * @param tableConstraints Optional constraints for the table
245
+ * @returns The builder instance
246
+ */
247
+ createTable(table: string, columnDefinitions: string[], tableConstraints?: string[]): SqlBuilder;
248
+ /**
249
+ * Check if an index exists in the database
250
+ * @param indexName The name of the index to check
251
+ * @param tableName The table the index is on
252
+ * @returns The builder instance
253
+ */
254
+ checkIndexExists(indexName: string, tableName: string): SqlBuilder;
255
+ /**
256
+ * Create an index if it doesn't exist
257
+ * @param indexName The name of the index to create
258
+ * @param tableName The table to create the index on
259
+ * @param columnName The column to index
260
+ * @param indexType Optional index type (e.g., 'UNIQUE')
261
+ * @returns The builder instance
262
+ */
263
+ createIndex(indexName: string, tableName: string, columnName: string, indexType?: string): SqlBuilder;
264
+ raw(sql: string, ...params: SqlParam[]): SqlBuilder;
265
+ /**
266
+ * Add a LIKE condition to the query
267
+ * @param column The column to check
268
+ * @param value The value to match (will be wrapped with % for LIKE)
269
+ * @param exact If true, will not add % wildcards
270
+ */
271
+ like(column: string, value: string, exact?: boolean): SqlBuilder;
272
+ /**
273
+ * Add a JSON LIKE condition for searching in JSON fields
274
+ * @param column The JSON column to search in
275
+ * @param key The JSON key to match
276
+ * @param value The value to match
277
+ */
278
+ jsonLike(column: string, key: string, value: string): SqlBuilder;
279
+ /**
280
+ * Get the built query
281
+ * @returns Object containing the SQL string and parameters array
282
+ */
283
+ build(): {
284
+ sql: string;
285
+ params: SqlParam[];
286
+ };
287
+ /**
288
+ * Reset the builder for reuse
289
+ * @returns The reset builder instance
290
+ */
291
+ reset(): SqlBuilder;
292
+ }
293
+
294
+ /**
295
+ * Type definition for SQL query parameters
296
+ */
297
+ export declare type SqlParam = string | number | boolean | null | undefined;
298
+
299
+ /**
300
+ * Interface for SQL query options with generic type support
301
+ */
302
+ declare interface SqlQueryOptions {
303
+ /** SQL query to execute */
304
+ sql: string;
305
+ /** Parameters to bind to the query */
306
+ params?: SqlParam[];
307
+ /** Whether to return only the first result */
308
+ first?: boolean;
309
+ }
310
+ export { SqlQueryOptions }
311
+ export { SqlQueryOptions as SqlQueryOptions_alias_1 }
312
+
313
+ export { }