import { C as CollectionRecord, Q as QueryDescriptor, H as QuerySubscriptionError, ap as PendingWrites, a7 as SubscriptionCallback, a6 as SubscribeOptions, S as StorageAdapter, ah as WhereClause, D as OrderByDirection, F as QueryCoverage } from './types-BVVjCckP.js'; import { CollectionDefinition, Operation, SchemaDefinition } from '@korajs/core'; import { KoraError } from '@korajs/core/lite'; /** * A local write while the app is read-only (`Store.setReadOnly`), for example while an * admin previews the app as another person. Reads and incoming sync are unaffected. */ declare class StoreReadOnlyError extends KoraError { readonly reason: string; constructor(reason: string); } /** Compares two query result sets; true means subscribers need not be notified. */ type ResultsEqual = (prev: readonly CollectionRecord[], next: readonly CollectionRecord[]) => boolean; /** * Per-subscription options accepted by `register` / `registerAndFetch`. */ interface RegisterOptions extends SubscribeOptions { /** Result-set comparator; defaults to structural comparison of every value. */ resultsEqual?: ResultsEqual; } /** * Configuration options for the SubscriptionManager. */ interface SubscriptionManagerOptions { /** * Minimum number of subscriptions before activating bloom filter. * Below this threshold, linear scanning is used (bloom filter overhead not worth it). * @default 100 */ bloomThreshold?: number; /** * Expected number of unique collection+field dependencies for bloom filter sizing. * @default 500 */ bloomExpectedItems?: number; /** * Target false positive rate for the bloom filter. * Lower values require more memory but reduce unnecessary precise checks. * @default 0.01 */ bloomFalsePositiveRate?: number; /** Called when a query subscription is registered (e.g. to register sync query subsets). */ onQuerySubscribed?: (descriptor: QueryDescriptor) => () => void; /** * Called for every subscription failure (the store emits `query:error`), in * addition to the subscriber's own `onError`. */ onQueryError?: (failure: QuerySubscriptionError) => void; /** * Instant-UI overlay (S3, internal): the registry of pending writes to patch * subscriptions with, or null. Read each time it is needed, so an overlay installed * after the manager was created is picked up. Omitted or null: the manager behaves * exactly as it did before the overlay existed (every code path below is gated on it). */ pendingWrites?: () => PendingWrites | null; /** The collection definition a query reads (decides whether it may be patched). */ getDefinition?: (collection: string) => CollectionDefinition | undefined; /** * Called after a subscription of `collection` read its query successfully (the SQL * result is in). The store uses it to decide writes whose commit answer was lost: a * read that works proves the adapter answers again (M2). Overlay only. */ onRead?: (collection: string) => void; /** * Called after a patch pass delivered rows built from the overlay (the store emits * `query:patched`). Overlay only. */ onPatched?: (info: { queryId: string; collection: string; resultCount: number; durationMs: number; }) => void; /** Monotonic milliseconds for the pass budget. Default `performance.now`. Injected by tests. */ now?: () => number; /** * Longest a patch pass may run before the remaining subscriptions fall back to the * commit path (design section 11). Default {@link DEFAULT_OVERLAY_PASS_BUDGET_MS}. */ overlayPassBudgetMs?: number; } /** Counters of the overlay's work, for tests and DevTools (S3). */ interface OverlayStats { /** Patch passes run. */ passes: number; /** Callbacks delivered by a patch pass (not by a SQL result). */ patchedDeliveries: number; /** Subscriptions a pass left to the commit path because it ran out of budget. */ budgetSkips: number; /** Entries the evaluator declined to apply (limit pages, ties, ...). */ skippedEntries: number; /** Duration of the most recent pass, in milliseconds (by the manager's clock). */ lastPassMs: number; } /** * A committed change to the rows of one collection that can affect query results * (RT-98). Every invalidation the store makes produces one: local writes and remote * applies (with the operation), and changes made without a new operation (rejection * re-folds, scope retraction, cascade settling, rematerialization, backup restore, * held/discarded writes). */ interface RecordsChange { /** Collection whose rows changed */ readonly collection: string; /** Changed record ids, or null when unknown (treat the whole collection as changed) */ readonly ids: readonly string[] | null; /** The operation that caused the change, when there is one */ readonly operation?: Operation; } /** Listener for {@link RecordsChange}s made by this runtime (not those relayed from peers). */ type RecordsChangeListener = (change: RecordsChange) => void; /** * Performance statistics for monitoring subscription checking efficiency. */ interface SubscriptionStats { /** Total number of mutation notifications processed */ totalChecks: number; /** Number of times bloom filter said "maybe" (proceeded to precise check) */ bloomFilterHits: number; /** Number of times bloom filter said "definitely not" (skipped all subscriptions) */ bloomFilterMisses: number; /** Number of times bloom filter said "maybe" but precise check found no match */ falsePositives: number; /** Average time per check in milliseconds */ averageCheckTimeMs: number; /** Whether bloom filter is currently active */ bloomFilterActive: boolean; /** Current subscription count */ subscriptionCount: number; } /** * Manages reactive subscriptions with two-level dependency checking. * * When a mutation occurs on a collection, affected subscriptions are re-evaluated * in a microtask batch and callbacks are invoked only if results actually changed. * * For large subscription counts (>= bloomThreshold), a bloom filter provides O(k) * pre-filtering to avoid scanning all subscriptions on every mutation: * * Level 1 (Bloom filter): Fast O(k) check -- does this mutation potentially affect * any subscription? If NO: skip all subscriptions (guaranteed correct). * If MAYBE: proceed to Level 2. * * Level 2 (Precise check): Only evaluate subscriptions that match the mutated * collection, including included (related) collection tracking. */ declare class SubscriptionManager { private subscriptions; private pendingCollections; private flushScheduled; /** Internal S0 phase timer: when the oldest unflushed change was recorded (null when none or timers off). */ private notifiedAt; private readonly onQuerySubscribed?; private readonly onQueryError?; private readonly onRead?; private readonly onPatched?; private getRegistry; private readonly getDefinition; private clock; private passBudgetMs; private attachedRegistry; private stopListening; private readonly overlayPending; private overlayScheduled; private readonly overlayCounters; private readonly changeListeners; /** * Collections changed before the first change listener attached (a store's open: * rematerialization, migration backfills). Replayed to that listener, so other tabs * hear about changes made while this tab was still opening. Bounded by the schema. */ private unheardCollections; private bloomFilter; private bloomDirty; private readonly bloomThreshold; private readonly bloomExpectedItems; private readonly bloomFalsePositiveRate; private totalChecks; private bloomFilterHits; private bloomFilterMisses; private falsePositives; private totalCheckTimeMs; constructor(options?: SubscriptionManagerOptions); /** * Register a new subscription. * * @param descriptor - The query descriptor defining what this subscription watches * @param callback - Called with results whenever they change * @param executeFn - Function to re-execute the query and get current results * @returns An unsubscribe function */ register(descriptor: QueryDescriptor, callback: SubscriptionCallback, executeFn: () => Promise, options?: RegisterOptions): () => void; /** * Register a subscription and immediately execute the query. * The initial results are stored as lastResults so subsequent flushes * correctly diff against the initial state. A failing initial run is reported * through `options.onError` and the `query:error` hook, never as an unhandled * rejection (STORE-12). * * @returns An unsubscribe function */ registerAndFetch(descriptor: QueryDescriptor, callback: SubscriptionCallback, executeFn: () => Promise, options?: RegisterOptions): () => void; private createSubscription; private track; /** * Run a subscription's query and deliver the result when it changed. Never * throws: failures go to the error channel. Runs are numbered so a slow, * older run never overwrites the result of a newer one. */ private run; private isCurrent; private reportError; /** * Notify the manager that a mutation occurred on a collection. * Schedules a microtask flush to batch multiple mutations in the same tick. */ notify(collection: string, operation: Operation): void; /** * Invalidate a collection after a local-view change that has no domain operation * (a re-fold, a retraction, a restore). Pass the record ids when known. */ invalidate(collection: string, ids?: readonly string[] | null): void; /** * The single entry point for a committed change made by this runtime (RT-98): it * schedules the affected queries and tells every change listener (the cross-tab * bus), so no invalidation path can reach this tab's queries without reaching the * other tabs' too. */ recordsChanged(change: RecordsChange): void; /** * Invalidate a collection for a change another runtime made to the shared * database. Not relayed to change listeners (the peer already broadcast it). */ invalidateFromPeer(collection: string): void; /** * Listen to every committed change this runtime makes. * * @returns An unsubscribe function */ onRecordsChanged(listener: RecordsChangeListener): () => void; /** * Immediately flush all pending notifications. * Useful for testing. In production, flushing happens via microtask. */ flush(): Promise; /** * Remove all subscriptions. Called on store close. */ clear(): void; /** Number of active subscriptions (for testing/debugging) */ get size(): number; /** * Get performance statistics for monitoring subscription checking efficiency. * Useful for DevTools integration and performance tuning. */ getStats(): SubscriptionStats; /** * Check if bloom filter is currently active. * Active when subscription count meets or exceeds the threshold. */ isBloomActive(): boolean; /** * Find subscriptions affected by mutations to the given collections. * Uses two-level checking when bloom filter is active: * * Level 1: Bloom filter pre-check -- if no subscription depends on any * of the mutated collections, skip everything (O(k) per collection). * * Level 2: Precise check -- linear scan of subscriptions, matching * against the mutated collections. */ private findAffectedSubscriptions; /** * Rebuild the bloom filter from all current subscriptions. * Adds collection-level dependencies for every subscription, plus * any included collection dependencies. */ private rebuildBloomFilter; /** * A pending write was added, rolled back or cleared for `collection`: recompute what * its patchable subscriptions display. Coalesced: any number of calls in one task * produce one pass per subscription, in a microtask (design 11). Never touches the * worker and never reaches the change listeners (the cross-tab bus, I11, F17). */ overlayChanged(collection: string): void; /** * Run the scheduled patch pass now. Called by the microtask; tests call it directly. * * Each affected, patchable subscription with a base recomputes * `displayed = applyOverlay(base, applicable entries)` and its callback runs when the * rows changed. A pass that exceeds its budget stops: the remaining subscriptions keep * what they show and catch up at the commit path (their SQL re-run). */ flushOverlay(): void; /** Counters of the overlay's work. */ getOverlayStats(): Readonly; /** Replace the pass clock and budget. For tests and benchmarks (deterministic budgets). */ configureOverlay(options: { now?: () => number; passBudgetMs?: number; pendingWrites?: () => PendingWrites | null; }): void; /** * What every subscription holds, in registration order: its base (last SQL result), * the epoch that read was issued at, and the rows it last delivered. For tests and * DevTools; the rows are the live arrays, not copies. */ inspectOverlay(): Array<{ readonly descriptor: QueryDescriptor; readonly base: readonly CollectionRecord[] | null; readonly baseIssuedAt: number | undefined; readonly displayed: readonly CollectionRecord[]; readonly patchable: boolean; }>; /** Whether a subscription's query may be patched (decided once). */ private isPatchableSub; /** Recompute one subscription's display from its base and deliver it when it changed. */ private patch; private overlayRows; /** * A SQL result arrived for `sub`: it becomes the base, the entries it may not contain * are applied on top, and entries every subscription has now read past are dropped. * * @returns The rows to display */ private settleRun; /** * The self-check (I10): the writes this result newly contains were shown from a * prediction; compare the prediction with what the database now holds and report a * difference (`store:overlay-diverged`). It judges only what it can judge exactly: * the last committed write of each record (a later write legitimately replaces the * fields of an earlier one), against the SQL result itself (never the display, which * other pending writes shape), in a collection nothing else touched while the write was * pending (a remote change, another tab, an unpredicted write may legitimately change * the record), on the fields the write set. Membership is judged only for a query whose * membership depends on the record alone: a page limit makes it depend on other rows * (and on rollbacks of other writes), and the two metadata times are only approximated. */ private verifySettle; /** * Drop committed entries that every patchable subscription of `collection` has read * past (its base was issued at or after the entry's commit). A subscription still * waiting for its first result holds them all. */ private settleEntries; /** * Forget cached rows a committed change may have made stale (F21). The post-commit * publication of a predicted local write is the exception: the registry cached its * committed row itself. */ private invalidateCachedRows; /** * The registry in force, attached to while subscriptions exist. Null with the overlay * off, which is the only thing the hot paths ever test. */ private registry; private detachRegistry; private onRegistryChange; private scheduleFlush; } /** * Fluent query builder for constructing and executing collection queries. * Supports where, orderBy, limit, offset, include, exec, count, and subscribe. * * The generic parameter `T` defaults to `CollectionRecord` for backward compatibility * but can be narrowed to a specific record type for full type inference. * * @example * ```typescript * const todos = await app.todos * .where({ completed: false }) * .orderBy('createdAt', 'desc') * .limit(10) * .exec() * ``` */ declare class QueryBuilder { private readonly collectionName; private readonly definition; private readonly adapter; private readonly subscriptionManager; private readonly schema?; private descriptor; constructor(collectionName: string, definition: CollectionDefinition, adapter: StorageAdapter, subscriptionManager: SubscriptionManager, initialWhere?: WhereClause, schema?: SchemaDefinition | undefined); /** * Add WHERE conditions (AND semantics). Conditions on new fields are added to the * existing ones; a condition on a field that already has one replaces it. * * A field whose value is `undefined` adds no condition (it does not remove an * earlier one); `null` matches missing values (`IS NULL`). Non-finite numbers are * refused. See {@link normalizeWhere} (RT-102). */ where(conditions: WhereClause): QueryBuilder; /** * Add ORDER BY clause. */ orderBy(field: string, direction?: OrderByDirection): QueryBuilder; /** * Set result limit. */ limit(n: number): QueryBuilder; /** * Set result offset. */ offset(n: number): QueryBuilder; /** * Include related records in the query results. * Follows relations defined in the schema to batch-fetch related data. * * @param targets - Relation target names (collection names or relation names) * @returns A new QueryBuilder with include targets added * * @example * ```typescript * const todosWithProject = await app.todos * .where({ completed: false }) * .include('project') * .exec() * ``` */ include(...targets: string[]): QueryBuilder; /** * Execute the query and return results. */ exec(): Promise; /** * Count the records this query matches: the length `exec()` would return, so `limit` and * `offset` apply. */ count(): Promise; /** * Subscribe to query results. The callback is called with the current results once the * initial query resolves (asynchronously), then again whenever the results change. * * @returns An unsubscribe function */ subscribe(callback: SubscriptionCallback, options?: SubscribeOptions): () => void; /** Comparator built once per collection definition and shared by its queries. */ private getResultsEqual; /** Get the internal descriptor (for testing/debugging) */ getDescriptor(): QueryDescriptor; private clone; /** * Resolve include targets to their actual collection names for subscription tracking. */ private resolveIncludeCollections; /** * Resolve includes after primary query, batch-fetching related records. */ private resolveIncludes; /** * Many-to-one: collect FK values from primary results, batch-fetch related, attach as singular. */ private resolveManyToOneInclude; /** * One-to-many: collect primary IDs, batch-fetch children, attach as array. */ private resolveOneToManyInclude; /** * Find a relation definition matching the include target. * Searches by relation name, target collection name, and singularized/pluralized variants. */ private findRelation; } /** * Normalise a `where` clause to its canonical form (RT-102). This is the ONE place that * decides what a where value means, so the SQL the store runs, the descriptor and the * query key (store cache, React/Vue/Svelte bindings) always agree: * * - `undefined` means "no condition": `where({ projectId: undefined })` is `where({})` * (the usual "nothing selected yet" pattern), and an operator whose operand is * `undefined` (`{ $gt: undefined }`) is dropped; a field left with no operator is * dropped. A later `.where({ x: undefined })` therefore does not remove an earlier * condition on `x`. * - `null` means SQL `IS NULL` (`$ne: null` means `IS NOT NULL`). * - Non-finite numbers (`NaN`, `Infinity`) have no stored representation: refused. * - `undefined` inside a `$in` list is refused (ambiguous: no condition cannot be one * element of a list). * * @param where - The clause as the developer wrote it * @returns A new clause with the rules above applied * @throws {QueryError} For a non-finite number or an `undefined` `$in` element */ declare function normalizeWhere(where: WhereClause): WhereClause; /** * The canonical identity of a query: equal keys if and only if the descriptors run the * same query (RT-102). Used by the store's query-store cache and by every framework * binding to decide when to share a store or re-subscribe. * * Unlike `JSON.stringify`, nothing is dropped or conflated: `where` keys are sorted * (their order does not change the query), `undefined` is dropped exactly as * {@link normalizeWhere} drops it, and `NaN`, `Date` and byte values keep distinct, * typed encodings. * * @param descriptor - The query descriptor (`queryBuilder.getDescriptor()`) * @returns A string key */ declare function queryKey(descriptor: QueryDescriptor): string; /** * Bridges the async QueryBuilder.subscribe() API with synchronous snapshot reads * required by React useSyncExternalStore, Vue composables, and Svelte stores. * * Uses lazy subscription: the underlying query subscription starts when the first * listener attaches and stops when the last listener detaches. */ declare class QueryStore { private snapshot; private listeners; private unsubscribeQuery; private active; private hasEmittedSnapshot; private error; private coverage; private readonly queryBuilder; constructor(queryBuilder: QueryBuilder); /** * Subscribe to snapshot changes. * * @returns Unsubscribe function */ subscribe: (onStoreChange: () => void) => (() => void); /** Synchronous read of the latest query results. */ getSnapshot: () => readonly T[]; /** * Whether the underlying query subscription has delivered at least one * authoritative result for the current subscription lifecycle. */ hasSnapshot: () => boolean; /** * The latest query failure, or null. Set when the query (or a re-run after a * write) fails; cleared by the next successful delivery. Listeners are notified * on both transitions, so bindings read it next to `getSnapshot()`. */ getError: () => Error | null; /** * Where the snapshot's rows come from and whether they are complete. The same object until * it changes. A query that reports nothing is a plain local one: pending until its first * result, then local and complete. */ getCoverage(): QueryCoverage; /** Tear down listeners and the underlying query subscription. */ destroy(): void; private startSubscription; private stopSubscription; private notifyListeners; } /** * Ensures a query builder is backed by an open store (not a legacy pending placeholder). */ declare function assertQueryReady(query: QueryBuilder): void; /** * Reference-counted cache of {@link QueryStore} instances keyed by query descriptor. * Identical queries from different components share one underlying subscription. */ declare class QueryStoreCache { private readonly scopeKey; private entries; constructor(scopeKey?: string); getOrCreate(queryBuilder: QueryBuilder): QueryStore; release(queryBuilder: QueryBuilder): void; clear(): void; get size(): number; private getKey; } /** * Process-wide shared query store cache for framework bindings. * * @deprecated Prefer {@link KoraApp.getQueryStoreCache} via `KoraProvider` context * so each app instance owns an isolated cache. */ declare function getSharedQueryStoreCache(): QueryStoreCache; export { QueryBuilder as Q, type RecordsChangeListener as R, SubscriptionManager as S, QueryStore as a, QueryStoreCache as b, type RecordsChange as c, type RegisterOptions as d, type ResultsEqual as e, StoreReadOnlyError as f, type SubscriptionManagerOptions as g, type SubscriptionStats as h, assertQueryReady as i, getSharedQueryStoreCache as j, normalizeWhere as n, queryKey as q };