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