@topgunbuild/core 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1161,7 +1161,7 @@ declare function serialize(data: unknown): Uint8Array;
1161
1161
  */
1162
1162
  declare function deserialize<T = unknown>(data: Uint8Array | ArrayBuffer): T;
1163
1163
 
1164
- type PredicateOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'regex' | 'and' | 'or' | 'not';
1164
+ type PredicateOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'regex' | 'contains' | 'containsAll' | 'containsAny' | 'and' | 'or' | 'not';
1165
1165
  interface PredicateNode {
1166
1166
  op: PredicateOp;
1167
1167
  attribute?: string;
@@ -1181,6 +1181,30 @@ declare class Predicates {
1181
1181
  static and(...predicates: PredicateNode[]): PredicateNode;
1182
1182
  static or(...predicates: PredicateNode[]): PredicateNode;
1183
1183
  static not(predicate: PredicateNode): PredicateNode;
1184
+ /**
1185
+ * Create a 'contains' predicate for text search.
1186
+ * Matches if attribute value contains the search text.
1187
+ *
1188
+ * @param attribute - Attribute name
1189
+ * @param value - Text to search for
1190
+ */
1191
+ static contains(attribute: string, value: string): PredicateNode;
1192
+ /**
1193
+ * Create a 'containsAll' predicate for text search.
1194
+ * Matches if attribute value contains ALL search values.
1195
+ *
1196
+ * @param attribute - Attribute name
1197
+ * @param values - Text values that must all be present
1198
+ */
1199
+ static containsAll(attribute: string, values: string[]): PredicateNode;
1200
+ /**
1201
+ * Create a 'containsAny' predicate for text search.
1202
+ * Matches if attribute value contains ANY search value.
1203
+ *
1204
+ * @param attribute - Attribute name
1205
+ * @param values - Text values, any of which can match
1206
+ */
1207
+ static containsAny(attribute: string, values: string[]): PredicateNode;
1184
1208
  }
1185
1209
  declare function evaluatePredicate(predicate: PredicateNode, data: any): boolean;
1186
1210
 
@@ -2465,7 +2489,7 @@ declare const MessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2465
2489
  keyPattern: z.ZodOptional<z.ZodString>;
2466
2490
  }, z.core.$strip>>;
2467
2491
  }, z.core.$strip>], "type">;
2468
- type Query = z.infer<typeof QuerySchema>;
2492
+ type Query$1 = z.infer<typeof QuerySchema>;
2469
2493
  type ClientOp = z.infer<typeof ClientOpSchema>;
2470
2494
  type Message = z.infer<typeof MessageSchema>;
2471
2495
  type PingMessage = z.infer<typeof PingMessageSchema>;
@@ -2962,4 +2986,3897 @@ type ReplicationProtocolMessage = ReplicationMessage | ReplicationBatchMessage |
2962
2986
  declare const PARTITION_COUNT = 271;
2963
2987
  declare const DEFAULT_BACKUP_COUNT = 1;
2964
2988
 
