js-bao 0.2.8

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,809 @@
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
+ type NodeSqliteEngineOptions = {
48
+ filePath?: string;
49
+ options?: {
50
+ readonly?: boolean;
51
+ fileMustExist?: boolean;
52
+ timeout?: number;
53
+ verbose?: (...args: any[]) => void;
54
+ };
55
+ };
56
+ type DatabaseEngineType = "sqljs" | "node-sqlite" | "alasql";
57
+ interface SqljsEngineOptions {
58
+ wasmURL?: string;
59
+ locateFile?: (file: string) => string;
60
+ }
61
+ type DatabaseEngineOptions = SqljsEngineOptions | NodeSqliteEngineOptions | Record<string, any>;
62
+ interface DatabaseConfig {
63
+ type: DatabaseEngineType;
64
+ options?: DatabaseEngineOptions;
65
+ }
66
+
67
+ type DocumentPermissionHint = "read" | "read-write";
68
+ interface ConnectedDocument {
69
+ docId: string;
70
+ yDoc: Y.Doc;
71
+ permissionHint: DocumentPermissionHint;
72
+ }
73
+ interface SaveOptions {
74
+ targetDocument?: string;
75
+ forceWrite?: boolean;
76
+ }
77
+ interface DocumentManager {
78
+ connectDocument(docId: string, yDoc: Y.Doc, permissionHint: DocumentPermissionHint): Promise<void>;
79
+ disconnectDocument(docId: string): Promise<void>;
80
+ getConnectedDocuments(): Map<string, ConnectedDocument>;
81
+ isDocumentConnected(docId: string): boolean;
82
+ }
83
+ interface DocumentConnectionEvent {
84
+ type: "connect" | "disconnect";
85
+ docId: string;
86
+ document?: ConnectedDocument;
87
+ }
88
+ type DocumentConnectionCallback = (event: DocumentConnectionEvent) => void;
89
+ declare class DocumentClosedError extends Error {
90
+ code: string;
91
+ constructor(message: string);
92
+ }
93
+ declare class DocumentResolutionError extends Error {
94
+ code: string;
95
+ constructor(message: string);
96
+ }
97
+
98
+ interface ComparisonOperators<T = any> {
99
+ $eq?: T;
100
+ $ne?: T;
101
+ $gt?: T;
102
+ $gte?: T;
103
+ $lt?: T;
104
+ $lte?: T;
105
+ $in?: T[];
106
+ $nin?: T[];
107
+ }
108
+ interface StringSetOperators {
109
+ /**
110
+ * Exact membership: StringSet contains this specific string
111
+ */
112
+ $contains?: string;
113
+ $all?: string[];
114
+ $size?: number | ComparisonOperators<number>;
115
+ }
116
+ interface SubstringOperators {
117
+ /** Prefix match */
118
+ $startsWith?: string;
119
+ /** Suffix match */
120
+ $endsWith?: string;
121
+ /** Substring anywhere */
122
+ $containsText?: string;
123
+ }
124
+ interface ExistenceOperators {
125
+ $exists?: boolean;
126
+ }
127
+ type FieldOperators<T = any> = ComparisonOperators<T> & ExistenceOperators & StringSetOperators & SubstringOperators;
128
+ interface LogicalOperators {
129
+ $and?: DocumentFilter[];
130
+ $or?: DocumentFilter[];
131
+ }
132
+ type DocumentFilter = {
133
+ [field: string]: any | FieldOperators<any>;
134
+ } & LogicalOperators;
135
+ type SortDirection = 1 | -1;
136
+ type SortSpec = {
137
+ [field: string]: SortDirection;
138
+ };
139
+ type ProjectionSpec = {
140
+ [field: string]: 1 | 0;
141
+ };
142
+ interface QueryOptions {
143
+ sort?: SortSpec;
144
+ projection?: ProjectionSpec;
145
+ documents?: string | string[];
146
+ limit?: number;
147
+ uniqueStartKey?: string;
148
+ direction?: 1 | -1;
149
+ }
150
+ interface PaginatedResult<T> {
151
+ data: T[];
152
+ nextCursor?: string;
153
+ prevCursor?: string;
154
+ hasMore: boolean;
155
+ }
156
+ interface TranslatedQuery {
157
+ sql: string;
158
+ params: any[];
159
+ sortFields: string[];
160
+ sortDirections?: (1 | -1)[];
161
+ }
162
+ type ProjectedResult<T, P extends ProjectionSpec> = {
163
+ [K in keyof P]: K extends keyof T ? T[K] : never;
164
+ };
165
+ type QueryResult<T, P extends ProjectionSpec | undefined> = P extends ProjectionSpec ? ProjectedResult<T, P> : T;
166
+
167
+ interface PaginationOptions {
168
+ limit?: number;
169
+ afterCursor?: string;
170
+ beforeCursor?: string;
171
+ direction?: "forward" | "backward";
172
+ }
173
+
174
+ interface ITransactionalDatabaseOperations {
175
+ insert(modelName: string, data: any): Promise<void>;
176
+ delete(modelName: string, id: string): Promise<void>;
177
+ query<T extends Record<string, any>>(sql: string, params?: any[]): Promise<T[]>;
178
+ }
179
+ /**
180
+ * Abstract class defining the interface for database engines.
181
+ * This allows for different database implementations (e.g., SQL.js, DuckDB) to be used interchangeably.
182
+ */
183
+ declare abstract class DatabaseEngine {
184
+ /**
185
+ * Ensures that the database engine is fully initialized and ready for use.
186
+ * For WASM-based engines, this might involve loading the WASM module.
187
+ */
188
+ abstract ensureReady(): Promise<void>;
189
+ /**
190
+ * Executes a SQL query against the database.
191
+ * @param sql The SQL query string.
192
+ * @param params Optional array of parameters for prepared statements.
193
+ * @returns A promise that resolves to an array of query results.
194
+ */
195
+ abstract query(sql: string, params?: any[]): Promise<any[]>;
196
+ /**
197
+ * Retrieves the last error message from the database engine, if any.
198
+ * @returns The last error message as a string, or undefined if no error occurred.
199
+ */
200
+ abstract getLastErrorMessage(): string | undefined;
201
+ /**
202
+ * Retrieves the schema for a given table.
203
+ * This is useful for understanding table structure, field types, etc.
204
+ * The exact return type might vary based on the database engine.
205
+ * @param tableName The name of the table.
206
+ * @returns A promise that resolves to the table schema information.
207
+ */
208
+ abstract getTableSchema(tableName: string): Promise<any>;
209
+ /**
210
+ * Destroys the database engine instance and releases any associated resources.
211
+ * This is crucial for cleanup, especially in testing environments or when the application is shutting down.
212
+ */
213
+ abstract destroy(): Promise<void>;
214
+ createTable(_modelName: string, _schema: Map<string, any>, // Assuming 'any' for field options for now, can be refined
215
+ _options: ModelOptions): Promise<void>;
216
+ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise<void>;
217
+ insertStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
218
+ removeStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
219
+ insert(_modelName: string, _data: any): Promise<void>;
220
+ delete(_modelName: string, _id: string): Promise<void>;
221
+ /**
222
+ * Deletes all records for a specific document from the given model table.
223
+ * This is used when disconnecting a document to remove all its data.
224
+ * @param modelName The name of the model/table
225
+ * @param docId The document ID to filter by
226
+ */
227
+ deleteByDocumentId(_modelName: string, _docId: string): Promise<void>;
228
+ getTableName(_modelName: string): string;
229
+ withTransaction<T>(_callback: (operations: ITransactionalDatabaseOperations) => Promise<T>): Promise<T>;
230
+ }
231
+
232
+ interface StringSetChangeTracker {
233
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
234
+ }
235
+ declare class StringSet {
236
+ private _values;
237
+ private _model;
238
+ private _fieldName;
239
+ constructor(model: StringSetChangeTracker, fieldName: string, initialValues?: string[]);
240
+ /**
241
+ * Add a string to the set
242
+ */
243
+ add(value: string): void;
244
+ /**
245
+ * Remove a string from the set
246
+ */
247
+ remove(value: string): void;
248
+ /**
249
+ * Check if the set contains a string
250
+ */
251
+ has(value: string): boolean;
252
+ /**
253
+ * Clear all strings from the set
254
+ */
255
+ clear(): void;
256
+ /**
257
+ * Get the number of strings in the set
258
+ */
259
+ get size(): number;
260
+ /**
261
+ * Get an iterator of all values
262
+ */
263
+ values(): IterableIterator<string>;
264
+ /**
265
+ * Make the StringSet iterable
266
+ */
267
+ [Symbol.iterator](): IterableIterator<string>;
268
+ /**
269
+ * Convert to array
270
+ */
271
+ toArray(): string[];
272
+ /**
273
+ * Union with another StringSet
274
+ */
275
+ union(other: StringSet): StringSet;
276
+ /**
277
+ * Intersection with another StringSet
278
+ */
279
+ intersection(other: StringSet): StringSet;
280
+ /**
281
+ * Difference with another StringSet (values in this set but not in other)
282
+ */
283
+ difference(other: StringSet): StringSet;
284
+ /**
285
+ * Get the current state including pending changes
286
+ * This is used internally by the model to determine the current view
287
+ */
288
+ _getCurrentState(): Set<string>;
289
+ /**
290
+ * Update the internal state (used when loading from Yjs or applying changes)
291
+ */
292
+ _updateInternalState(values: string[]): void;
293
+ }
294
+
295
+ declare class DocumentQueryTranslator {
296
+ private modelName;
297
+ private schema;
298
+ private tableName;
299
+ private quotedTableName;
300
+ private fieldSqlCache;
301
+ constructor(modelName: string, schema: Map<string, FieldOptions>);
302
+ private getQuotedField;
303
+ /**
304
+ * Translate document filter and options to SQL for find operations
305
+ */
306
+ translateFind(filter: DocumentFilter, options?: QueryOptions): TranslatedQuery;
307
+ /**
308
+ * Translate document filter to SQL for count operations
309
+ */
310
+ translateCount(filter: DocumentFilter, options?: Pick<QueryOptions, "documents">): {
311
+ sql: string;
312
+ params: any[];
313
+ };
314
+ /**
315
+ * Translate document filter to SQL WHERE clause
316
+ */
317
+ private translateFilter;
318
+ /**
319
+ * Translate logical operators ($and, $or)
320
+ */
321
+ private translateLogicalOperator;
322
+ /**
323
+ * Translate field condition to SQL
324
+ */
325
+ private translateFieldCondition;
326
+ /**
327
+ * Translate field operators to SQL
328
+ */
329
+ private translateFieldOperators;
330
+ /**
331
+ * Translate individual operator to SQL
332
+ */
333
+ private translateOperator;
334
+ /**
335
+ * Build SELECT clause based on projection
336
+ */
337
+ private buildSelectClause;
338
+ /**
339
+ * Build LIMIT clause
340
+ */
341
+ private buildLimitClause;
342
+ /**
343
+ * Build pagination WHERE clause from cursor
344
+ */
345
+ private buildPaginationClause;
346
+ /**
347
+ * Validate that field exists in schema
348
+ */
349
+ private validateField;
350
+ /**
351
+ * Validate projection fields
352
+ */
353
+ private validateProjection;
354
+ /**
355
+ * Validate operator is supported for field type
356
+ */
357
+ private validateOperatorForType;
358
+ /**
359
+ * Validate field value matches expected type
360
+ */
361
+ private validateFieldValue;
362
+ /**
363
+ * Validate array values for $in/$nin operators
364
+ */
365
+ private validateArrayValues;
366
+ /**
367
+ * Check if value is a primitive (not an object with operators)
368
+ */
369
+ private isPrimitiveValue;
370
+ /**
371
+ * Get the type of a value for validation
372
+ */
373
+ private getValueType;
374
+ /**
375
+ * Check if value type is compatible with field type
376
+ */
377
+ private isTypeCompatible;
378
+ /**
379
+ * Convert value for SQLite compatibility
380
+ */
381
+ private convertValueForSQLite;
382
+ private normalizeDocumentIds;
383
+ private buildDocumentClause;
384
+ }
385
+
386
+ interface StringSetMembership {
387
+ field: string;
388
+ contains: string;
389
+ }
390
+ type GroupByField = string | StringSetMembership;
391
+ interface AggregationOperation {
392
+ type: "count" | "sum" | "avg" | "min" | "max";
393
+ field?: string;
394
+ }
395
+ interface AggregationOptions {
396
+ groupBy: GroupByField[];
397
+ operations: AggregationOperation[];
398
+ filter?: DocumentFilter;
399
+ limit?: number;
400
+ sort?: {
401
+ field: string;
402
+ direction: 1 | -1;
403
+ };
404
+ }
405
+ type AggregationResult = Record<string, any> | Record<string, any>[];
406
+ interface AggregationAliasDebugInfo {
407
+ field: string;
408
+ contains: string;
409
+ originalAlias: string;
410
+ }
411
+ interface AggregationAliasDetail extends AggregationAliasDebugInfo {
412
+ alias: string;
413
+ membershipKey: string;
414
+ }
415
+ interface AggregationQueryPlan {
416
+ sql: string;
417
+ params: any[];
418
+ aliasMetadata?: AggregationAliasDetail[];
419
+ }
420
+ declare enum LogLevel {
421
+ SILENT = 0,
422
+ ERROR = 1,
423
+ WARN = 2,
424
+ INFO = 3,
425
+ DEBUG = 4,
426
+ VERBOSE = 5
427
+ }
428
+ declare class Logger {
429
+ private static _logLevel;
430
+ private static _logCallback;
431
+ static setLogLevel(level: LogLevel): void;
432
+ static getLogLevel(): LogLevel;
433
+ static setLogCallback(callback: ((message: string, level: LogLevel) => void) | null): void;
434
+ static error(message: string, ...args: any[]): void;
435
+ static warn(message: string, ...args: any[]): void;
436
+ static info(message: string, ...args: any[]): void;
437
+ static debug(message: string, ...args: any[]): void;
438
+ static verbose(message: string, ...args: any[]): void;
439
+ }
440
+ declare class UniqueConstraintViolationError extends Error {
441
+ modelName: string;
442
+ constraintName: string;
443
+ fields: string[];
444
+ recordIdAttempted?: string;
445
+ conflictingRecordId?: string;
446
+ constructor(message: string, modelName: string, constraintName: string, fields: string[], recordIdAttempted?: string, conflictingRecordId?: string);
447
+ }
448
+ declare class RecordNotFoundError extends Error {
449
+ constructor(message: string);
450
+ }
451
+ declare function generateULID(): string;
452
+ declare class BaseModel implements StringSetChangeTracker {
453
+ static modelName?: string;
454
+ private static listenersMap;
455
+ private static modelNameToDefaultDocId;
456
+ private static globalDefaultDocId;
457
+ private static defaultDocChangedListeners;
458
+ private static modelDocMappingChangedListeners;
459
+ private static readonly DEFAULT_LEGACY_DOC_ID;
460
+ protected static dbInstance: DatabaseEngine | null;
461
+ protected static connectedDocuments: Map<string, {
462
+ yDoc: Y.Doc;
463
+ permissionHint: DocumentPermissionHint;
464
+ }>;
465
+ protected static documentYMaps: Map<string, Y.Map<any>>;
466
+ private _localChanges;
467
+ private _isDirty;
468
+ private _isLoadingFromYjs;
469
+ private _stringSetFields;
470
+ private _metaDocId;
471
+ private _metaPermissionHint;
472
+ /**
473
+ * Returns the document id this instance is associated with, or null if not resolved yet.
474
+ */
475
+ getDocumentId(): string | null;
476
+ id: string;
477
+ type: string;
478
+ static setLogLevel(level: LogLevel): void;
479
+ static getLogLevel(): LogLevel;
480
+ static setModelDefaultDocumentId(modelName: string, docId: string): void;
481
+ static removeModelDefaultDocumentId(modelName: string): void;
482
+ static clearModelDefaultDocumentIds(): void;
483
+ static setGlobalDefaultDocumentId(docId: string): void;
484
+ static clearGlobalDefaultDocumentId(): void;
485
+ static getModelDefaultDocumentMapping(): Record<string, string>;
486
+ static getDocumentIdForModel(modelName: string): string | undefined;
487
+ static getGlobalDefaultDocumentId(): string | undefined;
488
+ static onDefaultDocChanged(listener: (payload: {
489
+ previous?: string;
490
+ current?: string;
491
+ }) => void): () => void;
492
+ static onModelDocMappingChanged(listener: (payload: {
493
+ modelName: string;
494
+ previous?: string;
495
+ current?: string;
496
+ }) => void): () => void;
497
+ static _clearMappingsForDocId(docId: string): void;
498
+ private static attachFieldAccessorsSet;
499
+ static attachFieldAccessors(modelClass: typeof BaseModel, fields: Map<string, FieldOptions>): void;
500
+ constructor(data?: Partial<any>);
501
+ private ensureLocalChanges;
502
+ private hasLocalChange;
503
+ private getFromYjs;
504
+ private getValue;
505
+ private setValue;
506
+ get isDirty(): boolean;
507
+ get hasUnsavedChanges(): boolean;
508
+ private clearLocalChanges;
509
+ discardChanges(): void;
510
+ protected validateFieldValue(fieldKey: string, value: any): void;
511
+ protected validateBeforeSave(): void;
512
+ getChangedFields(): string[];
513
+ getOriginalValue(fieldKey: string): any;
514
+ getCurrentValue(fieldKey: string): any;
515
+ hasFieldChanged(fieldKey: string): boolean;
516
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
517
+ private getStringSetCurrentValues;
518
+ private getStringSetFromYjs;
519
+ private getOrCreateStringSet;
520
+ static initialize(_yDoc: Y.Doc, _db: DatabaseEngine): Promise<void>;
521
+ static initializeForDocument(yDoc: Y.Doc, db: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise<void>;
522
+ static cleanupDocumentData(docId: string): Promise<void>;
523
+ static subscribe(callback: () => void): () => void;
524
+ protected static notifyListeners(): void;
525
+ /**
526
+ * Legacy migration method - no longer needed in the new multidoc architecture.
527
+ * Data migration is now handled during document initialization.
528
+ */
529
+ static migrateToNestedYMaps(): Promise<void>;
530
+ /**
531
+ * Utility to diff current instance data against YJS nested map data
532
+ * Returns object with added, modified, and removed fields
533
+ */
534
+ protected _diffWithYjsData(): {
535
+ added: Record<string, any>;
536
+ modified: Record<string, any>;
537
+ removed: string[];
538
+ };
539
+ /**
540
+ * Deep equality check for comparing field values
541
+ */
542
+ protected _deepEqual(a: any, b: any): boolean;
543
+ protected static _buildKeyFromValues(fields: string[], keyValues: any[], modelName: string, constraintName: string): string | null;
544
+ protected _buildUniqueKey(fields: string[], data: Record<string, any>, modelName: string, constraintName: string): string | null;
545
+ save(options?: SaveOptions): Promise<void>;
546
+ delete(): Promise<void>;
547
+ protected getCurrentJSState(): Record<string, any>;
548
+ protected toJSON(): Record<string, any>;
549
+ static find<T extends BaseModel>(this: new (...args: any[]) => T, id: string): Promise<T | null>;
550
+ /**
551
+ * Document-style query API - returns paginated results
552
+ */
553
+ static query<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: QueryOptions & {
554
+ projection?: P;
555
+ }): Promise<PaginatedResult<QueryResult<T, P>>>;
556
+ /**
557
+ * Main aggregation API - performs grouping, faceting, and statistical operations
558
+ * @param options Aggregation configuration with groupBy, operations, filter, limit, and sort
559
+ * @returns Nested object structure with aggregation results
560
+ *
561
+ * @example
562
+ * // Simple facet count
563
+ * const tagCounts = await Model.aggregate({
564
+ * groupBy: ['tags'],
565
+ * operations: [{ type: 'count' }]
566
+ * });
567
+ * // Result: { red: 15, blue: 8, green: 12 }
568
+ *
569
+ * @example
570
+ * // Multi-dimensional grouping with multiple operations
571
+ * const categoryStats = await Model.aggregate({
572
+ * groupBy: ['category', 'status'],
573
+ * operations: [
574
+ * { type: 'count' },
575
+ * { type: 'sum', field: 'amount' },
576
+ * { type: 'avg', field: 'score' }
577
+ * ],
578
+ * filter: { active: true },
579
+ * sort: { field: 'count', direction: 'desc' },
580
+ * limit: 10
581
+ * });
582
+ *
583
+ * @example
584
+ * // StringSet membership grouping
585
+ * const urgentCounts = await Model.aggregate({
586
+ * groupBy: [{ field: 'tags', contains: 'urgent' }],
587
+ * operations: [{ type: 'count' }]
588
+ * });
589
+ * // Result: { true: 5, false: 23 }
590
+ */
591
+ static aggregate<T extends BaseModel>(this: new (...args: any[]) => T, options: AggregationOptions): Promise<AggregationResult>;
592
+ /**
593
+ * Build SQL query for structured aggregation
594
+ */
595
+ protected static buildAggregationQuery(options: AggregationOptions, schema: any, modelName: string): AggregationQueryPlan;
596
+ /**
597
+ * Get the proper database table name (should match database engine naming)
598
+ */
599
+ protected static getDatabaseTableName(modelName: string): string;
600
+ /**
601
+ * Get the proper database junction table name for StringSet fields
602
+ */
603
+ protected static getDatabaseJunctionTableName(modelName: string, fieldName: string): string;
604
+ private static buildMembershipKey;
605
+ /**
606
+ * Build query for StringSet facet counts
607
+ */
608
+ protected static buildStringSetFacetQuery(stringSetFields: string[], options: AggregationOptions, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
609
+ /**
610
+ * Build query for regular field aggregation
611
+ */
612
+ protected static buildRegularAggregationQuery(regularGroupBy: string[], stringSetMemberships: StringSetMembership[], options: AggregationOptions, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
613
+ /**
614
+ * Process aggregation results into nested structure
615
+ */
616
+ protected static processAggregationResults(results: any[], options: AggregationOptions, aliasMetadata?: AggregationAliasDetail[]): AggregationResult;
617
+ /**
618
+ * Document-style query API - returns single result or null
619
+ */
620
+ static queryOne<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: Omit<QueryOptions, "limit" | "uniqueStartKey" | "direction"> & {
621
+ projection?: P;
622
+ }): Promise<QueryResult<T, P> | null>;
623
+ /**
624
+ * Document-style count API
625
+ */
626
+ static count(this: new (...args: any[]) => any, filter?: DocumentFilter, options?: Pick<QueryOptions, "documents">): Promise<number>;
627
+ static findAll<T extends BaseModel>(this: new (...args: any[]) => T): Promise<T[]>;
628
+ static findByUnique<T extends BaseModel>(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, value: any | any[]): Promise<T | null>;
629
+ 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">> & {
630
+ id?: string;
631
+ }, options?: {
632
+ objectMustExist?: boolean;
633
+ objectMustNotExist?: boolean;
634
+ targetDocument?: string;
635
+ }): Promise<T>;
636
+ /**
637
+ * Execute a callback with automatic transaction handling for all modified models
638
+ */
639
+ static withTransaction<T>(callback: () => Promise<T> | T): Promise<T>;
640
+ /**
641
+ * Sets up deep observation on a nested YMap to sync field-level changes to the database
642
+ */
643
+ protected static setupNestedYMapObserver(recordId: string, recordYMap: Y.Map<any>): void;
644
+ /**
645
+ * Sets up deep observation on a nested YMap for a specific document to sync field-level changes to the database
646
+ */
647
+ protected static setupNestedYMapObserverForDocument(recordId: string, recordYMap: Y.Map<any>, docId: string, permissionHint: DocumentPermissionHint): void;
648
+ }
649
+
650
+ interface RegisteredModelInfo {
651
+ class: typeof BaseModel;
652
+ options: ModelOptions;
653
+ fields: Map<string, FieldOptions>;
654
+ }
655
+ declare class ModelRegistry {
656
+ private static instance;
657
+ private models;
658
+ private modelOptions;
659
+ private activeSessionModels;
660
+ private dbEngine;
661
+ private constructor();
662
+ static getInstance(): ModelRegistry;
663
+ registerModel(modelClass: any, options: ModelOptions, fields: Map<string, FieldOptions>): void;
664
+ getModelClass(name: string): typeof BaseModel | undefined;
665
+ getModelOptions(name: string): ModelOptions | undefined;
666
+ getModelInfo(modelName: string): RegisteredModelInfo | undefined;
667
+ getAllRegisteredModelsInfo(): RegisteredModelInfo[];
668
+ private getModelNameFromClass;
669
+ setExplicitModelsForSession(modelClasses?: (typeof BaseModel)[]): void;
670
+ initializeAll(yDoc: Y.Doc, dbEngine: DatabaseEngine): Promise<void>;
671
+ initializeAllForDocument(yDoc: Y.Doc, dbEngine: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise<void>;
672
+ removeDocumentData(docId: string, dbEngine: DatabaseEngine): Promise<void>;
673
+ initializeRelationships(): Promise<void>;
674
+ private addPrototypeMethod;
675
+ clearSessionState(): void;
676
+ getActiveModels(): Map<string, typeof BaseModel>;
677
+ private validateSessionModels;
678
+ }
679
+
680
+ interface InitJsBaoOptions {
681
+ databaseConfig: DatabaseConfig;
682
+ /**
683
+ * Optional array of model classes to initialize.
684
+ * If not provided, the ORM will rely on models being registered
685
+ * via the @Model decorator (assuming they have been imported by the application).
686
+ */
687
+ models?: (typeof BaseModel)[];
688
+ }
689
+ interface InitJsBaoResult {
690
+ dbEngine: DatabaseEngine;
691
+ modelRegistry: ModelRegistry;
692
+ connectDocument: (docId: string, yDoc: Y.Doc, permissionHint: DocumentPermissionHint) => Promise<void>;
693
+ disconnectDocument: (docId: string) => Promise<void>;
694
+ getConnectedDocuments: () => Map<string, ConnectedDocument>;
695
+ isDocumentConnected: (docId: string) => boolean;
696
+ onDocumentConnectionChange: (callback: DocumentConnectionCallback) => () => void;
697
+ addDocumentModelMapping: (modelName: string, docId: string) => void;
698
+ removeDocumentModelMapping: (modelName: string) => void;
699
+ clearDocumentModelMappings: () => void;
700
+ setDefaultDocumentId: (docId: string) => void;
701
+ clearDefaultDocumentId: () => void;
702
+ getDocumentModelMapping: () => Record<string, string>;
703
+ getDocumentIdForModel: (modelName: string) => string | undefined;
704
+ getDefaultDocumentId: () => string | undefined;
705
+ onDefaultDocChanged: (listener: (payload: {
706
+ previous?: string;
707
+ current?: string;
708
+ }) => void) => () => void;
709
+ onModelDocMappingChanged: (listener: (payload: {
710
+ modelName: string;
711
+ previous?: string;
712
+ current?: string;
713
+ }) => void) => () => void;
714
+ }
715
+ /**
716
+ * Initializes the js-bao system with multi-document support.
717
+ * Sets up the database engine and prepares for document connections.
718
+ */
719
+ declare function initJsBao(options: InitJsBaoOptions): Promise<InitJsBaoResult>;
720
+ /**
721
+ * Function to reset the initialization state, primarily for testing or hot-reloading scenarios.
722
+ */
723
+ declare function resetJsBao(): Promise<void>;
724
+
725
+ declare function Field(options: FieldOptions): (target: any, propertyKey: string | symbol) => void;
726
+ declare function Model(options: ModelOptions): (targetClass: Function) => void;
727
+
728
+ interface ResolvedUniqueConstraint {
729
+ name: string;
730
+ fields: string[];
731
+ }
732
+ interface ModelSchemaRuntimeShape {
733
+ class: typeof BaseModel;
734
+ options: ModelOptions;
735
+ fields: Map<string, FieldOptions>;
736
+ resolvedUniqueConstraints: ResolvedUniqueConstraint[];
737
+ }
738
+ interface DefineModelSchemaInput<TFields extends Record<string, FieldOptions>> {
739
+ name: string;
740
+ fields: TFields;
741
+ options?: Omit<ModelOptions, "name">;
742
+ }
743
+ interface DefinedModelSchema<TFields extends Record<string, FieldOptions> = Record<string, FieldOptions>> {
744
+ name: string;
745
+ fields: TFields;
746
+ options: ModelOptions;
747
+ runtimeShape?: ModelSchemaRuntimeShape;
748
+ buildRuntimeShape(modelClass: typeof BaseModel): ModelSchemaRuntimeShape;
749
+ }
750
+ declare function defineModelSchema<TFields extends Record<string, FieldOptions>>(input: DefineModelSchemaInput<TFields>): DefinedModelSchema<TFields>;
751
+ type FieldValue<FO extends FieldOptions> = FO["type"] extends "string" ? string : FO["type"] extends "number" ? number : FO["type"] extends "boolean" ? boolean : FO["type"] extends "date" ? string : FO["type"] extends "id" ? string : FO["type"] extends "stringset" ? StringSet : unknown;
752
+ type InferAttrs<TSchema extends DefinedModelSchema<any>> = {
753
+ [K in keyof TSchema["fields"]]: FieldValue<TSchema["fields"][K]>;
754
+ };
755
+ interface CreateModelClassConfig<TSchema extends DefinedModelSchema<any>, TAttrs extends Record<string, any> = InferAttrs<TSchema>> {
756
+ schema: TSchema;
757
+ baseClass?: typeof BaseModel;
758
+ methods?: () => Record<string | symbol, any>;
759
+ statics?: (ctor: ModelConstructor<TAttrs>) => Record<string | symbol, any>;
760
+ }
761
+ type ModelConstructor<TAttrs extends Record<string, any>> = typeof BaseModel & {
762
+ prototype: BaseModel & TAttrs;
763
+ new (attrs?: Partial<TAttrs>): BaseModel & TAttrs;
764
+ };
765
+ /**
766
+ * @deprecated Use defineModelSchema + class + attachAndRegisterModel instead.
767
+ */
768
+ declare function createModelClass<TSchema extends DefinedModelSchema<any>, TAttrs extends Record<string, any> = InferAttrs<TSchema>>(config: CreateModelClassConfig<TSchema, TAttrs>): ModelConstructor<TAttrs>;
769
+ declare function attachSchemaToClass(modelClass: typeof BaseModel, schema: DefinedModelSchema<any>): ModelSchemaRuntimeShape;
770
+ declare function autoRegisterModel(modelClass: typeof BaseModel, runtimeShape?: ModelSchemaRuntimeShape): void;
771
+ declare function attachAndRegisterModel(modelClass: typeof BaseModel, schema: DefinedModelSchema<any>): void;
772
+
773
+ interface DumpOptions {
774
+ includeIndexes?: boolean;
775
+ }
776
+ type PlainYDoc = Record<string, Record<string, any>>;
777
+ interface DumpSummaryEntry {
778
+ count: number;
779
+ approxBytes: number;
780
+ }
781
+ interface DumpSummary {
782
+ models: Record<string, DumpSummaryEntry>;
783
+ totalCount: number;
784
+ totalApproxBytes: number;
785
+ }
786
+ /**
787
+ * Dumps a js-bao-shaped Y.Doc into a plain object:
788
+ * {
789
+ * [modelName]: {
790
+ * [recordId]: { ...fields },
791
+ * ...
792
+ * },
793
+ * ...
794
+ * }
795
+ *
796
+ * - By default ignores internal unique-index maps (`_uniqueIdx_*`); pass
797
+ * `{ includeIndexes: true }` to include them.
798
+ * - Converts each record's nested Y.Map to a plain object.
799
+ * - Leaves StringSet fields as the stored `{ value: true }` map.
800
+ */
801
+ declare function dumpYDocToPlain(yDoc: Y.Doc, options?: DumpOptions): PlainYDoc;
802
+ /**
803
+ * Creates a compact summary from a PlainYDoc:
804
+ * - count of records per model
805
+ * - approximate byte size per model (JSON string length, UTF-8)
806
+ */
807
+ declare function summarizePlainYDoc(dump: PlainYDoc): DumpSummary;
808
+
809
+ export { BaseModel, type ConnectedDocument, type DatabaseConfig, DatabaseEngine, DocumentClosedError, type DocumentConnectionCallback, type DocumentConnectionEvent, type DocumentFilter, type DocumentManager, type DocumentPermissionHint, DocumentResolutionError, type DumpOptions, type DumpSummary, type DumpSummaryEntry, Field, type FieldOptions, type InferAttrs, type InitJsBaoOptions, type InitJsBaoResult, LogLevel, Logger, Model, type ModelConstructor, type ModelOptions, ModelRegistry, type PaginatedResult, type PaginationOptions, type PlainYDoc, type ProjectionSpec, type QueryOptions, type QueryResult, RecordNotFoundError, type SaveOptions, StringSet, UniqueConstraintViolationError, attachAndRegisterModel, attachSchemaToClass, autoRegisterModel, createModelClass, defineModelSchema, dumpYDocToPlain, generateULID, initJsBao, resetJsBao, summarizePlainYDoc };