import * as Y from 'yjs'; interface RefersToRelationshipConfig { type: "refersTo"; model: string; relatedIdField: string; } interface HasManyRelationshipConfig { type: "hasMany"; model: string; relatedIdField: string; orderByField?: string; orderDirection?: "ASC" | "DESC"; } interface HasManyThroughRelationshipConfig { type: "hasManyThrough"; model: string; joinModel: string; joinModelLocalField: string; joinModelRelatedField: string; joinModelOrderByField?: string; joinModelOrderDirection?: "ASC" | "DESC"; } type RelationshipConfig = RefersToRelationshipConfig | HasManyRelationshipConfig | HasManyThroughRelationshipConfig; type FieldType = "string" | "number" | "boolean" | "date" | "id" | "stringset"; interface FieldOptions { type: FieldType; indexed?: boolean; required?: boolean; unique?: boolean; default?: any | (() => any); autoAssign?: boolean; /** * Auto-timestamp this field with `Date.now()` (milliseconds) on save. * * - `'create'` — stamp only on the first save (when `isNew === true`). * - `'update'` — stamp on every save (create AND update). * - `'both'` — stamp on every save (create AND update). * * If the caller passes an explicit value for the field in `data`, the * explicit value wins and the stamp is skipped. The stamp is applied * in `beforeSave` BEFORE any user-defined hooks, so user hooks may * still overwrite the value if they wish (last writer wins). */ autoStamp?: "create" | "update" | "both"; maxLength?: number; maxCount?: number; /** * Allowed-value set for a `string` field. When present, the codegen * generators (database-type codegen + doc-model v2 codegen) emit a * TypeScript string-literal union (`"a" | "b" | "c"`) instead of a bare * `string` for this field. * * Advisory / codegen-only: this is a TS-emission hint. The runtime and the * server do NOT enforce enum membership on write (see #843). Only valid on * `string` fields, and must be a non-empty array of strings. */ enum?: string[]; } interface UniqueConstraintConfig { name: string; fields: string[]; } interface ModelOptions { name: string; /** * Optional PascalCase class name. Used by the v2 codegen to drive * generated TypeScript class names (and relationship method names that * derive from a target's class name). When absent, the v2 codegen * falls back to suffix-based singularization of `name`. */ className?: string; uniqueConstraints?: UniqueConstraintConfig[]; relationships?: Record; } interface Schema { [modelName: string]: { fields: { [fieldName: string]: FieldOptions; }; }; } interface ITransactionalDatabaseOperations { insert(modelName: string, data: any): Promise; delete(modelName: string, id: string): Promise; query>(sql: string, params?: any[]): Promise; } /** * Abstract class defining the interface for database engines. * This allows for different database implementations (e.g., SQL.js, DuckDB) to be used interchangeably. */ declare abstract class DatabaseEngine { /** * Ensures that the database engine is fully initialized and ready for use. * For WASM-based engines, this might involve loading the WASM module. */ abstract ensureReady(): Promise; /** * Executes a SQL query against the database. * @param sql The SQL query string. * @param params Optional array of parameters for prepared statements. * @returns A promise that resolves to an array of query results. */ abstract query(sql: string, params?: any[]): Promise; /** * Retrieves the last error message from the database engine, if any. * @returns The last error message as a string, or undefined if no error occurred. */ abstract getLastErrorMessage(): string | undefined; /** * Retrieves the schema for a given table. * This is useful for understanding table structure, field types, etc. * The exact return type might vary based on the database engine. * @param tableName The name of the table. * @returns A promise that resolves to the table schema information. */ abstract getTableSchema(tableName: string): Promise; /** * Destroys the database engine instance and releases any associated resources. * This is crucial for cleanup, especially in testing environments or when the application is shutting down. */ abstract destroy(): Promise; createTable(_modelName: string, _schema: Map, // Assuming 'any' for field options for now, can be refined _options: ModelOptions): Promise; createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise; insertStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise; removeStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise; insert(_modelName: string, _data: any): Promise; delete(_modelName: string, _id: string): Promise; /** * Deletes all records for a specific document from the given model table. * This is used when disconnecting a document to remove all its data. * @param modelName The name of the model/table * @param docId The document ID to filter by */ deleteByDocumentId(_modelName: string, _docId: string): Promise; getTableName(_modelName: string): string; withTransaction(_callback: (operations: ITransactionalDatabaseOperations) => Promise): Promise; } interface StringSetChangeTracker { markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void; } declare class StringSet { private _values; private _model; private _fieldName; constructor(model: StringSetChangeTracker, fieldName: string, initialValues?: string[]); /** * Add a string to the set */ add(value: string): void; /** * Remove a string from the set */ remove(value: string): void; /** * Check if the set contains a string */ has(value: string): boolean; /** * Clear all strings from the set */ clear(): void; /** * Get the number of strings in the set */ get size(): number; /** * Get an iterator of all values */ values(): IterableIterator; /** * Make the StringSet iterable */ [Symbol.iterator](): IterableIterator; /** * Convert to array */ toArray(): string[]; /** * Union with another StringSet */ union(other: StringSet): StringSet; /** * Intersection with another StringSet */ intersection(other: StringSet): StringSet; /** * Difference with another StringSet (values in this set but not in other) */ difference(other: StringSet): StringSet; /** * Get the current state including pending changes * This is used internally by the model to determine the current view */ _getCurrentState(): Set; /** * Update the internal state (used when loading from Yjs or applying changes) */ _updateInternalState(values: string[]): void; } type DocumentPermissionHint = "read" | "read-write"; interface ConnectedDocument { docId: string; yDoc: Y.Doc; permissionHint: DocumentPermissionHint; } interface SaveOptions { targetDocument?: string; forceWrite?: boolean; upsertOn?: string; } interface DocumentConnectionEvent { type: "connect" | "disconnect"; docId: string; document?: ConnectedDocument; } type DocumentConnectionCallback = (event: DocumentConnectionEvent) => void; interface ComparisonOperators { $eq?: T; $ne?: T; $gt?: T; $gte?: T; $lt?: T; $lte?: T; $in?: T[]; $nin?: T[]; } interface StringSetOperators { /** * Exact membership: StringSet contains this specific string */ $contains?: string; $all?: string[]; $size?: number | ComparisonOperators; } interface SubstringOperators { /** Prefix match */ $startsWith?: string; /** Suffix match */ $endsWith?: string; /** Substring anywhere */ $containsText?: string; } interface ExistenceOperators { $exists?: boolean; } type FieldOperators = ComparisonOperators & ExistenceOperators & StringSetOperators & SubstringOperators; interface LogicalOperators { $and?: DocumentFilter[]; $or?: DocumentFilter[]; } type DocumentFilter = { [field: string]: any | FieldOperators; } & LogicalOperators; type SortDirection = 1 | -1; type SortSpec = { [field: string]: SortDirection; }; type ProjectionSpec = { [field: string]: 1 | 0; }; interface IncludeSpec { model: string; type: "refersTo" | "hasMany" | "refersToMany"; sourceField?: string; foreignKey?: string; localField?: string; as?: string; projection?: ProjectionSpec; limit?: number; sort?: SortSpec; filter?: DocumentFilter; include?: IncludeSpec[]; } interface QueryOptions { sort?: SortSpec; projection?: ProjectionSpec; documents?: string | string[]; limit?: number; uniqueStartKey?: string; direction?: 1 | -1; include?: IncludeSpec[]; } interface PaginatedResult { data: T[]; nextCursor?: string; prevCursor?: string; hasMore: boolean; } interface TranslatedQuery { sql: string; params: any[]; sortFields: string[]; sortDirections?: (1 | -1)[]; } type ProjectedResult = { [K in keyof P]: K extends keyof T ? T[K] : never; }; type QueryResult = P extends ProjectionSpec ? ProjectedResult : T; declare class DocumentQueryTranslator { private modelName; private schema; private tableName; private quotedTableName; private fieldSqlCache; constructor(modelName: string, schema: Map); private getQuotedField; /** * Translate document filter and options to SQL for find operations */ translateFind(filter: DocumentFilter, options?: QueryOptions): TranslatedQuery; /** * Translate document filter to SQL for count operations */ translateCount(filter: DocumentFilter, options?: Pick): { sql: string; params: any[]; }; /** * Translate document filter to SQL WHERE clause */ translateFilter(filter: DocumentFilter): { sql: string; params: any[]; }; /** * Translate logical operators ($and, $or) */ private translateLogicalOperator; /** * Translate field condition to SQL */ private translateFieldCondition; /** * Translate field operators to SQL */ private translateFieldOperators; /** * Translate individual operator to SQL */ private translateOperator; /** * Build SELECT clause based on projection */ private buildSelectClause; /** * Build LIMIT clause */ private buildLimitClause; /** * Build pagination WHERE clause from cursor */ private buildPaginationClause; /** * Validate that field exists in schema */ private validateField; /** * Validate projection fields */ private validateProjection; /** * Validate operator is supported for field type */ private validateOperatorForType; /** * Validate field value matches expected type */ private validateFieldValue; /** * Validate array values for $in/$nin operators */ private validateArrayValues; /** * Check if value is a primitive (not an object with operators) */ private isPrimitiveValue; /** * Get the type of a value for validation */ private getValueType; /** * Check if value type is compatible with field type */ private isTypeCompatible; /** * Convert value for SQLite compatibility */ private convertValueForSQLite; private normalizeDocumentIds; private buildDocumentClause; } interface StringSetMembership { field: string; contains: string; } type GroupByField = string | StringSetMembership; interface AggregationOperation { type: "count" | "sum" | "avg" | "min" | "max"; field?: string; } interface AggregationOptions { groupBy: GroupByField[]; operations: AggregationOperation[]; filter?: DocumentFilter; limit?: number; sort?: { field: string; direction: 1 | -1; }; } type AggregationResult = Record | Record[]; interface AggregationAliasDebugInfo { field: string; contains: string; originalAlias: string; } interface AggregationAliasDetail extends AggregationAliasDebugInfo { alias: string; membershipKey: string; } interface AggregationQueryPlan { sql: string; params: any[]; aliasMetadata?: AggregationAliasDetail[]; } declare enum LogLevel { SILENT = 0, ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4, VERBOSE = 5 } declare class Logger { private static _logLevel; private static _logCallback; static setLogLevel(level: LogLevel): void; static getLogLevel(): LogLevel; static setLogCallback(callback: ((message: string, level: LogLevel) => void) | null): void; static error(message: string, ...args: any[]): void; static warn(message: string, ...args: any[]): void; static info(message: string, ...args: any[]): void; static debug(message: string, ...args: any[]): void; static verbose(message: string, ...args: any[]): void; } declare class UniqueConstraintViolationError extends Error { modelName: string; constraintName: string; fields: string[]; recordIdAttempted?: string; conflictingRecordId?: string; constructor(message: string, modelName: string, constraintName: string, fields: string[], recordIdAttempted?: string, conflictingRecordId?: string); } declare class RecordNotFoundError extends Error { constructor(message: string); } declare function generateULID(): string; declare class BaseModel implements StringSetChangeTracker { static modelName?: string; private static listenersMap; private static modelNameToDefaultDocId; private static globalDefaultDocId; private static defaultDocChangedListeners; private static modelDocMappingChangedListeners; private static readonly DEFAULT_LEGACY_DOC_ID; protected static dbInstance: DatabaseEngine | null; protected static connectedDocuments: Map; protected static documentYMaps: Map>; private static _observedStringSetMaps; private _localChanges; private _isDirty; private _isLoadingFromYjs; private _stringSetFields; protected _constructorProvidedId: boolean; protected _constructorProvidedFields: Set; private _metaDocId; private _metaPermissionHint; /** * Returns the document id this instance is associated with, or null if not resolved yet. */ getDocumentId(): string | null; id: string; type: string; static setLogLevel(level: LogLevel): void; static getLogLevel(): LogLevel; static setModelDefaultDocumentId(modelName: string, docId: string): void; static removeModelDefaultDocumentId(modelName: string): void; static clearModelDefaultDocumentIds(): void; static setGlobalDefaultDocumentId(docId: string): void; static clearGlobalDefaultDocumentId(): void; static getModelDefaultDocumentMapping(): Record; static getDocumentIdForModel(modelName: string): string | undefined; static getGlobalDefaultDocumentId(): string | undefined; static onDefaultDocChanged(listener: (payload: { previous?: string; current?: string; }) => void): () => void; static onModelDocMappingChanged(listener: (payload: { modelName: string; previous?: string; current?: string; }) => void): () => void; static _clearMappingsForDocId(docId: string): void; private static attachFieldAccessorsSet; static attachFieldAccessors(modelClass: typeof BaseModel, fields: Map): void; constructor(data?: Partial); private ensureLocalChanges; private hasLocalChange; private getFromYjs; /** * Defensive normalization for the read/sync boundary (issue #625). * * Stringset fields are owned by getStringSetFromYjs (which expects the * raw Y.Map / legacy plain-object shape — #561 / #601), so they pass * through untouched. For any other field, a composite Yjs primitive * (Y.Map / Y.Array / Y.Text) must never reach user code or the DB layer * raw: normalize it to its plain-JS projection (toJSON / toString) and * warn, rather than throwing. Scalars pass through unchanged. */ private normalizeNonStringSetValue; private getValue; private setValue; get isDirty(): boolean; get hasUnsavedChanges(): boolean; private clearLocalChanges; discardChanges(): void; protected validateFieldValue(fieldKey: string, value: any): void; protected validateBeforeSave(): void; getChangedFields(): string[]; getOriginalValue(fieldKey: string): any; getCurrentValue(fieldKey: string): any; hasFieldChanged(fieldKey: string): boolean; markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void; private getStringSetCurrentValues; private getStringSetFromYjs; private getOrCreateStringSet; static initialize(_yDoc: Y.Doc, _db: DatabaseEngine): Promise; static initializeForDocument(yDoc: Y.Doc, db: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise; static cleanupDocumentData(docId: string): Promise; static subscribe(callback: () => void): () => void; protected static notifyListeners(): void; /** * Legacy migration method - no longer needed in the new multidoc architecture. * Data migration is now handled during document initialization. */ static migrateToNestedYMaps(): Promise; /** * Utility to diff current instance data against YJS nested map data * Returns object with added, modified, and removed fields */ protected _diffWithYjsData(): { added: Record; modified: Record; removed: string[]; stringSetChanges: Record; removals: Set; }>; }; /** * Apply a stringset change set to the parent record's Y.Map by mutating a * nested Y.Map keyed by member. Migrates from a legacy plain-object value * if the field hasn't been touched since the wire-format change in #561. */ private applyStringSetChangeToYMap; /** * Deep equality check for comparing field values */ protected _deepEqual(a: any, b: any): boolean; protected static _buildKeyFromValues(fields: string[], keyValues: any[], modelName: string, constraintName: string): string | null; protected _buildUniqueKey(fields: string[], data: Record, modelName: string, constraintName: string): string | null; save(options?: SaveOptions): Promise; delete(): Promise; protected getCurrentJSState(): Record; protected toJSON(): Record; static find(this: new (...args: any[]) => T, id: string): Promise; /** * Document-style query API - returns paginated results */ static query(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: QueryOptions & { projection?: P; }): Promise>>; /** * Main aggregation API - performs grouping, faceting, and statistical operations * @param options Aggregation configuration with groupBy, operations, filter, limit, and sort * @returns Nested object structure with aggregation results * * @example * // Simple facet count * const tagCounts = await Model.aggregate({ * groupBy: ['tags'], * operations: [{ type: 'count' }] * }); * // Result: { red: 15, blue: 8, green: 12 } * * @example * // Multi-dimensional grouping with multiple operations * const categoryStats = await Model.aggregate({ * groupBy: ['category', 'status'], * operations: [ * { type: 'count' }, * { type: 'sum', field: 'amount' }, * { type: 'avg', field: 'score' } * ], * filter: { active: true }, * sort: { field: 'count', direction: 'desc' }, * limit: 10 * }); * * @example * // StringSet membership grouping * const urgentCounts = await Model.aggregate({ * groupBy: [{ field: 'tags', contains: 'urgent' }], * operations: [{ type: 'count' }] * }); * // Result: { true: 5, false: 23 } */ static aggregate(this: new (...args: any[]) => T, options: AggregationOptions): Promise; /** * Build SQL query for structured aggregation */ protected static buildAggregationQuery(options: AggregationOptions, schema: any, modelName: string): AggregationQueryPlan; /** * Get the proper database table name (should match database engine naming) */ protected static getDatabaseTableName(modelName: string): string; /** * Get the proper database junction table name for StringSet fields */ protected static getDatabaseJunctionTableName(modelName: string, fieldName: string): string; private static buildMembershipKey; /** * Build query for StringSet facet counts */ protected static buildStringSetFacetQuery(stringSetFields: string[], options: AggregationOptions, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan; /** * Build query for regular field aggregation */ protected static buildRegularAggregationQuery(regularGroupBy: string[], stringSetMemberships: StringSetMembership[], options: AggregationOptions, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan; /** * Process aggregation results into nested structure */ protected static processAggregationResults(results: any[], options: AggregationOptions, aliasMetadata?: AggregationAliasDetail[]): AggregationResult; /** * Document-style query API - returns single result or null */ static queryOne(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: Omit & { projection?: P; }): Promise | null>; /** * Document-style count API */ static count(this: new (...args: any[]) => any, filter?: DocumentFilter, options?: Pick): Promise; static findAll(this: new (...args: any[]) => T): Promise; static findByUnique(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, value: any | any[]): Promise; static upsertByUnique(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, uniqueLookupValue: any | any[], dataToUpsert: Partial T>, keyof BaseModel | "toJSON">> & { id?: string; }, options?: { objectMustExist?: boolean; objectMustNotExist?: boolean; targetDocument?: string; }): Promise; /** * Execute a callback with automatic transaction handling for all modified models */ static withTransaction(callback: () => Promise | T): Promise; /** * Attach a one-shot observer to a nested-Y.Map stringset field. Calls * notifyListeners() when the nested map's keys change (i.e. when a remote * member arrives via Y.applyUpdate, or a local per-member set/delete). * Idempotent — re-calling on the same Y.Map is a no-op. */ protected static observeStringSetMapOnce(nestedMap: Y.Map): void; /** * Walk the schema's stringset fields on `recordYMap` and observe any nested * Y.Map values. Called from observer setup and from the parent observer body * so newly-arrived stringset Y.Maps (local migration or remote create) get * an observer too. */ protected static attachStringSetObserversToRecord(recordYMap: Y.Map, schema: any): void; /** * Sets up deep observation on a nested YMap to sync field-level changes to the database */ protected static setupNestedYMapObserver(recordId: string, recordYMap: Y.Map): void; /** * Sets up deep observation on a nested YMap for a specific document to sync field-level changes to the database */ protected static setupNestedYMapObserverForDocument(recordId: string, recordYMap: Y.Map, docId: string, permissionHint: DocumentPermissionHint): void; } interface RegisteredModelInfo { class: typeof BaseModel; options: ModelOptions; fields: Map; } declare class ModelRegistry { private static instance; private models; private modelOptions; private activeSessionModels; private dbEngine; private constructor(); static getInstance(): ModelRegistry; registerModel(modelClass: any, options: ModelOptions, fields: Map): void; getModelClass(name: string): typeof BaseModel | undefined; getModelOptions(name: string): ModelOptions | undefined; getModelInfo(modelName: string): RegisteredModelInfo | undefined; getAllRegisteredModelsInfo(): RegisteredModelInfo[]; private getModelNameFromClass; setExplicitModelsForSession(modelClasses?: (typeof BaseModel)[]): void; initializeAll(yDoc: Y.Doc, dbEngine: DatabaseEngine): Promise; initializeAllForDocument(yDoc: Y.Doc, dbEngine: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise; removeDocumentData(docId: string, dbEngine: DatabaseEngine): Promise; initializeRelationships(): Promise; private addPrototypeMethod; clearSessionState(): void; getActiveModels(): Map; private validateSessionModels; } interface SQLJSEngineOptions { wasmURL?: string; locateFile?: (file: string) => string; } declare class SqljsEngine implements DatabaseEngine { private static SQL; private db; private tableNames; private numOpenTransactions; private mutex; private readyPromise; constructor(options?: SQLJSEngineOptions); ensureReady(): Promise; private initialize; private updateTableNames; getTableName(modelName: string): string; private mapTypeToSQL; createTable(modelName: string, schema: Map, _options: ModelOptions): Promise; createStringSetJunctionTable(modelName: string, fieldName: string): Promise; insertStringSetValues(modelName: string, fieldName: string, recordId: string, values: string[]): Promise; removeStringSetValues(modelName: string, fieldName: string, recordId: string, values: string[]): Promise; insert(modelName: string, data: any): Promise; delete(modelName: string, id: string): Promise; deleteByDocumentId(modelName: string, docId: string): Promise; query>(sql: string, params?: any[]): Promise; withTransaction(callback: (transactionalOps: ITransactionalDatabaseOperations) => Promise): Promise; close(): Promise; getTableSchema(_tableName: string): Promise; destroy(): Promise; getLastErrorMessage(): string | undefined; } type NodeSqliteEngineOptions = { filePath?: string; options?: { readonly?: boolean; fileMustExist?: boolean; timeout?: number; verbose?: (...args: any[]) => void; }; }; type DatabaseEngineType = "sqljs" | "node-sqlite" | "alasql"; interface SqljsEngineOptions { wasmURL?: string; locateFile?: (file: string) => string; } type DatabaseEngineOptions = SqljsEngineOptions | NodeSqliteEngineOptions | Record; interface DatabaseConfig { type: DatabaseEngineType; options?: DatabaseEngineOptions; } declare class BrowserDatabaseFactory { /** * Dynamically loads browser-compatible engines only */ private static loadBrowserEngines; /** * Auto-detects the best available engine for browser */ private static getRecommendedEngineType; /** * Creates a fallback engine when the requested engine is not available */ private static createFallbackEngine; /** * Creates the specified database engine (browser-compatible only) */ private static createEngine; static getEngine(config: DatabaseConfig): Promise; /** * Gets information about available engines in browser environment */ static getAvailableEngines(): { type: string; available: boolean; reason?: string; }[]; } interface InitJsBaoOptions { databaseConfig: DatabaseConfig; /** * Optional array of model classes to initialize. * If not provided, the ORM will rely on models being registered * via attachAndRegisterModel (assuming they have been imported by the application). */ models?: (typeof BaseModel)[]; } interface InitJsBaoResult { dbEngine: DatabaseEngine; modelRegistry: ModelRegistry; connectDocument: (docId: string, yDoc: Y.Doc, permissionHint: DocumentPermissionHint) => Promise; disconnectDocument: (docId: string) => Promise; getConnectedDocuments: () => Map; isDocumentConnected: (docId: string) => boolean; onDocumentConnectionChange: (callback: DocumentConnectionCallback) => () => void; addDocumentModelMapping: (modelName: string, docId: string) => void; removeDocumentModelMapping: (modelName: string) => void; clearDocumentModelMappings: () => void; setDefaultDocumentId: (docId: string) => void; clearDefaultDocumentId: () => void; getDocumentModelMapping: () => Record; getDocumentIdForModel: (modelName: string) => string | undefined; getDefaultDocumentId: () => string | undefined; onDefaultDocChanged: (listener: (payload: { previous?: string; current?: string; }) => void) => () => void; onModelDocMappingChanged: (listener: (payload: { modelName: string; previous?: string; current?: string; }) => void) => () => void; } /** * Initializes the js-bao system for browser environments with multi-document support. * Sets up the database engine and prepares for document connections. */ declare function initJsBao(options: InitJsBaoOptions): Promise; /** * Function to reset the initialization state, primarily for testing or hot-reloading scenarios. */ declare function resetJsBao(): Promise; /** * Runtime environment detection utilities */ type RuntimeEnvironment = "browser" | "node" | "unknown"; /** * Detects the current runtime environment */ declare function detectEnvironment(): RuntimeEnvironment; /** * Checks if currently running in Node.js */ declare function isNode(): boolean; /** * Checks if currently running in browser */ declare function isBrowser(): boolean; /** * Environment-specific feature detection */ declare const features: { readonly hasWebWorkers: boolean; readonly hasFileSystem: boolean; readonly hasWebAssembly: boolean; hasBetterSqlite3(): Promise; }; interface ResolvedUniqueConstraint { name: string; fields: string[]; } interface ModelSchemaRuntimeShape { class: typeof BaseModel; options: ModelOptions; fields: Map; resolvedUniqueConstraints: ResolvedUniqueConstraint[]; } interface DefineModelSchemaInput> { name: string; fields: TFields; options?: Omit; } interface DefinedModelSchema = Record> { name: string; fields: TFields; options: ModelOptions; runtimeShape?: ModelSchemaRuntimeShape; buildRuntimeShape(modelClass: typeof BaseModel): ModelSchemaRuntimeShape; } declare function defineModelSchema>(input: DefineModelSchemaInput): DefinedModelSchema; type FieldValue = 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; type InferAttrs> = { [K in keyof TSchema["fields"]]: FieldValue; }; interface CreateModelClassConfig, TAttrs extends Record = InferAttrs> { schema: TSchema; baseClass?: typeof BaseModel; methods?: () => Record; statics?: (ctor: ModelConstructor) => Record; } type ModelConstructor> = typeof BaseModel & { prototype: BaseModel & TAttrs; new (attrs?: Partial): BaseModel & TAttrs; }; /** * @deprecated Use defineModelSchema + class + attachAndRegisterModel instead. */ declare function createModelClass, TAttrs extends Record = InferAttrs>(config: CreateModelClassConfig): ModelConstructor; declare function attachSchemaToClass(modelClass: typeof BaseModel, schema: DefinedModelSchema): ModelSchemaRuntimeShape; declare function autoRegisterModel(modelClass: typeof BaseModel, runtimeShape?: ModelSchemaRuntimeShape): void; declare function attachAndRegisterModel(modelClass: typeof BaseModel, schema: DefinedModelSchema): void; interface PaginationOptions { limit?: number; afterCursor?: string; beforeCursor?: string; direction?: "forward" | "backward"; } type RefersToMethod = () => Promise; type HasManyMethod = (options?: PaginationOptions) => Promise>; type HasManyThroughMethod = (options?: PaginationOptions) => Promise>; type AddRelationMethod = (target: T | string) => Promise; type RemoveRelationMethod = (target: T | string) => Promise; /** * YDoc Schema Discovery * * Reads _meta_* YMaps from a YDoc and returns a plain JSON description * of the schema. Works with any YDoc — no BaseModel or database needed. * * Usage: * import { discoverSchema } from "js-bao"; * const schema = discoverSchema(yDoc); */ interface DiscoveredField { type: string; indexed?: boolean; unique?: boolean; required?: boolean; default?: string | number | boolean; autoAssign?: boolean; autoStamp?: "create" | "update" | "both"; maxLength?: number; maxCount?: number; } interface DiscoveredConstraint { type: string; fields: string[]; } interface DiscoveredRelationship { type: string; model: string; [key: string]: any; } interface DiscoveredModel { fields: Record; constraints?: Record; relationships?: Record; } interface DiscoveredSchema { models: Record; } /** * Discover the schema embedded in a YDoc by reading its `_meta_*` maps. * * Returns a plain JSON object describing every model that has metadata. * Does not require BaseModel, a database, or any schema registration — * just a Y.Doc. */ declare function discoverSchema(yDoc: Y.Doc): DiscoveredSchema; /** * List model names that have data in the YDoc (non-`_` prefixed top-level maps). */ declare function discoverModelNames(yDoc: Y.Doc): string[]; /** * Convert a DiscoveredSchema to a TOML string matching the js-bao * schema format. * * Usage: * const schema = discoverSchema(yDoc); * const toml = schemaToToml(schema); */ declare function schemaToToml(schema: DiscoveredSchema): string; /** * TOML Schema Loader * * Parses a TOML schema file and returns an array of DefinedModelSchema * objects. Can be used in place of manual `defineModelSchema()` calls. * * TOML conventions: * - Property names are snake_case (auto_assign, max_count, …) * - Model names and field names are as-is (user-chosen) * - Relationships live under [models.*.relationships.*] * - Compound unique constraints are [[models.*.unique_constraints]] */ interface LoadSchemaOptions { /** * When true (default), throw on unknown keys at the model, field, * relationship, and unique-constraint level. When false, unknown * keys are silently ignored (legacy behavior). */ strict?: boolean; } /** * Parse a TOML string and return an array of DefinedModelSchema objects. * * By default operates in strict mode: unknown keys at the model, field, * relationship, or unique-constraint level cause an error. Pass * `{ strict: false }` to silently ignore unknown keys (legacy behavior). */ declare function loadSchemaFromTomlString(tomlString: string, options?: LoadSchemaOptions): DefinedModelSchema[]; /** * Meta Sync — writes _meta_* YMaps into a YDoc. * * Each model with data in a YDoc gets a `_meta_{modelName}` YMap that * describes the model's fields, constraints, and relationships. This * lets any language that can read a YDoc discover the schema without * external configuration. * * Two modes: * 1. **Schema-aware** — full schema known (from defineModelSchema / TOML). * Writes field metadata, constraints, and relationships. * 2. **Infer-on-write** — no schema. Infers types from record values. */ /** * Infer a _meta_ type string from a JS runtime value. * * Only an all-`true` Y.Map (the stringset wire shape) is tagged as * `stringset` (issue #625) — a Y.Map carrying a composite payload, or a * Y.Array / Y.Text, is not a stringset and stays untyped (`null`) rather * than being mis-tagged. */ declare function inferFieldType(value: unknown): "string" | "number" | "boolean" | "stringset" | null; /** * Register a named function default so metaSync can encode it. * Called once per known default generator. */ declare function registerFunctionDefault(fn: Function, name: string): void; /** * Clear the sync cache for a specific doc (or all docs). * Useful for testing or when schema changes at runtime. */ declare function clearMetaSyncCache(yDoc?: Y.Doc): void; /** * Sync full schema metadata into `_meta_{modelName}` inside a YDoc. * * Call this inside an existing `yDoc.transact()`. Y.Map `.set()` on * identical values is a CRDT no-op so there is no overhead after the * first write. * * Skips the sync if this (yDoc, modelName) pair has already been synced * in the current session. */ declare function syncModelMeta(yDoc: Y.Doc, modelName: string, schema: ModelSchemaRuntimeShape): void; /** * Infer-on-write: when no schema is available, infer field types from * the record data and write minimal _meta_. * * Call inside an existing `yDoc.transact()`. */ declare function syncInferredMeta(yDoc: Y.Doc, modelName: string, recordData: Record): void; export { type AddRelationMethod, type AggregationAliasDebugInfo, type AggregationOperation, type AggregationOptions, type AggregationResult, BaseModel, type DatabaseConfig, DatabaseEngine, type DatabaseEngineType, BrowserDatabaseFactory as DatabaseFactory, type DiscoveredConstraint, type DiscoveredField, type DiscoveredModel, type DiscoveredRelationship, type DiscoveredSchema, type FieldOptions, type FieldType, type GroupByField, type HasManyMethod, type HasManyThroughMethod, type InferAttrs, type InitJsBaoOptions, type InitJsBaoResult, LogLevel, Logger, type ModelConstructor, type ModelOptions, ModelRegistry, 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, clearMetaSyncCache, createModelClass, defineModelSchema, detectEnvironment, discoverModelNames, discoverSchema, features, generateULID, inferFieldType, initJsBao, isBrowser, isNode, loadSchemaFromTomlString, registerFunctionDefault, resetJsBao, schemaToToml, syncInferredMeta, syncModelMeta };