2965
- export { AuthMessageSchema, type BatchMessage, BatchMessageSchema, BuiltInProcessors, BuiltInResolvers, type CircuitBreakerConfig, type ClientOp, ClientOpMessageSchema, ClientOpSchema, type ClusterClientConfig, type ClusterEvents, type ReadOptions as ClusterReadOptions, type WriteOptions as ClusterWriteOptions, type ConflictResolver, type ConflictResolverDef, ConflictResolverDefSchema, type ConflictResolverFn, ConflictResolverSchema, type ConnectionPoolConfig, type ConnectionState, ConsistencyLevel, CounterRequestSchema, CounterResponseSchema, CounterSyncSchema, CounterUpdateSchema, DEFAULT_BACKUP_COUNT, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_EVENT_JOURNAL_CONFIG, DEFAULT_MIGRATION_CONFIG, DEFAULT_PARTITION_ROUTER_CONFIG, DEFAULT_PROCESSOR_RATE_LIMITS, DEFAULT_REPLICATION_CONFIG, DEFAULT_RESOLVER_RATE_LIMITS, DEFAULT_WRITE_CONCERN_TIMEOUT, type EntryProcessBatchRequest, EntryProcessBatchRequestSchema, type EntryProcessBatchResponse, EntryProcessBatchResponseSchema, type EntryProcessKeyResult, EntryProcessKeyResultSchema, type EntryProcessRequest, EntryProcessRequestSchema, type EntryProcessResponse, EntryProcessResponseSchema, type EntryProcessorDef, EntryProcessorDefSchema, type EntryProcessorFn, type EntryProcessorResult, EntryProcessorSchema, type EventJournal, type EventJournalConfig, EventJournalImpl, FORBIDDEN_PATTERNS, HLC, type JournalEvent, type JournalEventData, JournalEventDataSchema, type JournalEventInput, type JournalEventListener, type JournalEventMessage, JournalEventMessageSchema, type JournalEventType, JournalEventTypeSchema, type JournalReadRequest, JournalReadRequestSchema, type JournalReadResponse, JournalReadResponseSchema, type JournalSubscribeRequest, JournalSubscribeRequestSchema, type JournalUnsubscribeRequest, JournalUnsubscribeRequestSchema, LWWMap, type LWWRecord, LWWRecordSchema, type ListResolversRequest, ListResolversRequestSchema, type ListResolversResponse, ListResolversResponseSchema, LockReleaseSchema, LockRequestSchema, type MergeContext, type MergeKeyResult, type MergeRejectedMessage, MergeRejectedMessageSchema, type MergeRejection, type MergeResult, MerkleReqBucketMessageSchema, MerkleTree, type Message, MessageSchema, type MigrationChunkAckMessage, type MigrationChunkMessage, type MigrationCompleteMessage, type MigrationConfig, type MigrationMessage, type MigrationMetrics, type MigrationStartMessage, type MigrationStatus, type MigrationVerifyMessage, type NodeHealth, type NodeInfo, type NodeStatus, type NotOwnerError, ORMap, ORMapDiffRequestSchema, ORMapDiffResponseSchema, type ORMapMerkleNode, ORMapMerkleReqBucketSchema, ORMapMerkleTree, ORMapPushDiffSchema, type ORMapRecord, ORMapRecordSchema, type ORMapSnapshot, ORMapSyncInitSchema, ORMapSyncRespBucketsSchema, ORMapSyncRespLeafSchema, ORMapSyncRespRootSchema, type OpAckMessage, OpAckMessageSchema, OpBatchMessageSchema, type OpRejectedMessage, OpRejectedMessageSchema, type OpResult, OpResultSchema, PARTITION_COUNT, type PNCounter, type PNCounterConfig, PNCounterImpl, type PNCounterState, type PNCounterStateObject, PNCounterStateObjectSchema, type PartitionChange, type PartitionInfo, type PartitionMap, type PartitionMapDeltaMessage, type PartitionMapMessage, type PartitionMapRequestMessage, PartitionMapRequestSchema, type PartitionMigration, type PartitionRouterConfig, PartitionState, type PendingWrite, type PermissionPolicy, type PermissionType, type PingMessage, PingMessageSchema, type PongMessage, PongMessageSchema, type PredicateNode, PredicateNodeSchema, type PredicateOp, PredicateOpSchema, Predicates, type Principal, type ProcessorRateLimitConfig, type Query, QuerySchema, QuerySubMessageSchema, QueryUnsubMessageSchema, RESOLVER_FORBIDDEN_PATTERNS, type RegisterResolverRequest, RegisterResolverRequestSchema, type RegisterResolverResponse, RegisterResolverResponseSchema, type ReplicationAckMessage, type ReplicationBatchAckMessage, type ReplicationBatchMessage, type ReplicationConfig, type ReplicationHealth, type ReplicationLag, type ReplicationMessage, type ReplicationProtocolMessage, type ReplicationResult, type ReplicationTask, type ResolverRateLimitConfig, Ringbuffer, type RoutingError, type StaleMapError, SyncInitMessageSchema, SyncRespBucketsMessageSchema, SyncRespLeafMessageSchema, SyncRespRootMessageSchema, type Timestamp, TimestampSchema, TopicMessageEventSchema, TopicPubSchema, TopicSubSchema, TopicUnsubSchema, type UnregisterResolverRequest, UnregisterResolverRequestSchema, type UnregisterResolverResponse, UnregisterResolverResponseSchema, WRITE_CONCERN_ORDER, WriteConcern, WriteConcernSchema, type WriteConcernValue, type WriteOptions$1 as WriteOptions, type WriteResult, combineHashes, compareHLCTimestamps, compareTimestamps, deepMerge, deserialize, disableNativeHash, evaluatePredicate, getHighestWriteConcernLevel, hashORMapEntry, hashORMapRecord, hashString, isUsingNativeHash, isWriteConcernAchieved, resetNativeHash, serialize, timestampToString, validateProcessorCode, validateResolverCode };
2989
+ /**
2990
+ * Common types for sorted data structures
2991
+ */
2992
+ /**
2993
+ * Comparator function for ordering keys
2994
+ */
2995
+ type Comparator<K> = (a: K, b: K) => number;
2996
+ /**
2997
+ * Options for range queries
2998
+ */
2999
+ interface RangeOptions {
3000
+ /** Include the lower bound in results (default: true) */
3001
+ fromInclusive?: boolean;
3002
+ /** Include the upper bound in results (default: false) */
3003
+ toInclusive?: boolean;
3004
+ }
3005
+
3006
+ /**
3007
+ * Type-safe wrapper over sorted-btree for use in NavigableIndex
3008
+ *
3009
+ * Provides O(log N) operations for:
3010
+ * - set/get/delete
3011
+ * - range queries
3012
+ * - greaterThan/lessThan queries
3013
+ */
3014
+
3015
+ /**
3016
+ * A sorted map implementation backed by a B+ tree.
3017
+ * Provides efficient range queries and ordered iteration.
3018
+ *
3019
+ * @template K - Key type (must be comparable)
3020
+ * @template V - Value type
3021
+ */
3022
+ declare class SortedMap<K, V> {
3023
+ private readonly tree;
3024
+ private readonly comparator;
3025
+ constructor(comparator?: Comparator<K>);
3026
+ /**
3027
+ * Set a key-value pair. Updates existing key if present.
3028
+ * Time complexity: O(log N)
3029
+ */
3030
+ set(key: K, value: V): this;
3031
+ /**
3032
+ * Get the value for a key.
3033
+ * Time complexity: O(log N)
3034
+ */
3035
+ get(key: K): V | undefined;
3036
+ /**
3037
+ * Delete a key from the map.
3038
+ * Time complexity: O(log N)
3039
+ * @returns true if the key existed and was deleted
3040
+ */
3041
+ delete(key: K): boolean;
3042
+ /**
3043
+ * Check if a key exists in the map.
3044
+ * Time complexity: O(log N)
3045
+ */
3046
+ has(key: K): boolean;
3047
+ /**
3048
+ * Get the number of entries in the map.
3049
+ */
3050
+ get size(): number;
3051
+ /**
3052
+ * Check if the map is empty.
3053
+ */
3054
+ get isEmpty(): boolean;
3055
+ /**
3056
+ * Get the minimum key in the map.
3057
+ * Time complexity: O(log N)
3058
+ */
3059
+ minKey(): K | undefined;
3060
+ /**
3061
+ * Get the maximum key in the map.
3062
+ * Time complexity: O(log N)
3063
+ */
3064
+ maxKey(): K | undefined;
3065
+ /**
3066
+ * Iterate over entries in a range [from, to).
3067
+ * Time complexity: O(log N + K) where K is the number of results
3068
+ *
3069
+ * @param from - Lower bound
3070
+ * @param to - Upper bound
3071
+ * @param options - Range options for inclusive/exclusive bounds
3072
+ */
3073
+ range(from: K, to: K, options?: RangeOptions): IterableIterator<[K, V]>;
3074
+ /**
3075
+ * Iterate over entries where key > value (or >= if inclusive).
3076
+ * Time complexity: O(log N + K) where K is the number of results
3077
+ *
3078
+ * @param key - Lower bound
3079
+ * @param inclusive - Include the bound in results (default: false)
3080
+ */
3081
+ greaterThan(key: K, inclusive?: boolean): IterableIterator<[K, V]>;
3082
+ /**
3083
+ * Iterate over entries where key < value (or <= if inclusive).
3084
+ * Time complexity: O(log N + K) where K is the number of results
3085
+ *
3086
+ * Note: This method iterates from the beginning of the tree.
3087
+ * The O(log N) component is for finding the upper bound,
3088
+ * and O(K) is for yielding K results.
3089
+ *
3090
+ * @param key - Upper bound
3091
+ * @param inclusive - Include the bound in results (default: false)
3092
+ */
3093
+ lessThan(key: K, inclusive?: boolean): IterableIterator<[K, V]>;
3094
+ /**
3095
+ * Iterate over all entries in sorted order.
3096
+ * Time complexity: O(N)
3097
+ */
3098
+ entries(): IterableIterator<[K, V]>;
3099
+ /**
3100
+ * Iterate over all keys in sorted order.
3101
+ * Time complexity: O(N)
3102
+ */
3103
+ keys(): IterableIterator<K>;
3104
+ /**
3105
+ * Iterate over all values in sorted order.
3106
+ * Time complexity: O(N)
3107
+ */
3108
+ values(): IterableIterator<V>;
3109
+ /**
3110
+ * Iterate over entries in reverse sorted order.
3111
+ * Time complexity: O(N)
3112
+ */
3113
+ entriesReversed(): IterableIterator<[K, V]>;
3114
+ /**
3115
+ * Remove all entries from the map.
3116
+ */
3117
+ clear(): void;
3118
+ /**
3119
+ * Execute a callback for each entry in sorted order.
3120
+ */
3121
+ forEach(callback: (value: V, key: K, map: this) => void): void;
3122
+ /**
3123
+ * Create a new SortedMap from entries.
3124
+ */
3125
+ static from<K, V>(entries: Iterable<[K, V]>, comparator?: Comparator<K>): SortedMap<K, V>;
3126
+ /**
3127
+ * Get or set a value using a factory function.
3128
+ * If the key doesn't exist, the factory is called to create the value.
3129
+ */
3130
+ getOrSet(key: K, factory: () => V): V;
3131
+ /**
3132
+ * Update a value if the key exists.
3133
+ * @returns true if the key existed and was updated
3134
+ */
3135
+ update(key: K, updater: (value: V) => V): boolean;
3136
+ /**
3137
+ * Get the entry at a specific index (0-based).
3138
+ * Time complexity: O(N) - requires linear scan from the beginning.
3139
+ * Note: B+ trees do not support O(log N) index-based access.
3140
+ */
3141
+ at(index: number): [K, V] | undefined;
3142
+ /**
3143
+ * Find the greatest key less than the given key.
3144
+ * Time complexity: O(log N)
3145
+ */
3146
+ lowerKey(key: K): K | undefined;
3147
+ /**
3148
+ * Find the greatest key less than or equal to the given key.
3149
+ * Time complexity: O(log N)
3150
+ */
3151
+ floorKey(key: K): K | undefined;
3152
+ /**
3153
+ * Find the least key greater than the given key.
3154
+ * Time complexity: O(log N)
3155
+ */
3156
+ higherKey(key: K): K | undefined;
3157
+ /**
3158
+ * Find the least key greater than or equal to the given key.
3159
+ * Time complexity: O(log N)
3160
+ */
3161
+ ceilingKey(key: K): K | undefined;
3162
+ /**
3163
+ * Make the map iterable.
3164
+ */
3165
+ [Symbol.iterator](): IterableIterator<[K, V]>;
3166
+ }
3167
+
3168
+ /**
3169
+ * Attribute System for Query Engine
3170
+ *
3171
+ * Attributes extract value(s) from records for indexing and querying.
3172
+ * Inspired by CQEngine Attribute<O, A>.
3173
+ *
3174
+ * @module query/Attribute
3175
+ */
3176
+ /**
3177
+ * Attribute extracts value(s) from a record.
3178
+ * V = Record value type, A = Attribute value type
3179
+ */
3180
+ interface Attribute<V, A> {
3181
+ /** Unique attribute name */
3182
+ readonly name: string;
3183
+ /** Attribute value type */
3184
+ readonly type: 'simple' | 'multi';
3185
+ /**
3186
+ * Extract value from record.
3187
+ * Returns undefined if attribute doesn't exist.
3188
+ */
3189
+ getValue(record: V): A | undefined;
3190
+ /**
3191
+ * For multi-value attributes, returns all values.
3192
+ * For simple attributes, returns single-element array.
3193
+ */
3194
+ getValues(record: V): A[];
3195
+ }
3196
+ /**
3197
+ * Attribute that returns exactly one value per record.
3198
+ */
3199
+ declare class SimpleAttribute<V, A> implements Attribute<V, A> {
3200
+ readonly name: string;
3201
+ private readonly extractor;
3202
+ readonly type: "simple";
3203
+ constructor(name: string, extractor: (record: V) => A | undefined);
3204
+ getValue(record: V): A | undefined;
3205
+ getValues(record: V): A[];
3206
+ }
3207
+ /**
3208
+ * Factory function for SimpleAttribute.
3209
+ */
3210
+ declare function simpleAttribute<V, A>(name: string, extractor: (record: V) => A | undefined): SimpleAttribute<V, A>;
3211
+ /**
3212
+ * Attribute that returns zero or more values per record.
3213
+ * Example: tags, categories, roles.
3214
+ */
3215
+ declare class MultiValueAttribute<V, A> implements Attribute<V, A> {
3216
+ readonly name: string;
3217
+ private readonly extractor;
3218
+ readonly type: "multi";
3219
+ constructor(name: string, extractor: (record: V) => A[]);
3220
+ getValue(record: V): A | undefined;
3221
+ getValues(record: V): A[];
3222
+ }
3223
+ /**
3224
+ * Factory function for MultiValueAttribute.
3225
+ */
3226
+ declare function multiAttribute<V, A>(name: string, extractor: (record: V) => A[]): MultiValueAttribute<V, A>;
3227
+
3228
+ /**
3229
+ * ResultSet Interface
3230
+ *
3231
+ * Lazy result set from index queries.
3232
+ * Inspired by CQEngine ResultSet<O>.
3233
+ *
3234
+ * @module query/resultset/ResultSet
3235
+ */
3236
+ /**
3237
+ * Lazy result set from index query.
3238
+ * K = record key type
3239
+ */
3240
+ interface ResultSet<K> {
3241
+ /**
3242
+ * Iterate over matching keys.
3243
+ * Lazy evaluation where possible.
3244
+ */
3245
+ [Symbol.iterator](): Iterator<K>;
3246
+ /**
3247
+ * Cost of retrieving these results.
3248
+ * Used by QueryOptimizer for index selection.
3249
+ */
3250
+ getRetrievalCost(): number;
3251
+ /**
3252
+ * Estimated cost of merging/processing these results.
3253
+ * Usually based on result count.
3254
+ */
3255
+ getMergeCost(): number;
3256
+ /**
3257
+ * Check if result set contains key.
3258
+ */
3259
+ contains(key: K): boolean;
3260
+ /**
3261
+ * Get result count.
3262
+ * May require iteration for lazy result sets.
3263
+ */
3264
+ size(): number;
3265
+ /**
3266
+ * Materialize to array.
3267
+ */
3268
+ toArray(): K[];
3269
+ /**
3270
+ * Check if empty.
3271
+ */
3272
+ isEmpty(): boolean;
3273
+ }
3274
+
3275
+ /**
3276
+ * Base Index Interface
3277
+ *
3278
+ * Defines the contract for all index types in the Query Engine.
3279
+ * Inspired by CQEngine Index hierarchy.
3280
+ *
3281
+ * @module query/indexes/types
3282
+ */
3283
+
3284
+ /**
3285
+ * Base interface for all indexes.
3286
+ * K = record key type, V = record value type, A = attribute value type
3287
+ */
3288
+ interface Index<K, V, A = unknown> {
3289
+ /** Attribute this index is built on */
3290
+ readonly attribute: Attribute<V, A>;
3291
+ /** Index type identifier */
3292
+ readonly type: 'hash' | 'navigable' | 'compound' | 'standing' | 'inverted';
3293
+ /**
3294
+ * Cost of retrieving results from this index.
3295
+ * Lower is better. Used by QueryOptimizer.
3296
+ * CQEngine values: Standing=10, Compound=20, Hash=30, Navigable=40
3297
+ */
3298
+ getRetrievalCost(): number;
3299
+ /**
3300
+ * Check if this index supports the given query type.
3301
+ */
3302
+ supportsQuery(queryType: string): boolean;
3303
+ /**
3304
+ * Retrieve candidate keys matching the query.
3305
+ */
3306
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
3307
+ /**
3308
+ * Add a record to the index.
3309
+ */
3310
+ add(key: K, record: V): void;
3311
+ /**
3312
+ * Remove a record from the index.
3313
+ */
3314
+ remove(key: K, record: V): void;
3315
+ /**
3316
+ * Update a record in the index.
3317
+ */
3318
+ update(key: K, oldRecord: V, newRecord: V): void;
3319
+ /**
3320
+ * Clear all entries from the index.
3321
+ */
3322
+ clear(): void;
3323
+ /**
3324
+ * Get statistics about the index.
3325
+ */
3326
+ getStats(): IndexStats;
3327
+ }
3328
+ /**
3329
+ * Query parameters for index retrieval.
3330
+ */
3331
+ interface IndexQuery<A> {
3332
+ /** Query type */
3333
+ type: 'equal' | 'in' | 'has' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'contains' | 'containsAll' | 'containsAny' | 'compound';
3334
+ /** Value for equality queries */
3335
+ value?: A;
3336
+ /** Values for 'in' queries or compound queries */
3337
+ values?: A[];
3338
+ /** Lower bound for range queries */
3339
+ from?: A;
3340
+ /** Upper bound for range queries */
3341
+ to?: A;
3342
+ /** Include lower bound (default: true) */
3343
+ fromInclusive?: boolean;
3344
+ /** Include upper bound (default: false) */
3345
+ toInclusive?: boolean;
3346
+ }
3347
+ /**
3348
+ * Statistics about an index.
3349
+ */
3350
+ interface IndexStats {
3351
+ /** Number of distinct attribute values indexed */
3352
+ distinctValues: number;
3353
+ /** Total number of record references */
3354
+ totalEntries: number;
3355
+ /** Average entries per distinct value */
3356
+ avgEntriesPerValue: number;
3357
+ }
3358
+
3359
+ /**
3360
+ * HashIndex Implementation
3361
+ *
3362
+ * Hash-based index for O(1) equality lookups.
3363
+ * Supports: equal, in, has queries.
3364
+ *
3365
+ * Structure: Map<AttributeValue, Set<RecordKey>>
3366
+ *
3367
+ * CQEngine Reference: HashIndex.java (retrieval cost: 30)
3368
+ *
3369
+ * @module query/indexes/HashIndex
3370
+ */
3371
+
3372
+ /**
3373
+ * Hash-based index for O(1) equality lookups.
3374
+ *
3375
+ * K = record key type, V = record value type, A = attribute value type
3376
+ */
3377
+ declare class HashIndex<K, V, A> implements Index<K, V, A> {
3378
+ readonly attribute: Attribute<V, A>;
3379
+ readonly type: "hash";
3380
+ /** Map from attribute value to set of record keys */
3381
+ private data;
3382
+ /** Set of all keys with non-null attribute value */
3383
+ private allKeys;
3384
+ private static readonly RETRIEVAL_COST;
3385
+ private static readonly SUPPORTED_QUERIES;
3386
+ constructor(attribute: Attribute<V, A>);
3387
+ getRetrievalCost(): number;
3388
+ supportsQuery(queryType: string): boolean;
3389
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
3390
+ private retrieveEqual;
3391
+ private retrieveIn;
3392
+ private retrieveHas;
3393
+ add(key: K, record: V): void;
3394
+ remove(key: K, record: V): void;
3395
+ update(key: K, oldRecord: V, newRecord: V): void;
3396
+ clear(): void;
3397
+ getStats(): IndexStats;
3398
+ private arraysEqual;
3399
+ }
3400
+
3401
+ /**
3402
+ * NavigableIndex Implementation
3403
+ *
3404
+ * Sorted index for O(log N) range queries.
3405
+ * Supports: equal, in, has, gt, gte, lt, lte, between queries.
3406
+ *
3407
+ * Structure: SortedMap<AttributeValue, Set<RecordKey>>
3408
+ *
3409
+ * CQEngine Reference: NavigableIndex.java (retrieval cost: 40)
3410
+ *
3411
+ * @module query/indexes/NavigableIndex
3412
+ */
3413
+
3414
+ /**
3415
+ * Sorted index for O(log N) range queries.
3416
+ *
3417
+ * K = record key type, V = record value type, A = attribute value type (must be orderable)
3418
+ */
3419
+ declare class NavigableIndex<K, V, A extends string | number> implements Index<K, V, A> {
3420
+ readonly attribute: Attribute<V, A>;
3421
+ readonly type: "navigable";
3422
+ /** Sorted map from attribute value to set of record keys */
3423
+ private data;
3424
+ /** Set of all keys with non-null attribute value */
3425
+ private allKeys;
3426
+ /** Retrieval cost as per CQEngine cost model */
3427
+ private static readonly RETRIEVAL_COST;
3428
+ /** Supported query types */
3429
+ private static readonly SUPPORTED_QUERIES;
3430
+ /**
3431
+ * Create a NavigableIndex.
3432
+ *
3433
+ * @param attribute - Attribute to index
3434
+ * @param comparator - Optional custom comparator for ordering
3435
+ */
3436
+ constructor(attribute: Attribute<V, A>, comparator?: Comparator<A>);
3437
+ getRetrievalCost(): number;
3438
+ supportsQuery(queryType: string): boolean;
3439
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
3440
+ private retrieveEqual;
3441
+ private retrieveIn;
3442
+ private retrieveHas;
3443
+ private retrieveGreaterThan;
3444
+ private retrieveLessThan;
3445
+ private retrieveBetween;
3446
+ private iterateGreaterThan;
3447
+ private iterateLessThan;
3448
+ private iterateBetween;
3449
+ /**
3450
+ * Estimate size for gt/gte queries.
3451
+ * Uses rough estimate: assume uniform distribution, return half.
3452
+ */
3453
+ private estimateGreaterThanSize;
3454
+ /**
3455
+ * Estimate size for lt/lte queries.
3456
+ * Uses rough estimate: assume uniform distribution, return half.
3457
+ */
3458
+ private estimateLessThanSize;
3459
+ /**
3460
+ * Estimate size for between queries.
3461
+ * Uses rough estimate: assume uniform distribution, return quarter.
3462
+ */
3463
+ private estimateBetweenSize;
3464
+ add(key: K, record: V): void;
3465
+ remove(key: K, record: V): void;
3466
+ update(key: K, oldRecord: V, newRecord: V): void;
3467
+ clear(): void;
3468
+ getStats(): IndexStats;
3469
+ private arraysEqual;
3470
+ /**
3471
+ * Get the minimum indexed value.
3472
+ * Useful for debugging and range estimation.
3473
+ */
3474
+ getMinValue(): A | undefined;
3475
+ /**
3476
+ * Get the maximum indexed value.
3477
+ * Useful for debugging and range estimation.
3478
+ */
3479
+ getMaxValue(): A | undefined;
3480
+ }
3481
+
3482
+ /**
3483
+ * Fallback index that performs full scan.
3484
+ * Used when no suitable index exists for a query.
3485
+ *
3486
+ * K = record key type, V = record value type
3487
+ */
3488
+ declare class FallbackIndex<K, V> implements Index<K, V, unknown> {
3489
+ private readonly getAllKeys;
3490
+ private readonly getRecord;
3491
+ private readonly matchesPredicate;
3492
+ readonly type: "hash";
3493
+ /** Wildcard attribute for fallback */
3494
+ readonly attribute: SimpleAttribute<V, unknown>;
3495
+ /** Maximum retrieval cost ensures this is only used as fallback */
3496
+ private static readonly RETRIEVAL_COST;
3497
+ /**
3498
+ * Create a FallbackIndex.
3499
+ *
3500
+ * @param getAllKeys - Function to get all keys in the collection
3501
+ * @param getRecord - Function to get a record by key
3502
+ * @param matchesPredicate - Function to check if a record matches a query
3503
+ */
3504
+ constructor(getAllKeys: () => Iterable<K>, getRecord: (key: K) => V | undefined, matchesPredicate: (record: V, query: IndexQuery<unknown>) => boolean);
3505
+ getRetrievalCost(): number;
3506
+ /**
3507
+ * Supports any query type via full scan.
3508
+ */
3509
+ supportsQuery(): boolean;
3510
+ /**
3511
+ * Retrieve by performing full scan and applying predicate.
3512
+ */
3513
+ retrieve(query: IndexQuery<unknown>): ResultSet<K>;
3514
+ add(): void;
3515
+ remove(): void;
3516
+ update(): void;
3517
+ clear(): void;
3518
+ getStats(): IndexStats;
3519
+ }
3520
+ /**
3521
+ * Factory to create predicate matcher from query.
3522
+ * Used by FallbackIndex to evaluate queries against records.
3523
+ *
3524
+ * @param getAttribute - Function to get attribute value from record
3525
+ */
3526
+ declare function createPredicateMatcher<V>(getAttribute: (record: V, attrName: string) => unknown): (record: V, query: IndexQuery<unknown>) => boolean;
3527
+
3528
+ /**
3529
+ * Query Types and Plan Types for Query Engine
3530
+ *
3531
+ * Defines query node types for the cost-based optimizer
3532
+ * and execution plan types.
3533
+ *
3534
+ * @module query/QueryTypes
3535
+ */
3536
+
3537
+ /**
3538
+ * Base query node interface.
3539
+ * Compatible with existing PredicateNode from predicate.ts
3540
+ */
3541
+ interface QueryNode {
3542
+ type: string;
3543
+ }
3544
+ /**
3545
+ * Simple query node for attribute-based conditions.
3546
+ */
3547
+ interface SimpleQueryNode extends QueryNode {
3548
+ type: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'like' | 'regex' | 'in' | 'has' | 'contains' | 'containsAll' | 'containsAny';
3549
+ attribute: string;
3550
+ value?: unknown;
3551
+ values?: unknown[];
3552
+ /** For 'between' queries: lower bound */
3553
+ from?: unknown;
3554
+ /** For 'between' queries: upper bound */
3555
+ to?: unknown;
3556
+ /** For 'between' queries: include lower bound (default: true) */
3557
+ fromInclusive?: boolean;
3558
+ /** For 'between' queries: include upper bound (default: false) */
3559
+ toInclusive?: boolean;
3560
+ }
3561
+ /**
3562
+ * Logical query node for combining conditions.
3563
+ */
3564
+ interface LogicalQueryNode {
3565
+ type: 'and' | 'or' | 'not';
3566
+ children?: Query[];
3567
+ child?: Query;
3568
+ }
3569
+ /**
3570
+ * Union type for all query types.
3571
+ */
3572
+ type Query = SimpleQueryNode | LogicalQueryNode;
3573
+ /**
3574
+ * Query execution options for sort/limit/offset.
3575
+ */
3576
+ interface QueryOptions {
3577
+ /** Sort by field(s): field name -> direction */
3578
+ sort?: Record<string, 'asc' | 'desc'>;
3579
+ /** Maximum number of results to return */
3580
+ limit?: number;
3581
+ /** Number of results to skip */
3582
+ offset?: number;
3583
+ }
3584
+ /**
3585
+ * Execution plan step.
3586
+ * Represents a single operation in the query execution plan.
3587
+ */
3588
+ type PlanStep = IndexScanStep | FullScanStep | IntersectionStep | UnionStep | FilterStep | NotStep;
3589
+ /**
3590
+ * Index scan step - retrieves from an index.
3591
+ */
3592
+ interface IndexScanStep {
3593
+ type: 'index-scan';
3594
+ index: Index<unknown, unknown, unknown>;
3595
+ query: IndexQuery<unknown>;
3596
+ }
3597
+ /**
3598
+ * Full scan step - scans all records.
3599
+ */
3600
+ interface FullScanStep {
3601
+ type: 'full-scan';
3602
+ predicate: Query;
3603
+ }
3604
+ /**
3605
+ * Intersection step - AND of multiple result sets.
3606
+ */
3607
+ interface IntersectionStep {
3608
+ type: 'intersection';
3609
+ steps: PlanStep[];
3610
+ }
3611
+ /**
3612
+ * Union step - OR of multiple result sets.
3613
+ */
3614
+ interface UnionStep {
3615
+ type: 'union';
3616
+ steps: PlanStep[];
3617
+ }
3618
+ /**
3619
+ * Filter step - applies predicate to source results.
3620
+ */
3621
+ interface FilterStep {
3622
+ type: 'filter';
3623
+ source: PlanStep;
3624
+ predicate: Query;
3625
+ }
3626
+ /**
3627
+ * NOT step - negation (all keys minus matching keys).
3628
+ */
3629
+ interface NotStep {
3630
+ type: 'not';
3631
+ source: PlanStep;
3632
+ allKeys: () => Set<unknown>;
3633
+ }
3634
+ /**
3635
+ * Complete query execution plan.
3636
+ */
3637
+ interface QueryPlan {
3638
+ /** Root execution step */
3639
+ root: PlanStep;
3640
+ /** Estimated execution cost */
3641
+ estimatedCost: number;
3642
+ /** Whether any index is used */
3643
+ usesIndexes: boolean;
3644
+ /** Whether sort can use index order */
3645
+ indexedSort?: boolean;
3646
+ /** Sort configuration */
3647
+ sort?: {
3648
+ field: string;
3649
+ direction: 'asc' | 'desc';
3650
+ };
3651
+ /** Limit configuration */
3652
+ limit?: number;
3653
+ /** Offset configuration */
3654
+ offset?: number;
3655
+ }
3656
+ /**
3657
+ * Check if a query is a simple query node.
3658
+ */
3659
+ declare function isSimpleQuery(query: Query): query is SimpleQueryNode;
3660
+ /**
3661
+ * Check if a query is a logical query node.
3662
+ */
3663
+ declare function isLogicalQuery(query: Query): query is LogicalQueryNode;
3664
+
3665
+ /**
3666
+ * StandingQueryIndex Implementation
3667
+ *
3668
+ * Pre-computed index for a specific query.
3669
+ * Maintains result set incrementally as data changes.
3670
+ *
3671
+ * Lowest retrieval cost (10) - O(1) query execution.
3672
+ * Critical for Live Queries in TopGun where the same query
3673
+ * is executed repeatedly on every data change.
3674
+ *
3675
+ * CQEngine Reference: StandingQueryIndex.java (retrieval cost: 10)
3676
+ *
3677
+ * @module query/indexes/StandingQueryIndex
3678
+ */
3679
+
3680
+ /**
3681
+ * Change type for standing query updates.
3682
+ */
3683
+ type StandingQueryChange = 'added' | 'removed' | 'updated' | 'unchanged';
3684
+ /**
3685
+ * Options for creating a StandingQueryIndex.
3686
+ */
3687
+ interface StandingQueryIndexOptions<K, V> {
3688
+ /** Query this index answers */
3689
+ query: Query;
3690
+ /** Function to get record by key (optional, for validation) */
3691
+ getRecord?: (key: K) => V | undefined;
3692
+ }
3693
+ /**
3694
+ * Pre-computed index for a specific query.
3695
+ * Maintains result set incrementally as data changes.
3696
+ *
3697
+ * K = record key type, V = record value type
3698
+ */
3699
+ declare class StandingQueryIndex<K, V> implements Index<K, V, unknown> {
3700
+ readonly type: "standing";
3701
+ /**
3702
+ * Wildcard attribute - StandingQueryIndex doesn't index by attribute,
3703
+ * it indexes by query match.
3704
+ */
3705
+ readonly attribute: Attribute<V, unknown>;
3706
+ /** Pre-computed result set */
3707
+ private results;
3708
+ /** Query this index answers */
3709
+ private readonly query;
3710
+ /** Record accessor (optional) */
3711
+ private readonly getRecord?;
3712
+ /** Retrieval cost - lowest of all index types */
3713
+ private static readonly RETRIEVAL_COST;
3714
+ constructor(options: StandingQueryIndexOptions<K, V>);
3715
+ /**
3716
+ * Get the query this index answers.
3717
+ */
3718
+ getQuery(): Query;
3719
+ /**
3720
+ * Check if this index answers the given query.
3721
+ */
3722
+ answersQuery(query: Query): boolean;
3723
+ getRetrievalCost(): number;
3724
+ supportsQuery(_queryType: string): boolean;
3725
+ retrieve(_query: IndexQuery<unknown>): ResultSet<K>;
3726
+ /**
3727
+ * Get current result set (for live query updates).
3728
+ * Returns a copy to avoid external mutation.
3729
+ */
3730
+ getResults(): Set<K>;
3731
+ /**
3732
+ * Get result count.
3733
+ */
3734
+ getResultCount(): number;
3735
+ /**
3736
+ * Check if key is in results.
3737
+ */
3738
+ contains(key: K): boolean;
3739
+ add(key: K, record: V): void;
3740
+ remove(key: K, _record: V): void;
3741
+ update(key: K, oldRecord: V, newRecord: V): void;
3742
+ /**
3743
+ * Determine what changed for a record update.
3744
+ * Returns the type of change relative to the query results.
3745
+ *
3746
+ * @param key - Record key
3747
+ * @param oldRecord - Previous record value (undefined for new records)
3748
+ * @param newRecord - New record value (undefined for deleted records)
3749
+ * @returns Change type: 'added', 'removed', 'updated', or 'unchanged'
3750
+ */
3751
+ determineChange(_key: K, oldRecord: V | undefined, newRecord: V | undefined): StandingQueryChange;
3752
+ clear(): void;
3753
+ getStats(): IndexStats;
3754
+ /**
3755
+ * Build index from existing data.
3756
+ *
3757
+ * @param entries - Iterable of [key, record] pairs
3758
+ */
3759
+ buildFromData(entries: Iterable<[K, V]>): void;
3760
+ /**
3761
+ * Evaluate a record against the query predicate.
3762
+ *
3763
+ * @param record - Record to evaluate
3764
+ * @returns true if record matches the query
3765
+ */
3766
+ private evaluateRecord;
3767
+ /**
3768
+ * Evaluate a query node against a record.
3769
+ * Implements predicate evaluation logic.
3770
+ */
3771
+ private evaluateQuery;
3772
+ /**
3773
+ * Evaluate a simple query (attribute-based condition).
3774
+ */
3775
+ private evaluateSimpleQuery;
3776
+ /**
3777
+ * Evaluate a logical query (AND/OR/NOT).
3778
+ */
3779
+ private evaluateLogicalQuery;
3780
+ /**
3781
+ * Get attribute value from record using dot notation.
3782
+ */
3783
+ private getAttributeValue;
3784
+ /**
3785
+ * Match a value against a LIKE pattern.
3786
+ * Supports % as wildcard for any characters.
3787
+ */
3788
+ private matchLike;
3789
+ /**
3790
+ * Deep equality check for queries.
3791
+ */
3792
+ private queriesEqual;
3793
+ }
3794
+
3795
+ /**
3796
+ * Tokenizer Interface and Implementations
3797
+ *
3798
+ * Provides text tokenization for InvertedIndex full-text search.
3799
+ * Tokenizers split text into searchable tokens.
3800
+ *
3801
+ * @module query/tokenization/Tokenizer
3802
+ */
3803
+ /**
3804
+ * Interface for text tokenizers.
3805
+ * Tokenizers split text into an array of tokens (words, n-grams, etc.)
3806
+ */
3807
+ interface Tokenizer {
3808
+ /**
3809
+ * Split text into tokens.
3810
+ *
3811
+ * @param text - Text to tokenize
3812
+ * @returns Array of tokens
3813
+ */
3814
+ tokenize(text: string): string[];
3815
+ }
3816
+ /**
3817
+ * Tokenizer that splits on whitespace.
3818
+ * Simplest tokenizer - splits on any whitespace characters.
3819
+ *
3820
+ * Example: "hello world" → ["hello", "world"]
3821
+ */
3822
+ declare class WhitespaceTokenizer implements Tokenizer {
3823
+ tokenize(text: string): string[];
3824
+ }
3825
+ /**
3826
+ * Tokenizer that splits on word boundaries.
3827
+ * Splits on non-word characters (anything not [a-zA-Z0-9_]).
3828
+ *
3829
+ * Example: "hello-world! test123" → ["hello", "world", "test123"]
3830
+ */
3831
+ declare class WordBoundaryTokenizer implements Tokenizer {
3832
+ tokenize(text: string): string[];
3833
+ }
3834
+ /**
3835
+ * N-gram tokenizer for substring matching.
3836
+ * Creates overlapping character sequences of length n.
3837
+ *
3838
+ * Example (n=3): "hello" → ["hel", "ell", "llo"]
3839
+ *
3840
+ * Use cases:
3841
+ * - Fuzzy search (typo tolerance)
3842
+ * - Substring matching (contains anywhere)
3843
+ * - Partial word matching
3844
+ */
3845
+ declare class NGramTokenizer implements Tokenizer {
3846
+ private readonly n;
3847
+ /**
3848
+ * Create an N-gram tokenizer.
3849
+ *
3850
+ * @param n - Length of each n-gram (default: 3)
3851
+ */
3852
+ constructor(n?: number);
3853
+ tokenize(text: string): string[];
3854
+ /**
3855
+ * Get the n-gram size.
3856
+ */
3857
+ get size(): number;
3858
+ }
3859
+
3860
+ /**
3861
+ * Token Filter Interface and Implementations
3862
+ *
3863
+ * Token filters transform or filter tokens produced by tokenizers.
3864
+ * Common uses: lowercase normalization, stop word removal, length filtering.
3865
+ *
3866
+ * @module query/tokenization/TokenFilter
3867
+ */
3868
+ /**
3869
+ * Interface for token filters.
3870
+ * Filters transform an array of tokens into another array of tokens.
3871
+ */
3872
+ interface TokenFilter {
3873
+ /**
3874
+ * Apply filter to tokens.
3875
+ *
3876
+ * @param tokens - Input tokens
3877
+ * @returns Filtered tokens
3878
+ */
3879
+ apply(tokens: string[]): string[];
3880
+ }
3881
+ /**
3882
+ * Filter that converts all tokens to lowercase.
3883
+ * Essential for case-insensitive search.
3884
+ *
3885
+ * Example: ["Hello", "WORLD"] → ["hello", "world"]
3886
+ */
3887
+ declare class LowercaseFilter implements TokenFilter {
3888
+ apply(tokens: string[]): string[];
3889
+ }
3890
+ /**
3891
+ * Default English stop words.
3892
+ * Common words that don't add search value.
3893
+ */
3894
+ declare const DEFAULT_STOP_WORDS: string[];
3895
+ /**
3896
+ * Filter that removes stop words.
3897
+ * Stop words are common words that don't contribute to search relevance.
3898
+ *
3899
+ * Example: ["the", "quick", "brown", "fox"] → ["quick", "brown", "fox"]
3900
+ */
3901
+ declare class StopWordFilter implements TokenFilter {
3902
+ private readonly stopWords;
3903
+ /**
3904
+ * Create a stop word filter.
3905
+ *
3906
+ * @param stopWords - Array of stop words to remove (default: English stop words)
3907
+ */
3908
+ constructor(stopWords?: string[]);
3909
+ apply(tokens: string[]): string[];
3910
+ /**
3911
+ * Get the set of stop words.
3912
+ */
3913
+ getStopWords(): Set<string>;
3914
+ }
3915
+ /**
3916
+ * Filter that removes tokens shorter than a minimum length.
3917
+ * Useful for filtering out single characters or very short tokens.
3918
+ *
3919
+ * Example (minLength=3): ["a", "is", "the", "quick"] → ["the", "quick"]
3920
+ */
3921
+ declare class MinLengthFilter implements TokenFilter {
3922
+ private readonly minLength;
3923
+ /**
3924
+ * Create a minimum length filter.
3925
+ *
3926
+ * @param minLength - Minimum token length (default: 2)
3927
+ */
3928
+ constructor(minLength?: number);
3929
+ apply(tokens: string[]): string[];
3930
+ /**
3931
+ * Get the minimum length setting.
3932
+ */
3933
+ getMinLength(): number;
3934
+ }
3935
+ /**
3936
+ * Filter that removes tokens longer than a maximum length.
3937
+ * Useful for preventing very long tokens from being indexed.
3938
+ *
3939
+ * Example (maxLength=10): ["short", "verylongword"] → ["short"]
3940
+ */
3941
+ declare class MaxLengthFilter implements TokenFilter {
3942
+ private readonly maxLength;
3943
+ /**
3944
+ * Create a maximum length filter.
3945
+ *
3946
+ * @param maxLength - Maximum token length (default: 50)
3947
+ */
3948
+ constructor(maxLength?: number);
3949
+ apply(tokens: string[]): string[];
3950
+ /**
3951
+ * Get the maximum length setting.
3952
+ */
3953
+ getMaxLength(): number;
3954
+ }
3955
+ /**
3956
+ * Filter that trims whitespace from tokens.
3957
+ * Ensures clean tokens without leading/trailing spaces.
3958
+ */
3959
+ declare class TrimFilter implements TokenFilter {
3960
+ apply(tokens: string[]): string[];
3961
+ }
3962
+ /**
3963
+ * Filter that removes duplicate tokens.
3964
+ * Useful for reducing index size when tokens repeat.
3965
+ *
3966
+ * Example: ["hello", "world", "hello"] → ["hello", "world"]
3967
+ */
3968
+ declare class UniqueFilter implements TokenFilter {
3969
+ apply(tokens: string[]): string[];
3970
+ }
3971
+
3972
+ /**
3973
+ * Tokenization Pipeline
3974
+ *
3975
+ * Chains a tokenizer with multiple filters for text processing.
3976
+ * Provides factory methods for common configurations.
3977
+ *
3978
+ * @module query/tokenization/TokenizationPipeline
3979
+ */
3980
+
3981
+ /**
3982
+ * Pipeline configuration options.
3983
+ */
3984
+ interface TokenizationPipelineOptions {
3985
+ /** Tokenizer to use */
3986
+ tokenizer: Tokenizer;
3987
+ /** Filters to apply (in order) */
3988
+ filters?: TokenFilter[];
3989
+ }
3990
+ /**
3991
+ * Tokenization pipeline that chains a tokenizer with filters.
3992
+ *
3993
+ * Processing order:
3994
+ * 1. Tokenizer splits text into tokens
3995
+ * 2. Each filter transforms the token array in sequence
3996
+ *
3997
+ * Example:
3998
+ * ```typescript
3999
+ * const pipeline = TokenizationPipeline.simple();
4000
+ * pipeline.process("Hello World!"); // ["hello", "world"]
4001
+ * ```
4002
+ */
4003
+ declare class TokenizationPipeline {
4004
+ private readonly tokenizer;
4005
+ private readonly filters;
4006
+ /**
4007
+ * Create a tokenization pipeline.
4008
+ *
4009
+ * @param options - Pipeline configuration
4010
+ */
4011
+ constructor(options: TokenizationPipelineOptions);
4012
+ /**
4013
+ * Process text through the pipeline.
4014
+ *
4015
+ * @param text - Text to process
4016
+ * @returns Array of processed tokens
4017
+ */
4018
+ process(text: string): string[];
4019
+ /**
4020
+ * Get the tokenizer.
4021
+ */
4022
+ getTokenizer(): Tokenizer;
4023
+ /**
4024
+ * Get the filters.
4025
+ */
4026
+ getFilters(): TokenFilter[];
4027
+ /**
4028
+ * Create a simple pipeline with common defaults.
4029
+ * Uses word boundary tokenizer with lowercase and minimum length filters.
4030
+ *
4031
+ * Configuration:
4032
+ * - Tokenizer: WordBoundaryTokenizer
4033
+ * - Filters: LowercaseFilter, MinLengthFilter(2)
4034
+ *
4035
+ * @returns Simple tokenization pipeline
4036
+ */
4037
+ static simple(): TokenizationPipeline;
4038
+ /**
4039
+ * Create a pipeline optimized for search.
4040
+ * Includes stop word removal for better search relevance.
4041
+ *
4042
+ * Configuration:
4043
+ * - Tokenizer: WordBoundaryTokenizer
4044
+ * - Filters: LowercaseFilter, MinLengthFilter(2), StopWordFilter
4045
+ *
4046
+ * @returns Search-optimized tokenization pipeline
4047
+ */
4048
+ static search(): TokenizationPipeline;
4049
+ /**
4050
+ * Create a minimal pipeline with just tokenization and lowercase.
4051
+ * No filtering - preserves all tokens.
4052
+ *
4053
+ * Configuration:
4054
+ * - Tokenizer: WordBoundaryTokenizer
4055
+ * - Filters: LowercaseFilter
4056
+ *
4057
+ * @returns Minimal tokenization pipeline
4058
+ */
4059
+ static minimal(): TokenizationPipeline;
4060
+ /**
4061
+ * Create a custom pipeline from a tokenizer and filters.
4062
+ *
4063
+ * @param tokenizer - Tokenizer to use
4064
+ * @param filters - Filters to apply
4065
+ * @returns Custom tokenization pipeline
4066
+ */
4067
+ static custom(tokenizer: Tokenizer, filters?: TokenFilter[]): TokenizationPipeline;
4068
+ }
4069
+
4070
+ /**
4071
+ * InvertedIndex Implementation
4072
+ *
4073
+ * Full-text search index using inverted index structure.
4074
+ * Supports: contains, containsAll, containsAny, has queries.
4075
+ *
4076
+ * Structure:
4077
+ * tokenIndex: Map<Token, Set<RecordKey>>
4078
+ * reverseIndex: Map<RecordKey, Set<Token>>
4079
+ *
4080
+ * Retrieval cost: 50 (between NavigableIndex:40 and FallbackIndex)
4081
+ *
4082
+ * @module query/indexes/InvertedIndex
4083
+ */
4084
+
4085
+ /**
4086
+ * Extended statistics for InvertedIndex.
4087
+ */
4088
+ interface InvertedIndexStats extends IndexStats {
4089
+ /** Total unique tokens in the index */
4090
+ totalTokens: number;
4091
+ /** Average number of tokens per indexed document */
4092
+ avgTokensPerDocument: number;
4093
+ /** Maximum documents for any single token */
4094
+ maxDocumentsPerToken: number;
4095
+ }
4096
+ /**
4097
+ * Inverted index for full-text search.
4098
+ * Maps tokens to sets of document keys for O(K) query performance.
4099
+ *
4100
+ * K = record key type, V = record value type, A = attribute value type (should be string)
4101
+ */
4102
+ declare class InvertedIndex<K, V, A extends string = string> implements Index<K, V, A> {
4103
+ readonly attribute: Attribute<V, A>;
4104
+ private readonly pipeline;
4105
+ readonly type: "inverted";
4106
+ /** Token → Set of keys */
4107
+ private tokenIndex;
4108
+ /** Key → Set of tokens (for efficient removal/update) */
4109
+ private reverseIndex;
4110
+ /** All keys with indexed content */
4111
+ private allKeys;
4112
+ private static readonly RETRIEVAL_COST;
4113
+ private static readonly SUPPORTED_QUERIES;
4114
+ /**
4115
+ * Create an InvertedIndex.
4116
+ *
4117
+ * @param attribute - Attribute to index (should return string values)
4118
+ * @param pipeline - Tokenization pipeline (default: simple pipeline)
4119
+ */
4120
+ constructor(attribute: Attribute<V, A>, pipeline?: TokenizationPipeline);
4121
+ getRetrievalCost(): number;
4122
+ supportsQuery(queryType: string): boolean;
4123
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
4124
+ /**
4125
+ * Retrieve documents containing all tokens from the search text.
4126
+ * Uses AND semantics - document must contain ALL tokens.
4127
+ */
4128
+ private retrieveContains;
4129
+ /**
4130
+ * Retrieve documents containing ALL specified values.
4131
+ * Each value is tokenized, and ALL resulting tokens must match.
4132
+ */
4133
+ private retrieveContainsAll;
4134
+ /**
4135
+ * Retrieve documents containing ANY of the specified values.
4136
+ * Uses OR semantics - document can contain any token from any value.
4137
+ */
4138
+ private retrieveContainsAny;
4139
+ /**
4140
+ * Retrieve all documents with indexed content.
4141
+ */
4142
+ private retrieveHas;
4143
+ add(key: K, record: V): void;
4144
+ remove(key: K, _record: V): void;
4145
+ update(key: K, oldRecord: V, newRecord: V): void;
4146
+ clear(): void;
4147
+ getStats(): IndexStats;
4148
+ /**
4149
+ * Get extended statistics for full-text index.
4150
+ */
4151
+ getExtendedStats(): InvertedIndexStats;
4152
+ /**
4153
+ * Get the tokenization pipeline.
4154
+ */
4155
+ getPipeline(): TokenizationPipeline;
4156
+ /**
4157
+ * Check if a specific token exists in the index.
4158
+ */
4159
+ hasToken(token: string): boolean;
4160
+ /**
4161
+ * Get the number of documents for a specific token.
4162
+ */
4163
+ getTokenDocumentCount(token: string): number;
4164
+ private valuesEqual;
4165
+ }
4166
+
4167
+ /**
4168
+ * CompoundIndex Implementation (Phase 9.03)
4169
+ *
4170
+ * Multi-attribute index for optimizing AND queries.
4171
+ * Creates a composite key from multiple attribute values for O(1) lookup.
4172
+ *
4173
+ * Benefits:
4174
+ * - 100-1000× speedup for compound AND queries
4175
+ * - Eliminates ResultSet intersection overhead
4176
+ * - Single lookup instead of multiple index scans
4177
+ *
4178
+ * @module query/indexes/CompoundIndex
4179
+ */
4180
+
4181
+ /**
4182
+ * Options for compound index creation.
4183
+ */
4184
+ interface CompoundIndexOptions {
4185
+ /**
4186
+ * Separator for composite key generation.
4187
+ * Default: '|'
4188
+ * Choose a separator that won't appear in attribute values.
4189
+ */
4190
+ separator?: string;
4191
+ }
4192
+ /**
4193
+ * Compound index for O(1) multi-attribute queries.
4194
+ * Indexes multiple attributes as a single composite key.
4195
+ *
4196
+ * K = record key type, V = record value type
4197
+ */
4198
+ declare class CompoundIndex<K, V> implements Index<K, V, unknown> {
4199
+ readonly type: "compound";
4200
+ /** Attributes that make up this compound index (in order) */
4201
+ private readonly _attributes;
4202
+ /** Map from composite key to set of record keys */
4203
+ private data;
4204
+ /** Set of all indexed keys */
4205
+ private allKeys;
4206
+ /** Key separator */
4207
+ private readonly separator;
4208
+ /** Retrieval cost (lower than individual indexes combined) */
4209
+ private static readonly RETRIEVAL_COST;
4210
+ /**
4211
+ * Create a CompoundIndex.
4212
+ *
4213
+ * @param attributes - Array of attributes to index (order matters!)
4214
+ * @param options - Optional configuration
4215
+ *
4216
+ * @example
4217
+ * ```typescript
4218
+ * const statusAttr = simpleAttribute<Product, string>('status', p => p.status);
4219
+ * const categoryAttr = simpleAttribute<Product, string>('category', p => p.category);
4220
+ *
4221
+ * const compoundIndex = new CompoundIndex<string, Product>([statusAttr, categoryAttr]);
4222
+ * ```
4223
+ */
4224
+ constructor(attributes: Attribute<V, unknown>[], options?: CompoundIndexOptions);
4225
+ /**
4226
+ * Get the first attribute (used for Index interface compatibility).
4227
+ * Note: CompoundIndex spans multiple attributes.
4228
+ */
4229
+ get attribute(): Attribute<V, unknown>;
4230
+ /**
4231
+ * Get all attributes in this compound index.
4232
+ */
4233
+ get attributes(): Attribute<V, unknown>[];
4234
+ /**
4235
+ * Get attribute names as a combined identifier.
4236
+ */
4237
+ get compoundName(): string;
4238
+ getRetrievalCost(): number;
4239
+ supportsQuery(queryType: string): boolean;
4240
+ /**
4241
+ * Retrieve records matching compound query.
4242
+ *
4243
+ * @param query - Compound query with values matching each attribute
4244
+ * @returns ResultSet of matching keys
4245
+ *
4246
+ * @example
4247
+ * ```typescript
4248
+ * // Find products where status='active' AND category='electronics'
4249
+ * index.retrieve({
4250
+ * type: 'compound',
4251
+ * values: ['active', 'electronics']
4252
+ * });
4253
+ * ```
4254
+ */
4255
+ retrieve(query: IndexQuery<unknown>): ResultSet<K>;
4256
+ /**
4257
+ * Retrieve with explicit values (convenience method).
4258
+ *
4259
+ * @param values - Values in order of index attributes
4260
+ * @returns ResultSet of matching keys
4261
+ */
4262
+ retrieveByValues(...values: unknown[]): ResultSet<K>;
4263
+ add(key: K, record: V): void;
4264
+ remove(key: K, record: V): void;
4265
+ update(key: K, oldRecord: V, newRecord: V): void;
4266
+ clear(): void;
4267
+ getStats(): IndexStats;
4268
+ /**
4269
+ * Get extended statistics for compound index.
4270
+ */
4271
+ getExtendedStats(): CompoundIndexStats;
4272
+ /**
4273
+ * Check if this compound index can answer a query on the given attributes.
4274
+ * Compound indexes can be used if query attributes match in prefix order.
4275
+ *
4276
+ * @param attributeNames - Attribute names being queried
4277
+ * @returns true if this index can answer the query
4278
+ */
4279
+ canAnswerQuery(attributeNames: string[]): boolean;
4280
+ /**
4281
+ * Build composite key from array of values.
4282
+ */
4283
+ private buildCompositeKey;
4284
+ /**
4285
+ * Build composite key from record by extracting attribute values.
4286
+ * Returns null if any attribute value is undefined.
4287
+ */
4288
+ private buildCompositeKeyFromRecord;
4289
+ /**
4290
+ * Encode value for composite key.
4291
+ * Handles common types and escapes separator.
4292
+ */
4293
+ private encodeValue;
4294
+ /**
4295
+ * Escape regex special characters.
4296
+ */
4297
+ private escapeRegex;
4298
+ }
4299
+ /**
4300
+ * Extended statistics for compound index.
4301
+ */
4302
+ interface CompoundIndexStats extends IndexStats {
4303
+ /** Number of attributes in compound key */
4304
+ attributeCount: number;
4305
+ /** Names of indexed attributes */
4306
+ attributeNames: string[];
4307
+ /** Number of unique composite keys */
4308
+ compositeKeyCount: number;
4309
+ }
4310
+
4311
+ /**
4312
+ * Types for Adaptive Indexing System (Phase 8.02)
4313
+ *
4314
+ * Defines interfaces for query pattern tracking, index suggestions,
4315
+ * and auto-indexing configuration.
4316
+ *
4317
+ * @module query/adaptive/types
4318
+ */
4319
+ /**
4320
+ * Query type for pattern tracking.
4321
+ * Matches the query types from QueryTypes.ts and indexes/types.ts
4322
+ */
4323
+ type TrackedQueryType = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'in' | 'has' | 'contains' | 'containsAll' | 'containsAny' | 'compound';
4324
+ /**
4325
+ * Statistics for a single attribute + query type combination.
4326
+ */
4327
+ interface QueryStatistics {
4328
+ /** Attribute name being queried */
4329
+ attribute: string;
4330
+ /** Type of query (eq, gt, between, etc.) */
4331
+ queryType: TrackedQueryType;
4332
+ /** Number of times this pattern was queried */
4333
+ queryCount: number;
4334
+ /** Cumulative execution time in milliseconds */
4335
+ totalCost: number;
4336
+ /** Average execution time per query */
4337
+ averageCost: number;
4338
+ /** Timestamp of last query */
4339
+ lastQueried: number;
4340
+ /** Estimated result size (max observed) */
4341
+ estimatedCardinality: number;
4342
+ /** Whether an index exists for this attribute */
4343
+ hasIndex: boolean;
4344
+ }
4345
+ /**
4346
+ * Statistics for compound query patterns (Phase 9.03).
4347
+ * Tracks AND combinations of attributes for compound index suggestions.
4348
+ */
4349
+ interface CompoundQueryStatistics {
4350
+ /** Attribute names in the compound query (sorted) */
4351
+ attributes: string[];
4352
+ /** Combined key for identification */
4353
+ compoundKey: string;
4354
+ /** Number of times this pattern was queried */
4355
+ queryCount: number;
4356
+ /** Cumulative execution time in milliseconds */
4357
+ totalCost: number;
4358
+ /** Average execution time per query */
4359
+ averageCost: number;
4360
+ /** Timestamp of last query */
4361
+ lastQueried: number;
4362
+ /** Whether a compound index exists for this combination */
4363
+ hasCompoundIndex: boolean;
4364
+ }
4365
+ /**
4366
+ * Index type recommendation.
4367
+ */
4368
+ type RecommendedIndexType = 'hash' | 'navigable' | 'inverted' | 'compound';
4369
+ /**
4370
+ * Priority level for index suggestions.
4371
+ */
4372
+ type SuggestionPriority = 'high' | 'medium' | 'low';
4373
+ /**
4374
+ * Index suggestion generated by IndexAdvisor.
4375
+ */
4376
+ interface IndexSuggestion {
4377
+ /** Attribute to index (or compound key for compound indexes) */
4378
+ attribute: string;
4379
+ /** Recommended index type */
4380
+ indexType: RecommendedIndexType;
4381
+ /** Human-readable explanation */
4382
+ reason: string;
4383
+ /** Expected performance improvement multiplier */
4384
+ estimatedBenefit: number;
4385
+ /** Estimated memory overhead in bytes */
4386
+ estimatedCost: number;
4387
+ /** Priority based on query patterns */
4388
+ priority: SuggestionPriority;
4389
+ /** Query count that triggered this suggestion */
4390
+ queryCount: number;
4391
+ /** Average query cost in milliseconds */
4392
+ averageCost: number;
4393
+ /** For compound indexes: array of attribute names in order */
4394
+ compoundAttributes?: string[];
4395
+ }
4396
+ /**
4397
+ * Options for getting index suggestions.
4398
+ */
4399
+ interface IndexSuggestionOptions {
4400
+ /** Minimum query count to consider (default: 10) */
4401
+ minQueryCount?: number;
4402
+ /** Minimum average cost in ms to consider (default: 1) */
4403
+ minAverageCost?: number;
4404
+ /** Whether to exclude already indexed attributes (default: true) */
4405
+ excludeExistingIndexes?: boolean;
4406
+ /** Maximum number of suggestions to return (default: unlimited) */
4407
+ maxSuggestions?: number;
4408
+ }
4409
+ /**
4410
+ * Configuration for Index Advisor.
4411
+ */
4412
+ interface AdvisorConfig {
4413
+ /** Enable advisor mode (default: true) */
4414
+ enabled: boolean;
4415
+ /** Minimum query count before suggesting (default: 10) */
4416
+ minQueryCount?: number;
4417
+ /** Minimum average cost in ms to suggest (default: 1) */
4418
+ minAverageCost?: number;
4419
+ }
4420
+ /**
4421
+ * Callback for index creation events.
4422
+ */
4423
+ type IndexCreatedCallback = (attribute: string, indexType: RecommendedIndexType) => void;
4424
+ /**
4425
+ * Configuration for Auto-Index Manager.
4426
+ */
4427
+ interface AutoIndexConfig {
4428
+ /** Enable auto-indexing (default: false) */
4429
+ enabled: boolean;
4430
+ /** Number of queries before auto-creating index (default: 10) */
4431
+ threshold?: number;
4432
+ /** Maximum number of auto-created indexes (default: 20) */
4433
+ maxIndexes?: number;
4434
+ /** Callback when index is automatically created */
4435
+ onIndexCreated?: IndexCreatedCallback;
4436
+ }
4437
+ /**
4438
+ * Default indexing strategy.
4439
+ * - 'none': No automatic indexing (default)
4440
+ * - 'scalar': Index all top-level scalar (primitive) fields
4441
+ * - 'all': Index all fields including nested (not recommended)
4442
+ */
4443
+ type DefaultIndexingStrategy = 'none' | 'scalar' | 'all';
4444
+ /**
4445
+ * Complete adaptive indexing configuration.
4446
+ */
4447
+ interface AdaptiveIndexingConfig {
4448
+ /** Index Advisor configuration */
4449
+ advisor?: AdvisorConfig;
4450
+ /** Auto-Index Manager configuration */
4451
+ autoIndex?: AutoIndexConfig;
4452
+ }
4453
+ /**
4454
+ * Progress callback for lazy index building (Phase 9.01).
4455
+ */
4456
+ type IndexBuildProgressCallback = (attributeName: string, progress: number, // 0-100
4457
+ recordsProcessed: number, totalRecords: number) => void;
4458
+ /**
4459
+ * Extended options for IndexedLWWMap/IndexedORMap.
4460
+ */
4461
+ interface IndexedMapOptions {
4462
+ /** Adaptive indexing configuration */
4463
+ adaptiveIndexing?: AdaptiveIndexingConfig;
4464
+ /** Default indexing strategy (default: 'none') */
4465
+ defaultIndexing?: DefaultIndexingStrategy;
4466
+ /**
4467
+ * Enable lazy index building (Phase 9.01).
4468
+ * When true, indexes are not built until first query.
4469
+ * Default: false
4470
+ */
4471
+ lazyIndexBuilding?: boolean;
4472
+ /**
4473
+ * Callback for index building progress (Phase 9.01).
4474
+ * Called during lazy index materialization.
4475
+ */
4476
+ onIndexBuilding?: IndexBuildProgressCallback;
4477
+ }
4478
+
4479
+ /**
4480
+ * Lazy Index Types
4481
+ *
4482
+ * Types and interfaces for lazy index building (Phase 9.01).
4483
+ * Lazy indexes defer actual index construction until first query.
4484
+ *
4485
+ * @module query/indexes/lazy/types
4486
+ */
4487
+
4488
+ /**
4489
+ * Extended interface for lazy indexes.
4490
+ * Adds lazy-specific properties and methods.
4491
+ */
4492
+ interface LazyIndex<K, V, A = unknown> extends Index<K, V, A> {
4493
+ /**
4494
+ * Whether the index has been materialized (built).
4495
+ */
4496
+ readonly isBuilt: boolean;
4497
+ /**
4498
+ * Number of pending records awaiting materialization.
4499
+ */
4500
+ readonly pendingCount: number;
4501
+ /**
4502
+ * Force materialization of the index.
4503
+ * Called automatically on first query, but can be called manually.
4504
+ *
4505
+ * @param progressCallback - Optional progress callback
4506
+ */
4507
+ materialize(progressCallback?: IndexBuildProgressCallback): void;
4508
+ /**
4509
+ * Check if this is a lazy index wrapper.
4510
+ */
4511
+ readonly isLazy: true;
4512
+ }
4513
+ /**
4514
+ * Options for lazy index creation.
4515
+ */
4516
+ interface LazyIndexOptions {
4517
+ /**
4518
+ * Progress callback for index building.
4519
+ */
4520
+ onProgress?: IndexBuildProgressCallback;
4521
+ /**
4522
+ * Batch size for progress reporting.
4523
+ * Default: 1000
4524
+ */
4525
+ progressBatchSize?: number;
4526
+ }
4527
+
4528
+ /**
4529
+ * LazyHashIndex Implementation
4530
+ *
4531
+ * Hash-based index with deferred building (Phase 9.01).
4532
+ * Records are buffered until first query, then index is materialized.
4533
+ *
4534
+ * Benefits:
4535
+ * - Fast application startup (indexes built on-demand)
4536
+ * - Memory efficiency (unused indexes not built)
4537
+ * - Bulk import optimization (no index overhead during import)
4538
+ *
4539
+ * @module query/indexes/lazy/LazyHashIndex
4540
+ */
4541
+
4542
+ /**
4543
+ * Lazy hash-based index for O(1) equality lookups.
4544
+ * Defers index construction until first query.
4545
+ *
4546
+ * K = record key type, V = record value type, A = attribute value type
4547
+ */
4548
+ declare class LazyHashIndex<K, V, A> implements LazyIndex<K, V, A> {
4549
+ readonly attribute: Attribute<V, A>;
4550
+ readonly type: "hash";
4551
+ readonly isLazy: true;
4552
+ /** Underlying hash index (created on first query) */
4553
+ private innerIndex;
4554
+ /** Pending records before materialization */
4555
+ private pendingRecords;
4556
+ /** Track if index has been built */
4557
+ private built;
4558
+ /** Progress callback */
4559
+ private readonly onProgress?;
4560
+ /** Batch size for progress reporting */
4561
+ private readonly progressBatchSize;
4562
+ constructor(attribute: Attribute<V, A>, options?: LazyIndexOptions);
4563
+ get isBuilt(): boolean;
4564
+ get pendingCount(): number;
4565
+ getRetrievalCost(): number;
4566
+ supportsQuery(queryType: string): boolean;
4567
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
4568
+ add(key: K, record: V): void;
4569
+ remove(key: K, record: V): void;
4570
+ update(key: K, oldRecord: V, newRecord: V): void;
4571
+ clear(): void;
4572
+ getStats(): IndexStats;
4573
+ /**
4574
+ * Force materialization of the index.
4575
+ * Called automatically on first query.
4576
+ */
4577
+ materialize(progressCallback?: IndexBuildProgressCallback): void;
4578
+ /**
4579
+ * Get the underlying HashIndex (for testing/debugging).
4580
+ * Returns null if not yet materialized.
4581
+ */
4582
+ getInnerIndex(): HashIndex<K, V, A> | null;
4583
+ }
4584
+
4585
+ /**
4586
+ * LazyNavigableIndex Implementation
4587
+ *
4588
+ * Sorted index with deferred building (Phase 9.01).
4589
+ * Records are buffered until first query, then index is materialized.
4590
+ *
4591
+ * Benefits:
4592
+ * - Fast application startup (indexes built on-demand)
4593
+ * - Memory efficiency (unused indexes not built)
4594
+ * - Bulk import optimization (no index overhead during import)
4595
+ *
4596
+ * @module query/indexes/lazy/LazyNavigableIndex
4597
+ */
4598
+
4599
+ /**
4600
+ * Lazy sorted index for O(log N) range queries.
4601
+ * Defers index construction until first query.
4602
+ *
4603
+ * K = record key type, V = record value type, A = attribute value type (must be orderable)
4604
+ */
4605
+ declare class LazyNavigableIndex<K, V, A extends string | number> implements LazyIndex<K, V, A> {
4606
+ readonly attribute: Attribute<V, A>;
4607
+ readonly type: "navigable";
4608
+ readonly isLazy: true;
4609
+ /** Underlying navigable index (created on first query) */
4610
+ private innerIndex;
4611
+ /** Pending records before materialization */
4612
+ private pendingRecords;
4613
+ /** Track if index has been built */
4614
+ private built;
4615
+ /** Custom comparator (stored for later index creation) */
4616
+ private readonly comparator?;
4617
+ /** Progress callback */
4618
+ private readonly onProgress?;
4619
+ /** Batch size for progress reporting */
4620
+ private readonly progressBatchSize;
4621
+ constructor(attribute: Attribute<V, A>, comparator?: Comparator<A>, options?: LazyIndexOptions);
4622
+ get isBuilt(): boolean;
4623
+ get pendingCount(): number;
4624
+ getRetrievalCost(): number;
4625
+ supportsQuery(queryType: string): boolean;
4626
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
4627
+ add(key: K, record: V): void;
4628
+ remove(key: K, record: V): void;
4629
+ update(key: K, oldRecord: V, newRecord: V): void;
4630
+ clear(): void;
4631
+ getStats(): IndexStats;
4632
+ /**
4633
+ * Force materialization of the index.
4634
+ * Called automatically on first query.
4635
+ */
4636
+ materialize(progressCallback?: IndexBuildProgressCallback): void;
4637
+ /**
4638
+ * Get the underlying NavigableIndex (for testing/debugging).
4639
+ * Returns null if not yet materialized.
4640
+ */
4641
+ getInnerIndex(): NavigableIndex<K, V, A> | null;
4642
+ /**
4643
+ * Get the minimum indexed value.
4644
+ * Forces materialization if not built.
4645
+ */
4646
+ getMinValue(): A | undefined;
4647
+ /**
4648
+ * Get the maximum indexed value.
4649
+ * Forces materialization if not built.
4650
+ */
4651
+ getMaxValue(): A | undefined;
4652
+ }
4653
+
4654
+ /**
4655
+ * LazyInvertedIndex Implementation
4656
+ *
4657
+ * Full-text search index with deferred building (Phase 9.01).
4658
+ * Records are buffered until first query, then index is materialized.
4659
+ *
4660
+ * Benefits:
4661
+ * - Fast application startup (indexes built on-demand)
4662
+ * - Memory efficiency (unused indexes not built)
4663
+ * - Bulk import optimization (no index overhead during import)
4664
+ *
4665
+ * @module query/indexes/lazy/LazyInvertedIndex
4666
+ */
4667
+
4668
+ /**
4669
+ * Lazy inverted index for full-text search.
4670
+ * Defers index construction until first query.
4671
+ *
4672
+ * K = record key type, V = record value type, A = attribute value type (should be string)
4673
+ */
4674
+ declare class LazyInvertedIndex<K, V, A extends string = string> implements LazyIndex<K, V, A> {
4675
+ readonly attribute: Attribute<V, A>;
4676
+ readonly type: "inverted";
4677
+ readonly isLazy: true;
4678
+ /** Underlying inverted index (created on first query) */
4679
+ private innerIndex;
4680
+ /** Pending records before materialization */
4681
+ private pendingRecords;
4682
+ /** Track if index has been built */
4683
+ private built;
4684
+ /** Tokenization pipeline (stored for later index creation) */
4685
+ private readonly pipeline;
4686
+ /** Progress callback */
4687
+ private readonly onProgress?;
4688
+ /** Batch size for progress reporting */
4689
+ private readonly progressBatchSize;
4690
+ constructor(attribute: Attribute<V, A>, pipeline?: TokenizationPipeline, options?: LazyIndexOptions);
4691
+ get isBuilt(): boolean;
4692
+ get pendingCount(): number;
4693
+ getRetrievalCost(): number;
4694
+ supportsQuery(queryType: string): boolean;
4695
+ retrieve(query: IndexQuery<A>): ResultSet<K>;
4696
+ add(key: K, record: V): void;
4697
+ remove(key: K, record: V): void;
4698
+ update(key: K, oldRecord: V, newRecord: V): void;
4699
+ clear(): void;
4700
+ getStats(): IndexStats;
4701
+ /**
4702
+ * Get extended statistics for full-text index.
4703
+ * Forces materialization if not built.
4704
+ */
4705
+ getExtendedStats(): InvertedIndexStats;
4706
+ /**
4707
+ * Force materialization of the index.
4708
+ * Called automatically on first query.
4709
+ */
4710
+ materialize(progressCallback?: IndexBuildProgressCallback): void;
4711
+ /**
4712
+ * Get the underlying InvertedIndex (for testing/debugging).
4713
+ * Returns null if not yet materialized.
4714
+ */
4715
+ getInnerIndex(): InvertedIndex<K, V, A> | null;
4716
+ /**
4717
+ * Get the tokenization pipeline.
4718
+ */
4719
+ getPipeline(): TokenizationPipeline;
4720
+ /**
4721
+ * Check if a specific token exists in the index.
4722
+ * Forces materialization if not built.
4723
+ */
4724
+ hasToken(token: string): boolean;
4725
+ /**
4726
+ * Get the number of documents for a specific token.
4727
+ * Forces materialization if not built.
4728
+ */
4729
+ getTokenDocumentCount(token: string): number;
4730
+ }
4731
+
4732
+ /**
4733
+ * SetResultSet Implementation
4734
+ *
4735
+ * ResultSet backed by a Set, used for HashIndex results.
4736
+ *
4737
+ * @module query/resultset/SetResultSet
4738
+ */
4739
+
4740
+ /**
4741
+ * ResultSet backed by a Set.
4742
+ * Provides O(1) contains() check and direct iteration.
4743
+ */
4744
+ declare class SetResultSet<K> implements ResultSet<K> {
4745
+ private readonly keys;
4746
+ private readonly retrievalCost;
4747
+ constructor(keys: Set<K>, retrievalCost: number);
4748
+ [Symbol.iterator](): Iterator<K>;
4749
+ getRetrievalCost(): number;
4750
+ getMergeCost(): number;
4751
+ contains(key: K): boolean;
4752
+ size(): number;
4753
+ toArray(): K[];
4754
+ isEmpty(): boolean;
4755
+ }
4756
+
4757
+ /**
4758
+ * LazyResultSet Implementation
4759
+ *
4760
+ * Lazily evaluated result set for range queries.
4761
+ * Used when materializing all results upfront would be expensive.
4762
+ *
4763
+ * @module query/resultset/LazyResultSet
4764
+ */
4765
+
4766
+ /**
4767
+ * Factory function type that creates a generator for lazy iteration.
4768
+ */
4769
+ type IteratorFactory<K> = () => Generator<K>;
4770
+ /**
4771
+ * Lazily evaluated result set.
4772
+ * Used for range queries where materializing all results upfront is expensive.
4773
+ *
4774
+ * K = record key type
4775
+ */
4776
+ declare class LazyResultSet<K> implements ResultSet<K> {
4777
+ private readonly iteratorFactory;
4778
+ private readonly retrievalCost;
4779
+ private readonly estimatedSize;
4780
+ /** Cached materialized results */
4781
+ private cached;
4782
+ /**
4783
+ * Create a LazyResultSet.
4784
+ *
4785
+ * @param iteratorFactory - Factory that creates a fresh generator each time
4786
+ * @param retrievalCost - Cost of retrieving results from the index
4787
+ * @param estimatedSize - Estimated result count for merge cost calculation
4788
+ */
4789
+ constructor(iteratorFactory: IteratorFactory<K>, retrievalCost: number, estimatedSize: number);
4790
+ [Symbol.iterator](): Generator<K>;
4791
+ getRetrievalCost(): number;
4792
+ getMergeCost(): number;
4793
+ contains(key: K): boolean;
4794
+ size(): number;
4795
+ toArray(): K[];
4796
+ isEmpty(): boolean;
4797
+ /**
4798
+ * Check if the result set has been materialized.
4799
+ * Useful for testing lazy evaluation behavior.
4800
+ */
4801
+ isMaterialized(): boolean;
4802
+ /**
4803
+ * Force materialization of the result set.
4804
+ * Returns the cached array.
4805
+ */
4806
+ materialize(): K[];
4807
+ /**
4808
+ * Get the estimated size before materialization.
4809
+ */
4810
+ getEstimatedSize(): number;
4811
+ }
4812
+
4813
+ /**
4814
+ * IntersectionResultSet Implementation
4815
+ *
4816
+ * Intersection of multiple result sets (AND logic).
4817
+ * Implements CQEngine "smallest first" strategy:
4818
+ * iterate the smallest set, check membership in others.
4819
+ *
4820
+ * @module query/resultset/IntersectionResultSet
4821
+ */
4822
+
4823
+ /**
4824
+ * Intersection of multiple result sets (AND logic).
4825
+ * CQEngine strategy: iterate smallest set, check membership in others.
4826
+ *
4827
+ * K = record key type
4828
+ */
4829
+ declare class IntersectionResultSet<K> implements ResultSet<K> {
4830
+ /** Cached materialized results */
4831
+ private cached;
4832
+ /** Result sets sorted by merge cost */
4833
+ private sortedResultSets;
4834
+ /**
4835
+ * Create an IntersectionResultSet.
4836
+ *
4837
+ * @param resultSets - Result sets to intersect
4838
+ */
4839
+ constructor(resultSets: ResultSet<K>[]);
4840
+ /**
4841
+ * Lazy iteration over intersection.
4842
+ * Iterates smallest set, yields only keys present in all sets.
4843
+ */
4844
+ [Symbol.iterator](): Generator<K>;
4845
+ /**
4846
+ * Retrieval cost is minimum of all (we only iterate smallest).
4847
+ */
4848
+ getRetrievalCost(): number;
4849
+ /**
4850
+ * Merge cost is estimated as smallest set size (upper bound).
4851
+ */
4852
+ getMergeCost(): number;
4853
+ /**
4854
+ * Check if key is in all result sets.
4855
+ */
4856
+ contains(key: K): boolean;
4857
+ /**
4858
+ * Get size by materializing results.
4859
+ */
4860
+ size(): number;
4861
+ /**
4862
+ * Materialize to array with caching.
4863
+ */
4864
+ toArray(): K[];
4865
+ /**
4866
+ * Check if empty (tries to avoid full materialization).
4867
+ */
4868
+ isEmpty(): boolean;
4869
+ /**
4870
+ * Check if results have been materialized.
4871
+ */
4872
+ isMaterialized(): boolean;
4873
+ }
4874
+
4875
+ /**
4876
+ * UnionResultSet Implementation
4877
+ *
4878
+ * Union of multiple result sets (OR logic).
4879
+ * Deduplicates results using a Set during iteration.
4880
+ *
4881
+ * @module query/resultset/UnionResultSet
4882
+ */
4883
+
4884
+ /**
4885
+ * Union of multiple result sets (OR logic).
4886
+ * Deduplicates results.
4887
+ *
4888
+ * K = record key type
4889
+ */
4890
+ declare class UnionResultSet<K> implements ResultSet<K> {
4891
+ private readonly resultSets;
4892
+ /** Cached materialized results */
4893
+ private cached;
4894
+ /**
4895
+ * Create a UnionResultSet.
4896
+ *
4897
+ * @param resultSets - Result sets to union
4898
+ */
4899
+ constructor(resultSets: ResultSet<K>[]);
4900
+ /**
4901
+ * Lazy iteration over union with deduplication.
4902
+ */
4903
+ [Symbol.iterator](): Generator<K>;
4904
+ /**
4905
+ * Retrieval cost is sum of all costs.
4906
+ */
4907
+ getRetrievalCost(): number;
4908
+ /**
4909
+ * Merge cost upper bound: sum of all sizes.
4910
+ */
4911
+ getMergeCost(): number;
4912
+ /**
4913
+ * Check if key is in any result set.
4914
+ */
4915
+ contains(key: K): boolean;
4916
+ /**
4917
+ * Get size by materializing results.
4918
+ */
4919
+ size(): number;
4920
+ /**
4921
+ * Materialize to array with caching.
4922
+ */
4923
+ toArray(): K[];
4924
+ /**
4925
+ * Check if empty (all sources must be empty).
4926
+ */
4927
+ isEmpty(): boolean;
4928
+ /**
4929
+ * Check if results have been materialized.
4930
+ */
4931
+ isMaterialized(): boolean;
4932
+ }
4933
+
4934
+ /**
4935
+ * FilteringResultSet Implementation
4936
+ *
4937
+ * Filters a source result set with a predicate.
4938
+ * Used when an index is available for part of a query,
4939
+ * but additional filtering is needed.
4940
+ *
4941
+ * @module query/resultset/FilteringResultSet
4942
+ */
4943
+
4944
+ /**
4945
+ * Predicate function for filtering records.
4946
+ */
4947
+ type PredicateFn<V> = (record: V) => boolean;
4948
+ /**
4949
+ * Filters a source result set with a predicate.
4950
+ *
4951
+ * K = record key type, V = record value type
4952
+ */
4953
+ declare class FilteringResultSet<K, V> implements ResultSet<K> {
4954
+ private readonly source;
4955
+ private readonly getRecord;
4956
+ private readonly predicate;
4957
+ /** Cached materialized results */
4958
+ private cached;
4959
+ /**
4960
+ * Create a FilteringResultSet.
4961
+ *
4962
+ * @param source - Source result set to filter
4963
+ * @param getRecord - Function to get record by key
4964
+ * @param predicate - Predicate function to filter records
4965
+ */
4966
+ constructor(source: ResultSet<K>, getRecord: (key: K) => V | undefined, predicate: PredicateFn<V>);
4967
+ /**
4968
+ * Lazy iteration with filtering.
4969
+ */
4970
+ [Symbol.iterator](): Generator<K>;
4971
+ /**
4972
+ * Retrieval cost: source cost + filter overhead.
4973
+ */
4974
+ getRetrievalCost(): number;
4975
+ /**
4976
+ * Merge cost: estimate half of source (pessimistic).
4977
+ */
4978
+ getMergeCost(): number;
4979
+ /**
4980
+ * Check if key is in source and passes predicate.
4981
+ */
4982
+ contains(key: K): boolean;
4983
+ /**
4984
+ * Get size by materializing results.
4985
+ */
4986
+ size(): number;
4987
+ /**
4988
+ * Materialize to array with caching.
4989
+ */
4990
+ toArray(): K[];
4991
+ /**
4992
+ * Check if empty (tries to find at least one match).
4993
+ */
4994
+ isEmpty(): boolean;
4995
+ /**
4996
+ * Check if results have been materialized.
4997
+ */
4998
+ isMaterialized(): boolean;
4999
+ }
5000
+
5001
+ /**
5002
+ * SortedResultSet Implementation
5003
+ *
5004
+ * ResultSet with sorting support.
5005
+ * If source is from NavigableIndex on sort field, results are already sorted.
5006
+ * Otherwise, performs in-memory sort.
5007
+ *
5008
+ * @module query/resultset/SortedResultSet
5009
+ */
5010
+
5011
+ /**
5012
+ * Comparator function for sorting.
5013
+ */
5014
+ type CompareFn<V> = (a: V, b: V) => number;
5015
+ /**
5016
+ * ResultSet with sorting support.
5017
+ *
5018
+ * K = record key type, V = record value type
5019
+ */
5020
+ declare class SortedResultSet<K, V> implements ResultSet<K> {
5021
+ private readonly source;
5022
+ private readonly getRecord;
5023
+ private readonly sortField;
5024
+ private readonly direction;
5025
+ private readonly isPreSorted;
5026
+ /** Cached sorted results */
5027
+ private cached;
5028
+ /**
5029
+ * Create a SortedResultSet.
5030
+ *
5031
+ * @param source - Source result set
5032
+ * @param getRecord - Function to get record by key
5033
+ * @param sortField - Field to sort by
5034
+ * @param direction - Sort direction ('asc' or 'desc')
5035
+ * @param isPreSorted - Whether source is already sorted (from NavigableIndex)
5036
+ */
5037
+ constructor(source: ResultSet<K>, getRecord: (key: K) => V | undefined, sortField: string, direction: 'asc' | 'desc', isPreSorted?: boolean);
5038
+ /**
5039
+ * Lazy iteration with sorting.
5040
+ */
5041
+ [Symbol.iterator](): Generator<K>;
5042
+ /**
5043
+ * Materialize to sorted array with caching.
5044
+ */
5045
+ toArray(): K[];
5046
+ /**
5047
+ * Retrieval cost: source cost + sort overhead.
5048
+ * Pre-sorted has minimal overhead.
5049
+ */
5050
+ getRetrievalCost(): number;
5051
+ /**
5052
+ * Merge cost: same as source (sorting doesn't change size).
5053
+ */
5054
+ getMergeCost(): number;
5055
+ /**
5056
+ * Check if key is in source.
5057
+ */
5058
+ contains(key: K): boolean;
5059
+ /**
5060
+ * Get size (same as source).
5061
+ */
5062
+ size(): number;
5063
+ /**
5064
+ * Check if empty.
5065
+ */
5066
+ isEmpty(): boolean;
5067
+ /**
5068
+ * Check if results have been materialized.
5069
+ */
5070
+ isMaterialized(): boolean;
5071
+ /**
5072
+ * Check if this result set is pre-sorted.
5073
+ */
5074
+ isIndexSorted(): boolean;
5075
+ /**
5076
+ * Get sort field.
5077
+ */
5078
+ getSortField(): string;
5079
+ /**
5080
+ * Get sort direction.
5081
+ */
5082
+ getSortDirection(): 'asc' | 'desc';
5083
+ }
5084
+ /**
5085
+ * Create a comparator function for a field.
5086
+ *
5087
+ * @param field - Field name to compare
5088
+ * @param direction - Sort direction
5089
+ */
5090
+ declare function createFieldComparator<V>(field: string, direction: 'asc' | 'desc'): CompareFn<V>;
5091
+
5092
+ /**
5093
+ * LimitResultSet Implementation
5094
+ *
5095
+ * Applies offset/limit to source ResultSet.
5096
+ * Implements early termination for efficiency.
5097
+ *
5098
+ * @module query/resultset/LimitResultSet
5099
+ */
5100
+
5101
+ /**
5102
+ * Applies offset/limit to source ResultSet.
5103
+ * Implements early termination for efficiency.
5104
+ *
5105
+ * K = record key type
5106
+ */
5107
+ declare class LimitResultSet<K> implements ResultSet<K> {
5108
+ private readonly source;
5109
+ private readonly offset;
5110
+ private readonly limit;
5111
+ /** Cached materialized results */
5112
+ private cached;
5113
+ /**
5114
+ * Create a LimitResultSet.
5115
+ *
5116
+ * @param source - Source result set
5117
+ * @param offset - Number of results to skip (default: 0)
5118
+ * @param limit - Maximum number of results (default: Infinity)
5119
+ */
5120
+ constructor(source: ResultSet<K>, offset?: number, limit?: number);
5121
+ /**
5122
+ * Lazy iteration with offset/limit and early termination.
5123
+ */
5124
+ [Symbol.iterator](): Generator<K>;
5125
+ /**
5126
+ * Retrieval cost: source cost (limit doesn't change retrieval cost).
5127
+ */
5128
+ getRetrievalCost(): number;
5129
+ /**
5130
+ * Merge cost: min(source size, offset + limit).
5131
+ */
5132
+ getMergeCost(): number;
5133
+ /**
5134
+ * Check if key is in result (with offset/limit constraints).
5135
+ * This is expensive as it requires iteration to determine position.
5136
+ */
5137
+ contains(key: K): boolean;
5138
+ /**
5139
+ * Get size by materializing results.
5140
+ */
5141
+ size(): number;
5142
+ /**
5143
+ * Materialize to array with caching.
5144
+ */
5145
+ toArray(): K[];
5146
+ /**
5147
+ * Check if empty.
5148
+ */
5149
+ isEmpty(): boolean;
5150
+ /**
5151
+ * Check if results have been materialized.
5152
+ */
5153
+ isMaterialized(): boolean;
5154
+ /**
5155
+ * Get the offset value.
5156
+ */
5157
+ getOffset(): number;
5158
+ /**
5159
+ * Get the limit value.
5160
+ */
5161
+ getLimit(): number;
5162
+ }
5163
+
5164
+ /**
5165
+ * IndexRegistry Implementation
5166
+ *
5167
+ * Central registry for managing indexes on a collection.
5168
+ * Provides index lookup, lifecycle management, and bulk operations.
5169
+ *
5170
+ * @module query/IndexRegistry
5171
+ */
5172
+
5173
+ /**
5174
+ * Registry for managing indexes on a collection.
5175
+ * Provides index lookup and lifecycle management.
5176
+ *
5177
+ * K = record key type, V = record value type
5178
+ */
5179
+ declare class IndexRegistry<K, V> {
5180
+ /** Indexes grouped by attribute name */
5181
+ private attributeIndexes;
5182
+ /** Compound indexes (Phase 9.03) - keyed by sorted attribute names */
5183
+ private compoundIndexes;
5184
+ /** Fallback index for full scan (optional) */
5185
+ private fallbackIndex;
5186
+ /**
5187
+ * Register an index for an attribute.
5188
+ * Multiple indexes can be registered for the same attribute.
5189
+ *
5190
+ * @param index - Index to register
5191
+ */
5192
+ addIndex<A>(index: Index<K, V, A>): void;
5193
+ /**
5194
+ * Register a compound index (Phase 9.03).
5195
+ *
5196
+ * @param index - Compound index to register
5197
+ */
5198
+ addCompoundIndex(index: CompoundIndex<K, V>): void;
5199
+ /**
5200
+ * Remove an index from the registry.
5201
+ *
5202
+ * @param index - Index to remove
5203
+ * @returns true if index was found and removed
5204
+ */
5205
+ removeIndex<A>(index: Index<K, V, A>): boolean;
5206
+ /**
5207
+ * Remove a compound index (Phase 9.03).
5208
+ *
5209
+ * @param index - Compound index to remove
5210
+ * @returns true if index was found and removed
5211
+ */
5212
+ removeCompoundIndex(index: CompoundIndex<K, V>): boolean;
5213
+ /**
5214
+ * Get all indexes for an attribute.
5215
+ *
5216
+ * @param attributeName - Attribute name
5217
+ * @returns Array of indexes (empty if none)
5218
+ */
5219
+ getIndexes(attributeName: string): Index<K, V, unknown>[];
5220
+ /**
5221
+ * Get all registered indexes across all attributes.
5222
+ *
5223
+ * @returns Array of all indexes
5224
+ */
5225
+ getAllIndexes(): Index<K, V, unknown>[];
5226
+ /**
5227
+ * Get all indexed attribute names.
5228
+ *
5229
+ * @returns Array of attribute names
5230
+ */
5231
+ getIndexedAttributes(): string[];
5232
+ /**
5233
+ * Check if an attribute has any indexes.
5234
+ *
5235
+ * @param attributeName - Attribute name
5236
+ * @returns true if attribute has indexes
5237
+ */
5238
+ hasIndex(attributeName: string): boolean;
5239
+ /**
5240
+ * Find the best index for a query type on an attribute.
5241
+ * Returns the index with lowest retrieval cost that supports the query type.
5242
+ *
5243
+ * @param attributeName - Attribute name to search on
5244
+ * @param queryType - Query type (e.g., 'equal', 'gt', 'between')
5245
+ * @returns Best matching index or null if none found
5246
+ */
5247
+ findBestIndex(attributeName: string, queryType: string): Index<K, V, unknown> | null;
5248
+ /**
5249
+ * Find all indexes that support a query type on an attribute.
5250
+ *
5251
+ * @param attributeName - Attribute name
5252
+ * @param queryType - Query type
5253
+ * @returns Array of matching indexes sorted by retrieval cost
5254
+ */
5255
+ findIndexes(attributeName: string, queryType: string): Index<K, V, unknown>[];
5256
+ /**
5257
+ * Find a compound index that covers the given attribute names (Phase 9.03).
5258
+ * The compound index must cover ALL the attributes (exact match or superset).
5259
+ *
5260
+ * @param attributeNames - Array of attribute names to search for
5261
+ * @returns Matching compound index or null
5262
+ */
5263
+ findCompoundIndex(attributeNames: string[]): CompoundIndex<K, V> | null;
5264
+ /**
5265
+ * Check if a compound index exists for the given attributes (Phase 9.03).
5266
+ *
5267
+ * @param attributeNames - Array of attribute names
5268
+ * @returns true if a compound index exists
5269
+ */
5270
+ hasCompoundIndex(attributeNames: string[]): boolean;
5271
+ /**
5272
+ * Get all compound indexes (Phase 9.03).
5273
+ *
5274
+ * @returns Array of all compound indexes
5275
+ */
5276
+ getCompoundIndexes(): CompoundIndex<K, V>[];
5277
+ /**
5278
+ * Create a compound key from attribute names (sorted for consistency).
5279
+ */
5280
+ private makeCompoundKey;
5281
+ /**
5282
+ * Set a fallback index for queries without a suitable index.
5283
+ * Typically a FallbackIndex that performs full scan.
5284
+ *
5285
+ * @param fallback - Fallback index
5286
+ */
5287
+ setFallbackIndex(fallback: Index<K, V, unknown>): void;
5288
+ /**
5289
+ * Get the fallback index.
5290
+ *
5291
+ * @returns Fallback index or null if not set
5292
+ */
5293
+ getFallbackIndex(): Index<K, V, unknown> | null;
5294
+ /**
5295
+ * Notify all indexes of a record addition.
5296
+ * Should be called when a new record is added to the collection.
5297
+ *
5298
+ * @param key - Record key
5299
+ * @param record - Record value
5300
+ */
5301
+ onRecordAdded(key: K, record: V): void;
5302
+ /**
5303
+ * Notify all indexes of a record update.
5304
+ * Should be called when a record's value changes.
5305
+ *
5306
+ * @param key - Record key
5307
+ * @param oldRecord - Previous record value
5308
+ * @param newRecord - New record value
5309
+ */
5310
+ onRecordUpdated(key: K, oldRecord: V, newRecord: V): void;
5311
+ /**
5312
+ * Notify all indexes of a record removal.
5313
+ * Should be called when a record is removed from the collection.
5314
+ *
5315
+ * @param key - Record key
5316
+ * @param record - Removed record value
5317
+ */
5318
+ onRecordRemoved(key: K, record: V): void;
5319
+ /**
5320
+ * Clear all indexes.
5321
+ * Does not remove index registrations, only clears their data.
5322
+ */
5323
+ clear(): void;
5324
+ /**
5325
+ * Get total number of registered indexes.
5326
+ */
5327
+ get size(): number;
5328
+ /**
5329
+ * Get statistics about the registry.
5330
+ */
5331
+ getStats(): IndexRegistryStats;
5332
+ }
5333
+ /**
5334
+ * Statistics about the IndexRegistry.
5335
+ */
5336
+ interface IndexRegistryStats {
5337
+ /** Total number of indexes */
5338
+ totalIndexes: number;
5339
+ /** Number of indexed attributes */
5340
+ indexedAttributes: number;
5341
+ /** Number of compound indexes (Phase 9.03) */
5342
+ compoundIndexes?: number;
5343
+ /** Stats for each index */
5344
+ indexes: Array<{
5345
+ attribute: string;
5346
+ type: string;
5347
+ stats: {
5348
+ distinctValues: number;
5349
+ totalEntries: number;
5350
+ avgEntriesPerValue: number;
5351
+ };
5352
+ }>;
5353
+ }
5354
+
5355
+ /**
5356
+ * StandingQueryRegistry Implementation
5357
+ *
5358
+ * Registry for managing StandingQueryIndexes.
5359
+ * Used by Live Query system to maintain pre-computed results.
5360
+ *
5361
+ * Features:
5362
+ * - Reference counting for shared indexes
5363
+ * - Automatic cleanup when all subscribers unsubscribe
5364
+ * - Efficient update propagation to all indexes
5365
+ *
5366
+ * @module query/StandingQueryRegistry
5367
+ */
5368
+
5369
+ /**
5370
+ * Options for creating a StandingQueryRegistry.
5371
+ */
5372
+ interface StandingQueryRegistryOptions<K, V> {
5373
+ /** Function to get record by key */
5374
+ getRecord: (key: K) => V | undefined;
5375
+ /** Function to get all entries for building index */
5376
+ getAllEntries: () => Iterable<[K, V]>;
5377
+ }
5378
+ /**
5379
+ * Statistics about the StandingQueryRegistry.
5380
+ */
5381
+ interface StandingQueryRegistryStats {
5382
+ /** Number of registered indexes */
5383
+ indexCount: number;
5384
+ /** Total reference count across all indexes */
5385
+ totalRefCount: number;
5386
+ /** Total number of results across all indexes */
5387
+ totalResults: number;
5388
+ }
5389
+ /**
5390
+ * Registry for managing StandingQueryIndexes.
5391
+ * Provides reference counting and lifecycle management.
5392
+ *
5393
+ * K = record key type, V = record value type
5394
+ */
5395
+ declare class StandingQueryRegistry<K, V> {
5396
+ /** Map from query hash to StandingQueryIndex */
5397
+ private indexes;
5398
+ /** Reference count for each query (multiple subscriptions can use same index) */
5399
+ private refCounts;
5400
+ /** Record accessor */
5401
+ private readonly getRecord;
5402
+ /** All entries accessor (for building index) */
5403
+ private readonly getAllEntries;
5404
+ constructor(options: StandingQueryRegistryOptions<K, V>);
5405
+ /**
5406
+ * Register a standing query.
5407
+ * Creates new index or returns existing if query already registered.
5408
+ * Increments reference count.
5409
+ *
5410
+ * @param query - Query to register
5411
+ * @returns StandingQueryIndex for the query
5412
+ */
5413
+ register(query: Query): StandingQueryIndex<K, V>;
5414
+ /**
5415
+ * Unregister a standing query.
5416
+ * Decrements reference count. Only removes when refcount reaches 0.
5417
+ *
5418
+ * @param query - Query to unregister
5419
+ * @returns true if index was removed, false if still has references
5420
+ */
5421
+ unregister(query: Query): boolean;
5422
+ /**
5423
+ * Get index for a query if registered.
5424
+ *
5425
+ * @param query - Query to look up
5426
+ * @returns StandingQueryIndex or undefined if not registered
5427
+ */
5428
+ getIndex(query: Query): StandingQueryIndex<K, V> | undefined;
5429
+ /**
5430
+ * Get index by hash directly.
5431
+ *
5432
+ * @param hash - Query hash
5433
+ * @returns StandingQueryIndex or undefined if not registered
5434
+ */
5435
+ getIndexByHash(hash: string): StandingQueryIndex<K, V> | undefined;
5436
+ /**
5437
+ * Check if query has a standing index.
5438
+ *
5439
+ * @param query - Query to check
5440
+ * @returns true if index exists
5441
+ */
5442
+ hasIndex(query: Query): boolean;
5443
+ /**
5444
+ * Get reference count for a query.
5445
+ *
5446
+ * @param query - Query to check
5447
+ * @returns Reference count (0 if not registered)
5448
+ */
5449
+ getRefCount(query: Query): number;
5450
+ /**
5451
+ * Notify all indexes of record addition.
5452
+ * Returns map of query hash to change type for affected queries.
5453
+ *
5454
+ * @param key - Record key
5455
+ * @param record - New record value
5456
+ * @returns Map of query hash to change type
5457
+ */
5458
+ onRecordAdded(key: K, record: V): Map<string, StandingQueryChange>;
5459
+ /**
5460
+ * Notify all indexes of record update.
5461
+ * Returns map of query hash to change type for affected queries.
5462
+ *
5463
+ * @param key - Record key
5464
+ * @param oldRecord - Previous record value
5465
+ * @param newRecord - New record value
5466
+ * @returns Map of query hash to change type
5467
+ */
5468
+ onRecordUpdated(key: K, oldRecord: V, newRecord: V): Map<string, StandingQueryChange>;
5469
+ /**
5470
+ * Notify all indexes of record removal.
5471
+ * Returns map of query hash to change type for affected queries.
5472
+ *
5473
+ * @param key - Record key
5474
+ * @param record - Removed record value
5475
+ * @returns Map of query hash to change type
5476
+ */
5477
+ onRecordRemoved(key: K, record: V): Map<string, StandingQueryChange>;
5478
+ /**
5479
+ * Get all registered queries.
5480
+ *
5481
+ * @returns Array of registered queries
5482
+ */
5483
+ getRegisteredQueries(): Query[];
5484
+ /**
5485
+ * Get all query hashes.
5486
+ *
5487
+ * @returns Array of query hashes
5488
+ */
5489
+ getQueryHashes(): string[];
5490
+ /**
5491
+ * Get statistics about the registry.
5492
+ *
5493
+ * @returns Registry statistics
5494
+ */
5495
+ getStats(): StandingQueryRegistryStats;
5496
+ /**
5497
+ * Clear all indexes.
5498
+ */
5499
+ clear(): void;
5500
+ /**
5501
+ * Get number of registered indexes.
5502
+ */
5503
+ get size(): number;
5504
+ /**
5505
+ * Compute hash for a query.
5506
+ * Used as key in indexes map.
5507
+ */
5508
+ hashQuery(query: Query): string;
5509
+ }
5510
+
5511
+ /**
5512
+ * QueryOptimizer Implementation
5513
+ *
5514
+ * Cost-based query optimizer for the Query Engine.
5515
+ * Selects optimal index and execution strategy for queries.
5516
+ *
5517
+ * Algorithm based on CQEngine CollectionQueryEngine:
5518
+ * - StandingQueryIndex: Check first (lowest cost = 10)
5519
+ * - AND queries: "smallest first" strategy - sort by merge cost, iterate smallest
5520
+ * - OR queries: Union all results with deduplication
5521
+ * - NOT queries: Get all keys, subtract matching keys
5522
+ *
5523
+ * @module query/QueryOptimizer
5524
+ */
5525
+
5526
+ /**
5527
+ * Options for creating a QueryOptimizer.
5528
+ */
5529
+ interface QueryOptimizerOptions<K, V> {
5530
+ /** Index registry for attribute-based indexes */
5531
+ indexRegistry: IndexRegistry<K, V>;
5532
+ /** Standing query registry for pre-computed queries (optional) */
5533
+ standingQueryRegistry?: StandingQueryRegistry<K, V>;
5534
+ }
5535
+ /**
5536
+ * Cost-based query optimizer.
5537
+ * Selects optimal index and execution strategy for queries.
5538
+ *
5539
+ * K = record key type, V = record value type
5540
+ */
5541
+ declare class QueryOptimizer<K, V> {
5542
+ private readonly indexRegistry;
5543
+ private readonly standingQueryRegistry?;
5544
+ /**
5545
+ * Create a QueryOptimizer.
5546
+ *
5547
+ * @param indexRegistryOrOptions - IndexRegistry or options object
5548
+ * @param standingQueryRegistry - Optional StandingQueryRegistry (deprecated, use options)
5549
+ */
5550
+ constructor(indexRegistryOrOptions: IndexRegistry<K, V> | QueryOptimizerOptions<K, V>, standingQueryRegistry?: StandingQueryRegistry<K, V>);
5551
+ /**
5552
+ * Optimize a query and return an execution plan.
5553
+ *
5554
+ * Optimization order (by cost):
5555
+ * 1. StandingQueryIndex (cost: 10) - pre-computed results
5556
+ * 2. Other indexes via optimizeNode
5557
+ *
5558
+ * @param query - Query to optimize
5559
+ * @returns Query execution plan
5560
+ */
5561
+ optimize(query: Query): QueryPlan;
5562
+ /**
5563
+ * Optimize a query with sort/limit/offset options.
5564
+ *
5565
+ * @param query - Query to optimize
5566
+ * @param options - Query options (sort, limit, offset)
5567
+ * @returns Query execution plan with options
5568
+ */
5569
+ optimizeWithOptions(query: Query, options: QueryOptions): QueryPlan;
5570
+ /**
5571
+ * Optimize a single query node.
5572
+ */
5573
+ private optimizeNode;
5574
+ /**
5575
+ * Optimize a simple (attribute-based) query.
5576
+ */
5577
+ private optimizeSimple;
5578
+ /**
5579
+ * Optimize a logical (AND/OR/NOT) query.
5580
+ */
5581
+ private optimizeLogical;
5582
+ /**
5583
+ * Optimize AND query.
5584
+ * Strategy: Find child with lowest cost, use as base, filter with rest.
5585
+ *
5586
+ * CQEngine "smallest first" strategy:
5587
+ * 1. Check for CompoundIndex covering all eq children (Phase 9.03)
5588
+ * 2. Sort children by merge cost
5589
+ * 3. Use intersection if multiple indexes available
5590
+ * 4. Apply remaining predicates as filters
5591
+ */
5592
+ private optimizeAnd;
5593
+ /**
5594
+ * Try to use a CompoundIndex for an AND query (Phase 9.03).
5595
+ *
5596
+ * Returns a compound index scan step if:
5597
+ * 1. All children are simple 'eq' queries
5598
+ * 2. A CompoundIndex exists covering all queried attributes
5599
+ *
5600
+ * @param children - Children of the AND query
5601
+ * @returns IndexScanStep using CompoundIndex, or null if not applicable
5602
+ */
5603
+ private tryCompoundIndex;
5604
+ /**
5605
+ * Build values array for compound index query in correct attribute order.
5606
+ *
5607
+ * @param compoundIndex - The compound index to use
5608
+ * @param eqQueries - Array of 'eq' queries
5609
+ * @returns Values array in compound index order, or null if mismatch
5610
+ */
5611
+ private buildCompoundValues;
5612
+ /**
5613
+ * Optimize OR query.
5614
+ * Strategy: Union of all child results with deduplication.
5615
+ */
5616
+ private optimizeOr;
5617
+ /**
5618
+ * Optimize NOT query.
5619
+ * Strategy: Get all keys, subtract matching keys.
5620
+ */
5621
+ private optimizeNot;
5622
+ /**
5623
+ * Map query type to index query type.
5624
+ * Some query types have different names in indexes.
5625
+ */
5626
+ private mapQueryType;
5627
+ /**
5628
+ * Build an IndexQuery from a SimpleQueryNode.
5629
+ */
5630
+ private buildIndexQuery;
5631
+ /**
5632
+ * Estimate the execution cost of a plan step.
5633
+ */
5634
+ private estimateCost;
5635
+ /**
5636
+ * Check if a plan step uses any indexes.
5637
+ */
5638
+ private usesIndexes;
5639
+ }
5640
+
5641
+ /**
5642
+ * LiveQueryManager Implementation
5643
+ *
5644
+ * Manages live query subscriptions using StandingQueryIndexes.
5645
+ * Provides reactive updates when data changes.
5646
+ *
5647
+ * Features:
5648
+ * - Initial results on subscribe
5649
+ * - Delta updates on record changes
5650
+ * - Shared indexes for identical queries
5651
+ * - Automatic cleanup on unsubscribe
5652
+ *
5653
+ * @module query/LiveQueryManager
5654
+ */
5655
+
5656
+ /**
5657
+ * Initial results event sent when subscribing.
5658
+ */
5659
+ interface LiveQueryInitialEvent<K> {
5660
+ type: 'initial';
5661
+ query: Query;
5662
+ results: K[];
5663
+ }
5664
+ /**
5665
+ * Delta event sent when data changes.
5666
+ */
5667
+ interface LiveQueryDeltaEvent<K, V> {
5668
+ type: 'delta';
5669
+ query: Query;
5670
+ key: K;
5671
+ record: V;
5672
+ change: StandingQueryChange;
5673
+ operation: 'added' | 'updated' | 'removed';
5674
+ newResultCount: number;
5675
+ }
5676
+ /**
5677
+ * Union type for all live query events.
5678
+ */
5679
+ type LiveQueryEvent<K, V> = LiveQueryInitialEvent<K> | LiveQueryDeltaEvent<K, V>;
5680
+ /**
5681
+ * Callback for live query events.
5682
+ */
5683
+ type LiveQueryCallback<K, V> = (event: LiveQueryEvent<K, V>) => void;
5684
+ /**
5685
+ * Options for creating a LiveQueryManager.
5686
+ */
5687
+ interface LiveQueryManagerOptions<K, V> {
5688
+ /** Function to get record by key */
5689
+ getRecord: (key: K) => V | undefined;
5690
+ /** Function to get all entries for building index */
5691
+ getAllEntries: () => Iterable<[K, V]>;
5692
+ }
5693
+ /**
5694
+ * Manages live query subscriptions using StandingQueryIndexes.
5695
+ * Provides reactive updates when data changes.
5696
+ *
5697
+ * K = record key type, V = record value type
5698
+ */
5699
+ declare class LiveQueryManager<K, V> {
5700
+ private registry;
5701
+ /** Subscription callbacks by query hash */
5702
+ private subscriptions;
5703
+ constructor(options: LiveQueryManagerOptions<K, V>);
5704
+ /**
5705
+ * Subscribe to a live query.
5706
+ * Sends initial results immediately, then delta updates on changes.
5707
+ *
5708
+ * @param query - Query to subscribe to
5709
+ * @param callback - Callback for query events
5710
+ * @returns Unsubscribe function
5711
+ */
5712
+ subscribe(query: Query, callback: LiveQueryCallback<K, V>): () => void;
5713
+ /**
5714
+ * Get current results for a query (snapshot).
5715
+ * Does not subscribe to updates.
5716
+ *
5717
+ * @param query - Query to execute
5718
+ * @returns Array of matching keys
5719
+ */
5720
+ getResults(query: Query): K[];
5721
+ /**
5722
+ * Check if a query has active subscriptions.
5723
+ *
5724
+ * @param query - Query to check
5725
+ * @returns true if query has subscribers
5726
+ */
5727
+ hasSubscribers(query: Query): boolean;
5728
+ /**
5729
+ * Get subscriber count for a query.
5730
+ *
5731
+ * @param query - Query to check
5732
+ * @returns Number of subscribers
5733
+ */
5734
+ getSubscriberCount(query: Query): number;
5735
+ /**
5736
+ * Notify of record addition.
5737
+ * Triggers subscription callbacks for affected queries.
5738
+ *
5739
+ * @param key - Record key
5740
+ * @param record - New record value
5741
+ */
5742
+ onRecordAdded(key: K, record: V): void;
5743
+ /**
5744
+ * Notify of record update.
5745
+ * Triggers subscription callbacks for affected queries.
5746
+ *
5747
+ * @param key - Record key
5748
+ * @param oldRecord - Previous record value
5749
+ * @param newRecord - New record value
5750
+ */
5751
+ onRecordUpdated(key: K, oldRecord: V, newRecord: V): void;
5752
+ /**
5753
+ * Notify of record removal.
5754
+ * Triggers subscription callbacks for affected queries.
5755
+ *
5756
+ * @param key - Record key
5757
+ * @param record - Removed record value
5758
+ */
5759
+ onRecordRemoved(key: K, record: V): void;
5760
+ /**
5761
+ * Notify subscribers of changes.
5762
+ */
5763
+ private notifySubscribers;
5764
+ /**
5765
+ * Get the underlying registry for direct access.
5766
+ * Useful for testing and debugging.
5767
+ *
5768
+ * @returns StandingQueryRegistry instance
5769
+ */
5770
+ getRegistry(): StandingQueryRegistry<K, V>;
5771
+ /**
5772
+ * Get all active query hashes.
5773
+ *
5774
+ * @returns Array of query hashes with active subscriptions
5775
+ */
5776
+ getActiveQueries(): string[];
5777
+ /**
5778
+ * Get statistics about the manager.
5779
+ *
5780
+ * @returns Statistics object
5781
+ */
5782
+ getStats(): LiveQueryManagerStats;
5783
+ /**
5784
+ * Clear all subscriptions and indexes.
5785
+ */
5786
+ clear(): void;
5787
+ }
5788
+ /**
5789
+ * Statistics about the LiveQueryManager.
5790
+ */
5791
+ interface LiveQueryManagerStats extends StandingQueryRegistryStats {
5792
+ /** Number of active queries with subscribers */
5793
+ activeQueries: number;
5794
+ /** Total number of subscribers across all queries */
5795
+ totalSubscribers: number;
5796
+ }
5797
+
5798
+ /**
5799
+ * QueryPatternTracker (Phase 8.02.1)
5800
+ *
5801
+ * Collects runtime statistics on query execution patterns.
5802
+ * Used by IndexAdvisor to generate index suggestions.
5803
+ *
5804
+ * Features:
5805
+ * - Tracks query count, cost, and cardinality per attribute
5806
+ * - Low overhead (< 1% of query time)
5807
+ * - Optional sampling for high-throughput scenarios
5808
+ * - Memory-bounded (circular buffer for old stats)
5809
+ *
5810
+ * @module query/adaptive/QueryPatternTracker
5811
+ */
5812
+
5813
+ /**
5814
+ * Options for QueryPatternTracker.
5815
+ */
5816
+ interface QueryPatternTrackerOptions {
5817
+ /**
5818
+ * Sampling rate: 1 = track all queries, N = track 1 in N queries.
5819
+ * Higher values reduce overhead but decrease accuracy.
5820
+ * Default: 1 (track all)
5821
+ */
5822
+ samplingRate?: number;
5823
+ /**
5824
+ * Maximum number of unique attribute+queryType combinations to track.
5825
+ * Prevents unbounded memory growth.
5826
+ * Default: 1000
5827
+ */
5828
+ maxTrackedPatterns?: number;
5829
+ /**
5830
+ * Time-to-live for statistics in milliseconds.
5831
+ * Statistics older than this are considered stale.
5832
+ * Default: 24 hours
5833
+ */
5834
+ statsTtl?: number;
5835
+ }
5836
+ /**
5837
+ * QueryPatternTracker collects runtime statistics on query execution.
5838
+ *
5839
+ * @example
5840
+ * ```typescript
5841
+ * const tracker = new QueryPatternTracker();
5842
+ *
5843
+ * // Record queries during execution
5844
+ * tracker.recordQuery('category', 'eq', 5.2, 100, false);
5845
+ * tracker.recordQuery('category', 'eq', 4.8, 100, false);
5846
+ *
5847
+ * // Record compound AND queries (Phase 9.03)
5848
+ * tracker.recordCompoundQuery(['status', 'category'], 10.5, 50, false);
5849
+ *
5850
+ * // Get statistics
5851
+ * const stats = tracker.getStatistics();
5852
+ * // [{ attribute: 'category', queryType: 'eq', queryCount: 2, averageCost: 5.0, ... }]
5853
+ * ```
5854
+ */
5855
+ declare class QueryPatternTracker {
5856
+ private stats;
5857
+ private compoundStats;
5858
+ private queryCounter;
5859
+ private readonly samplingRate;
5860
+ private readonly maxTrackedPatterns;
5861
+ private readonly statsTtl;
5862
+ constructor(options?: QueryPatternTrackerOptions);
5863
+ /**
5864
+ * Record a query execution for pattern tracking.
5865
+ *
5866
+ * @param attribute - The attribute being queried
5867
+ * @param queryType - The type of query (eq, gt, between, etc.)
5868
+ * @param executionTime - Query execution time in milliseconds
5869
+ * @param resultSize - Number of results returned
5870
+ * @param hasIndex - Whether an index was used
5871
+ */
5872
+ recordQuery(attribute: string, queryType: TrackedQueryType, executionTime: number, resultSize: number, hasIndex: boolean): void;
5873
+ /**
5874
+ * Record a compound (AND) query execution for pattern tracking (Phase 9.03).
5875
+ *
5876
+ * @param attributes - Array of attribute names being queried together
5877
+ * @param executionTime - Query execution time in milliseconds
5878
+ * @param resultSize - Number of results returned
5879
+ * @param hasCompoundIndex - Whether a compound index was used
5880
+ */
5881
+ recordCompoundQuery(attributes: string[], executionTime: number, resultSize: number, hasCompoundIndex: boolean): void;
5882
+ /**
5883
+ * Get all compound query statistics (Phase 9.03).
5884
+ *
5885
+ * @returns Array of compound query statistics, sorted by query count descending
5886
+ */
5887
+ getCompoundStatistics(): CompoundQueryStatistics[];
5888
+ /**
5889
+ * Get compound statistics for a specific attribute combination.
5890
+ *
5891
+ * @param attributes - Array of attribute names
5892
+ * @returns Compound query statistics or undefined
5893
+ */
5894
+ getCompoundStats(attributes: string[]): CompoundQueryStatistics | undefined;
5895
+ /**
5896
+ * Check if attributes appear in any tracked compound queries.
5897
+ *
5898
+ * @param attribute - The attribute name to check
5899
+ * @returns True if attribute is part of any compound query pattern
5900
+ */
5901
+ isInCompoundPattern(attribute: string): boolean;
5902
+ /**
5903
+ * Update compound index status.
5904
+ *
5905
+ * @param attributes - Array of attribute names
5906
+ * @param hasCompoundIndex - Whether a compound index exists
5907
+ */
5908
+ updateCompoundIndexStatus(attributes: string[], hasCompoundIndex: boolean): void;
5909
+ /**
5910
+ * Get all query statistics.
5911
+ *
5912
+ * @returns Array of query statistics, sorted by query count descending
5913
+ */
5914
+ getStatistics(): QueryStatistics[];
5915
+ /**
5916
+ * Get statistics for a specific attribute.
5917
+ *
5918
+ * @param attribute - The attribute name
5919
+ * @returns Array of query statistics for this attribute
5920
+ */
5921
+ getAttributeStats(attribute: string): QueryStatistics[];
5922
+ /**
5923
+ * Get statistics for a specific attribute and query type.
5924
+ *
5925
+ * @param attribute - The attribute name
5926
+ * @param queryType - The query type
5927
+ * @returns Query statistics or undefined
5928
+ */
5929
+ getStats(attribute: string, queryType: TrackedQueryType): QueryStatistics | undefined;
5930
+ /**
5931
+ * Check if an attribute has been queried.
5932
+ *
5933
+ * @param attribute - The attribute name
5934
+ * @returns True if the attribute has query statistics
5935
+ */
5936
+ hasStats(attribute: string): boolean;
5937
+ /**
5938
+ * Get the total number of queries recorded.
5939
+ *
5940
+ * @returns Total query count across all patterns
5941
+ */
5942
+ getTotalQueryCount(): number;
5943
+ /**
5944
+ * Get the number of unique attribute+queryType patterns tracked.
5945
+ *
5946
+ * @returns Number of unique patterns
5947
+ */
5948
+ getPatternCount(): number;
5949
+ /**
5950
+ * Update index status for an attribute.
5951
+ * Called when an index is added or removed.
5952
+ *
5953
+ * @param attribute - The attribute name
5954
+ * @param hasIndex - Whether an index now exists
5955
+ */
5956
+ updateIndexStatus(attribute: string, hasIndex: boolean): void;
5957
+ /**
5958
+ * Reset query count for an attribute after index creation.
5959
+ * This prevents immediate re-suggestion of the same index.
5960
+ *
5961
+ * @param attribute - The attribute name
5962
+ */
5963
+ resetAttributeStats(attribute: string): void;
5964
+ /**
5965
+ * Clear all statistics.
5966
+ */
5967
+ clear(): void;
5968
+ /**
5969
+ * Get a summary of tracking overhead.
5970
+ *
5971
+ * @returns Tracking overhead info
5972
+ */
5973
+ getTrackingInfo(): {
5974
+ patternsTracked: number;
5975
+ compoundPatternsTracked: number;
5976
+ totalQueries: number;
5977
+ samplingRate: number;
5978
+ memoryEstimate: number;
5979
+ };
5980
+ /**
5981
+ * Evict the oldest (least recently queried) entry.
5982
+ */
5983
+ private evictOldest;
5984
+ /**
5985
+ * Prune stale statistics older than TTL.
5986
+ */
5987
+ private pruneStale;
5988
+ /**
5989
+ * Evict the oldest compound query entry (Phase 9.03).
5990
+ */
5991
+ private evictOldestCompound;
5992
+ /**
5993
+ * Prune stale compound statistics (Phase 9.03).
5994
+ */
5995
+ private pruneStaleCompound;
5996
+ }
5997
+
5998
+ /**
5999
+ * IndexAdvisor (Phase 8.02.2)
6000
+ *
6001
+ * Analyzes query patterns and generates index suggestions.
6002
+ * Used in production mode to help developers optimize their indexes.
6003
+ *
6004
+ * Features:
6005
+ * - Cost/benefit analysis for index suggestions
6006
+ * - Automatic index type selection based on query type
6007
+ * - Priority-based ranking of suggestions
6008
+ * - Memory cost estimation
6009
+ *
6010
+ * @module query/adaptive/IndexAdvisor
6011
+ */
6012
+
6013
+ /**
6014
+ * IndexAdvisor analyzes query patterns and generates index suggestions.
6015
+ *
6016
+ * @example
6017
+ * ```typescript
6018
+ * const tracker = new QueryPatternTracker();
6019
+ * const advisor = new IndexAdvisor(tracker);
6020
+ *
6021
+ * // After application runs...
6022
+ * const suggestions = advisor.getSuggestions();
6023
+ * // [
6024
+ * // {
6025
+ * // attribute: 'category',
6026
+ * // indexType: 'hash',
6027
+ * // reason: 'Queried 1000× with average cost 5.2ms. Expected 500× speedup.',
6028
+ * // priority: 'high'
6029
+ * // }
6030
+ * // ]
6031
+ * ```
6032
+ */
6033
+ declare class IndexAdvisor {
6034
+ private readonly tracker;
6035
+ constructor(tracker: QueryPatternTracker);
6036
+ /**
6037
+ * Get index suggestions based on query patterns.
6038
+ *
6039
+ * @param options - Suggestion options
6040
+ * @returns Array of index suggestions sorted by priority
6041
+ */
6042
+ getSuggestions(options?: IndexSuggestionOptions): IndexSuggestion[];
6043
+ /**
6044
+ * Get a suggestion for a specific attribute.
6045
+ *
6046
+ * @param attribute - The attribute name
6047
+ * @returns Index suggestion or null if not recommended
6048
+ */
6049
+ getSuggestionForAttribute(attribute: string): IndexSuggestion | null;
6050
+ /**
6051
+ * Check if an attribute should be indexed based on patterns.
6052
+ *
6053
+ * @param attribute - The attribute name
6054
+ * @param threshold - Minimum query count threshold
6055
+ * @returns True if attribute should be indexed
6056
+ */
6057
+ shouldIndex(attribute: string, threshold?: number): boolean;
6058
+ /**
6059
+ * Get recommended index type for a query type.
6060
+ *
6061
+ * @param queryType - The query type
6062
+ * @returns Recommended index type or null if not indexable
6063
+ */
6064
+ getRecommendedIndexType(queryType: TrackedQueryType): RecommendedIndexType | null;
6065
+ /**
6066
+ * Group statistics by attribute.
6067
+ */
6068
+ private groupByAttribute;
6069
+ /**
6070
+ * Find the best (most beneficial) pattern for an attribute.
6071
+ */
6072
+ private findBestPattern;
6073
+ /**
6074
+ * Generate a suggestion for a query pattern.
6075
+ */
6076
+ private generateSuggestion;
6077
+ /**
6078
+ * Select appropriate index type based on query type.
6079
+ */
6080
+ private selectIndexType;
6081
+ /**
6082
+ * Count how many query patterns would benefit from an index type.
6083
+ */
6084
+ private countBenefitingPatterns;
6085
+ /**
6086
+ * Estimate performance benefit of adding an index.
6087
+ *
6088
+ * Heuristic based on:
6089
+ * - Full scan vs indexed: typically 100-1000× speedup
6090
+ * - Query frequency amplifies benefit
6091
+ */
6092
+ private estimateBenefit;
6093
+ /**
6094
+ * Estimate memory cost of adding an index.
6095
+ */
6096
+ private estimateMemoryCost;
6097
+ /**
6098
+ * Calculate priority based on query patterns and benefit.
6099
+ */
6100
+ private calculatePriority;
6101
+ /**
6102
+ * Generate human-readable reason for the suggestion.
6103
+ */
6104
+ private generateReason;
6105
+ /**
6106
+ * Get compound index suggestions based on AND query patterns.
6107
+ *
6108
+ * @param options - Suggestion options
6109
+ * @returns Array of compound index suggestions
6110
+ */
6111
+ getCompoundSuggestions(options?: IndexSuggestionOptions): IndexSuggestion[];
6112
+ /**
6113
+ * Get a suggestion for a specific compound attribute combination.
6114
+ *
6115
+ * @param attributes - Array of attribute names
6116
+ * @returns Compound index suggestion or null if not recommended
6117
+ */
6118
+ getCompoundSuggestionFor(attributes: string[]): IndexSuggestion | null;
6119
+ /**
6120
+ * Check if a compound index should be created for the given attributes.
6121
+ *
6122
+ * @param attributes - Array of attribute names
6123
+ * @param threshold - Minimum query count threshold
6124
+ * @returns True if compound index should be created
6125
+ */
6126
+ shouldCreateCompoundIndex(attributes: string[], threshold?: number): boolean;
6127
+ /**
6128
+ * Generate a suggestion for a compound query pattern.
6129
+ */
6130
+ private generateCompoundSuggestion;
6131
+ /**
6132
+ * Estimate performance benefit of adding a compound index.
6133
+ *
6134
+ * Compound indexes provide significant speedup for AND queries:
6135
+ * - Eliminates intersection operations (100-1000× for each attribute)
6136
+ * - Single O(1) lookup instead of multiple index scans
6137
+ */
6138
+ private estimateCompoundBenefit;
6139
+ /**
6140
+ * Estimate memory cost of adding a compound index.
6141
+ */
6142
+ private estimateCompoundMemoryCost;
6143
+ /**
6144
+ * Calculate priority for compound index suggestion.
6145
+ */
6146
+ private calculateCompoundPriority;
6147
+ /**
6148
+ * Generate human-readable reason for compound index suggestion.
6149
+ */
6150
+ private generateCompoundReason;
6151
+ }
6152
+
6153
+ /**
6154
+ * AutoIndexManager (Phase 8.02.3)
6155
+ *
6156
+ * Automatically creates indexes based on query patterns.
6157
+ * Intended for development mode to simplify index management.
6158
+ *
6159
+ * Features:
6160
+ * - Automatic index creation after threshold queries
6161
+ * - Safety limits to prevent memory exhaustion
6162
+ * - Callback notifications for index creation events
6163
+ * - Integration with IndexAdvisor for type selection
6164
+ *
6165
+ * @module query/adaptive/AutoIndexManager
6166
+ */
6167
+
6168
+ /**
6169
+ * Interface for indexed map operations.
6170
+ * Used to decouple AutoIndexManager from IndexedLWWMap/IndexedORMap.
6171
+ */
6172
+ interface IndexableMap<K, V> {
6173
+ /** Get all current indexes */
6174
+ getIndexes(): {
6175
+ attribute: {
6176
+ name: string;
6177
+ };
6178
+ type: string;
6179
+ }[];
6180
+ /** Check if attribute has an index */
6181
+ hasIndexOn(attributeName: string): boolean;
6182
+ /** Add a hash index */
6183
+ addHashIndex<A>(attribute: Attribute<V, A>): void;
6184
+ /** Add a navigable index */
6185
+ addNavigableIndex<A extends string | number>(attribute: Attribute<V, A>): void;
6186
+ /** Add an inverted index */
6187
+ addInvertedIndex<A extends string>(attribute: Attribute<V, A>): void;
6188
+ }
6189
+ /**
6190
+ * AutoIndexManager automatically creates indexes based on query patterns.
6191
+ *
6192
+ * @example
6193
+ * ```typescript
6194
+ * const manager = new AutoIndexManager(tracker, advisor, {
6195
+ * enabled: true,
6196
+ * threshold: 10,
6197
+ * maxIndexes: 20,
6198
+ * onIndexCreated: (attr, type) => console.log(`Created ${type} on ${attr}`)
6199
+ * });
6200
+ *
6201
+ * manager.registerAttribute(simpleAttribute('category', p => p.category));
6202
+ * manager.setMap(indexedMap);
6203
+ *
6204
+ * // After 10 queries on 'category', index is auto-created
6205
+ * ```
6206
+ */
6207
+ declare class AutoIndexManager<K, V> {
6208
+ private readonly tracker;
6209
+ private readonly advisor;
6210
+ private readonly config;
6211
+ private readonly attributeQueryCounts;
6212
+ private readonly registeredAttributes;
6213
+ private readonly createdIndexes;
6214
+ private map;
6215
+ constructor(tracker: QueryPatternTracker, advisor: IndexAdvisor, config: AutoIndexConfig);
6216
+ /**
6217
+ * Set the indexed map to create indexes on.
6218
+ */
6219
+ setMap(map: IndexableMap<K, V>): void;
6220
+ /**
6221
+ * Register an attribute that can be auto-indexed.
6222
+ *
6223
+ * @param attribute - The attribute to register
6224
+ * @param allowedIndexTypes - Optional list of allowed index types
6225
+ */
6226
+ registerAttribute<A>(attribute: Attribute<V, A>, allowedIndexTypes?: RecommendedIndexType[]): void;
6227
+ /**
6228
+ * Unregister an attribute.
6229
+ *
6230
+ * @param attributeName - Name of attribute to unregister
6231
+ */
6232
+ unregisterAttribute(attributeName: string): void;
6233
+ /**
6234
+ * Check if an attribute is registered.
6235
+ *
6236
+ * @param attributeName - Name of attribute to check
6237
+ * @returns True if attribute is registered
6238
+ */
6239
+ hasAttribute(attributeName: string): boolean;
6240
+ /**
6241
+ * Get a registered attribute.
6242
+ *
6243
+ * @param attributeName - Name of attribute
6244
+ * @returns The attribute or undefined
6245
+ */
6246
+ getAttribute(attributeName: string): Attribute<V, unknown> | undefined;
6247
+ /**
6248
+ * Get all registered attribute names.
6249
+ *
6250
+ * @returns Array of registered attribute names
6251
+ */
6252
+ getRegisteredAttributeNames(): string[];
6253
+ /**
6254
+ * Called when a query is executed. Tracks patterns and triggers auto-indexing.
6255
+ *
6256
+ * @param attribute - The attribute being queried
6257
+ * @param queryType - The type of query
6258
+ */
6259
+ onQueryExecuted(attribute: string, queryType: TrackedQueryType): void;
6260
+ /**
6261
+ * Check if we're at the index limit.
6262
+ *
6263
+ * @returns True if max indexes reached
6264
+ */
6265
+ isAtLimit(): boolean;
6266
+ /**
6267
+ * Get number of auto-created indexes.
6268
+ *
6269
+ * @returns Number of indexes created by this manager
6270
+ */
6271
+ getAutoCreatedIndexCount(): number;
6272
+ /**
6273
+ * Get remaining index capacity.
6274
+ *
6275
+ * @returns Number of indexes that can still be created
6276
+ */
6277
+ getRemainingCapacity(): number;
6278
+ /**
6279
+ * Reset query counts (e.g., after clearing data).
6280
+ */
6281
+ resetCounts(): void;
6282
+ /**
6283
+ * Get current configuration.
6284
+ */
6285
+ getConfig(): Readonly<AutoIndexConfig>;
6286
+ /**
6287
+ * Update configuration at runtime.
6288
+ *
6289
+ * @param updates - Partial config updates
6290
+ */
6291
+ updateConfig(updates: Partial<AutoIndexConfig>): void;
6292
+ /**
6293
+ * Try to create an index for the attribute.
6294
+ */
6295
+ private tryCreateIndex;
6296
+ /**
6297
+ * Create an index on the map.
6298
+ */
6299
+ private createIndex;
6300
+ }
6301
+
6302
+ /**
6303
+ * IndexedLWWMap Implementation
6304
+ *
6305
+ * LWWMap with index support for O(1) to O(log N) queries.
6306
+ * Wraps LWWMap with indexing capabilities using the Wrapper Pattern.
6307
+ *
6308
+ * Features:
6309
+ * - Hash and Navigable indexes for efficient queries
6310
+ * - Live queries with StandingQueryIndex
6311
+ * - Automatic index updates on CRDT operations
6312
+ * - Cost-based query optimization
6313
+ * - Adaptive indexing with query pattern tracking (Phase 8.02)
6314
+ *
6315
+ * @module IndexedLWWMap
6316
+ */
6317
+
6318
+ /**
6319
+ * LWWMap with index support for O(1) to O(log N) queries.
6320
+ *
6321
+ * K = key type (extends string for compatibility)
6322
+ * V = value type
6323
+ */
6324
+ declare class IndexedLWWMap<K extends string, V> extends LWWMap<K, V> {
6325
+ private indexRegistry;
6326
+ private standingQueryRegistry;
6327
+ private liveQueryManager;
6328
+ private queryOptimizer;
6329
+ private readonly queryTracker;
6330
+ private readonly indexAdvisor;
6331
+ private readonly autoIndexManager;
6332
+ private readonly defaultIndexingStrategy;
6333
+ private readonly options;
6334
+ constructor(hlc: HLC, options?: IndexedMapOptions);
6335
+ /**
6336
+ * Add a hash index on an attribute.
6337
+ * If lazyIndexBuilding is enabled, creates a LazyHashIndex instead.
6338
+ *
6339
+ * @param attribute - Attribute to index
6340
+ * @returns Created HashIndex (or LazyHashIndex)
6341
+ */
6342
+ addHashIndex<A>(attribute: Attribute<V, A>): HashIndex<K, V, A> | LazyHashIndex<K, V, A>;
6343
+ /**
6344
+ * Add a navigable index on an attribute.
6345
+ * Navigable indexes support range queries (gt, gte, lt, lte, between).
6346
+ * If lazyIndexBuilding is enabled, creates a LazyNavigableIndex instead.
6347
+ *
6348
+ * @param attribute - Attribute to index
6349
+ * @param comparator - Optional custom comparator
6350
+ * @returns Created NavigableIndex (or LazyNavigableIndex)
6351
+ */
6352
+ addNavigableIndex<A extends string | number>(attribute: Attribute<V, A>, comparator?: (a: A, b: A) => number): NavigableIndex<K, V, A> | LazyNavigableIndex<K, V, A>;
6353
+ /**
6354
+ * Add an inverted index for full-text search on an attribute.
6355
+ * Inverted indexes support text search queries (contains, containsAll, containsAny).
6356
+ * If lazyIndexBuilding is enabled, creates a LazyInvertedIndex instead.
6357
+ *
6358
+ * @param attribute - Text attribute to index
6359
+ * @param pipeline - Optional custom tokenization pipeline
6360
+ * @returns Created InvertedIndex (or LazyInvertedIndex)
6361
+ *
6362
+ * @example
6363
+ * ```typescript
6364
+ * const nameAttr = simpleAttribute<Product, string>('name', p => p.name);
6365
+ * products.addInvertedIndex(nameAttr);
6366
+ *
6367
+ * // Search for products containing "wireless"
6368
+ * products.query({ type: 'contains', attribute: 'name', value: 'wireless' });
6369
+ * ```
6370
+ */
6371
+ addInvertedIndex<A extends string = string>(attribute: Attribute<V, A>, pipeline?: TokenizationPipeline): InvertedIndex<K, V, A> | LazyInvertedIndex<K, V, A>;
6372
+ /**
6373
+ * Add a custom index.
6374
+ *
6375
+ * @param index - Index to add
6376
+ */
6377
+ addIndex<A>(index: Index<K, V, A>): void;
6378
+ /**
6379
+ * Remove an index.
6380
+ *
6381
+ * @param index - Index to remove
6382
+ * @returns true if index was found and removed
6383
+ */
6384
+ removeIndex<A>(index: Index<K, V, A>): boolean;
6385
+ /**
6386
+ * Get all indexes.
6387
+ *
6388
+ * @returns Array of all indexes
6389
+ */
6390
+ getIndexes(): Index<K, V, unknown>[];
6391
+ /**
6392
+ * Check if an attribute is indexed.
6393
+ *
6394
+ * @param attributeName - Attribute name
6395
+ * @returns true if attribute has indexes
6396
+ */
6397
+ hasIndexOn(attributeName: string): boolean;
6398
+ /**
6399
+ * Build index from existing data.
6400
+ */
6401
+ private buildIndex;
6402
+ /**
6403
+ * Execute a query using indexes.
6404
+ * Returns lazy ResultSet of matching keys.
6405
+ *
6406
+ * Also tracks query patterns for adaptive indexing (Phase 8.02).
6407
+ *
6408
+ * @param query - Query to execute
6409
+ * @returns ResultSet of matching keys
6410
+ */
6411
+ query(query: Query): ResultSet<K>;
6412
+ /**
6413
+ * Execute a query and return materialized results.
6414
+ * Returns array of [key, value] pairs.
6415
+ *
6416
+ * @param query - Query to execute
6417
+ * @returns Array of [key, value] pairs
6418
+ */
6419
+ queryEntries(query: Query): [K, V][];
6420
+ /**
6421
+ * Execute a query and return matching values.
6422
+ *
6423
+ * @param query - Query to execute
6424
+ * @returns Array of matching values
6425
+ */
6426
+ queryValues(query: Query): V[];
6427
+ /**
6428
+ * Count matching records without materializing results.
6429
+ *
6430
+ * @param query - Query to execute
6431
+ * @returns Number of matching records
6432
+ */
6433
+ count(query: Query): number;
6434
+ /**
6435
+ * Execute plan and return result set.
6436
+ */
6437
+ private executePlan;
6438
+ /**
6439
+ * Perform full scan with predicate evaluation.
6440
+ */
6441
+ private fullScan;
6442
+ /**
6443
+ * Check if record matches predicate.
6444
+ * Converts Query to PredicateNode format for evaluation.
6445
+ */
6446
+ private matchesPredicate;
6447
+ /**
6448
+ * Check if record matches IndexQuery (used by FallbackIndex).
6449
+ * This is a simplified matcher for full scan fallback.
6450
+ */
6451
+ private matchesIndexQuery;
6452
+ /**
6453
+ * Convert Query to PredicateNode format.
6454
+ */
6455
+ private queryToPredicate;
6456
+ /**
6457
+ * Subscribe to a live query.
6458
+ * Callback receives initial results and delta updates.
6459
+ *
6460
+ * @param query - Query to subscribe to
6461
+ * @param callback - Callback for query events
6462
+ * @returns Unsubscribe function
6463
+ */
6464
+ subscribeLiveQuery(query: Query, callback: LiveQueryCallback<K, V>): () => void;
6465
+ /**
6466
+ * Get current live query results (snapshot).
6467
+ *
6468
+ * @param query - Query to execute
6469
+ * @returns Array of matching keys
6470
+ */
6471
+ getLiveQueryResults(query: Query): K[];
6472
+ /**
6473
+ * Check if a query has active subscribers.
6474
+ *
6475
+ * @param query - Query to check
6476
+ * @returns true if query has subscribers
6477
+ */
6478
+ hasLiveQuerySubscribers(query: Query): boolean;
6479
+ /**
6480
+ * Set a value (with index updates).
6481
+ */
6482
+ set(key: K, value: V, ttlMs?: number): LWWRecord<V>;
6483
+ /**
6484
+ * Remove a value (with index updates).
6485
+ */
6486
+ remove(key: K): LWWRecord<V>;
6487
+ /**
6488
+ * Merge a remote record (with index updates).
6489
+ */
6490
+ merge(key: K, remote: LWWRecord<V>): boolean;
6491
+ /**
6492
+ * Clear all data (and indexes).
6493
+ */
6494
+ clear(): void;
6495
+ /**
6496
+ * Returns all keys (non-tombstoned, non-expired).
6497
+ */
6498
+ keys(): Iterable<K>;
6499
+ /**
6500
+ * Get index statistics.
6501
+ */
6502
+ getIndexStats(): Map<string, IndexStats>;
6503
+ /**
6504
+ * Get index registry statistics.
6505
+ */
6506
+ getIndexRegistryStats(): IndexRegistryStats;
6507
+ /**
6508
+ * Get query optimizer for plan inspection.
6509
+ */
6510
+ getQueryOptimizer(): QueryOptimizer<K, V>;
6511
+ /**
6512
+ * Get live query manager for direct access.
6513
+ */
6514
+ getLiveQueryManager(): LiveQueryManager<K, V>;
6515
+ /**
6516
+ * Get standing query registry for direct access.
6517
+ */
6518
+ getStandingQueryRegistry(): StandingQueryRegistry<K, V>;
6519
+ /**
6520
+ * Explain query execution plan.
6521
+ *
6522
+ * @param query - Query to explain
6523
+ * @returns Query execution plan
6524
+ */
6525
+ explainQuery(query: Query): QueryPlan;
6526
+ /**
6527
+ * Register an attribute for auto-indexing.
6528
+ * Required before auto-index can create indexes on this attribute.
6529
+ *
6530
+ * @param attribute - The attribute to register
6531
+ * @param allowedIndexTypes - Optional list of allowed index types
6532
+ */
6533
+ registerAttribute<A>(attribute: Attribute<V, A>, allowedIndexTypes?: RecommendedIndexType[]): void;
6534
+ /**
6535
+ * Unregister an attribute from auto-indexing.
6536
+ *
6537
+ * @param attributeName - Name of attribute to unregister
6538
+ */
6539
+ unregisterAttribute(attributeName: string): void;
6540
+ /**
6541
+ * Get index suggestions based on query patterns.
6542
+ * Use this in production to get recommendations for manual index creation.
6543
+ *
6544
+ * @param options - Suggestion options
6545
+ * @returns Array of index suggestions sorted by priority
6546
+ *
6547
+ * @example
6548
+ * ```typescript
6549
+ * const suggestions = products.getIndexSuggestions();
6550
+ * // [{ attribute: 'category', indexType: 'hash', priority: 'high', ... }]
6551
+ * ```
6552
+ */
6553
+ getIndexSuggestions(options?: IndexSuggestionOptions): IndexSuggestion[];
6554
+ /**
6555
+ * Get query pattern statistics.
6556
+ * Useful for debugging and understanding query patterns.
6557
+ *
6558
+ * @returns Array of query statistics
6559
+ */
6560
+ getQueryStatistics(): QueryStatistics[];
6561
+ /**
6562
+ * Reset query statistics.
6563
+ * Call this to clear accumulated query patterns.
6564
+ */
6565
+ resetQueryStatistics(): void;
6566
+ /**
6567
+ * Get query pattern tracker for advanced usage.
6568
+ */
6569
+ getQueryTracker(): QueryPatternTracker;
6570
+ /**
6571
+ * Get index advisor for advanced usage.
6572
+ */
6573
+ getIndexAdvisor(): IndexAdvisor;
6574
+ /**
6575
+ * Get auto-index manager (if enabled).
6576
+ */
6577
+ getAutoIndexManager(): AutoIndexManager<K, V> | null;
6578
+ /**
6579
+ * Check if auto-indexing is enabled.
6580
+ */
6581
+ isAutoIndexingEnabled(): boolean;
6582
+ /**
6583
+ * Check if lazy index building is enabled.
6584
+ */
6585
+ isLazyIndexingEnabled(): boolean;
6586
+ /**
6587
+ * Force materialization of all lazy indexes.
6588
+ * Useful to pre-warm indexes before critical operations.
6589
+ *
6590
+ * @param progressCallback - Optional progress callback
6591
+ */
6592
+ materializeAllIndexes(progressCallback?: IndexBuildProgressCallback): void;
6593
+ /**
6594
+ * Get count of pending records across all lazy indexes.
6595
+ * Returns 0 if no lazy indexes or all are materialized.
6596
+ */
6597
+ getPendingIndexCount(): number;
6598
+ /**
6599
+ * Check if any lazy indexes are still pending (not built).
6600
+ */
6601
+ hasUnbuiltIndexes(): boolean;
6602
+ /**
6603
+ * Track query pattern for adaptive indexing.
6604
+ */
6605
+ private trackQueryPattern;
6606
+ /**
6607
+ * Extract attribute name from query.
6608
+ */
6609
+ private extractAttribute;
6610
+ /**
6611
+ * Extract query type from query.
6612
+ */
6613
+ private extractQueryType;
6614
+ }
6615
+
6616
+ /**
6617
+ * IndexedORMap Implementation
6618
+ *
6619
+ * ORMap with index support for O(1) to O(log N) queries.
6620
+ * Wraps ORMap with indexing capabilities using the Wrapper Pattern.
6621
+ *
6622
+ * Note: ORMap stores multiple values per key (with tags).
6623
+ * Indexes track unique (key, tag) composite keys.
6624
+ *
6625
+ * Features:
6626
+ * - Hash and Navigable indexes for efficient queries
6627
+ * - Composite key indexing (key:tag)
6628
+ * - Automatic index updates on CRDT operations
6629
+ * - Lazy filtering for tombstones
6630
+ * - Adaptive indexing with query pattern tracking (Phase 8.02)
6631
+ *
6632
+ * @module IndexedORMap
6633
+ */
6634
+
6635
+ /**
6636
+ * Result of a query on IndexedORMap.
6637
+ */
6638
+ interface ORMapQueryResult<K, V> {
6639
+ key: K;
6640
+ tag: string;
6641
+ value: V;
6642
+ }
6643
+ /**
6644
+ * ORMap with index support.
6645
+ *
6646
+ * Note: ORMap stores multiple values per key (with tags).
6647
+ * Indexes track unique (key, tag) pairs using composite keys.
6648
+ *
6649
+ * K = key type (extends string for compatibility)
6650
+ * V = value type
6651
+ */
6652
+ declare class IndexedORMap<K extends string, V> extends ORMap<K, V> {
6653
+ private indexRegistry;
6654
+ private queryOptimizer;
6655
+ private readonly queryTracker;
6656
+ private readonly indexAdvisor;
6657
+ private readonly autoIndexManager;
6658
+ private readonly defaultIndexingStrategy;
6659
+ private readonly options;
6660
+ constructor(hlc: HLC, options?: IndexedMapOptions);
6661
+ /**
6662
+ * Add a hash index on an attribute.
6663
+ *
6664
+ * @param attribute - Attribute to index
6665
+ * @returns Created HashIndex
6666
+ */
6667
+ addHashIndex<A>(attribute: Attribute<V, A>): HashIndex<string, V, A>;
6668
+ /**
6669
+ * Add a navigable index on an attribute.
6670
+ * Navigable indexes support range queries (gt, gte, lt, lte, between).
6671
+ *
6672
+ * @param attribute - Attribute to index
6673
+ * @param comparator - Optional custom comparator
6674
+ * @returns Created NavigableIndex
6675
+ */
6676
+ addNavigableIndex<A extends string | number>(attribute: Attribute<V, A>, comparator?: (a: A, b: A) => number): NavigableIndex<string, V, A>;
6677
+ /**
6678
+ * Add an inverted index for full-text search on an attribute.
6679
+ * Inverted indexes support text search queries (contains, containsAll, containsAny).
6680
+ *
6681
+ * @param attribute - Text attribute to index
6682
+ * @param pipeline - Optional custom tokenization pipeline
6683
+ * @returns Created InvertedIndex
6684
+ */
6685
+ addInvertedIndex<A extends string = string>(attribute: Attribute<V, A>, pipeline?: TokenizationPipeline): InvertedIndex<string, V, A>;
6686
+ /**
6687
+ * Add a custom index.
6688
+ *
6689
+ * @param index - Index to add
6690
+ */
6691
+ addIndex<A>(index: Index<string, V, A>): void;
6692
+ /**
6693
+ * Remove an index.
6694
+ *
6695
+ * @param index - Index to remove
6696
+ * @returns true if index was found and removed
6697
+ */
6698
+ removeIndex<A>(index: Index<string, V, A>): boolean;
6699
+ /**
6700
+ * Get all indexes.
6701
+ *
6702
+ * @returns Array of all indexes
6703
+ */
6704
+ getIndexes(): Index<string, V, unknown>[];
6705
+ /**
6706
+ * Check if an attribute is indexed.
6707
+ *
6708
+ * @param attributeName - Attribute name
6709
+ * @returns true if attribute has indexes
6710
+ */
6711
+ hasIndexOn(attributeName: string): boolean;
6712
+ /**
6713
+ * Build index from existing data.
6714
+ */
6715
+ private buildIndexFromExisting;
6716
+ /**
6717
+ * Execute a query across all records.
6718
+ * Returns array of matching results with key, tag, and value.
6719
+ *
6720
+ * Also tracks query patterns for adaptive indexing (Phase 8.02).
6721
+ *
6722
+ * @param query - Query to execute
6723
+ * @returns Array of query results
6724
+ */
6725
+ query(query: Query): ORMapQueryResult<K, V>[];
6726
+ /**
6727
+ * Execute a query and return matching values only.
6728
+ *
6729
+ * @param query - Query to execute
6730
+ * @returns Array of matching values
6731
+ */
6732
+ queryValues(query: Query): V[];
6733
+ /**
6734
+ * Count matching records without materializing results.
6735
+ *
6736
+ * @param query - Query to execute
6737
+ * @returns Number of matching records
6738
+ */
6739
+ count(query: Query): number;
6740
+ /**
6741
+ * Execute plan and return result set.
6742
+ */
6743
+ private executePlan;
6744
+ /**
6745
+ * Perform full scan with predicate evaluation.
6746
+ */
6747
+ private fullScan;
6748
+ /**
6749
+ * Add a value (with index updates).
6750
+ */
6751
+ add(key: K, value: V, ttlMs?: number): ORMapRecord<V>;
6752
+ /**
6753
+ * Remove a value (with index updates).
6754
+ */
6755
+ remove(key: K, value: V): string[];
6756
+ /**
6757
+ * Apply a record from remote (with index updates).
6758
+ */
6759
+ apply(key: K, record: ORMapRecord<V>): boolean;
6760
+ /**
6761
+ * Apply a tombstone (with index updates).
6762
+ */
6763
+ applyTombstone(tag: string): void;
6764
+ /**
6765
+ * Clear all data (and indexes).
6766
+ */
6767
+ clear(): void;
6768
+ /**
6769
+ * Create composite key from map key and tag.
6770
+ * Uses '||' as separator since HLC tags contain ':'
6771
+ */
6772
+ private createCompositeKey;
6773
+ /**
6774
+ * Parse composite key into [key, tag].
6775
+ * Expects '||' separator.
6776
+ */
6777
+ private parseCompositeKey;
6778
+ /**
6779
+ * Get all composite keys from the map.
6780
+ */
6781
+ private getAllCompositeKeys;
6782
+ /**
6783
+ * Get record by composite key.
6784
+ */
6785
+ private getRecordByCompositeKey;
6786
+ /**
6787
+ * Check if record matches predicate.
6788
+ */
6789
+ private matchesPredicate;
6790
+ /**
6791
+ * Check if record matches IndexQuery (used by FallbackIndex).
6792
+ * This is a simplified matcher for full scan fallback.
6793
+ */
6794
+ private matchesIndexQuery;
6795
+ /**
6796
+ * Convert Query to PredicateNode format.
6797
+ */
6798
+ private queryToPredicate;
6799
+ /**
6800
+ * Get index statistics.
6801
+ */
6802
+ getIndexStats(): Map<string, IndexStats>;
6803
+ /**
6804
+ * Get index registry statistics.
6805
+ */
6806
+ getIndexRegistryStats(): IndexRegistryStats;
6807
+ /**
6808
+ * Get query optimizer for plan inspection.
6809
+ */
6810
+ getQueryOptimizer(): QueryOptimizer<string, V>;
6811
+ /**
6812
+ * Explain query execution plan.
6813
+ *
6814
+ * @param query - Query to explain
6815
+ * @returns Query execution plan
6816
+ */
6817
+ explainQuery(query: Query): QueryPlan;
6818
+ /**
6819
+ * Register an attribute for auto-indexing.
6820
+ * Required before auto-index can create indexes on this attribute.
6821
+ *
6822
+ * @param attribute - The attribute to register
6823
+ * @param allowedIndexTypes - Optional list of allowed index types
6824
+ */
6825
+ registerAttribute<A>(attribute: Attribute<V, A>, allowedIndexTypes?: RecommendedIndexType[]): void;
6826
+ /**
6827
+ * Unregister an attribute from auto-indexing.
6828
+ *
6829
+ * @param attributeName - Name of attribute to unregister
6830
+ */
6831
+ unregisterAttribute(attributeName: string): void;
6832
+ /**
6833
+ * Get index suggestions based on query patterns.
6834
+ * Use this in production to get recommendations for manual index creation.
6835
+ *
6836
+ * @param options - Suggestion options
6837
+ * @returns Array of index suggestions sorted by priority
6838
+ */
6839
+ getIndexSuggestions(options?: IndexSuggestionOptions): IndexSuggestion[];
6840
+ /**
6841
+ * Get query pattern statistics.
6842
+ * Useful for debugging and understanding query patterns.
6843
+ *
6844
+ * @returns Array of query statistics
6845
+ */
6846
+ getQueryStatistics(): QueryStatistics[];
6847
+ /**
6848
+ * Reset query statistics.
6849
+ * Call this to clear accumulated query patterns.
6850
+ */
6851
+ resetQueryStatistics(): void;
6852
+ /**
6853
+ * Get query pattern tracker for advanced usage.
6854
+ */
6855
+ getQueryTracker(): QueryPatternTracker;
6856
+ /**
6857
+ * Get index advisor for advanced usage.
6858
+ */
6859
+ getIndexAdvisor(): IndexAdvisor;
6860
+ /**
6861
+ * Get auto-index manager (if enabled).
6862
+ */
6863
+ getAutoIndexManager(): AutoIndexManager<string, V> | null;
6864
+ /**
6865
+ * Check if auto-indexing is enabled.
6866
+ */
6867
+ isAutoIndexingEnabled(): boolean;
6868
+ /**
6869
+ * Track query pattern for adaptive indexing.
6870
+ */
6871
+ private trackQueryPattern;
6872
+ /**
6873
+ * Extract attribute name from query.
6874
+ */
6875
+ private extractAttribute;
6876
+ /**
6877
+ * Extract query type from query.
6878
+ */
6879
+ private extractQueryType;
6880
+ }
6881
+
6882
+ export { type Attribute, AuthMessageSchema, type BatchMessage, BatchMessageSchema, BuiltInProcessors, BuiltInResolvers, type CircuitBreakerConfig, type ClientOp, ClientOpMessageSchema, ClientOpSchema, type ClusterClientConfig, type ClusterEvents, type ReadOptions as ClusterReadOptions, type WriteOptions as ClusterWriteOptions, type CompareFn, type ConflictResolver, type ConflictResolverDef, ConflictResolverDefSchema, type ConflictResolverFn, ConflictResolverSchema, type ConnectionPoolConfig, type ConnectionState, ConsistencyLevel, CounterRequestSchema, CounterResponseSchema, CounterSyncSchema, CounterUpdateSchema, DEFAULT_BACKUP_COUNT, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_EVENT_JOURNAL_CONFIG, DEFAULT_MIGRATION_CONFIG, DEFAULT_PARTITION_ROUTER_CONFIG, DEFAULT_PROCESSOR_RATE_LIMITS, DEFAULT_REPLICATION_CONFIG, DEFAULT_RESOLVER_RATE_LIMITS, DEFAULT_STOP_WORDS, DEFAULT_WRITE_CONCERN_TIMEOUT, type EntryProcessBatchRequest, EntryProcessBatchRequestSchema, type EntryProcessBatchResponse, EntryProcessBatchResponseSchema, type EntryProcessKeyResult, EntryProcessKeyResultSchema, type EntryProcessRequest, EntryProcessRequestSchema, type EntryProcessResponse, EntryProcessResponseSchema, type EntryProcessorDef, EntryProcessorDefSchema, type EntryProcessorFn, type EntryProcessorResult, EntryProcessorSchema, type EventJournal, type EventJournalConfig, EventJournalImpl, FORBIDDEN_PATTERNS, FallbackIndex, type FilterStep, FilteringResultSet, type FullScanStep, HLC, HashIndex, type Index, type IndexQuery, IndexRegistry, type IndexRegistryStats, type IndexScanStep, type IndexStats, IndexedLWWMap, IndexedORMap, IntersectionResultSet, type IntersectionStep, InvertedIndex, type InvertedIndexStats, type IteratorFactory, type JournalEvent, type JournalEventData, JournalEventDataSchema, type JournalEventInput, type JournalEventListener, type JournalEventMessage, JournalEventMessageSchema, type JournalEventType, JournalEventTypeSchema, type JournalReadRequest, JournalReadRequestSchema, type JournalReadResponse, JournalReadResponseSchema, type JournalSubscribeRequest, JournalSubscribeRequestSchema, type JournalUnsubscribeRequest, JournalUnsubscribeRequestSchema, LWWMap, type LWWRecord, LWWRecordSchema, LazyResultSet, LimitResultSet, type ListResolversRequest, ListResolversRequestSchema, type ListResolversResponse, ListResolversResponseSchema, type LiveQueryCallback, type LiveQueryDeltaEvent, type LiveQueryEvent, type LiveQueryInitialEvent, LiveQueryManager, type LiveQueryManagerOptions, type LiveQueryManagerStats, LockReleaseSchema, LockRequestSchema, type LogicalQueryNode, LowercaseFilter, MaxLengthFilter, type MergeContext, type MergeKeyResult, type MergeRejectedMessage, MergeRejectedMessageSchema, type MergeRejection, type MergeResult, MerkleReqBucketMessageSchema, MerkleTree, type Message, MessageSchema, type MigrationChunkAckMessage, type MigrationChunkMessage, type MigrationCompleteMessage, type MigrationConfig, type MigrationMessage, type MigrationMetrics, type MigrationStartMessage, type MigrationStatus, type MigrationVerifyMessage, MinLengthFilter, MultiValueAttribute, NGramTokenizer, NavigableIndex, type NodeHealth, type NodeInfo, type NodeStatus, type NotOwnerError, type NotStep, ORMap, ORMapDiffRequestSchema, ORMapDiffResponseSchema, type ORMapMerkleNode, ORMapMerkleReqBucketSchema, ORMapMerkleTree, ORMapPushDiffSchema, type ORMapQueryResult, type ORMapRecord, ORMapRecordSchema, type ORMapSnapshot, ORMapSyncInitSchema, ORMapSyncRespBucketsSchema, ORMapSyncRespLeafSchema, ORMapSyncRespRootSchema, type OpAckMessage, OpAckMessageSchema, OpBatchMessageSchema, type OpRejectedMessage, OpRejectedMessageSchema, type OpResult, OpResultSchema, PARTITION_COUNT, type PNCounter, type PNCounterConfig, PNCounterImpl, type PNCounterState, type PNCounterStateObject, PNCounterStateObjectSchema, type PartitionChange, type PartitionInfo, type PartitionMap, type PartitionMapDeltaMessage, type PartitionMapMessage, type PartitionMapRequestMessage, PartitionMapRequestSchema, type PartitionMigration, type PartitionRouterConfig, PartitionState, type PendingWrite, type PermissionPolicy, type PermissionType, type PingMessage, PingMessageSchema, type PlanStep, type PongMessage, PongMessageSchema, type PredicateFn, type PredicateNode, PredicateNodeSchema, type PredicateOp, PredicateOpSchema, Predicates, type Principal, type ProcessorRateLimitConfig, type Query$1 as Query, type Query as QueryExpression, type QueryNode, QueryOptimizer, type QueryOptimizerOptions, type QueryOptions, type QueryPlan, QuerySchema, QuerySubMessageSchema, QueryUnsubMessageSchema, RESOLVER_FORBIDDEN_PATTERNS, type RegisterResolverRequest, RegisterResolverRequestSchema, type RegisterResolverResponse, RegisterResolverResponseSchema, type ReplicationAckMessage, type ReplicationBatchAckMessage, type ReplicationBatchMessage, type ReplicationConfig, type ReplicationHealth, type ReplicationLag, type ReplicationMessage, type ReplicationProtocolMessage, type ReplicationResult, type ReplicationTask, type ResolverRateLimitConfig, type ResultSet, Ringbuffer, type RoutingError, SetResultSet, SimpleAttribute, type SimpleQueryNode, SortedMap, SortedResultSet, type StaleMapError, type StandingQueryChange, StandingQueryIndex, type StandingQueryIndexOptions, StandingQueryRegistry, type StandingQueryRegistryOptions, type StandingQueryRegistryStats, StopWordFilter, SyncInitMessageSchema, SyncRespBucketsMessageSchema, SyncRespLeafMessageSchema, SyncRespRootMessageSchema, type Timestamp, TimestampSchema, type TokenFilter, TokenizationPipeline, type TokenizationPipelineOptions, type Tokenizer, TopicMessageEventSchema, TopicPubSchema, TopicSubSchema, TopicUnsubSchema, TrimFilter, UnionResultSet, type UnionStep, UniqueFilter, type UnregisterResolverRequest, UnregisterResolverRequestSchema, type UnregisterResolverResponse, UnregisterResolverResponseSchema, WRITE_CONCERN_ORDER, WhitespaceTokenizer, WordBoundaryTokenizer, WriteConcern, WriteConcernSchema, type WriteConcernValue, type WriteOptions$1 as WriteOptions, type WriteResult, combineHashes, compareHLCTimestamps, compareTimestamps, createFieldComparator, createPredicateMatcher, deepMerge, deserialize, disableNativeHash, evaluatePredicate, getHighestWriteConcernLevel, hashORMapEntry, hashORMapRecord, hashString, isLogicalQuery, isSimpleQuery, isUsingNativeHash, isWriteConcernAchieved, multiAttribute, resetNativeHash, serialize, simpleAttribute, timestampToString, validateProcessorCode, validateResolverCode };