js-bao 0.2.10 → 0.3.0-alpha.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.
@@ -0,0 +1,1084 @@
1
+ import * as Y from 'yjs';
2
+
3
+ interface RefersToRelationshipConfig {
4
+ type: "refersTo";
5
+ model: string;
6
+ relatedIdField: string;
7
+ }
8
+ interface HasManyRelationshipConfig {
9
+ type: "hasMany";
10
+ model: string;
11
+ relatedIdField: string;
12
+ orderByField?: string;
13
+ orderDirection?: "ASC" | "DESC";
14
+ }
15
+ interface HasManyThroughRelationshipConfig {
16
+ type: "hasManyThrough";
17
+ model: string;
18
+ joinModel: string;
19
+ joinModelLocalField: string;
20
+ joinModelRelatedField: string;
21
+ joinModelOrderByField?: string;
22
+ joinModelOrderDirection?: "ASC" | "DESC";
23
+ }
24
+ type RelationshipConfig = RefersToRelationshipConfig | HasManyRelationshipConfig | HasManyThroughRelationshipConfig;
25
+
26
+ type FieldType = "string" | "number" | "boolean" | "date" | "id" | "stringset";
27
+ interface FieldOptions {
28
+ type: FieldType;
29
+ indexed?: boolean;
30
+ required?: boolean;
31
+ unique?: boolean;
32
+ default?: any | (() => any);
33
+ autoAssign?: boolean;
34
+ maxLength?: number;
35
+ maxCount?: number;
36
+ }
37
+ interface UniqueConstraintConfig {
38
+ name: string;
39
+ fields: string[];
40
+ }
41
+ interface ModelOptions {
42
+ name: string;
43
+ uniqueConstraints?: UniqueConstraintConfig[];
44
+ relationships?: Record<string, RelationshipConfig>;
45
+ }
46
+
47
+ interface ITransactionalDatabaseOperations {
48
+ insert(modelName: string, data: any): Promise<void>;
49
+ delete(modelName: string, id: string): Promise<void>;
50
+ query<T extends Record<string, any>>(sql: string, params?: any[]): Promise<T[]>;
51
+ }
52
+ /**
53
+ * Abstract class defining the interface for database engines.
54
+ * This allows for different database implementations (e.g., SQL.js, DuckDB) to be used interchangeably.
55
+ */
56
+ declare abstract class DatabaseEngine {
57
+ /**
58
+ * Ensures that the database engine is fully initialized and ready for use.
59
+ * For WASM-based engines, this might involve loading the WASM module.
60
+ */
61
+ abstract ensureReady(): Promise<void>;
62
+ /**
63
+ * Executes a SQL query against the database.
64
+ * @param sql The SQL query string.
65
+ * @param params Optional array of parameters for prepared statements.
66
+ * @returns A promise that resolves to an array of query results.
67
+ */
68
+ abstract query(sql: string, params?: any[]): Promise<any[]>;
69
+ /**
70
+ * Retrieves the last error message from the database engine, if any.
71
+ * @returns The last error message as a string, or undefined if no error occurred.
72
+ */
73
+ abstract getLastErrorMessage(): string | undefined;
74
+ /**
75
+ * Retrieves the schema for a given table.
76
+ * This is useful for understanding table structure, field types, etc.
77
+ * The exact return type might vary based on the database engine.
78
+ * @param tableName The name of the table.
79
+ * @returns A promise that resolves to the table schema information.
80
+ */
81
+ abstract getTableSchema(tableName: string): Promise<any>;
82
+ /**
83
+ * Destroys the database engine instance and releases any associated resources.
84
+ * This is crucial for cleanup, especially in testing environments or when the application is shutting down.
85
+ */
86
+ abstract destroy(): Promise<void>;
87
+ createTable(_modelName: string, _schema: Map<string, any>, // Assuming 'any' for field options for now, can be refined
88
+ _options: ModelOptions): Promise<void>;
89
+ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise<void>;
90
+ insertStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
91
+ removeStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
92
+ insert(_modelName: string, _data: any): Promise<void>;
93
+ delete(_modelName: string, _id: string): Promise<void>;
94
+ /**
95
+ * Deletes all records for a specific document from the given model table.
96
+ * This is used when disconnecting a document to remove all its data.
97
+ * @param modelName The name of the model/table
98
+ * @param docId The document ID to filter by
99
+ */
100
+ deleteByDocumentId(_modelName: string, _docId: string): Promise<void>;
101
+ getTableName(_modelName: string): string;
102
+ withTransaction<T>(_callback: (operations: ITransactionalDatabaseOperations) => Promise<T>): Promise<T>;
103
+ }
104
+
105
+ interface StringSetChangeTracker {
106
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
107
+ }
108
+
109
+ type DocumentPermissionHint = "read" | "read-write";
110
+ interface SaveOptions$1 {
111
+ targetDocument?: string;
112
+ forceWrite?: boolean;
113
+ }
114
+
115
+ interface ComparisonOperators<T = any> {
116
+ $eq?: T;
117
+ $ne?: T;
118
+ $gt?: T;
119
+ $gte?: T;
120
+ $lt?: T;
121
+ $lte?: T;
122
+ $in?: T[];
123
+ $nin?: T[];
124
+ }
125
+ interface StringSetOperators {
126
+ /**
127
+ * Exact membership: StringSet contains this specific string
128
+ */
129
+ $contains?: string;
130
+ $all?: string[];
131
+ $size?: number | ComparisonOperators<number>;
132
+ }
133
+ interface SubstringOperators {
134
+ /** Prefix match */
135
+ $startsWith?: string;
136
+ /** Suffix match */
137
+ $endsWith?: string;
138
+ /** Substring anywhere */
139
+ $containsText?: string;
140
+ }
141
+ interface ExistenceOperators {
142
+ $exists?: boolean;
143
+ }
144
+ type FieldOperators<T = any> = ComparisonOperators<T> & ExistenceOperators & StringSetOperators & SubstringOperators;
145
+ interface LogicalOperators {
146
+ $and?: DocumentFilter[];
147
+ $or?: DocumentFilter[];
148
+ }
149
+ type DocumentFilter = {
150
+ [field: string]: any | FieldOperators<any>;
151
+ } & LogicalOperators;
152
+ type SortDirection = 1 | -1;
153
+ type SortSpec = {
154
+ [field: string]: SortDirection;
155
+ };
156
+ type ProjectionSpec = {
157
+ [field: string]: 1 | 0;
158
+ };
159
+ interface QueryOptions {
160
+ sort?: SortSpec;
161
+ projection?: ProjectionSpec;
162
+ documents?: string | string[];
163
+ limit?: number;
164
+ uniqueStartKey?: string;
165
+ direction?: 1 | -1;
166
+ }
167
+ interface PaginatedResult<T> {
168
+ data: T[];
169
+ nextCursor?: string;
170
+ prevCursor?: string;
171
+ hasMore: boolean;
172
+ }
173
+ interface TranslatedQuery {
174
+ sql: string;
175
+ params: any[];
176
+ sortFields: string[];
177
+ sortDirections?: (1 | -1)[];
178
+ }
179
+ type ProjectedResult<T, P extends ProjectionSpec> = {
180
+ [K in keyof P]: K extends keyof T ? T[K] : never;
181
+ };
182
+ type QueryResult<T, P extends ProjectionSpec | undefined> = P extends ProjectionSpec ? ProjectedResult<T, P> : T;
183
+
184
+ declare class DocumentQueryTranslator {
185
+ private modelName;
186
+ private schema;
187
+ private tableName;
188
+ private quotedTableName;
189
+ private fieldSqlCache;
190
+ constructor(modelName: string, schema: Map<string, FieldOptions>);
191
+ private getQuotedField;
192
+ /**
193
+ * Translate document filter and options to SQL for find operations
194
+ */
195
+ translateFind(filter: DocumentFilter, options?: QueryOptions): TranslatedQuery;
196
+ /**
197
+ * Translate document filter to SQL for count operations
198
+ */
199
+ translateCount(filter: DocumentFilter, options?: Pick<QueryOptions, "documents">): {
200
+ sql: string;
201
+ params: any[];
202
+ };
203
+ /**
204
+ * Translate document filter to SQL WHERE clause
205
+ */
206
+ private translateFilter;
207
+ /**
208
+ * Translate logical operators ($and, $or)
209
+ */
210
+ private translateLogicalOperator;
211
+ /**
212
+ * Translate field condition to SQL
213
+ */
214
+ private translateFieldCondition;
215
+ /**
216
+ * Translate field operators to SQL
217
+ */
218
+ private translateFieldOperators;
219
+ /**
220
+ * Translate individual operator to SQL
221
+ */
222
+ private translateOperator;
223
+ /**
224
+ * Build SELECT clause based on projection
225
+ */
226
+ private buildSelectClause;
227
+ /**
228
+ * Build LIMIT clause
229
+ */
230
+ private buildLimitClause;
231
+ /**
232
+ * Build pagination WHERE clause from cursor
233
+ */
234
+ private buildPaginationClause;
235
+ /**
236
+ * Validate that field exists in schema
237
+ */
238
+ private validateField;
239
+ /**
240
+ * Validate projection fields
241
+ */
242
+ private validateProjection;
243
+ /**
244
+ * Validate operator is supported for field type
245
+ */
246
+ private validateOperatorForType;
247
+ /**
248
+ * Validate field value matches expected type
249
+ */
250
+ private validateFieldValue;
251
+ /**
252
+ * Validate array values for $in/$nin operators
253
+ */
254
+ private validateArrayValues;
255
+ /**
256
+ * Check if value is a primitive (not an object with operators)
257
+ */
258
+ private isPrimitiveValue;
259
+ /**
260
+ * Get the type of a value for validation
261
+ */
262
+ private getValueType;
263
+ /**
264
+ * Check if value type is compatible with field type
265
+ */
266
+ private isTypeCompatible;
267
+ /**
268
+ * Convert value for SQLite compatibility
269
+ */
270
+ private convertValueForSQLite;
271
+ private normalizeDocumentIds;
272
+ private buildDocumentClause;
273
+ }
274
+
275
+ interface StringSetMembership$1 {
276
+ field: string;
277
+ contains: string;
278
+ }
279
+ type GroupByField$1 = string | StringSetMembership$1;
280
+ interface AggregationOperation$1 {
281
+ type: "count" | "sum" | "avg" | "min" | "max";
282
+ field?: string;
283
+ }
284
+ interface AggregationOptions$1 {
285
+ groupBy: GroupByField$1[];
286
+ operations: AggregationOperation$1[];
287
+ filter?: DocumentFilter;
288
+ limit?: number;
289
+ sort?: {
290
+ field: string;
291
+ direction: 1 | -1;
292
+ };
293
+ }
294
+ type AggregationResult$1 = Record<string, any> | Record<string, any>[];
295
+ interface AggregationAliasDebugInfo {
296
+ field: string;
297
+ contains: string;
298
+ originalAlias: string;
299
+ }
300
+ interface AggregationAliasDetail extends AggregationAliasDebugInfo {
301
+ alias: string;
302
+ membershipKey: string;
303
+ }
304
+ interface AggregationQueryPlan {
305
+ sql: string;
306
+ params: any[];
307
+ aliasMetadata?: AggregationAliasDetail[];
308
+ }
309
+ declare enum LogLevel {
310
+ SILENT = 0,
311
+ ERROR = 1,
312
+ WARN = 2,
313
+ INFO = 3,
314
+ DEBUG = 4,
315
+ VERBOSE = 5
316
+ }
317
+ declare class BaseModel implements StringSetChangeTracker {
318
+ static modelName?: string;
319
+ private static listenersMap;
320
+ private static modelNameToDefaultDocId;
321
+ private static globalDefaultDocId;
322
+ private static defaultDocChangedListeners;
323
+ private static modelDocMappingChangedListeners;
324
+ private static readonly DEFAULT_LEGACY_DOC_ID;
325
+ protected static dbInstance: DatabaseEngine | null;
326
+ protected static connectedDocuments: Map<string, {
327
+ yDoc: Y.Doc;
328
+ permissionHint: DocumentPermissionHint;
329
+ }>;
330
+ protected static documentYMaps: Map<string, Y.Map<any>>;
331
+ private _localChanges;
332
+ private _isDirty;
333
+ private _isLoadingFromYjs;
334
+ private _stringSetFields;
335
+ private _metaDocId;
336
+ private _metaPermissionHint;
337
+ /**
338
+ * Returns the document id this instance is associated with, or null if not resolved yet.
339
+ */
340
+ getDocumentId(): string | null;
341
+ id: string;
342
+ type: string;
343
+ static setLogLevel(level: LogLevel): void;
344
+ static getLogLevel(): LogLevel;
345
+ static setModelDefaultDocumentId(modelName: string, docId: string): void;
346
+ static removeModelDefaultDocumentId(modelName: string): void;
347
+ static clearModelDefaultDocumentIds(): void;
348
+ static setGlobalDefaultDocumentId(docId: string): void;
349
+ static clearGlobalDefaultDocumentId(): void;
350
+ static getModelDefaultDocumentMapping(): Record<string, string>;
351
+ static getDocumentIdForModel(modelName: string): string | undefined;
352
+ static getGlobalDefaultDocumentId(): string | undefined;
353
+ static onDefaultDocChanged(listener: (payload: {
354
+ previous?: string;
355
+ current?: string;
356
+ }) => void): () => void;
357
+ static onModelDocMappingChanged(listener: (payload: {
358
+ modelName: string;
359
+ previous?: string;
360
+ current?: string;
361
+ }) => void): () => void;
362
+ static _clearMappingsForDocId(docId: string): void;
363
+ private static attachFieldAccessorsSet;
364
+ static attachFieldAccessors(modelClass: typeof BaseModel, fields: Map<string, FieldOptions>): void;
365
+ constructor(data?: Partial<any>);
366
+ private ensureLocalChanges;
367
+ private hasLocalChange;
368
+ private getFromYjs;
369
+ private getValue;
370
+ private setValue;
371
+ get isDirty(): boolean;
372
+ get hasUnsavedChanges(): boolean;
373
+ private clearLocalChanges;
374
+ discardChanges(): void;
375
+ protected validateFieldValue(fieldKey: string, value: any): void;
376
+ protected validateBeforeSave(): void;
377
+ getChangedFields(): string[];
378
+ getOriginalValue(fieldKey: string): any;
379
+ getCurrentValue(fieldKey: string): any;
380
+ hasFieldChanged(fieldKey: string): boolean;
381
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
382
+ private getStringSetCurrentValues;
383
+ private getStringSetFromYjs;
384
+ private getOrCreateStringSet;
385
+ static initialize(_yDoc: Y.Doc, _db: DatabaseEngine): Promise<void>;
386
+ static initializeForDocument(yDoc: Y.Doc, db: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise<void>;
387
+ static cleanupDocumentData(docId: string): Promise<void>;
388
+ static subscribe(callback: () => void): () => void;
389
+ protected static notifyListeners(): void;
390
+ /**
391
+ * Legacy migration method - no longer needed in the new multidoc architecture.
392
+ * Data migration is now handled during document initialization.
393
+ */
394
+ static migrateToNestedYMaps(): Promise<void>;
395
+ /**
396
+ * Utility to diff current instance data against YJS nested map data
397
+ * Returns object with added, modified, and removed fields
398
+ */
399
+ protected _diffWithYjsData(): {
400
+ added: Record<string, any>;
401
+ modified: Record<string, any>;
402
+ removed: string[];
403
+ };
404
+ /**
405
+ * Deep equality check for comparing field values
406
+ */
407
+ protected _deepEqual(a: any, b: any): boolean;
408
+ protected static _buildKeyFromValues(fields: string[], keyValues: any[], modelName: string, constraintName: string): string | null;
409
+ protected _buildUniqueKey(fields: string[], data: Record<string, any>, modelName: string, constraintName: string): string | null;
410
+ save(options?: SaveOptions$1): Promise<void>;
411
+ delete(): Promise<void>;
412
+ protected getCurrentJSState(): Record<string, any>;
413
+ protected toJSON(): Record<string, any>;
414
+ static find<T extends BaseModel>(this: new (...args: any[]) => T, id: string): Promise<T | null>;
415
+ /**
416
+ * Document-style query API - returns paginated results
417
+ */
418
+ static query<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: QueryOptions & {
419
+ projection?: P;
420
+ }): Promise<PaginatedResult<QueryResult<T, P>>>;
421
+ /**
422
+ * Main aggregation API - performs grouping, faceting, and statistical operations
423
+ * @param options Aggregation configuration with groupBy, operations, filter, limit, and sort
424
+ * @returns Nested object structure with aggregation results
425
+ *
426
+ * @example
427
+ * // Simple facet count
428
+ * const tagCounts = await Model.aggregate({
429
+ * groupBy: ['tags'],
430
+ * operations: [{ type: 'count' }]
431
+ * });
432
+ * // Result: { red: 15, blue: 8, green: 12 }
433
+ *
434
+ * @example
435
+ * // Multi-dimensional grouping with multiple operations
436
+ * const categoryStats = await Model.aggregate({
437
+ * groupBy: ['category', 'status'],
438
+ * operations: [
439
+ * { type: 'count' },
440
+ * { type: 'sum', field: 'amount' },
441
+ * { type: 'avg', field: 'score' }
442
+ * ],
443
+ * filter: { active: true },
444
+ * sort: { field: 'count', direction: 'desc' },
445
+ * limit: 10
446
+ * });
447
+ *
448
+ * @example
449
+ * // StringSet membership grouping
450
+ * const urgentCounts = await Model.aggregate({
451
+ * groupBy: [{ field: 'tags', contains: 'urgent' }],
452
+ * operations: [{ type: 'count' }]
453
+ * });
454
+ * // Result: { true: 5, false: 23 }
455
+ */
456
+ static aggregate<T extends BaseModel>(this: new (...args: any[]) => T, options: AggregationOptions$1): Promise<AggregationResult$1>;
457
+ /**
458
+ * Build SQL query for structured aggregation
459
+ */
460
+ protected static buildAggregationQuery(options: AggregationOptions$1, schema: any, modelName: string): AggregationQueryPlan;
461
+ /**
462
+ * Get the proper database table name (should match database engine naming)
463
+ */
464
+ protected static getDatabaseTableName(modelName: string): string;
465
+ /**
466
+ * Get the proper database junction table name for StringSet fields
467
+ */
468
+ protected static getDatabaseJunctionTableName(modelName: string, fieldName: string): string;
469
+ private static buildMembershipKey;
470
+ /**
471
+ * Build query for StringSet facet counts
472
+ */
473
+ protected static buildStringSetFacetQuery(stringSetFields: string[], options: AggregationOptions$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
474
+ /**
475
+ * Build query for regular field aggregation
476
+ */
477
+ protected static buildRegularAggregationQuery(regularGroupBy: string[], stringSetMemberships: StringSetMembership$1[], options: AggregationOptions$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
478
+ /**
479
+ * Process aggregation results into nested structure
480
+ */
481
+ protected static processAggregationResults(results: any[], options: AggregationOptions$1, aliasMetadata?: AggregationAliasDetail[]): AggregationResult$1;
482
+ /**
483
+ * Document-style query API - returns single result or null
484
+ */
485
+ static queryOne<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: Omit<QueryOptions, "limit" | "uniqueStartKey" | "direction"> & {
486
+ projection?: P;
487
+ }): Promise<QueryResult<T, P> | null>;
488
+ /**
489
+ * Document-style count API
490
+ */
491
+ static count(this: new (...args: any[]) => any, filter?: DocumentFilter, options?: Pick<QueryOptions, "documents">): Promise<number>;
492
+ static findAll<T extends BaseModel>(this: new (...args: any[]) => T): Promise<T[]>;
493
+ static findByUnique<T extends BaseModel>(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, value: any | any[]): Promise<T | null>;
494
+ static upsertByUnique<T extends BaseModel>(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, uniqueLookupValue: any | any[], dataToUpsert: Partial<Omit<InstanceType<new (...args: any[]) => T>, keyof BaseModel | "toJSON">> & {
495
+ id?: string;
496
+ }, options?: {
497
+ objectMustExist?: boolean;
498
+ objectMustNotExist?: boolean;
499
+ targetDocument?: string;
500
+ }): Promise<T>;
501
+ /**
502
+ * Execute a callback with automatic transaction handling for all modified models
503
+ */
504
+ static withTransaction<T>(callback: () => Promise<T> | T): Promise<T>;
505
+ /**
506
+ * Sets up deep observation on a nested YMap to sync field-level changes to the database
507
+ */
508
+ protected static setupNestedYMapObserver(recordId: string, recordYMap: Y.Map<any>): void;
509
+ /**
510
+ * Sets up deep observation on a nested YMap for a specific document to sync field-level changes to the database
511
+ */
512
+ protected static setupNestedYMapObserverForDocument(recordId: string, recordYMap: Y.Map<any>, docId: string, permissionHint: DocumentPermissionHint): void;
513
+ }
514
+
515
+ /**
516
+ * Durable Object Engine
517
+ *
518
+ * Database engine implementation that runs inside a Cloudflare Durable Object.
519
+ * Uses the DO's embedded SQLite database via ctx.storage.sql.
520
+ *
521
+ * Key characteristics:
522
+ * - Synchronous SQL execution (DO SQLite is sync)
523
+ * - No doc ID column needed (one DO = one document)
524
+ * - Uses JSON schema (records + stringset_index tables)
525
+ * - Schemaless: any model/field can be saved and queried without registration
526
+ * - Indexes are additive: register/drop individual field indexes independently
527
+ */
528
+
529
+ /** Row shape from the _indexes table */
530
+ interface IndexEntry {
531
+ model_name: string;
532
+ field_name: string;
533
+ field_type: string;
534
+ is_unique: number;
535
+ created_at: string;
536
+ }
537
+ /** Row shape from the _unique_constraints table */
538
+ interface UniqueConstraintEntry {
539
+ model_name: string;
540
+ constraint_name: string;
541
+ fields: string[];
542
+ created_at: string;
543
+ }
544
+ /** Row shape from the _model_fields table */
545
+ interface ModelFieldInfo {
546
+ model_name: string;
547
+ field_name: string;
548
+ inferred_type: string;
549
+ first_seen_at: string;
550
+ }
551
+
552
+ /**
553
+ * Aggregation types shared between Yjs and DO backends.
554
+ */
555
+
556
+ /**
557
+ * Describes a StringSet membership check in a groupBy clause.
558
+ * Groups records by whether they have a specific value in a StringSet field.
559
+ */
560
+ interface StringSetMembership {
561
+ field: string;
562
+ contains: string;
563
+ }
564
+ /**
565
+ * A groupBy field can be a plain field name or a StringSet membership check.
566
+ */
567
+ type GroupByField = string | StringSetMembership;
568
+ /**
569
+ * An aggregation operation (count, sum, avg, min, max).
570
+ */
571
+ interface AggregationOperation {
572
+ type: "count" | "sum" | "avg" | "min" | "max";
573
+ /** Required for sum, avg, min, max; not used for count */
574
+ field?: string;
575
+ }
576
+ /**
577
+ * Options for an aggregation query.
578
+ */
579
+ interface AggregationOptions {
580
+ groupBy: GroupByField[];
581
+ operations: AggregationOperation[];
582
+ filter?: DocumentFilter;
583
+ limit?: number;
584
+ sort?: {
585
+ /** Can be operation result field like 'count', 'sum_fieldName', etc. */
586
+ field: string;
587
+ /** 1 for ascending, -1 for descending */
588
+ direction: 1 | -1;
589
+ };
590
+ }
591
+ /**
592
+ * Result of an aggregation query — nested object keyed by group values.
593
+ */
594
+ type AggregationResult = Record<string, any> | Record<string, any>[];
595
+
596
+ /**
597
+ * Database Durable Object Factory
598
+ *
599
+ * Creates a Durable Object class that serves as a schemaless database store.
600
+ * Each DO instance has its own SQLite database.
601
+ *
602
+ * Usage:
603
+ * ```typescript
604
+ * import { createDatabaseDO } from 'js-bao/cloudflare/do';
605
+ *
606
+ * export const MyDatabaseDO = createDatabaseDO({
607
+ * hooks: {
608
+ * beforeSave: async (ctx) => {
609
+ * // Access control logic
610
+ * return { allow: true };
611
+ * },
612
+ * },
613
+ * });
614
+ * ```
615
+ */
616
+
617
+ /**
618
+ * Request body types for RPC endpoints
619
+ */
620
+ interface QueryRequest {
621
+ modelName: string;
622
+ filter: DocumentFilter;
623
+ options?: QueryOptions;
624
+ }
625
+ interface SaveRequest {
626
+ modelName: string;
627
+ id: string;
628
+ data: Record<string, any>;
629
+ stringSets?: Record<string, string[]>;
630
+ ifNotExists?: boolean;
631
+ condition?: DocumentFilter;
632
+ }
633
+ interface DeleteRequest {
634
+ modelName: string;
635
+ id: string;
636
+ condition?: DocumentFilter;
637
+ }
638
+ interface CountRequest {
639
+ modelName: string;
640
+ filter: DocumentFilter;
641
+ }
642
+ /**
643
+ * Response types
644
+ */
645
+ interface QueryResponse {
646
+ data: Record<string, any>[];
647
+ hasMore?: boolean;
648
+ nextCursor?: string;
649
+ prevCursor?: string;
650
+ }
651
+ interface SaveResponse {
652
+ success: boolean;
653
+ id: string;
654
+ }
655
+ interface DeleteResponse {
656
+ success: boolean;
657
+ }
658
+ interface CountResponse {
659
+ count: number;
660
+ }
661
+ interface ErrorResponse {
662
+ error: string;
663
+ code?: string;
664
+ }
665
+ interface AggregateRequest {
666
+ modelName: string;
667
+ options: AggregationOptions;
668
+ }
669
+ interface AggregateResponse {
670
+ result: AggregationResult;
671
+ }
672
+ interface SyncIndexesRequest {
673
+ models: Array<{
674
+ modelName: string;
675
+ indexes: Array<{
676
+ fieldName: string;
677
+ fieldType: string;
678
+ unique: boolean;
679
+ }>;
680
+ uniqueConstraints: Array<{
681
+ name: string;
682
+ fields: string[];
683
+ }>;
684
+ }>;
685
+ }
686
+ interface SyncIndexesResponse {
687
+ registered: number;
688
+ }
689
+ interface PatchRequest {
690
+ modelName: string;
691
+ id: string;
692
+ data: Record<string, any>;
693
+ stringSets?: Record<string, string[]>;
694
+ condition?: DocumentFilter;
695
+ }
696
+ interface PatchResponse {
697
+ success: boolean;
698
+ id: string;
699
+ }
700
+ interface BatchOperation {
701
+ op: "save" | "patch" | "delete" | "increment" | "addToSet" | "removeFromSet";
702
+ modelName: string;
703
+ id: string;
704
+ data?: Record<string, any>;
705
+ stringSets?: Record<string, string[]>;
706
+ fields?: Record<string, number>;
707
+ ifNotExists?: boolean;
708
+ condition?: DocumentFilter;
709
+ }
710
+ interface BatchRequest {
711
+ operations: BatchOperation[];
712
+ }
713
+ interface BatchOperationResult {
714
+ success: boolean;
715
+ id: string;
716
+ error?: string;
717
+ values?: Record<string, number>;
718
+ }
719
+ interface BatchResponse {
720
+ results: BatchOperationResult[];
721
+ }
722
+ interface IncrementRequest {
723
+ modelName: string;
724
+ id: string;
725
+ fields: Record<string, number>;
726
+ condition?: DocumentFilter;
727
+ }
728
+ interface IncrementResponse {
729
+ success: boolean;
730
+ id: string;
731
+ values: Record<string, number>;
732
+ }
733
+ interface StringSetUpdateRequest {
734
+ modelName: string;
735
+ id: string;
736
+ sets: Record<string, string[]>;
737
+ condition?: DocumentFilter;
738
+ }
739
+ interface StringSetUpdateResponse {
740
+ success: boolean;
741
+ }
742
+ interface DescribeResponse {
743
+ modelName: string;
744
+ fields: ModelFieldInfo[];
745
+ }
746
+
747
+ /**
748
+ * Durable Object Client Engine
749
+ *
750
+ * Client-side engine that proxies database operations to a Cloudflare
751
+ * Durable Object via HTTP fetch calls.
752
+ *
753
+ * This engine runs in the browser or Node.js and communicates with
754
+ * the DO-based backend.
755
+ */
756
+
757
+ interface DOClientEngineConfig {
758
+ /**
759
+ * Base URL of the Cloudflare Worker
760
+ * e.g., "https://my-worker.my-subdomain.workers.dev"
761
+ */
762
+ endpoint: string;
763
+ /**
764
+ * Optional custom fetch function (useful for testing)
765
+ */
766
+ fetch?: typeof fetch;
767
+ /**
768
+ * Optional authorization header value
769
+ */
770
+ authorization?: string;
771
+ /**
772
+ * Request timeout in milliseconds (default: 30000)
773
+ */
774
+ timeout?: number;
775
+ }
776
+ declare class DOClientEngine extends DatabaseEngine {
777
+ private endpoint;
778
+ private customFetch;
779
+ private authorization?;
780
+ private timeout;
781
+ private currentDocId;
782
+ constructor(config: DOClientEngineConfig);
783
+ /**
784
+ * Set the current document ID for subsequent operations.
785
+ */
786
+ setCurrentDocument(docId: string): void;
787
+ /**
788
+ * Get the current document ID.
789
+ */
790
+ getCurrentDocument(): string | null;
791
+ /**
792
+ * Build the URL for a DO endpoint.
793
+ */
794
+ private buildUrl;
795
+ /**
796
+ * Make a fetch request to the DO.
797
+ */
798
+ private doFetch;
799
+ /**
800
+ * Query records from the DO.
801
+ */
802
+ queryModel(modelName: string, filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<Record<string, any>>>;
803
+ /**
804
+ * Save a record to the DO.
805
+ */
806
+ saveModel(modelName: string, id: string, data: Record<string, any>, stringSets?: Record<string, string[]>, options?: {
807
+ ifNotExists?: boolean;
808
+ condition?: DocumentFilter;
809
+ }): Promise<string>;
810
+ /**
811
+ * Patch (partial update) a record in the DO.
812
+ * Only the provided fields are updated; existing fields are preserved.
813
+ */
814
+ patchModel(modelName: string, id: string, data: Record<string, any>, stringSets?: Record<string, string[]>, options?: {
815
+ condition?: DocumentFilter;
816
+ }): Promise<string>;
817
+ /**
818
+ * Delete a record from the DO.
819
+ */
820
+ deleteModel(modelName: string, id: string, options?: {
821
+ condition?: DocumentFilter;
822
+ }): Promise<boolean>;
823
+ /**
824
+ * Count records matching a filter.
825
+ */
826
+ countModel(modelName: string, filter?: DocumentFilter): Promise<number>;
827
+ /**
828
+ * Aggregate records with groupBy and operations (count, sum, avg, min, max).
829
+ */
830
+ aggregateModel(modelName: string, options: AggregationOptions): Promise<AggregationResult>;
831
+ /**
832
+ * Atomically add values to StringSet fields on a record.
833
+ */
834
+ addToStringSet(modelName: string, id: string, sets: Record<string, string[]>, options?: {
835
+ condition?: DocumentFilter;
836
+ }): Promise<void>;
837
+ /**
838
+ * Atomically remove values from StringSet fields on a record.
839
+ */
840
+ removeFromStringSet(modelName: string, id: string, sets: Record<string, string[]>, options?: {
841
+ condition?: DocumentFilter;
842
+ }): Promise<void>;
843
+ /**
844
+ * Atomically increment/decrement numeric fields on a record.
845
+ * Returns the new values after the increment.
846
+ */
847
+ incrementFields(modelName: string, id: string, fields: Record<string, number>, options?: {
848
+ condition?: DocumentFilter;
849
+ }): Promise<Record<string, number>>;
850
+ /**
851
+ * Execute multiple save/patch/delete operations in a single request.
852
+ * All operations run in a single transaction on the server.
853
+ */
854
+ batchWrite(operations: BatchOperation[]): Promise<BatchOperationResult[]>;
855
+ /**
856
+ * Check if the DO is healthy.
857
+ */
858
+ healthCheck(): Promise<{
859
+ status: string;
860
+ }>;
861
+ /**
862
+ * Batch sync indexes: send all desired indexes in one request.
863
+ * The DO compares against its _indexes table and registers only what's missing.
864
+ * Returns the number of indexes/constraints newly registered.
865
+ */
866
+ syncIndexesBatch(request: SyncIndexesRequest): Promise<number>;
867
+ /**
868
+ * Register an index on a model field.
869
+ * Creates a SQLite index on json_extract(data_json, '$.fieldName').
870
+ * Set unique=true to enforce uniqueness on this field.
871
+ */
872
+ registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise<void>;
873
+ /**
874
+ * Drop an index from a model field.
875
+ */
876
+ dropIndex(modelName: string, fieldName: string): Promise<void>;
877
+ /**
878
+ * List indexes, optionally filtered by model name.
879
+ */
880
+ listIndexes(modelName?: string): Promise<IndexEntry[]>;
881
+ /**
882
+ * Describe tracked fields for a model.
883
+ */
884
+ describe(modelName: string): Promise<ModelFieldInfo[]>;
885
+ /**
886
+ * Register a composite unique constraint across multiple fields.
887
+ */
888
+ registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise<void>;
889
+ /**
890
+ * Drop a composite unique constraint.
891
+ */
892
+ dropUniqueConstraint(modelName: string, constraintName: string): Promise<void>;
893
+ /**
894
+ * List composite unique constraints, optionally filtered by model name.
895
+ */
896
+ listUniqueConstraints(modelName?: string): Promise<UniqueConstraintEntry[]>;
897
+ /**
898
+ * Ensure the engine is ready.
899
+ * For DOClient, this verifies connectivity.
900
+ */
901
+ ensureReady(): Promise<void>;
902
+ /**
903
+ * Execute raw SQL.
904
+ * Not supported in DO client mode - use queryModel instead.
905
+ */
906
+ query(_sql: string, _params?: any[]): Promise<any[]>;
907
+ /**
908
+ * Get last error message.
909
+ */
910
+ getLastErrorMessage(): string | undefined;
911
+ /**
912
+ * Get table schema.
913
+ * Not directly supported - schema is managed by the DO.
914
+ */
915
+ getTableSchema(_tableName: string): Promise<any>;
916
+ /**
917
+ * Destroy the engine.
918
+ * Nothing to clean up for the client.
919
+ */
920
+ destroy(): Promise<void>;
921
+ /**
922
+ * Create table.
923
+ * No-op in DO client mode - schema is managed by the DO.
924
+ */
925
+ createTable(_modelName: string, _schema: Map<string, FieldOptions>, _options: ModelOptions): Promise<void>;
926
+ /**
927
+ * Create StringSet junction table.
928
+ * No-op in DO client mode.
929
+ */
930
+ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise<void>;
931
+ /**
932
+ * Insert a record.
933
+ * Delegates to saveModel.
934
+ */
935
+ insert(modelName: string, data: any): Promise<void>;
936
+ /**
937
+ * Delete a record.
938
+ * Delegates to deleteModel.
939
+ */
940
+ delete(modelName: string, id: string): Promise<void>;
941
+ /**
942
+ * Get table name.
943
+ * All models use 'records' in JSON schema.
944
+ */
945
+ getTableName(_modelName: string): string;
946
+ /**
947
+ * Transaction support.
948
+ * DO client doesn't support client-side transactions.
949
+ * Operations are atomic on the DO side.
950
+ */
951
+ withTransaction<T>(callback: (operations: ITransactionalDatabaseOperations) => Promise<T>): Promise<T>;
952
+ }
953
+
954
+ /**
955
+ * Durable Object Mode Initialization
956
+ *
957
+ * Alternative initialization for js-bao that uses Cloudflare Durable Objects
958
+ * instead of yjs for document storage.
959
+ *
960
+ * Key differences from yjs mode:
961
+ * - No yjs dependency
962
+ * - Server-authoritative (DO is source of truth)
963
+ * - HTTP-based communication with DO backend
964
+ * - One DO per document
965
+ * - Schemaless: any field can be saved/queried without registration
966
+ * - Only indexes need explicit registration for performance
967
+ */
968
+
969
+ /**
970
+ * A model can be identified by either a BaseModel subclass or a plain string name.
971
+ * Use a string when you don't have a model class (e.g., schemaless / CSV import).
972
+ */
973
+ type ModelIdentifier = typeof BaseModel | string;
974
+ /**
975
+ * Configuration for connectDoDb
976
+ */
977
+ interface ConnectDoDbOptions {
978
+ /** Base URL of the Cloudflare Worker */
979
+ endpoint: string;
980
+ /** Document ID to connect to */
981
+ id: string;
982
+ /** Model classes to create pre-bound accessors for */
983
+ models?: (typeof BaseModel)[];
984
+ /** Optional authorization header value */
985
+ authorization?: string;
986
+ /** Optional custom fetch function (for testing) */
987
+ fetch?: typeof fetch;
988
+ /** Request timeout in milliseconds (default: 30000) */
989
+ timeout?: number;
990
+ }
991
+ /**
992
+ * Pre-bound model accessor — all methods are scoped to a specific model.
993
+ */
994
+ interface SaveOptions {
995
+ stringSets?: Record<string, string[]>;
996
+ ifNotExists?: boolean;
997
+ condition?: DocumentFilter;
998
+ }
999
+ interface PatchOptions {
1000
+ stringSets?: Record<string, string[]>;
1001
+ condition?: DocumentFilter;
1002
+ }
1003
+ interface WriteCondition {
1004
+ condition?: DocumentFilter;
1005
+ }
1006
+ interface ModelAccessor {
1007
+ query<T extends Record<string, any> = Record<string, any>>(filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<T>>;
1008
+ find<T extends Record<string, any> = Record<string, any>>(id: string): Promise<T | null>;
1009
+ save(data: Record<string, any>, options?: SaveOptions | Record<string, string[]>): Promise<string>;
1010
+ patch(id: string, data: Record<string, any>, options?: PatchOptions | Record<string, string[]>): Promise<string>;
1011
+ delete(id: string, options?: WriteCondition): Promise<boolean>;
1012
+ count(filter?: DocumentFilter): Promise<number>;
1013
+ aggregate(options: AggregationOptions): Promise<AggregationResult>;
1014
+ increment(id: string, fields: Record<string, number>, options?: WriteCondition): Promise<Record<string, number>>;
1015
+ addToSet(id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1016
+ removeFromSet(id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1017
+ }
1018
+ /**
1019
+ * Result of connectDoDb — provides both ad-hoc and pre-bound model access.
1020
+ *
1021
+ * Ad-hoc: `db.query(User, filter)` — works with any model class.
1022
+ * Pre-bound: `db.User.query(filter)` — only for models passed in `models` array.
1023
+ */
1024
+ interface DoDb {
1025
+ /** The underlying DO client engine */
1026
+ readonly engine: DOClientEngine;
1027
+ /** The connected document ID */
1028
+ readonly docId: string;
1029
+ query<T extends Record<string, any> = Record<string, any>>(model: ModelIdentifier, filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<T>>;
1030
+ find<T extends Record<string, any> = Record<string, any>>(model: ModelIdentifier, id: string): Promise<T | null>;
1031
+ save(model: ModelIdentifier, data: Record<string, any>, options?: SaveOptions | Record<string, string[]>): Promise<string>;
1032
+ patch(model: ModelIdentifier, id: string, data: Record<string, any>, options?: PatchOptions | Record<string, string[]>): Promise<string>;
1033
+ delete(model: ModelIdentifier, id: string, options?: WriteCondition): Promise<boolean>;
1034
+ count(model: ModelIdentifier, filter?: DocumentFilter): Promise<number>;
1035
+ aggregate(model: ModelIdentifier, options: AggregationOptions): Promise<AggregationResult>;
1036
+ increment(model: ModelIdentifier, id: string, fields: Record<string, number>, options?: WriteCondition): Promise<Record<string, number>>;
1037
+ addToSet(model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1038
+ removeFromSet(model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1039
+ batch(operations: BatchOperation[]): Promise<BatchOperationResult[]>;
1040
+ describe(modelName: string): Promise<ModelFieldInfo[]>;
1041
+ registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise<void>;
1042
+ dropIndex(modelName: string, fieldName: string): Promise<void>;
1043
+ listIndexes(modelName?: string): Promise<IndexEntry[]>;
1044
+ registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise<void>;
1045
+ dropUniqueConstraint(modelName: string, constraintName: string): Promise<void>;
1046
+ listUniqueConstraints(modelName?: string): Promise<UniqueConstraintEntry[]>;
1047
+ syncIndexes(modelClass: typeof BaseModel): Promise<number>;
1048
+ /**
1049
+ * Sync indexes for all models passed in the `models` array at init.
1050
+ * Returns total number of indexes/constraints newly registered.
1051
+ */
1052
+ syncAllIndexes(): Promise<number>;
1053
+ [modelName: string]: any;
1054
+ }
1055
+ /**
1056
+ * Connect to a Durable Object document database.
1057
+ *
1058
+ * Combines initialization and document connection into a single call.
1059
+ * Returns an object with both ad-hoc and pre-bound model access.
1060
+ *
1061
+ * Usage:
1062
+ * ```typescript
1063
+ * import { connectDoDb } from 'js-bao/cloudflare';
1064
+ * import { User, Post } from './models';
1065
+ *
1066
+ * const db = connectDoDb({
1067
+ * endpoint: 'https://my-worker.workers.dev',
1068
+ * id: 'my-document',
1069
+ * models: [User, Post],
1070
+ * });
1071
+ *
1072
+ * // Pre-bound model access (models registered at init)
1073
+ * await db.User.save({ id: 'u-1', name: 'Alice' });
1074
+ * const users = await db.User.query({ name: 'Alice' });
1075
+ * const user = await db.User.find('u-1');
1076
+ *
1077
+ * // Ad-hoc model access (any model class)
1078
+ * await db.save(User, { id: 'u-2', name: 'Bob' });
1079
+ * const results = await db.query(User, { name: 'Bob' });
1080
+ * ```
1081
+ */
1082
+ declare function connectDoDb(options: ConnectDoDbOptions): DoDb;
1083
+
1084
+ export { type AggregateRequest, type AggregateResponse, type AggregationOperation, type AggregationOptions, type AggregationResult, type BatchOperation, type BatchOperationResult, type BatchRequest, type BatchResponse, type ConnectDoDbOptions, type CountRequest, type CountResponse, DOClientEngine, type DOClientEngineConfig, type DeleteRequest, type DeleteResponse, type DescribeResponse, type DoDb, type DocumentFilter, type ErrorResponse, type GroupByField, type IncrementRequest, type IncrementResponse, type IndexEntry, type ModelAccessor, type ModelFieldInfo, type ModelIdentifier, type PaginatedResult, type PatchOptions, type PatchRequest, type PatchResponse, type ProjectionSpec, type QueryOptions, type QueryRequest, type QueryResponse, type SaveOptions, type SaveRequest, type SaveResponse, type SortSpec, type StringSetMembership, type StringSetUpdateRequest, type StringSetUpdateResponse, type SyncIndexesRequest, type SyncIndexesResponse, type UniqueConstraintEntry, type WriteCondition, connectDoDb };