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 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; } type DocumentPermissionHint = "read" | "read-write"; interface SaveOptions$1 { targetDocument?: string; forceWrite?: boolean; upsertOn?: string; } 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$1 { field: string; contains: string; } type GroupByField$1 = string | StringSetMembership$1; interface AggregationOperation$1 { type: "count" | "sum" | "avg" | "min" | "max"; field?: string; } interface AggregationOptions$1 { groupBy: GroupByField$1[]; operations: AggregationOperation$1[]; filter?: DocumentFilter; limit?: number; sort?: { field: string; direction: 1 | -1; }; } type AggregationResult$1 = 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 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$1): 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$1): Promise; /** * Build SQL query for structured aggregation */ protected static buildAggregationQuery(options: AggregationOptions$1, 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$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan; /** * Build query for regular field aggregation */ protected static buildRegularAggregationQuery(regularGroupBy: string[], stringSetMemberships: StringSetMembership$1[], options: AggregationOptions$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan; /** * Process aggregation results into nested structure */ protected static processAggregationResults(results: any[], options: AggregationOptions$1, aliasMetadata?: AggregationAliasDetail[]): AggregationResult$1; /** * 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; } /** * Durable Object Engine * * Database engine implementation that runs inside a Cloudflare Durable Object. * Uses the DO's embedded SQLite database via ctx.storage.sql. * * Key characteristics: * - Synchronous SQL execution (DO SQLite is sync) * - No doc ID column needed (one DO = one document) * - Uses JSON schema (records + stringset_index tables) * - Schemaless: any model/field can be saved and queried without registration * - Indexes are additive: register/drop individual field indexes independently */ /** Row shape from the _indexes table */ interface IndexEntry { model_name: string; field_name: string; field_type: string; is_unique: number; created_at: string; } /** Row shape from the _unique_constraints table */ interface UniqueConstraintEntry { model_name: string; constraint_name: string; fields: string[]; created_at: string; } /** Row shape from the _model_fields table */ interface ModelFieldInfo { model_name: string; field_name: string; inferred_type: string; first_seen_at: string; } /** * Aggregation types shared between Yjs and DO backends. */ /** * Describes a StringSet membership check in a groupBy clause. * Groups records by whether they have a specific value in a StringSet field. */ interface StringSetMembership { field: string; contains: string; } /** * A groupBy field can be a plain field name or a StringSet membership check. */ type GroupByField = string | StringSetMembership; /** * An aggregation operation (count, sum, avg, min, max). */ interface AggregationOperation { type: "count" | "sum" | "avg" | "min" | "max"; /** Required for sum, avg, min, max; not used for count */ field?: string; } /** * Options for an aggregation query. */ interface AggregationOptions { groupBy: GroupByField[]; operations: AggregationOperation[]; filter?: DocumentFilter; limit?: number; sort?: { /** Can be operation result field like 'count', 'sum_fieldName', etc. */ field: string; /** 1 for ascending, -1 for descending */ direction: 1 | -1; }; } /** * Result of an aggregation query — nested object keyed by group values. */ type AggregationResult = Record | Record[]; /** * Hook type definitions for Durable Object access control. * * Hooks run server-side inside the DO before CRUD operations. * They can allow/deny operations and inject query filters. */ /** Context passed to all hooks */ interface HookContext { /** The model (type discriminator) being operated on */ modelName: string; /** The document ID (derived from the DO instance) */ docId: string; /** The raw request (for reading headers, auth tokens, etc.) */ request: Request; /** The DO's SQLite engine (for direct queries, e.g. lookup functions) */ engine: any; } /** Context for beforeSave hooks */ interface BeforeSaveContext extends HookContext { /** Record ID being saved */ id: string; /** Data being saved */ data: Record; /** StringSet values being saved (if any) */ stringSets?: Record; /** Whether this is a new record (true) or an update (false) */ isNew: boolean; } /** Context for beforeDelete hooks */ interface BeforeDeleteContext extends HookContext { /** Record ID being deleted */ id: string; /** The existing record being deleted (parsed from data_json) */ record: Record | null; } /** Context for beforeQuery hooks */ interface BeforeQueryContext extends HookContext { /** The filter being applied */ filter: DocumentFilter; /** Query options (sort, limit, etc.) */ options?: QueryOptions; } /** Context for afterQuery hooks */ interface AfterQueryContext extends HookContext { /** The query results to filter */ results: Record[]; } /** Result from beforeSave/beforeDelete hooks */ interface HookResult { allow: boolean; /** Reason for denial (returned to client as error message) */ reason?: string; } /** Result from beforeQuery hooks — can inject additional filters */ interface BeforeQueryResult extends HookResult { /** Additional filter merged into the query via $and */ injectFilter?: DocumentFilter; } /** Result from afterQuery hooks — returns filtered results */ interface AfterQueryResult { /** The filtered results to return */ results: Record[]; } /** Hook definitions for createDatabaseDO */ interface DatabaseDOHooks { beforeSave?: (ctx: BeforeSaveContext) => Promise; beforeDelete?: (ctx: BeforeDeleteContext) => Promise; beforeQuery?: (ctx: BeforeQueryContext) => Promise; afterQuery?: (ctx: AfterQueryContext) => Promise; } /** * Database Durable Object Factory * * Creates a Durable Object class that serves as a schemaless database store. * Each DO instance has its own SQLite database. * * Usage: * ```typescript * import { createDatabaseDO } from 'js-bao/cloudflare/do'; * * export const MyDatabaseDO = createDatabaseDO({ * hooks: { * beforeSave: async (ctx) => { * // Access control logic * return { allow: true }; * }, * }, * }); * ``` */ /** * Request body types for RPC endpoints */ interface QueryRequest { modelName: string; filter: DocumentFilter; options?: QueryOptions; } interface SaveRequest { modelName: string; id?: string; data: Record; stringSets?: Record; ifNotExists?: boolean; condition?: DocumentFilter; upsertOn?: string; /** * Per-call auto-timestamp directives for schemaless writes. * * Each entry is a list of field names to stamp with `Date.now()` * (milliseconds) at the corresponding lifecycle event: * * - `create` — field is stamped only when the record is new * (no row exists yet for this `modelName` + `id`). * - `update` — field is stamped on every save (create AND update). * * If the caller already provided an explicit value for the field * in `data`, the explicit value wins and the stamp is skipped. * Stamping happens BEFORE the `beforeSave` user hook runs, so user * hooks may still overwrite the stamped value if they wish. */ autoStamps?: { create?: string[]; update?: string[]; }; } interface DeleteRequest { modelName: string; id: string; condition?: DocumentFilter; } interface CountRequest { modelName: string; filter: DocumentFilter; } interface RegisterIndexRequest { modelName: string; fieldName: string; fieldType: string; unique?: boolean; } interface DropIndexRequest { modelName: string; fieldName: string; } interface RegisterUniqueConstraintRequest { modelName: string; constraintName: string; fields: string[]; } interface DropUniqueConstraintRequest { modelName: string; constraintName: string; } /** * Response types */ interface QueryResponse { data: Record[]; hasMore?: boolean; nextCursor?: string; prevCursor?: string; } interface SaveResponse { success: boolean; id: string; } interface DeleteResponse { success: boolean; } interface CountResponse { count: number; } interface ErrorResponse { error: string; code?: string; } interface RegisterIndexResponse { success: boolean; modelName: string; fieldName: string; } interface DropIndexResponse { success: boolean; modelName: string; fieldName: string; } interface IndexListResponse { indexes: IndexEntry[]; } interface RegisterUniqueConstraintResponse { success: boolean; modelName: string; constraintName: string; } interface DropUniqueConstraintResponse { success: boolean; modelName: string; constraintName: string; } interface UniqueConstraintListResponse { constraints: UniqueConstraintEntry[]; } interface AggregateRequest { modelName: string; options: AggregationOptions; } interface AggregateResponse { result: AggregationResult; } interface SyncIndexesRequest { models: Array<{ modelName: string; indexes: Array<{ fieldName: string; fieldType: string; unique: boolean; }>; uniqueConstraints: Array<{ name: string; fields: string[]; }>; }>; } interface SyncIndexesResponse { registered: number; } interface PatchRequest { modelName: string; id: string; data: Record; stringSets?: Record; condition?: DocumentFilter; /** * Per-call auto-timestamp directives. A patch is always treated as * an update (`isNew === false`), so only the `update` list is * applied; the `create` list is ignored on patch. * * Explicit values in `data` win. */ autoStamps?: { create?: string[]; update?: string[]; }; } interface PatchResponse { success: boolean; id: string; } interface BatchOperation { op: "save" | "patch" | "delete" | "increment" | "addToSet" | "removeFromSet"; modelName: string; id?: string; data?: Record; stringSets?: Record; fields?: Record; ifNotExists?: boolean; condition?: DocumentFilter; upsertOn?: string; /** * Per-operation auto-timestamp directives. Same semantics as * `SaveRequest.autoStamps` / `PatchRequest.autoStamps`. Applied * BEFORE the user `beforeSave` hook runs, with explicit values * in `data` always winning. * * For `op: "patch"`, only the `update` list applies (patches are * always treated as updates). */ autoStamps?: { create?: string[]; update?: string[]; }; } interface BatchRequest { operations: BatchOperation[]; } interface BatchOperationResult { success: boolean; id: string; error?: string; values?: Record; } interface BatchResponse { results: BatchOperationResult[]; } interface IncrementRequest { modelName: string; id: string; fields: Record; condition?: DocumentFilter; } interface IncrementResponse { success: boolean; id: string; values: Record; } interface StringSetUpdateRequest { modelName: string; id: string; sets: Record; condition?: DocumentFilter; } interface StringSetUpdateResponse { success: boolean; } /** * Durable Object Client Engine * * Client-side engine that proxies database operations to a Cloudflare * Durable Object via HTTP fetch calls. * * This engine runs in the browser or Node.js and communicates with * the DO-based backend. */ interface DOClientEngineConfig { /** * Base URL of the Cloudflare Worker * e.g., "https://my-worker.my-subdomain.workers.dev" */ endpoint: string; /** * Optional custom fetch function (useful for testing) */ fetch?: typeof fetch; /** * Optional authorization header value */ authorization?: string; /** * Request timeout in milliseconds (default: 30000) */ timeout?: number; } declare class DOClientEngine extends DatabaseEngine { private endpoint; private customFetch; private authorization?; private timeout; private currentDocId; constructor(config: DOClientEngineConfig); /** * Set the current document ID for subsequent operations. */ setCurrentDocument(docId: string): void; /** * Get the current document ID. */ getCurrentDocument(): string | null; /** * Build the URL for a DO endpoint. */ private buildUrl; /** * Make a fetch request to the DO. */ private doFetch; /** * Query records from the DO. */ queryModel(modelName: string, filter?: DocumentFilter, options?: QueryOptions): Promise>>; /** * Save a record to the DO. */ saveModel(modelName: string, id: string | undefined, data: Record, stringSets?: Record, options?: { ifNotExists?: boolean; condition?: DocumentFilter; upsertOn?: string; }): Promise; /** * Patch (partial update) a record in the DO. * Only the provided fields are updated; existing fields are preserved. */ patchModel(modelName: string, id: string, data: Record, stringSets?: Record, options?: { condition?: DocumentFilter; }): Promise; /** * Delete a record from the DO. */ deleteModel(modelName: string, id: string, options?: { condition?: DocumentFilter; }): Promise; /** * Count records matching a filter. */ countModel(modelName: string, filter?: DocumentFilter): Promise; /** * Aggregate records with groupBy and operations (count, sum, avg, min, max). */ aggregateModel(modelName: string, options: AggregationOptions): Promise; /** * Atomically add values to StringSet fields on a record. */ addToStringSet(modelName: string, id: string, sets: Record, options?: { condition?: DocumentFilter; }): Promise; /** * Atomically remove values from StringSet fields on a record. */ removeFromStringSet(modelName: string, id: string, sets: Record, options?: { condition?: DocumentFilter; }): Promise; /** * Atomically increment/decrement numeric fields on a record. * Returns the new values after the increment. */ incrementFields(modelName: string, id: string, fields: Record, options?: { condition?: DocumentFilter; }): Promise>; /** * Execute multiple save/patch/delete operations in a single request. * All operations run in a single transaction on the server. */ batchWrite(operations: BatchOperation[]): Promise; /** * Check if the DO is healthy. */ healthCheck(): Promise<{ status: string; }>; /** * Batch sync indexes: send all desired indexes in one request. * The DO compares against its _indexes table and registers only what's missing. * Returns the number of indexes/constraints newly registered. */ syncIndexesBatch(request: SyncIndexesRequest): Promise; /** * Register an index on a model field. * Creates a SQLite index on json_extract(data_json, '$.fieldName'). * Set unique=true to enforce uniqueness on this field. */ registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise; /** * Drop an index from a model field. */ dropIndex(modelName: string, fieldName: string): Promise; /** * List indexes, optionally filtered by model name. */ listIndexes(modelName?: string): Promise; /** * Describe tracked fields for a model. */ describe(modelName: string): Promise; /** * Register a composite unique constraint across multiple fields. */ registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise; /** * Drop a composite unique constraint. */ dropUniqueConstraint(modelName: string, constraintName: string): Promise; /** * List composite unique constraints, optionally filtered by model name. */ listUniqueConstraints(modelName?: string): Promise; /** * Ensure the engine is ready. * For DOClient, this verifies connectivity. */ ensureReady(): Promise; /** * Execute raw SQL. * Not supported in DO client mode - use queryModel instead. */ query(_sql: string, _params?: any[]): Promise; /** * Get last error message. */ getLastErrorMessage(): string | undefined; /** * Get table schema. * Not directly supported - schema is managed by the DO. */ getTableSchema(_tableName: string): Promise; /** * Destroy the engine. * Nothing to clean up for the client. */ destroy(): Promise; /** * Create table. * No-op in DO client mode - schema is managed by the DO. */ createTable(_modelName: string, _schema: Map, _options: ModelOptions): Promise; /** * Create StringSet junction table. * No-op in DO client mode. */ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise; /** * Insert a record. * Delegates to saveModel. */ insert(modelName: string, data: any): Promise; /** * Delete a record. * Delegates to deleteModel. */ delete(modelName: string, id: string): Promise; /** * Get table name. * All models use 'records' in JSON schema. */ getTableName(_modelName: string): string; /** * Transaction support. * DO client doesn't support client-side transactions. * Operations are atomic on the DO side. */ withTransaction(callback: (operations: ITransactionalDatabaseOperations) => Promise): Promise; } /** * Durable Object Mode Initialization * * Alternative initialization for js-bao that uses Cloudflare Durable Objects * instead of yjs for document storage. * * Key differences from yjs mode: * - No yjs dependency * - Server-authoritative (DO is source of truth) * - HTTP-based communication with DO backend * - One DO per document * - Schemaless: any field can be saved/queried without registration * - Only indexes need explicit registration for performance */ /** * A model can be identified by either a BaseModel subclass or a plain string name. * Use a string when you don't have a model class (e.g., schemaless / CSV import). */ type ModelIdentifier = typeof BaseModel | string; /** * Configuration for DO mode initialization */ interface InitJsBaoDOOptions { /** * Base URL of the Cloudflare Worker * e.g., "https://my-worker.my-subdomain.workers.dev" */ endpoint: string; /** * Optional authorization header value */ authorization?: string; /** * Optional custom fetch function (for testing) */ fetch?: typeof fetch; /** * Request timeout in milliseconds (default: 30000) */ timeout?: number; } /** * Result of DO mode initialization */ interface InitJsBaoDOResult { /** * The DO client engine */ engine: DOClientEngine; /** * Connect to a document (sets the current document for operations) */ connectDocument: (docId: string) => Promise; /** * Disconnect from the current document */ disconnectDocument: () => Promise; /** * Get the current document ID */ getCurrentDocument: () => string | null; /** * Check if connected to a document */ isConnected: () => boolean; /** * Query records from the current document */ query: >(model: ModelIdentifier, filter?: DocumentFilter, options?: QueryOptions) => Promise>; /** * Find a single record by ID */ find: >(model: ModelIdentifier, id: string) => Promise; /** * Save a record to the current document */ save: (model: ModelIdentifier, data: Record, options?: SaveOptions | Record) => Promise; /** * Patch (partial update) a record — only the provided fields are changed */ patch: (model: ModelIdentifier, id: string, data: Record, options?: PatchOptions | Record) => Promise; /** * Delete a record from the current document */ delete: (model: ModelIdentifier, id: string, options?: WriteCondition) => Promise; /** * Count records matching a filter */ count: (model: ModelIdentifier, filter?: DocumentFilter) => Promise; /** * Aggregate records with groupBy and operations (count, sum, avg, min, max) */ aggregate: (model: ModelIdentifier, options: AggregationOptions) => Promise; /** * Atomically add values to StringSet fields on a record */ addToSet: (model: ModelIdentifier, id: string, sets: Record, options?: WriteCondition) => Promise; /** * Atomically remove values from StringSet fields on a record */ removeFromSet: (model: ModelIdentifier, id: string, sets: Record, options?: WriteCondition) => Promise; /** * Atomically increment/decrement numeric fields on a record. * Returns the new values after the increment. */ increment: (model: ModelIdentifier, id: string, fields: Record, options?: WriteCondition) => Promise>; /** * Execute multiple save/patch/delete operations in a single request */ batch: (operations: BatchOperation[]) => Promise; /** * Describe tracked fields for a model (names and inferred types). */ describe: (modelName: string) => Promise; /** * Register an index on a model field for query performance. * Set unique=true to enforce uniqueness on this field. */ registerIndex: (modelName: string, fieldName: string, fieldType?: string, unique?: boolean) => Promise; /** * Drop an index from a model field. */ dropIndex: (modelName: string, fieldName: string) => Promise; /** * List all registered indexes, optionally filtered by model name. */ listIndexes: (modelName?: string) => Promise; /** * Register a composite unique constraint across multiple fields. */ registerUniqueConstraint: (modelName: string, constraintName: string, fields: string[]) => Promise; /** * Drop a composite unique constraint. */ dropUniqueConstraint: (modelName: string, constraintName: string) => Promise; /** * List composite unique constraints, optionally filtered by model name. */ listUniqueConstraints: (modelName?: string) => Promise; /** * Sync indexes from a model's schema definition. * * Reads the model's field definitions and registers indexes for any field * with `indexed: true` or `unique: true`. Also registers composite unique * constraints from the model's `uniqueConstraints` option. * * **Additive only** — never drops existing indexes, since other developers * may have registered indexes that aren't in this model's schema. * * @returns The number of indexes/constraints that were newly registered. */ syncIndexes: (modelClass: typeof BaseModel) => Promise; } /** * Initialize js-bao in Durable Object mode. * * Usage: * ```typescript * import { initJsBaoDO } from 'js-bao/cloudflare'; * import { Statement } from './models'; * * const jsbao = await initJsBaoDO({ * endpoint: 'https://my-worker.workers.dev', * }); * * await jsbao.connectDocument('my-doc-id'); * * // Save any data — no schema registration required * await jsbao.save(Statement, { id: 'stmt-1', amount: 100, label: 'rent' }); * * // Query on any field * const results = await jsbao.query(Statement, { amount: { $gt: 50 } }); * * // Optionally register indexes for performance * await jsbao.registerIndex('Statement', 'amount', 'number'); * ``` */ declare function initJsBaoDO(options: InitJsBaoDOOptions): Promise; /** * Reset DO mode state (for testing) */ declare function resetJsBaoDO(): Promise; /** * Get the active DO engine (if any) */ declare function getActiveDOEngine(): DOClientEngine | null; /** * Configuration for connectDoDb */ interface ConnectDoDbOptions { /** Base URL of the Cloudflare Worker */ endpoint: string; /** Document ID to connect to */ id: string; /** Model classes to create pre-bound accessors for */ models?: (typeof BaseModel)[]; /** Optional authorization header value */ authorization?: string; /** Optional custom fetch function (for testing) */ fetch?: typeof fetch; /** Request timeout in milliseconds (default: 30000) */ timeout?: number; } /** * Pre-bound model accessor — all methods are scoped to a specific model. */ interface SaveOptions { stringSets?: Record; ifNotExists?: boolean; condition?: DocumentFilter; upsertOn?: string; } interface PatchOptions { stringSets?: Record; condition?: DocumentFilter; } interface WriteCondition { condition?: DocumentFilter; } interface ModelAccessor { query = Record>(filter?: DocumentFilter, options?: QueryOptions): Promise>; find = Record>(id: string): Promise; save(data: Record, options?: SaveOptions | Record): Promise; patch(id: string, data: Record, options?: PatchOptions | Record): Promise; delete(id: string, options?: WriteCondition): Promise; count(filter?: DocumentFilter): Promise; aggregate(options: AggregationOptions): Promise; increment(id: string, fields: Record, options?: WriteCondition): Promise>; addToSet(id: string, sets: Record, options?: WriteCondition): Promise; removeFromSet(id: string, sets: Record, options?: WriteCondition): Promise; } /** * Result of connectDoDb — provides both ad-hoc and pre-bound model access. * * Ad-hoc: `db.query(User, filter)` — works with any model class. * Pre-bound: `db.User.query(filter)` — only for models passed in `models` array. */ interface DoDb { /** The underlying DO client engine */ readonly engine: DOClientEngine; /** The connected document ID */ readonly docId: string; query = Record>(model: ModelIdentifier, filter?: DocumentFilter, options?: QueryOptions): Promise>; find = Record>(model: ModelIdentifier, id: string): Promise; save(model: ModelIdentifier, data: Record, options?: SaveOptions | Record): Promise; patch(model: ModelIdentifier, id: string, data: Record, options?: PatchOptions | Record): Promise; delete(model: ModelIdentifier, id: string, options?: WriteCondition): Promise; count(model: ModelIdentifier, filter?: DocumentFilter): Promise; aggregate(model: ModelIdentifier, options: AggregationOptions): Promise; increment(model: ModelIdentifier, id: string, fields: Record, options?: WriteCondition): Promise>; addToSet(model: ModelIdentifier, id: string, sets: Record, options?: WriteCondition): Promise; removeFromSet(model: ModelIdentifier, id: string, sets: Record, options?: WriteCondition): Promise; batch(operations: BatchOperation[]): Promise; describe(modelName: string): Promise; registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise; dropIndex(modelName: string, fieldName: string): Promise; listIndexes(modelName?: string): Promise; registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise; dropUniqueConstraint(modelName: string, constraintName: string): Promise; listUniqueConstraints(modelName?: string): Promise; syncIndexes(modelClass: typeof BaseModel): Promise; /** * Sync indexes for all models passed in the `models` array at init. * Returns total number of indexes/constraints newly registered. */ syncAllIndexes(): Promise; [modelName: string]: any; } /** * Connect to a Durable Object document database. * * Combines initialization and document connection into a single call. * Returns an object with both ad-hoc and pre-bound model access. * * Usage: * ```typescript * import { connectDoDb } from 'js-bao/cloudflare'; * import { User, Post } from './models'; * * const db = connectDoDb({ * endpoint: 'https://my-worker.workers.dev', * id: 'my-document', * models: [User, Post], * }); * * // Pre-bound model access (models registered at init) * await db.User.save({ id: 'u-1', name: 'Alice' }); * const users = await db.User.query({ name: 'Alice' }); * const user = await db.User.find('u-1'); * * // Ad-hoc model access (any model class) * await db.save(User, { id: 'u-2', name: 'Bob' }); * const results = await db.query(User, { name: 'Bob' }); * ``` */ declare function connectDoDb(options: ConnectDoDbOptions): DoDb; /** * 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; interface ResolvedUniqueConstraint { name: string; fields: string[]; } interface ModelSchemaRuntimeShape { class: typeof BaseModel; options: ModelOptions; fields: Map; resolvedUniqueConstraints: ResolvedUniqueConstraint[]; } interface DefinedModelSchema = Record> { name: string; fields: TFields; options: ModelOptions; runtimeShape?: ModelSchemaRuntimeShape; buildRuntimeShape(modelClass: typeof BaseModel): ModelSchemaRuntimeShape; } /** * 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 AfterQueryContext, type AfterQueryResult, type AggregateRequest, type AggregateResponse, type AggregationOperation, type AggregationOptions, type AggregationResult, type BatchOperation, type BatchOperationResult, type BatchRequest, type BatchResponse, type BeforeDeleteContext, type BeforeQueryContext, type BeforeQueryResult, type BeforeSaveContext, type ConnectDoDbOptions, type CountRequest, type CountResponse, DOClientEngine, type DOClientEngineConfig, type DatabaseDOHooks, type DeleteRequest, type DeleteResponse, type DiscoveredConstraint, type DiscoveredField, type DiscoveredModel, type DiscoveredRelationship, type DiscoveredSchema, type DoDb, type DocumentFilter, type DropIndexRequest, type DropIndexResponse, type DropUniqueConstraintRequest, type DropUniqueConstraintResponse, type ErrorResponse, type GroupByField, type HookContext, type HookResult, type IncrementRequest, type IncrementResponse, type IndexEntry, type IndexListResponse, type InitJsBaoDOOptions, type InitJsBaoDOResult, type ModelAccessor, type PaginatedResult, type PatchOptions, type PatchRequest, type PatchResponse, type ProjectionSpec, type QueryOptions, type QueryRequest, type QueryResponse, type RegisterIndexRequest, type RegisterIndexResponse, type RegisterUniqueConstraintRequest, type RegisterUniqueConstraintResponse, type SaveOptions, type SaveRequest, type SaveResponse, type SortSpec, type StringSetMembership, type StringSetUpdateRequest, type StringSetUpdateResponse, type SyncIndexesRequest, type SyncIndexesResponse, type UniqueConstraintEntry, type UniqueConstraintListResponse, type WriteCondition, clearMetaSyncCache, connectDoDb, discoverModelNames, discoverSchema, getActiveDOEngine, inferFieldType, initJsBaoDO, loadSchemaFromTomlString, registerFunctionDefault, resetJsBaoDO, schemaToToml, syncInferredMeta, syncModelMeta };