@topgunbuild/core 0.10.0 → 0.11.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.js CHANGED
@@ -30,11 +30,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AuthFailMessageSchema: () => AuthFailMessageSchema,
33
34
  AuthMessageSchema: () => AuthMessageSchema,
34
35
  BM25Scorer: () => BM25Scorer,
35
36
  BatchMessageSchema: () => BatchMessageSchema,
36
37
  BuiltInProcessors: () => BuiltInProcessors,
37
38
  BuiltInResolvers: () => BuiltInResolvers,
39
+ COST_WEIGHTS: () => COST_WEIGHTS,
40
+ CRDTDebugger: () => CRDTDebugger,
41
+ CRDTInvariants: () => CRDTInvariants,
38
42
  ClientOpMessageSchema: () => ClientOpMessageSchema,
39
43
  ClientOpSchema: () => ClientOpSchema,
40
44
  ClusterSearchReqMessageSchema: () => ClusterSearchReqMessageSchema,
@@ -76,6 +80,7 @@ __export(index_exports, {
76
80
  DEFAULT_RESOLVER_RATE_LIMITS: () => DEFAULT_RESOLVER_RATE_LIMITS,
77
81
  DEFAULT_STOP_WORDS: () => DEFAULT_STOP_WORDS,
78
82
  DEFAULT_WRITE_CONCERN_TIMEOUT: () => DEFAULT_WRITE_CONCERN_TIMEOUT,
83
+ DeltaRecordSchema: () => DeltaRecordSchema,
79
84
  ENGLISH_STOPWORDS: () => ENGLISH_STOPWORDS,
80
85
  EntryProcessBatchRequestSchema: () => EntryProcessBatchRequestSchema,
81
86
  EntryProcessBatchResponseSchema: () => EntryProcessBatchResponseSchema,
@@ -91,12 +96,24 @@ __export(index_exports, {
91
96
  FallbackIndex: () => FallbackIndex,
92
97
  FilteringResultSet: () => FilteringResultSet,
93
98
  FullTextIndex: () => FullTextIndex,
99
+ GcPruneMessageSchema: () => GcPruneMessageSchema,
100
+ GcPrunePayloadSchema: () => GcPrunePayloadSchema,
94
101
  HLC: () => HLC,
95
102
  HashIndex: () => HashIndex,
103
+ HttpQueryRequestSchema: () => HttpQueryRequestSchema,
104
+ HttpQueryResultSchema: () => HttpQueryResultSchema,
105
+ HttpSearchRequestSchema: () => HttpSearchRequestSchema,
106
+ HttpSearchResultSchema: () => HttpSearchResultSchema,
107
+ HttpSyncErrorSchema: () => HttpSyncErrorSchema,
108
+ HttpSyncRequestSchema: () => HttpSyncRequestSchema,
109
+ HttpSyncResponseSchema: () => HttpSyncResponseSchema,
110
+ HybridQueryDeltaPayloadSchema: () => HybridQueryDeltaPayloadSchema,
111
+ HybridQueryRespPayloadSchema: () => HybridQueryRespPayloadSchema,
96
112
  IndexRegistry: () => IndexRegistry,
97
113
  IndexedLWWMap: () => IndexedLWWMap,
98
114
  IndexedORMap: () => IndexedORMap,
99
115
  IntersectionResultSet: () => IntersectionResultSet,
116
+ InvariantChecker: () => InvariantChecker,
100
117
  InvertedIndex: () => InvertedIndex,
101
118
  JournalEventDataSchema: () => JournalEventDataSchema,
102
119
  JournalEventMessageSchema: () => JournalEventMessageSchema,
@@ -112,9 +129,12 @@ __export(index_exports, {
112
129
  ListResolversRequestSchema: () => ListResolversRequestSchema,
113
130
  ListResolversResponseSchema: () => ListResolversResponseSchema,
114
131
  LiveQueryManager: () => LiveQueryManager,
132
+ LockGrantedPayloadSchema: () => LockGrantedPayloadSchema,
115
133
  LockReleaseSchema: () => LockReleaseSchema,
134
+ LockReleasedPayloadSchema: () => LockReleasedPayloadSchema,
116
135
  LockRequestSchema: () => LockRequestSchema,
117
136
  LowercaseFilter: () => LowercaseFilter,
137
+ MapDeltaSchema: () => MapDeltaSchema,
118
138
  MaxLengthFilter: () => MaxLengthFilter,
119
139
  MergeRejectedMessageSchema: () => MergeRejectedMessageSchema,
120
140
  MerkleReqBucketMessageSchema: () => MerkleReqBucketMessageSchema,
@@ -156,12 +176,17 @@ __export(index_exports, {
156
176
  QuerySchema: () => QuerySchema,
157
177
  QuerySubMessageSchema: () => QuerySubMessageSchema,
158
178
  QueryUnsubMessageSchema: () => QueryUnsubMessageSchema,
179
+ QueryUpdateMessageSchema: () => QueryUpdateMessageSchema,
180
+ QueryUpdatePayloadSchema: () => QueryUpdatePayloadSchema,
159
181
  RESOLVER_FORBIDDEN_PATTERNS: () => RESOLVER_FORBIDDEN_PATTERNS,
182
+ RealClock: () => RealClock,
160
183
  ReciprocalRankFusion: () => ReciprocalRankFusion,
161
184
  RegisterResolverRequestSchema: () => RegisterResolverRequestSchema,
162
185
  RegisterResolverResponseSchema: () => RegisterResolverResponseSchema,
163
186
  Ringbuffer: () => Ringbuffer,
187
+ ScenarioRunner: () => ScenarioRunner,
164
188
  SearchCursor: () => SearchCursor,
189
+ SearchDebugger: () => SearchDebugger,
165
190
  SearchMessageSchema: () => SearchMessageSchema,
166
191
  SearchOptionsSchema: () => SearchOptionsSchema,
167
192
  SearchPayloadSchema: () => SearchPayloadSchema,
@@ -174,6 +199,10 @@ __export(index_exports, {
174
199
  SearchUpdateMessageSchema: () => SearchUpdateMessageSchema,
175
200
  SearchUpdatePayloadSchema: () => SearchUpdatePayloadSchema,
176
201
  SearchUpdateTypeSchema: () => SearchUpdateTypeSchema,
202
+ SeededRNG: () => SeededRNG,
203
+ ServerBatchEventMessageSchema: () => ServerBatchEventMessageSchema,
204
+ ServerEventMessageSchema: () => ServerEventMessageSchema,
205
+ ServerEventPayloadSchema: () => ServerEventPayloadSchema,
177
206
  SetResultSet: () => SetResultSet,
178
207
  SimpleAttribute: () => SimpleAttribute,
179
208
  SortedMap: () => SortedMap,
@@ -182,6 +211,8 @@ __export(index_exports, {
182
211
  StandingQueryRegistry: () => StandingQueryRegistry,
183
212
  StopWordFilter: () => StopWordFilter,
184
213
  SyncInitMessageSchema: () => SyncInitMessageSchema,
214
+ SyncMapEntrySchema: () => SyncMapEntrySchema,
215
+ SyncResetRequiredPayloadSchema: () => SyncResetRequiredPayloadSchema,
185
216
  SyncRespBucketsMessageSchema: () => SyncRespBucketsMessageSchema,
186
217
  SyncRespLeafMessageSchema: () => SyncRespLeafMessageSchema,
187
218
  SyncRespRootMessageSchema: () => SyncRespRootMessageSchema,
@@ -196,11 +227,14 @@ __export(index_exports, {
196
227
  UniqueFilter: () => UniqueFilter,
197
228
  UnregisterResolverRequestSchema: () => UnregisterResolverRequestSchema,
198
229
  UnregisterResolverResponseSchema: () => UnregisterResolverResponseSchema,
230
+ VirtualClock: () => VirtualClock,
231
+ VirtualNetwork: () => VirtualNetwork,
199
232
  WRITE_CONCERN_ORDER: () => WRITE_CONCERN_ORDER,
200
233
  WhitespaceTokenizer: () => WhitespaceTokenizer,
201
234
  WordBoundaryTokenizer: () => WordBoundaryTokenizer,
202
235
  WriteConcern: () => WriteConcern,
203
236
  WriteConcernSchema: () => WriteConcernSchema,
237
+ calculateTotalCost: () => calculateTotalCost,
204
238
  combineHashes: () => combineHashes,
205
239
  compareHLCTimestamps: () => compareHLCTimestamps,
206
240
  compareTimestamps: () => compareTimestamps,
@@ -213,7 +247,9 @@ __export(index_exports, {
213
247
  disableNativeHash: () => disableNativeHash,
214
248
  encodeBase64Url: () => encodeBase64Url,
215
249
  evaluatePredicate: () => evaluatePredicate,
250
+ getCRDTDebugger: () => getCRDTDebugger,
216
251
  getHighestWriteConcernLevel: () => getHighestWriteConcernLevel,
252
+ getSearchDebugger: () => getSearchDebugger,
217
253
  hashORMapEntry: () => hashORMapEntry,
218
254
  hashORMapRecord: () => hashORMapRecord,
219
255
  hashObject: () => hashObject,
@@ -222,9 +258,12 @@ __export(index_exports, {
222
258
  isSimpleQuery: () => isSimpleQuery,
223
259
  isUsingNativeHash: () => isUsingNativeHash,
224
260
  isWriteConcernAchieved: () => isWriteConcernAchieved,
261
+ logger: () => logger,
225
262
  multiAttribute: () => multiAttribute,
226
263
  porterStem: () => porterStem,
264
+ resetCRDTDebugger: () => resetCRDTDebugger,
227
265
  resetNativeHash: () => resetNativeHash,
266
+ resetSearchDebugger: () => resetSearchDebugger,
228
267
  serialize: () => serialize,
229
268
  simpleAttribute: () => simpleAttribute,
230
269
  timestampToString: () => timestampToString,
@@ -233,22 +272,48 @@ __export(index_exports, {
233
272
  });
234
273
  module.exports = __toCommonJS(index_exports);
235
274
 
275
+ // src/utils/logger.ts
276
+ var import_pino = __toESM(require("pino"));
277
+ var logLevel = typeof process !== "undefined" && process.env && process.env.LOG_LEVEL || "info";
278
+ var logger = (0, import_pino.default)({
279
+ level: logLevel,
280
+ browser: {
281
+ asObject: true
282
+ }
283
+ });
284
+
236
285
  // src/HLC.ts
237
- var _HLC = class _HLC {
238
- constructor(nodeId) {
286
+ var HLC = class {
287
+ constructor(nodeId, options = {}) {
239
288
  this.nodeId = nodeId;
289
+ this.strictMode = options.strictMode ?? false;
290
+ this.maxDriftMs = options.maxDriftMs ?? 6e4;
291
+ this.clockSource = options.clockSource ?? { now: () => Date.now() };
240
292
  this.lastMillis = 0;
241
293
  this.lastCounter = 0;
242
294
  }
243
295
  get getNodeId() {
244
296
  return this.nodeId;
245
297
  }
298
+ get getStrictMode() {
299
+ return this.strictMode;
300
+ }
301
+ get getMaxDriftMs() {
302
+ return this.maxDriftMs;
303
+ }
304
+ /**
305
+ * Returns the clock source used by this HLC instance.
306
+ * Useful for LWWMap/ORMap to access the same clock for TTL checks.
307
+ */
308
+ getClockSource() {
309
+ return this.clockSource;
310
+ }
246
311
  /**
247
312
  * Generates a new unique timestamp for a local event.
248
313
  * Ensures monotonicity: always greater than any previously generated or received timestamp.
249
314
  */
250
315
  now() {
251
- const systemTime = Date.now();
316
+ const systemTime = this.clockSource.now();
252
317
  if (systemTime > this.lastMillis) {
253
318
  this.lastMillis = systemTime;
254
319
  this.lastCounter = 0;
@@ -266,9 +331,19 @@ var _HLC = class _HLC {
266
331
  * Must be called whenever a message/event is received from another node.
267
332
  */
268
333
  update(remote) {
269
- const systemTime = Date.now();
270
- if (remote.millis > systemTime + _HLC.MAX_DRIFT) {
271
- console.warn(`Clock drift detected: Remote time ${remote.millis} is far ahead of local ${systemTime}`);
334
+ const systemTime = this.clockSource.now();
335
+ const drift = remote.millis - systemTime;
336
+ if (drift > this.maxDriftMs) {
337
+ if (this.strictMode) {
338
+ throw new Error(`Clock drift detected: Remote time ${remote.millis} is ${drift}ms ahead of local ${systemTime} (threshold: ${this.maxDriftMs}ms)`);
339
+ } else {
340
+ logger.warn({
341
+ drift,
342
+ remoteMillis: remote.millis,
343
+ localMillis: systemTime,
344
+ maxDriftMs: this.maxDriftMs
345
+ }, "Clock drift detected");
346
+ }
272
347
  }
273
348
  const maxMillis = Math.max(this.lastMillis, systemTime, remote.millis);
274
349
  if (maxMillis === this.lastMillis && maxMillis === remote.millis) {
@@ -317,9 +392,6 @@ var _HLC = class _HLC {
317
392
  };
318
393
  }
319
394
  };
320
- // Max allowable drift in milliseconds (1 minute)
321
- _HLC.MAX_DRIFT = 6e4;
322
- var HLC = _HLC;
323
395
 
324
396
  // src/utils/hash.ts
325
397
  var nativeHash = null;
@@ -543,7 +615,7 @@ var LWWMap = class {
543
615
  return void 0;
544
616
  }
545
617
  if (record.ttlMs) {
546
- const now = Date.now();
618
+ const now = this.hlc.getClockSource().now();
547
619
  if (record.timestamp.millis + record.ttlMs < now) {
548
620
  return void 0;
549
621
  }
@@ -620,7 +692,7 @@ var LWWMap = class {
620
692
  */
621
693
  entries() {
622
694
  const iterator = this.data.entries();
623
- const now = Date.now();
695
+ const clockSource = this.hlc.getClockSource();
624
696
  return {
625
697
  [Symbol.iterator]() {
626
698
  return this;
@@ -630,7 +702,7 @@ var LWWMap = class {
630
702
  while (!result.done) {
631
703
  const [key, record] = result.value;
632
704
  if (record.value !== null) {
633
- if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {
705
+ if (record.ttlMs && record.timestamp.millis + record.ttlMs < clockSource.now()) {
634
706
  result = iterator.next();
635
707
  continue;
636
708
  }
@@ -967,7 +1039,7 @@ var ORMap = class {
967
1039
  const keyMap = this.items.get(key);
968
1040
  if (!keyMap) return [];
969
1041
  const values = [];
970
- const now = Date.now();
1042
+ const now = this.hlc.getClockSource().now();
971
1043
  for (const [tag, record] of keyMap.entries()) {
972
1044
  if (!this.tombstones.has(tag)) {
973
1045
  if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {
@@ -987,7 +1059,7 @@ var ORMap = class {
987
1059
  const keyMap = this.items.get(key);
988
1060
  if (!keyMap) return [];
989
1061
  const records = [];
990
- const now = Date.now();
1062
+ const now = this.hlc.getClockSource().now();
991
1063
  for (const [tag, record] of keyMap.entries()) {
992
1064
  if (!this.tombstones.has(tag)) {
993
1065
  if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {
@@ -1508,7 +1580,7 @@ var EventJournalImpl = class {
1508
1580
  try {
1509
1581
  listener(event);
1510
1582
  } catch (e) {
1511
- console.error("EventJournal listener error:", e);
1583
+ logger.error({ err: e, context: "listener" }, "EventJournal listener error");
1512
1584
  }
1513
1585
  }
1514
1586
  return event;
@@ -1554,7 +1626,7 @@ var EventJournalImpl = class {
1554
1626
  try {
1555
1627
  listener(event);
1556
1628
  } catch (e) {
1557
- console.error("EventJournal replay error:", e);
1629
+ logger.error({ err: e, context: "replay" }, "EventJournal replay error");
1558
1630
  }
1559
1631
  }
1560
1632
  }
@@ -2213,7 +2285,7 @@ var Predicates = class {
2213
2285
  static containsAny(attribute, values) {
2214
2286
  return { op: "containsAny", attribute, value: values };
2215
2287
  }
2216
- // ============== Full-Text Search Predicates (Phase 12) ==============
2288
+ // ============== Full-Text Search Predicates ==============
2217
2289
  /**
2218
2290
  * Create a 'match' predicate for full-text search.
2219
2291
  * Uses BM25 scoring to find relevant documents.
@@ -2357,7 +2429,7 @@ function evaluatePredicate(predicate, data) {
2357
2429
  }
2358
2430
  }
2359
2431
 
2360
- // src/schemas.ts
2432
+ // src/schemas/base-schemas.ts
2361
2433
  var import_zod3 = require("zod");
2362
2434
  var WriteConcernSchema = import_zod3.z.enum([
2363
2435
  "FIRE_AND_FORGET",
@@ -2407,35 +2479,16 @@ var QuerySchema = import_zod3.z.object({
2407
2479
  sort: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.enum(["asc", "desc"])).optional(),
2408
2480
  limit: import_zod3.z.number().optional(),
2409
2481
  cursor: import_zod3.z.string().optional()
2410
- // Phase 14.1: replaces offset
2411
- });
2412
- var CursorStatusSchema = import_zod3.z.enum(["valid", "expired", "invalid", "none"]);
2413
- var QueryRespPayloadSchema = import_zod3.z.object({
2414
- queryId: import_zod3.z.string(),
2415
- results: import_zod3.z.array(import_zod3.z.object({
2416
- key: import_zod3.z.string(),
2417
- value: import_zod3.z.unknown()
2418
- })),
2419
- nextCursor: import_zod3.z.string().optional(),
2420
- hasMore: import_zod3.z.boolean().optional(),
2421
- /** Debug info: status of input cursor processing */
2422
- cursorStatus: CursorStatusSchema.optional()
2423
- });
2424
- var QueryRespMessageSchema = import_zod3.z.object({
2425
- type: import_zod3.z.literal("QUERY_RESP"),
2426
- payload: QueryRespPayloadSchema
2482
+ // Replaces offset for pagination
2427
2483
  });
2428
2484
  var ClientOpSchema = import_zod3.z.object({
2429
2485
  id: import_zod3.z.string().optional(),
2430
2486
  mapName: import_zod3.z.string(),
2431
2487
  key: import_zod3.z.string(),
2432
- // Permissive opType to match ServerCoordinator behavior logic
2433
- // It can be 'REMOVE', 'OR_ADD', 'OR_REMOVE' or undefined/other (implies PUT/LWW)
2434
2488
  opType: import_zod3.z.string().optional(),
2435
2489
  record: LWWRecordSchema.nullable().optional(),
2436
2490
  orRecord: ORMapRecordSchema.nullable().optional(),
2437
2491
  orTag: import_zod3.z.string().nullable().optional(),
2438
- // Write Concern fields (Phase 5.01)
2439
2492
  writeConcern: WriteConcernSchema.optional(),
2440
2493
  timeout: import_zod3.z.number().optional()
2441
2494
  });
@@ -2443,548 +2496,751 @@ var AuthMessageSchema = import_zod3.z.object({
2443
2496
  type: import_zod3.z.literal("AUTH"),
2444
2497
  token: import_zod3.z.string()
2445
2498
  });
2446
- var QuerySubMessageSchema = import_zod3.z.object({
2447
- type: import_zod3.z.literal("QUERY_SUB"),
2448
- payload: import_zod3.z.object({
2449
- queryId: import_zod3.z.string(),
2450
- mapName: import_zod3.z.string(),
2451
- query: QuerySchema
2452
- })
2453
- });
2454
- var QueryUnsubMessageSchema = import_zod3.z.object({
2455
- type: import_zod3.z.literal("QUERY_UNSUB"),
2456
- payload: import_zod3.z.object({
2457
- queryId: import_zod3.z.string()
2458
- })
2459
- });
2460
- var ClientOpMessageSchema = import_zod3.z.object({
2461
- type: import_zod3.z.literal("CLIENT_OP"),
2499
+
2500
+ // src/schemas/sync-schemas.ts
2501
+ var import_zod4 = require("zod");
2502
+ var ClientOpMessageSchema = import_zod4.z.object({
2503
+ type: import_zod4.z.literal("CLIENT_OP"),
2462
2504
  payload: ClientOpSchema
2463
2505
  });
2464
- var OpBatchMessageSchema = import_zod3.z.object({
2465
- type: import_zod3.z.literal("OP_BATCH"),
2466
- payload: import_zod3.z.object({
2467
- ops: import_zod3.z.array(ClientOpSchema),
2468
- // Batch-level Write Concern (can be overridden per-op)
2506
+ var OpBatchMessageSchema = import_zod4.z.object({
2507
+ type: import_zod4.z.literal("OP_BATCH"),
2508
+ payload: import_zod4.z.object({
2509
+ ops: import_zod4.z.array(ClientOpSchema),
2469
2510
  writeConcern: WriteConcernSchema.optional(),
2470
- timeout: import_zod3.z.number().optional()
2511
+ timeout: import_zod4.z.number().optional()
2471
2512
  })
2472
2513
  });
2473
- var SyncInitMessageSchema = import_zod3.z.object({
2474
- type: import_zod3.z.literal("SYNC_INIT"),
2475
- mapName: import_zod3.z.string(),
2476
- lastSyncTimestamp: import_zod3.z.number().optional()
2514
+ var SyncInitMessageSchema = import_zod4.z.object({
2515
+ type: import_zod4.z.literal("SYNC_INIT"),
2516
+ mapName: import_zod4.z.string(),
2517
+ lastSyncTimestamp: import_zod4.z.number().optional()
2477
2518
  });
2478
- var SyncRespRootMessageSchema = import_zod3.z.object({
2479
- type: import_zod3.z.literal("SYNC_RESP_ROOT"),
2480
- payload: import_zod3.z.object({
2481
- mapName: import_zod3.z.string(),
2482
- rootHash: import_zod3.z.number(),
2519
+ var SyncRespRootMessageSchema = import_zod4.z.object({
2520
+ type: import_zod4.z.literal("SYNC_RESP_ROOT"),
2521
+ payload: import_zod4.z.object({
2522
+ mapName: import_zod4.z.string(),
2523
+ rootHash: import_zod4.z.number(),
2483
2524
  timestamp: TimestampSchema
2484
2525
  })
2485
2526
  });
2486
- var SyncRespBucketsMessageSchema = import_zod3.z.object({
2487
- type: import_zod3.z.literal("SYNC_RESP_BUCKETS"),
2488
- payload: import_zod3.z.object({
2489
- mapName: import_zod3.z.string(),
2490
- path: import_zod3.z.string(),
2491
- buckets: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number())
2527
+ var SyncRespBucketsMessageSchema = import_zod4.z.object({
2528
+ type: import_zod4.z.literal("SYNC_RESP_BUCKETS"),
2529
+ payload: import_zod4.z.object({
2530
+ mapName: import_zod4.z.string(),
2531
+ path: import_zod4.z.string(),
2532
+ buckets: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number())
2492
2533
  })
2493
2534
  });
2494
- var SyncRespLeafMessageSchema = import_zod3.z.object({
2495
- type: import_zod3.z.literal("SYNC_RESP_LEAF"),
2496
- payload: import_zod3.z.object({
2497
- mapName: import_zod3.z.string(),
2498
- path: import_zod3.z.string(),
2499
- records: import_zod3.z.array(import_zod3.z.object({
2500
- key: import_zod3.z.string(),
2535
+ var SyncRespLeafMessageSchema = import_zod4.z.object({
2536
+ type: import_zod4.z.literal("SYNC_RESP_LEAF"),
2537
+ payload: import_zod4.z.object({
2538
+ mapName: import_zod4.z.string(),
2539
+ path: import_zod4.z.string(),
2540
+ records: import_zod4.z.array(import_zod4.z.object({
2541
+ key: import_zod4.z.string(),
2501
2542
  record: LWWRecordSchema
2502
2543
  }))
2503
2544
  })
2504
2545
  });
2505
- var MerkleReqBucketMessageSchema = import_zod3.z.object({
2506
- type: import_zod3.z.literal("MERKLE_REQ_BUCKET"),
2507
- payload: import_zod3.z.object({
2508
- mapName: import_zod3.z.string(),
2509
- path: import_zod3.z.string()
2546
+ var MerkleReqBucketMessageSchema = import_zod4.z.object({
2547
+ type: import_zod4.z.literal("MERKLE_REQ_BUCKET"),
2548
+ payload: import_zod4.z.object({
2549
+ mapName: import_zod4.z.string(),
2550
+ path: import_zod4.z.string()
2551
+ })
2552
+ });
2553
+ var ORMapSyncInitSchema = import_zod4.z.object({
2554
+ type: import_zod4.z.literal("ORMAP_SYNC_INIT"),
2555
+ mapName: import_zod4.z.string(),
2556
+ rootHash: import_zod4.z.number(),
2557
+ bucketHashes: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number()),
2558
+ lastSyncTimestamp: import_zod4.z.number().optional()
2559
+ });
2560
+ var ORMapSyncRespRootSchema = import_zod4.z.object({
2561
+ type: import_zod4.z.literal("ORMAP_SYNC_RESP_ROOT"),
2562
+ payload: import_zod4.z.object({
2563
+ mapName: import_zod4.z.string(),
2564
+ rootHash: import_zod4.z.number(),
2565
+ timestamp: TimestampSchema
2510
2566
  })
2511
2567
  });
2512
- var LockRequestSchema = import_zod3.z.object({
2513
- type: import_zod3.z.literal("LOCK_REQUEST"),
2514
- payload: import_zod3.z.object({
2515
- requestId: import_zod3.z.string(),
2516
- name: import_zod3.z.string(),
2517
- ttl: import_zod3.z.number().optional()
2568
+ var ORMapSyncRespBucketsSchema = import_zod4.z.object({
2569
+ type: import_zod4.z.literal("ORMAP_SYNC_RESP_BUCKETS"),
2570
+ payload: import_zod4.z.object({
2571
+ mapName: import_zod4.z.string(),
2572
+ path: import_zod4.z.string(),
2573
+ buckets: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number())
2518
2574
  })
2519
2575
  });
2520
- var LockReleaseSchema = import_zod3.z.object({
2521
- type: import_zod3.z.literal("LOCK_RELEASE"),
2522
- payload: import_zod3.z.object({
2523
- requestId: import_zod3.z.string().optional(),
2524
- name: import_zod3.z.string(),
2525
- fencingToken: import_zod3.z.number()
2576
+ var ORMapMerkleReqBucketSchema = import_zod4.z.object({
2577
+ type: import_zod4.z.literal("ORMAP_MERKLE_REQ_BUCKET"),
2578
+ payload: import_zod4.z.object({
2579
+ mapName: import_zod4.z.string(),
2580
+ path: import_zod4.z.string()
2526
2581
  })
2527
2582
  });
2528
- var TopicSubSchema = import_zod3.z.object({
2529
- type: import_zod3.z.literal("TOPIC_SUB"),
2530
- payload: import_zod3.z.object({
2531
- topic: import_zod3.z.string()
2583
+ var ORMapSyncRespLeafSchema = import_zod4.z.object({
2584
+ type: import_zod4.z.literal("ORMAP_SYNC_RESP_LEAF"),
2585
+ payload: import_zod4.z.object({
2586
+ mapName: import_zod4.z.string(),
2587
+ path: import_zod4.z.string(),
2588
+ entries: import_zod4.z.array(import_zod4.z.object({
2589
+ key: import_zod4.z.string(),
2590
+ records: import_zod4.z.array(ORMapRecordSchema),
2591
+ tombstones: import_zod4.z.array(import_zod4.z.string())
2592
+ }))
2532
2593
  })
2533
2594
  });
2534
- var TopicUnsubSchema = import_zod3.z.object({
2535
- type: import_zod3.z.literal("TOPIC_UNSUB"),
2536
- payload: import_zod3.z.object({
2537
- topic: import_zod3.z.string()
2595
+ var ORMapDiffRequestSchema = import_zod4.z.object({
2596
+ type: import_zod4.z.literal("ORMAP_DIFF_REQUEST"),
2597
+ payload: import_zod4.z.object({
2598
+ mapName: import_zod4.z.string(),
2599
+ keys: import_zod4.z.array(import_zod4.z.string())
2538
2600
  })
2539
2601
  });
2540
- var TopicPubSchema = import_zod3.z.object({
2541
- type: import_zod3.z.literal("TOPIC_PUB"),
2542
- payload: import_zod3.z.object({
2543
- topic: import_zod3.z.string(),
2544
- data: import_zod3.z.any()
2602
+ var ORMapDiffResponseSchema = import_zod4.z.object({
2603
+ type: import_zod4.z.literal("ORMAP_DIFF_RESPONSE"),
2604
+ payload: import_zod4.z.object({
2605
+ mapName: import_zod4.z.string(),
2606
+ entries: import_zod4.z.array(import_zod4.z.object({
2607
+ key: import_zod4.z.string(),
2608
+ records: import_zod4.z.array(ORMapRecordSchema),
2609
+ tombstones: import_zod4.z.array(import_zod4.z.string())
2610
+ }))
2545
2611
  })
2546
2612
  });
2547
- var TopicMessageEventSchema = import_zod3.z.object({
2548
- type: import_zod3.z.literal("TOPIC_MESSAGE"),
2549
- payload: import_zod3.z.object({
2550
- topic: import_zod3.z.string(),
2551
- data: import_zod3.z.any(),
2552
- publisherId: import_zod3.z.string().optional(),
2553
- timestamp: import_zod3.z.number()
2613
+ var ORMapPushDiffSchema = import_zod4.z.object({
2614
+ type: import_zod4.z.literal("ORMAP_PUSH_DIFF"),
2615
+ payload: import_zod4.z.object({
2616
+ mapName: import_zod4.z.string(),
2617
+ entries: import_zod4.z.array(import_zod4.z.object({
2618
+ key: import_zod4.z.string(),
2619
+ records: import_zod4.z.array(ORMapRecordSchema),
2620
+ tombstones: import_zod4.z.array(import_zod4.z.string())
2621
+ }))
2554
2622
  })
2555
2623
  });
2556
- var PNCounterStateObjectSchema = import_zod3.z.object({
2557
- p: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number()),
2558
- // positive counts per node
2559
- n: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number())
2560
- // negative counts per node
2624
+ var OpResultSchema = import_zod4.z.object({
2625
+ opId: import_zod4.z.string(),
2626
+ success: import_zod4.z.boolean(),
2627
+ achievedLevel: WriteConcernSchema,
2628
+ error: import_zod4.z.string().optional()
2561
2629
  });
2562
- var CounterRequestSchema = import_zod3.z.object({
2563
- type: import_zod3.z.literal("COUNTER_REQUEST"),
2564
- payload: import_zod3.z.object({
2565
- name: import_zod3.z.string()
2630
+ var OpAckMessageSchema = import_zod4.z.object({
2631
+ type: import_zod4.z.literal("OP_ACK"),
2632
+ payload: import_zod4.z.object({
2633
+ lastId: import_zod4.z.string(),
2634
+ achievedLevel: WriteConcernSchema.optional(),
2635
+ results: import_zod4.z.array(OpResultSchema).optional()
2566
2636
  })
2567
2637
  });
2568
- var CounterSyncSchema = import_zod3.z.object({
2569
- type: import_zod3.z.literal("COUNTER_SYNC"),
2570
- payload: import_zod3.z.object({
2571
- name: import_zod3.z.string(),
2572
- state: PNCounterStateObjectSchema
2638
+ var OpRejectedMessageSchema = import_zod4.z.object({
2639
+ type: import_zod4.z.literal("OP_REJECTED"),
2640
+ payload: import_zod4.z.object({
2641
+ opId: import_zod4.z.string(),
2642
+ reason: import_zod4.z.string(),
2643
+ code: import_zod4.z.number().optional()
2573
2644
  })
2574
2645
  });
2575
- var CounterResponseSchema = import_zod3.z.object({
2576
- type: import_zod3.z.literal("COUNTER_RESPONSE"),
2577
- payload: import_zod3.z.object({
2578
- name: import_zod3.z.string(),
2579
- state: PNCounterStateObjectSchema
2646
+ var BatchMessageSchema = import_zod4.z.object({
2647
+ type: import_zod4.z.literal("BATCH"),
2648
+ count: import_zod4.z.number(),
2649
+ data: import_zod4.z.instanceof(Uint8Array)
2650
+ });
2651
+
2652
+ // src/schemas/query-schemas.ts
2653
+ var import_zod5 = require("zod");
2654
+ var QuerySubMessageSchema = import_zod5.z.object({
2655
+ type: import_zod5.z.literal("QUERY_SUB"),
2656
+ payload: import_zod5.z.object({
2657
+ queryId: import_zod5.z.string(),
2658
+ mapName: import_zod5.z.string(),
2659
+ query: QuerySchema
2580
2660
  })
2581
2661
  });
2582
- var CounterUpdateSchema = import_zod3.z.object({
2583
- type: import_zod3.z.literal("COUNTER_UPDATE"),
2584
- payload: import_zod3.z.object({
2585
- name: import_zod3.z.string(),
2586
- state: PNCounterStateObjectSchema
2662
+ var QueryUnsubMessageSchema = import_zod5.z.object({
2663
+ type: import_zod5.z.literal("QUERY_UNSUB"),
2664
+ payload: import_zod5.z.object({
2665
+ queryId: import_zod5.z.string()
2587
2666
  })
2588
2667
  });
2589
- var PingMessageSchema = import_zod3.z.object({
2590
- type: import_zod3.z.literal("PING"),
2591
- timestamp: import_zod3.z.number()
2592
- // Client's Date.now()
2668
+ var CursorStatusSchema = import_zod5.z.enum(["valid", "expired", "invalid", "none"]);
2669
+ var QueryRespPayloadSchema = import_zod5.z.object({
2670
+ queryId: import_zod5.z.string(),
2671
+ results: import_zod5.z.array(import_zod5.z.object({
2672
+ key: import_zod5.z.string(),
2673
+ value: import_zod5.z.unknown()
2674
+ })),
2675
+ nextCursor: import_zod5.z.string().optional(),
2676
+ hasMore: import_zod5.z.boolean().optional(),
2677
+ cursorStatus: CursorStatusSchema.optional()
2593
2678
  });
2594
- var PongMessageSchema = import_zod3.z.object({
2595
- type: import_zod3.z.literal("PONG"),
2596
- timestamp: import_zod3.z.number(),
2597
- // Echo back client's timestamp
2598
- serverTime: import_zod3.z.number()
2599
- // Server's Date.now() (for clock skew detection)
2679
+ var QueryRespMessageSchema = import_zod5.z.object({
2680
+ type: import_zod5.z.literal("QUERY_RESP"),
2681
+ payload: QueryRespPayloadSchema
2600
2682
  });
2601
- var BatchMessageSchema = import_zod3.z.object({
2602
- type: import_zod3.z.literal("BATCH"),
2603
- count: import_zod3.z.number(),
2604
- data: import_zod3.z.instanceof(Uint8Array)
2683
+
2684
+ // src/schemas/search-schemas.ts
2685
+ var import_zod6 = require("zod");
2686
+ var SearchOptionsSchema = import_zod6.z.object({
2687
+ limit: import_zod6.z.number().optional(),
2688
+ minScore: import_zod6.z.number().optional(),
2689
+ boost: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.number()).optional()
2605
2690
  });
2606
- var ORMapSyncInitSchema = import_zod3.z.object({
2607
- type: import_zod3.z.literal("ORMAP_SYNC_INIT"),
2608
- mapName: import_zod3.z.string(),
2609
- rootHash: import_zod3.z.number(),
2610
- bucketHashes: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number()),
2611
- // path -> hash
2612
- lastSyncTimestamp: import_zod3.z.number().optional()
2691
+ var SearchPayloadSchema = import_zod6.z.object({
2692
+ requestId: import_zod6.z.string(),
2693
+ mapName: import_zod6.z.string(),
2694
+ query: import_zod6.z.string(),
2695
+ options: SearchOptionsSchema.optional()
2613
2696
  });
2614
- var ORMapSyncRespRootSchema = import_zod3.z.object({
2615
- type: import_zod3.z.literal("ORMAP_SYNC_RESP_ROOT"),
2616
- payload: import_zod3.z.object({
2617
- mapName: import_zod3.z.string(),
2618
- rootHash: import_zod3.z.number(),
2619
- timestamp: TimestampSchema
2697
+ var SearchMessageSchema = import_zod6.z.object({
2698
+ type: import_zod6.z.literal("SEARCH"),
2699
+ payload: SearchPayloadSchema
2700
+ });
2701
+ var SearchRespPayloadSchema = import_zod6.z.object({
2702
+ requestId: import_zod6.z.string(),
2703
+ results: import_zod6.z.array(import_zod6.z.object({
2704
+ key: import_zod6.z.string(),
2705
+ value: import_zod6.z.unknown(),
2706
+ score: import_zod6.z.number(),
2707
+ matchedTerms: import_zod6.z.array(import_zod6.z.string())
2708
+ })),
2709
+ totalCount: import_zod6.z.number(),
2710
+ error: import_zod6.z.string().optional()
2711
+ });
2712
+ var SearchRespMessageSchema = import_zod6.z.object({
2713
+ type: import_zod6.z.literal("SEARCH_RESP"),
2714
+ payload: SearchRespPayloadSchema
2715
+ });
2716
+ var SearchUpdateTypeSchema = import_zod6.z.enum(["ENTER", "UPDATE", "LEAVE"]);
2717
+ var SearchSubPayloadSchema = import_zod6.z.object({
2718
+ subscriptionId: import_zod6.z.string(),
2719
+ mapName: import_zod6.z.string(),
2720
+ query: import_zod6.z.string(),
2721
+ options: SearchOptionsSchema.optional()
2722
+ });
2723
+ var SearchSubMessageSchema = import_zod6.z.object({
2724
+ type: import_zod6.z.literal("SEARCH_SUB"),
2725
+ payload: SearchSubPayloadSchema
2726
+ });
2727
+ var SearchUpdatePayloadSchema = import_zod6.z.object({
2728
+ subscriptionId: import_zod6.z.string(),
2729
+ key: import_zod6.z.string(),
2730
+ value: import_zod6.z.unknown(),
2731
+ score: import_zod6.z.number(),
2732
+ matchedTerms: import_zod6.z.array(import_zod6.z.string()),
2733
+ type: SearchUpdateTypeSchema
2734
+ });
2735
+ var SearchUpdateMessageSchema = import_zod6.z.object({
2736
+ type: import_zod6.z.literal("SEARCH_UPDATE"),
2737
+ payload: SearchUpdatePayloadSchema
2738
+ });
2739
+ var SearchUnsubPayloadSchema = import_zod6.z.object({
2740
+ subscriptionId: import_zod6.z.string()
2741
+ });
2742
+ var SearchUnsubMessageSchema = import_zod6.z.object({
2743
+ type: import_zod6.z.literal("SEARCH_UNSUB"),
2744
+ payload: SearchUnsubPayloadSchema
2745
+ });
2746
+
2747
+ // src/schemas/cluster-schemas.ts
2748
+ var import_zod7 = require("zod");
2749
+ var PartitionMapRequestSchema = import_zod7.z.object({
2750
+ type: import_zod7.z.literal("PARTITION_MAP_REQUEST"),
2751
+ payload: import_zod7.z.object({
2752
+ currentVersion: import_zod7.z.number().optional()
2753
+ }).optional()
2754
+ });
2755
+ var ClusterSubRegisterPayloadSchema = import_zod7.z.object({
2756
+ subscriptionId: import_zod7.z.string(),
2757
+ coordinatorNodeId: import_zod7.z.string(),
2758
+ mapName: import_zod7.z.string(),
2759
+ type: import_zod7.z.enum(["SEARCH", "QUERY"]),
2760
+ searchQuery: import_zod7.z.string().optional(),
2761
+ searchOptions: import_zod7.z.object({
2762
+ limit: import_zod7.z.number().int().positive().optional(),
2763
+ minScore: import_zod7.z.number().optional(),
2764
+ boost: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.number()).optional()
2765
+ }).optional(),
2766
+ queryPredicate: import_zod7.z.any().optional(),
2767
+ querySort: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.enum(["asc", "desc"])).optional()
2768
+ });
2769
+ var ClusterSubRegisterMessageSchema = import_zod7.z.object({
2770
+ type: import_zod7.z.literal("CLUSTER_SUB_REGISTER"),
2771
+ payload: ClusterSubRegisterPayloadSchema
2772
+ });
2773
+ var ClusterSubAckPayloadSchema = import_zod7.z.object({
2774
+ subscriptionId: import_zod7.z.string(),
2775
+ nodeId: import_zod7.z.string(),
2776
+ success: import_zod7.z.boolean(),
2777
+ error: import_zod7.z.string().optional(),
2778
+ initialResults: import_zod7.z.array(import_zod7.z.object({
2779
+ key: import_zod7.z.string(),
2780
+ value: import_zod7.z.unknown(),
2781
+ score: import_zod7.z.number().optional(),
2782
+ matchedTerms: import_zod7.z.array(import_zod7.z.string()).optional()
2783
+ })).optional(),
2784
+ totalHits: import_zod7.z.number().int().nonnegative().optional()
2785
+ });
2786
+ var ClusterSubAckMessageSchema = import_zod7.z.object({
2787
+ type: import_zod7.z.literal("CLUSTER_SUB_ACK"),
2788
+ payload: ClusterSubAckPayloadSchema
2789
+ });
2790
+ var ClusterSubUpdatePayloadSchema = import_zod7.z.object({
2791
+ subscriptionId: import_zod7.z.string(),
2792
+ sourceNodeId: import_zod7.z.string(),
2793
+ key: import_zod7.z.string(),
2794
+ value: import_zod7.z.unknown(),
2795
+ score: import_zod7.z.number().optional(),
2796
+ matchedTerms: import_zod7.z.array(import_zod7.z.string()).optional(),
2797
+ changeType: import_zod7.z.enum(["ENTER", "UPDATE", "LEAVE"]),
2798
+ timestamp: import_zod7.z.number()
2799
+ });
2800
+ var ClusterSubUpdateMessageSchema = import_zod7.z.object({
2801
+ type: import_zod7.z.literal("CLUSTER_SUB_UPDATE"),
2802
+ payload: ClusterSubUpdatePayloadSchema
2803
+ });
2804
+ var ClusterSubUnregisterPayloadSchema = import_zod7.z.object({
2805
+ subscriptionId: import_zod7.z.string()
2806
+ });
2807
+ var ClusterSubUnregisterMessageSchema = import_zod7.z.object({
2808
+ type: import_zod7.z.literal("CLUSTER_SUB_UNREGISTER"),
2809
+ payload: ClusterSubUnregisterPayloadSchema
2810
+ });
2811
+ var ClusterSearchReqPayloadSchema = import_zod7.z.object({
2812
+ requestId: import_zod7.z.string(),
2813
+ mapName: import_zod7.z.string(),
2814
+ query: import_zod7.z.string(),
2815
+ options: import_zod7.z.object({
2816
+ limit: import_zod7.z.number().int().positive().max(1e3),
2817
+ minScore: import_zod7.z.number().optional(),
2818
+ boost: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.number()).optional(),
2819
+ includeMatchedTerms: import_zod7.z.boolean().optional(),
2820
+ afterScore: import_zod7.z.number().optional(),
2821
+ afterKey: import_zod7.z.string().optional()
2822
+ }),
2823
+ timeoutMs: import_zod7.z.number().int().positive().optional()
2824
+ });
2825
+ var ClusterSearchReqMessageSchema = import_zod7.z.object({
2826
+ type: import_zod7.z.literal("CLUSTER_SEARCH_REQ"),
2827
+ payload: ClusterSearchReqPayloadSchema
2828
+ });
2829
+ var ClusterSearchRespPayloadSchema = import_zod7.z.object({
2830
+ requestId: import_zod7.z.string(),
2831
+ nodeId: import_zod7.z.string(),
2832
+ results: import_zod7.z.array(import_zod7.z.object({
2833
+ key: import_zod7.z.string(),
2834
+ value: import_zod7.z.unknown(),
2835
+ score: import_zod7.z.number(),
2836
+ matchedTerms: import_zod7.z.array(import_zod7.z.string()).optional()
2837
+ })),
2838
+ totalHits: import_zod7.z.number().int().nonnegative(),
2839
+ executionTimeMs: import_zod7.z.number().nonnegative(),
2840
+ error: import_zod7.z.string().optional()
2841
+ });
2842
+ var ClusterSearchRespMessageSchema = import_zod7.z.object({
2843
+ type: import_zod7.z.literal("CLUSTER_SEARCH_RESP"),
2844
+ payload: ClusterSearchRespPayloadSchema
2845
+ });
2846
+ var ClusterSearchSubscribePayloadSchema = import_zod7.z.object({
2847
+ subscriptionId: import_zod7.z.string(),
2848
+ mapName: import_zod7.z.string(),
2849
+ query: import_zod7.z.string(),
2850
+ options: SearchOptionsSchema.optional()
2851
+ });
2852
+ var ClusterSearchSubscribeMessageSchema = import_zod7.z.object({
2853
+ type: import_zod7.z.literal("CLUSTER_SEARCH_SUBSCRIBE"),
2854
+ payload: ClusterSearchSubscribePayloadSchema
2855
+ });
2856
+ var ClusterSearchUnsubscribePayloadSchema = import_zod7.z.object({
2857
+ subscriptionId: import_zod7.z.string()
2858
+ });
2859
+ var ClusterSearchUnsubscribeMessageSchema = import_zod7.z.object({
2860
+ type: import_zod7.z.literal("CLUSTER_SEARCH_UNSUBSCRIBE"),
2861
+ payload: ClusterSearchUnsubscribePayloadSchema
2862
+ });
2863
+ var ClusterSearchUpdatePayloadSchema = import_zod7.z.object({
2864
+ subscriptionId: import_zod7.z.string(),
2865
+ nodeId: import_zod7.z.string(),
2866
+ key: import_zod7.z.string(),
2867
+ value: import_zod7.z.unknown(),
2868
+ score: import_zod7.z.number(),
2869
+ matchedTerms: import_zod7.z.array(import_zod7.z.string()).optional(),
2870
+ type: SearchUpdateTypeSchema
2871
+ });
2872
+ var ClusterSearchUpdateMessageSchema = import_zod7.z.object({
2873
+ type: import_zod7.z.literal("CLUSTER_SEARCH_UPDATE"),
2874
+ payload: ClusterSearchUpdatePayloadSchema
2875
+ });
2876
+
2877
+ // src/schemas/messaging-schemas.ts
2878
+ var import_zod8 = require("zod");
2879
+ var TopicSubSchema = import_zod8.z.object({
2880
+ type: import_zod8.z.literal("TOPIC_SUB"),
2881
+ payload: import_zod8.z.object({ topic: import_zod8.z.string() })
2882
+ });
2883
+ var TopicUnsubSchema = import_zod8.z.object({
2884
+ type: import_zod8.z.literal("TOPIC_UNSUB"),
2885
+ payload: import_zod8.z.object({ topic: import_zod8.z.string() })
2886
+ });
2887
+ var TopicPubSchema = import_zod8.z.object({
2888
+ type: import_zod8.z.literal("TOPIC_PUB"),
2889
+ payload: import_zod8.z.object({
2890
+ topic: import_zod8.z.string(),
2891
+ data: import_zod8.z.any()
2620
2892
  })
2621
2893
  });
2622
- var ORMapSyncRespBucketsSchema = import_zod3.z.object({
2623
- type: import_zod3.z.literal("ORMAP_SYNC_RESP_BUCKETS"),
2624
- payload: import_zod3.z.object({
2625
- mapName: import_zod3.z.string(),
2626
- path: import_zod3.z.string(),
2627
- buckets: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number())
2894
+ var TopicMessageEventSchema = import_zod8.z.object({
2895
+ type: import_zod8.z.literal("TOPIC_MESSAGE"),
2896
+ payload: import_zod8.z.object({
2897
+ topic: import_zod8.z.string(),
2898
+ data: import_zod8.z.any(),
2899
+ publisherId: import_zod8.z.string().optional(),
2900
+ timestamp: import_zod8.z.number()
2628
2901
  })
2629
2902
  });
2630
- var ORMapMerkleReqBucketSchema = import_zod3.z.object({
2631
- type: import_zod3.z.literal("ORMAP_MERKLE_REQ_BUCKET"),
2632
- payload: import_zod3.z.object({
2633
- mapName: import_zod3.z.string(),
2634
- path: import_zod3.z.string()
2903
+ var LockRequestSchema = import_zod8.z.object({
2904
+ type: import_zod8.z.literal("LOCK_REQUEST"),
2905
+ payload: import_zod8.z.object({
2906
+ requestId: import_zod8.z.string(),
2907
+ name: import_zod8.z.string(),
2908
+ ttl: import_zod8.z.number().optional()
2635
2909
  })
2636
2910
  });
2637
- var ORMapSyncRespLeafSchema = import_zod3.z.object({
2638
- type: import_zod3.z.literal("ORMAP_SYNC_RESP_LEAF"),
2639
- payload: import_zod3.z.object({
2640
- mapName: import_zod3.z.string(),
2641
- path: import_zod3.z.string(),
2642
- entries: import_zod3.z.array(import_zod3.z.object({
2643
- key: import_zod3.z.string(),
2644
- records: import_zod3.z.array(ORMapRecordSchema),
2645
- tombstones: import_zod3.z.array(import_zod3.z.string())
2646
- // Tombstone tags for this key's records
2647
- }))
2911
+ var LockReleaseSchema = import_zod8.z.object({
2912
+ type: import_zod8.z.literal("LOCK_RELEASE"),
2913
+ payload: import_zod8.z.object({
2914
+ requestId: import_zod8.z.string().optional(),
2915
+ name: import_zod8.z.string(),
2916
+ fencingToken: import_zod8.z.number()
2648
2917
  })
2649
2918
  });
2650
- var ORMapDiffRequestSchema = import_zod3.z.object({
2651
- type: import_zod3.z.literal("ORMAP_DIFF_REQUEST"),
2652
- payload: import_zod3.z.object({
2653
- mapName: import_zod3.z.string(),
2654
- keys: import_zod3.z.array(import_zod3.z.string())
2919
+ var PNCounterStateObjectSchema = import_zod8.z.object({
2920
+ p: import_zod8.z.record(import_zod8.z.string(), import_zod8.z.number()),
2921
+ n: import_zod8.z.record(import_zod8.z.string(), import_zod8.z.number())
2922
+ });
2923
+ var CounterRequestSchema = import_zod8.z.object({
2924
+ type: import_zod8.z.literal("COUNTER_REQUEST"),
2925
+ payload: import_zod8.z.object({ name: import_zod8.z.string() })
2926
+ });
2927
+ var CounterSyncSchema = import_zod8.z.object({
2928
+ type: import_zod8.z.literal("COUNTER_SYNC"),
2929
+ payload: import_zod8.z.object({
2930
+ name: import_zod8.z.string(),
2931
+ state: PNCounterStateObjectSchema
2655
2932
  })
2656
2933
  });
2657
- var ORMapDiffResponseSchema = import_zod3.z.object({
2658
- type: import_zod3.z.literal("ORMAP_DIFF_RESPONSE"),
2659
- payload: import_zod3.z.object({
2660
- mapName: import_zod3.z.string(),
2661
- entries: import_zod3.z.array(import_zod3.z.object({
2662
- key: import_zod3.z.string(),
2663
- records: import_zod3.z.array(ORMapRecordSchema),
2664
- tombstones: import_zod3.z.array(import_zod3.z.string())
2665
- }))
2934
+ var CounterResponseSchema = import_zod8.z.object({
2935
+ type: import_zod8.z.literal("COUNTER_RESPONSE"),
2936
+ payload: import_zod8.z.object({
2937
+ name: import_zod8.z.string(),
2938
+ state: PNCounterStateObjectSchema
2666
2939
  })
2667
2940
  });
2668
- var ORMapPushDiffSchema = import_zod3.z.object({
2669
- type: import_zod3.z.literal("ORMAP_PUSH_DIFF"),
2670
- payload: import_zod3.z.object({
2671
- mapName: import_zod3.z.string(),
2672
- entries: import_zod3.z.array(import_zod3.z.object({
2673
- key: import_zod3.z.string(),
2674
- records: import_zod3.z.array(ORMapRecordSchema),
2675
- tombstones: import_zod3.z.array(import_zod3.z.string())
2676
- }))
2941
+ var CounterUpdateSchema = import_zod8.z.object({
2942
+ type: import_zod8.z.literal("COUNTER_UPDATE"),
2943
+ payload: import_zod8.z.object({
2944
+ name: import_zod8.z.string(),
2945
+ state: PNCounterStateObjectSchema
2677
2946
  })
2678
2947
  });
2679
- var PartitionMapRequestSchema = import_zod3.z.object({
2680
- type: import_zod3.z.literal("PARTITION_MAP_REQUEST"),
2681
- payload: import_zod3.z.object({
2682
- currentVersion: import_zod3.z.number().optional()
2683
- }).optional()
2948
+ var PingMessageSchema = import_zod8.z.object({
2949
+ type: import_zod8.z.literal("PING"),
2950
+ timestamp: import_zod8.z.number()
2684
2951
  });
2685
- var EntryProcessorSchema = import_zod3.z.object({
2686
- name: import_zod3.z.string().min(1).max(100),
2687
- code: import_zod3.z.string().min(1).max(1e4),
2688
- args: import_zod3.z.unknown().optional()
2952
+ var PongMessageSchema = import_zod8.z.object({
2953
+ type: import_zod8.z.literal("PONG"),
2954
+ timestamp: import_zod8.z.number(),
2955
+ serverTime: import_zod8.z.number()
2689
2956
  });
2690
- var EntryProcessRequestSchema = import_zod3.z.object({
2691
- type: import_zod3.z.literal("ENTRY_PROCESS"),
2692
- requestId: import_zod3.z.string(),
2693
- mapName: import_zod3.z.string(),
2694
- key: import_zod3.z.string(),
2957
+ var EntryProcessorSchema = import_zod8.z.object({
2958
+ name: import_zod8.z.string().min(1).max(100),
2959
+ code: import_zod8.z.string().min(1).max(1e4),
2960
+ args: import_zod8.z.unknown().optional()
2961
+ });
2962
+ var EntryProcessRequestSchema = import_zod8.z.object({
2963
+ type: import_zod8.z.literal("ENTRY_PROCESS"),
2964
+ requestId: import_zod8.z.string(),
2965
+ mapName: import_zod8.z.string(),
2966
+ key: import_zod8.z.string(),
2695
2967
  processor: EntryProcessorSchema
2696
2968
  });
2697
- var EntryProcessBatchRequestSchema = import_zod3.z.object({
2698
- type: import_zod3.z.literal("ENTRY_PROCESS_BATCH"),
2699
- requestId: import_zod3.z.string(),
2700
- mapName: import_zod3.z.string(),
2701
- keys: import_zod3.z.array(import_zod3.z.string()),
2969
+ var EntryProcessBatchRequestSchema = import_zod8.z.object({
2970
+ type: import_zod8.z.literal("ENTRY_PROCESS_BATCH"),
2971
+ requestId: import_zod8.z.string(),
2972
+ mapName: import_zod8.z.string(),
2973
+ keys: import_zod8.z.array(import_zod8.z.string()),
2702
2974
  processor: EntryProcessorSchema
2703
2975
  });
2704
- var EntryProcessResponseSchema = import_zod3.z.object({
2705
- type: import_zod3.z.literal("ENTRY_PROCESS_RESPONSE"),
2706
- requestId: import_zod3.z.string(),
2707
- success: import_zod3.z.boolean(),
2708
- result: import_zod3.z.unknown().optional(),
2709
- newValue: import_zod3.z.unknown().optional(),
2710
- error: import_zod3.z.string().optional()
2976
+ var EntryProcessResponseSchema = import_zod8.z.object({
2977
+ type: import_zod8.z.literal("ENTRY_PROCESS_RESPONSE"),
2978
+ requestId: import_zod8.z.string(),
2979
+ success: import_zod8.z.boolean(),
2980
+ result: import_zod8.z.unknown().optional(),
2981
+ newValue: import_zod8.z.unknown().optional(),
2982
+ error: import_zod8.z.string().optional()
2711
2983
  });
2712
- var EntryProcessKeyResultSchema = import_zod3.z.object({
2713
- success: import_zod3.z.boolean(),
2714
- result: import_zod3.z.unknown().optional(),
2715
- newValue: import_zod3.z.unknown().optional(),
2716
- error: import_zod3.z.string().optional()
2984
+ var EntryProcessKeyResultSchema = import_zod8.z.object({
2985
+ success: import_zod8.z.boolean(),
2986
+ result: import_zod8.z.unknown().optional(),
2987
+ newValue: import_zod8.z.unknown().optional(),
2988
+ error: import_zod8.z.string().optional()
2717
2989
  });
2718
- var EntryProcessBatchResponseSchema = import_zod3.z.object({
2719
- type: import_zod3.z.literal("ENTRY_PROCESS_BATCH_RESPONSE"),
2720
- requestId: import_zod3.z.string(),
2721
- results: import_zod3.z.record(import_zod3.z.string(), EntryProcessKeyResultSchema)
2990
+ var EntryProcessBatchResponseSchema = import_zod8.z.object({
2991
+ type: import_zod8.z.literal("ENTRY_PROCESS_BATCH_RESPONSE"),
2992
+ requestId: import_zod8.z.string(),
2993
+ results: import_zod8.z.record(import_zod8.z.string(), EntryProcessKeyResultSchema)
2722
2994
  });
2723
- var JournalEventTypeSchema = import_zod3.z.enum(["PUT", "UPDATE", "DELETE"]);
2724
- var JournalEventDataSchema = import_zod3.z.object({
2725
- sequence: import_zod3.z.string(),
2726
- // bigint as string
2995
+ var JournalEventTypeSchema = import_zod8.z.enum(["PUT", "UPDATE", "DELETE"]);
2996
+ var JournalEventDataSchema = import_zod8.z.object({
2997
+ sequence: import_zod8.z.string(),
2727
2998
  type: JournalEventTypeSchema,
2728
- mapName: import_zod3.z.string(),
2729
- key: import_zod3.z.string(),
2730
- value: import_zod3.z.unknown().optional(),
2731
- previousValue: import_zod3.z.unknown().optional(),
2999
+ mapName: import_zod8.z.string(),
3000
+ key: import_zod8.z.string(),
3001
+ value: import_zod8.z.unknown().optional(),
3002
+ previousValue: import_zod8.z.unknown().optional(),
2732
3003
  timestamp: TimestampSchema,
2733
- nodeId: import_zod3.z.string(),
2734
- metadata: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional()
3004
+ nodeId: import_zod8.z.string(),
3005
+ metadata: import_zod8.z.record(import_zod8.z.string(), import_zod8.z.unknown()).optional()
2735
3006
  });
2736
- var JournalSubscribeRequestSchema = import_zod3.z.object({
2737
- type: import_zod3.z.literal("JOURNAL_SUBSCRIBE"),
2738
- requestId: import_zod3.z.string(),
2739
- fromSequence: import_zod3.z.string().optional(),
2740
- // bigint as string
2741
- mapName: import_zod3.z.string().optional(),
2742
- types: import_zod3.z.array(JournalEventTypeSchema).optional()
3007
+ var JournalSubscribeRequestSchema = import_zod8.z.object({
3008
+ type: import_zod8.z.literal("JOURNAL_SUBSCRIBE"),
3009
+ requestId: import_zod8.z.string(),
3010
+ fromSequence: import_zod8.z.string().optional(),
3011
+ mapName: import_zod8.z.string().optional(),
3012
+ types: import_zod8.z.array(JournalEventTypeSchema).optional()
2743
3013
  });
2744
- var JournalUnsubscribeRequestSchema = import_zod3.z.object({
2745
- type: import_zod3.z.literal("JOURNAL_UNSUBSCRIBE"),
2746
- subscriptionId: import_zod3.z.string()
3014
+ var JournalUnsubscribeRequestSchema = import_zod8.z.object({
3015
+ type: import_zod8.z.literal("JOURNAL_UNSUBSCRIBE"),
3016
+ subscriptionId: import_zod8.z.string()
2747
3017
  });
2748
- var JournalEventMessageSchema = import_zod3.z.object({
2749
- type: import_zod3.z.literal("JOURNAL_EVENT"),
3018
+ var JournalEventMessageSchema = import_zod8.z.object({
3019
+ type: import_zod8.z.literal("JOURNAL_EVENT"),
2750
3020
  event: JournalEventDataSchema
2751
3021
  });
2752
- var JournalReadRequestSchema = import_zod3.z.object({
2753
- type: import_zod3.z.literal("JOURNAL_READ"),
2754
- requestId: import_zod3.z.string(),
2755
- fromSequence: import_zod3.z.string(),
2756
- limit: import_zod3.z.number().optional(),
2757
- mapName: import_zod3.z.string().optional()
3022
+ var JournalReadRequestSchema = import_zod8.z.object({
3023
+ type: import_zod8.z.literal("JOURNAL_READ"),
3024
+ requestId: import_zod8.z.string(),
3025
+ fromSequence: import_zod8.z.string(),
3026
+ limit: import_zod8.z.number().optional(),
3027
+ mapName: import_zod8.z.string().optional()
2758
3028
  });
2759
- var JournalReadResponseSchema = import_zod3.z.object({
2760
- type: import_zod3.z.literal("JOURNAL_READ_RESPONSE"),
2761
- requestId: import_zod3.z.string(),
2762
- events: import_zod3.z.array(JournalEventDataSchema),
2763
- hasMore: import_zod3.z.boolean()
3029
+ var JournalReadResponseSchema = import_zod8.z.object({
3030
+ type: import_zod8.z.literal("JOURNAL_READ_RESPONSE"),
3031
+ requestId: import_zod8.z.string(),
3032
+ events: import_zod8.z.array(JournalEventDataSchema),
3033
+ hasMore: import_zod8.z.boolean()
2764
3034
  });
2765
- var SearchOptionsSchema = import_zod3.z.object({
2766
- limit: import_zod3.z.number().optional(),
2767
- minScore: import_zod3.z.number().optional(),
2768
- boost: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number()).optional()
3035
+ var ConflictResolverSchema = import_zod8.z.object({
3036
+ name: import_zod8.z.string().min(1).max(100),
3037
+ code: import_zod8.z.string().max(5e4),
3038
+ priority: import_zod8.z.number().int().min(0).max(100).optional(),
3039
+ keyPattern: import_zod8.z.string().optional()
2769
3040
  });
2770
- var SearchPayloadSchema = import_zod3.z.object({
2771
- requestId: import_zod3.z.string(),
2772
- mapName: import_zod3.z.string(),
2773
- query: import_zod3.z.string(),
2774
- options: SearchOptionsSchema.optional()
3041
+ var RegisterResolverRequestSchema = import_zod8.z.object({
3042
+ type: import_zod8.z.literal("REGISTER_RESOLVER"),
3043
+ requestId: import_zod8.z.string(),
3044
+ mapName: import_zod8.z.string(),
3045
+ resolver: ConflictResolverSchema
2775
3046
  });
2776
- var SearchMessageSchema = import_zod3.z.object({
2777
- type: import_zod3.z.literal("SEARCH"),
2778
- payload: SearchPayloadSchema
3047
+ var RegisterResolverResponseSchema = import_zod8.z.object({
3048
+ type: import_zod8.z.literal("REGISTER_RESOLVER_RESPONSE"),
3049
+ requestId: import_zod8.z.string(),
3050
+ success: import_zod8.z.boolean(),
3051
+ error: import_zod8.z.string().optional()
2779
3052
  });
2780
- var SearchRespPayloadSchema = import_zod3.z.object({
2781
- requestId: import_zod3.z.string(),
2782
- results: import_zod3.z.array(import_zod3.z.object({
2783
- key: import_zod3.z.string(),
2784
- value: import_zod3.z.unknown(),
2785
- score: import_zod3.z.number(),
2786
- matchedTerms: import_zod3.z.array(import_zod3.z.string())
2787
- })),
2788
- totalCount: import_zod3.z.number(),
2789
- error: import_zod3.z.string().optional()
3053
+ var UnregisterResolverRequestSchema = import_zod8.z.object({
3054
+ type: import_zod8.z.literal("UNREGISTER_RESOLVER"),
3055
+ requestId: import_zod8.z.string(),
3056
+ mapName: import_zod8.z.string(),
3057
+ resolverName: import_zod8.z.string()
2790
3058
  });
2791
- var SearchRespMessageSchema = import_zod3.z.object({
2792
- type: import_zod3.z.literal("SEARCH_RESP"),
2793
- payload: SearchRespPayloadSchema
3059
+ var UnregisterResolverResponseSchema = import_zod8.z.object({
3060
+ type: import_zod8.z.literal("UNREGISTER_RESOLVER_RESPONSE"),
3061
+ requestId: import_zod8.z.string(),
3062
+ success: import_zod8.z.boolean(),
3063
+ error: import_zod8.z.string().optional()
2794
3064
  });
2795
- var SearchUpdateTypeSchema = import_zod3.z.enum(["ENTER", "UPDATE", "LEAVE"]);
2796
- var SearchSubPayloadSchema = import_zod3.z.object({
2797
- subscriptionId: import_zod3.z.string(),
2798
- mapName: import_zod3.z.string(),
2799
- query: import_zod3.z.string(),
2800
- options: SearchOptionsSchema.optional()
3065
+ var MergeRejectedMessageSchema = import_zod8.z.object({
3066
+ type: import_zod8.z.literal("MERGE_REJECTED"),
3067
+ mapName: import_zod8.z.string(),
3068
+ key: import_zod8.z.string(),
3069
+ attemptedValue: import_zod8.z.unknown(),
3070
+ reason: import_zod8.z.string(),
3071
+ timestamp: TimestampSchema
2801
3072
  });
2802
- var SearchSubMessageSchema = import_zod3.z.object({
2803
- type: import_zod3.z.literal("SEARCH_SUB"),
2804
- payload: SearchSubPayloadSchema
3073
+ var ListResolversRequestSchema = import_zod8.z.object({
3074
+ type: import_zod8.z.literal("LIST_RESOLVERS"),
3075
+ requestId: import_zod8.z.string(),
3076
+ mapName: import_zod8.z.string().optional()
2805
3077
  });
2806
- var SearchUpdatePayloadSchema = import_zod3.z.object({
2807
- subscriptionId: import_zod3.z.string(),
2808
- key: import_zod3.z.string(),
2809
- value: import_zod3.z.unknown(),
2810
- score: import_zod3.z.number(),
2811
- matchedTerms: import_zod3.z.array(import_zod3.z.string()),
2812
- type: SearchUpdateTypeSchema
3078
+ var ListResolversResponseSchema = import_zod8.z.object({
3079
+ type: import_zod8.z.literal("LIST_RESOLVERS_RESPONSE"),
3080
+ requestId: import_zod8.z.string(),
3081
+ resolvers: import_zod8.z.array(import_zod8.z.object({
3082
+ mapName: import_zod8.z.string(),
3083
+ name: import_zod8.z.string(),
3084
+ priority: import_zod8.z.number().optional(),
3085
+ keyPattern: import_zod8.z.string().optional()
3086
+ }))
2813
3087
  });
2814
- var SearchUpdateMessageSchema = import_zod3.z.object({
2815
- type: import_zod3.z.literal("SEARCH_UPDATE"),
2816
- payload: SearchUpdatePayloadSchema
3088
+
3089
+ // src/schemas/client-message-schemas.ts
3090
+ var import_zod9 = require("zod");
3091
+ var ServerEventPayloadSchema = import_zod9.z.object({
3092
+ mapName: import_zod9.z.string(),
3093
+ eventType: import_zod9.z.enum(["PUT", "REMOVE", "OR_ADD", "OR_REMOVE"]),
3094
+ key: import_zod9.z.string(),
3095
+ record: LWWRecordSchema.optional(),
3096
+ orRecord: ORMapRecordSchema.optional(),
3097
+ orTag: import_zod9.z.string().optional()
2817
3098
  });
2818
- var SearchUnsubPayloadSchema = import_zod3.z.object({
2819
- subscriptionId: import_zod3.z.string()
3099
+ var ServerEventMessageSchema = import_zod9.z.object({
3100
+ type: import_zod9.z.literal("SERVER_EVENT"),
3101
+ payload: ServerEventPayloadSchema
2820
3102
  });
2821
- var SearchUnsubMessageSchema = import_zod3.z.object({
2822
- type: import_zod3.z.literal("SEARCH_UNSUB"),
2823
- payload: SearchUnsubPayloadSchema
3103
+ var ServerBatchEventMessageSchema = import_zod9.z.object({
3104
+ type: import_zod9.z.literal("SERVER_BATCH_EVENT"),
3105
+ payload: import_zod9.z.object({
3106
+ events: import_zod9.z.array(ServerEventPayloadSchema)
3107
+ })
2824
3108
  });
2825
- var ConflictResolverSchema = import_zod3.z.object({
2826
- name: import_zod3.z.string().min(1).max(100),
2827
- code: import_zod3.z.string().max(5e4),
2828
- priority: import_zod3.z.number().int().min(0).max(100).optional(),
2829
- keyPattern: import_zod3.z.string().optional()
3109
+ var QueryUpdatePayloadSchema = import_zod9.z.object({
3110
+ queryId: import_zod9.z.string(),
3111
+ key: import_zod9.z.string(),
3112
+ value: import_zod9.z.unknown(),
3113
+ type: import_zod9.z.enum(["ENTER", "UPDATE", "REMOVE"])
2830
3114
  });
2831
- var RegisterResolverRequestSchema = import_zod3.z.object({
2832
- type: import_zod3.z.literal("REGISTER_RESOLVER"),
2833
- requestId: import_zod3.z.string(),
2834
- mapName: import_zod3.z.string(),
2835
- resolver: ConflictResolverSchema
3115
+ var QueryUpdateMessageSchema = import_zod9.z.object({
3116
+ type: import_zod9.z.literal("QUERY_UPDATE"),
3117
+ payload: QueryUpdatePayloadSchema
2836
3118
  });
2837
- var RegisterResolverResponseSchema = import_zod3.z.object({
2838
- type: import_zod3.z.literal("REGISTER_RESOLVER_RESPONSE"),
2839
- requestId: import_zod3.z.string(),
2840
- success: import_zod3.z.boolean(),
2841
- error: import_zod3.z.string().optional()
3119
+ var GcPrunePayloadSchema = import_zod9.z.object({
3120
+ olderThan: TimestampSchema
2842
3121
  });
2843
- var UnregisterResolverRequestSchema = import_zod3.z.object({
2844
- type: import_zod3.z.literal("UNREGISTER_RESOLVER"),
2845
- requestId: import_zod3.z.string(),
2846
- mapName: import_zod3.z.string(),
2847
- resolverName: import_zod3.z.string()
3122
+ var GcPruneMessageSchema = import_zod9.z.object({
3123
+ type: import_zod9.z.literal("GC_PRUNE"),
3124
+ payload: GcPrunePayloadSchema
2848
3125
  });
2849
- var UnregisterResolverResponseSchema = import_zod3.z.object({
2850
- type: import_zod3.z.literal("UNREGISTER_RESOLVER_RESPONSE"),
2851
- requestId: import_zod3.z.string(),
2852
- success: import_zod3.z.boolean(),
2853
- error: import_zod3.z.string().optional()
3126
+ var AuthFailMessageSchema = import_zod9.z.object({
3127
+ type: import_zod9.z.literal("AUTH_FAIL"),
3128
+ error: import_zod9.z.string().optional(),
3129
+ code: import_zod9.z.number().optional()
2854
3130
  });
2855
- var MergeRejectedMessageSchema = import_zod3.z.object({
2856
- type: import_zod3.z.literal("MERGE_REJECTED"),
2857
- mapName: import_zod3.z.string(),
2858
- key: import_zod3.z.string(),
2859
- attemptedValue: import_zod3.z.unknown(),
2860
- reason: import_zod3.z.string(),
2861
- timestamp: TimestampSchema
3131
+ var HybridQueryRespPayloadSchema = import_zod9.z.object({
3132
+ subscriptionId: import_zod9.z.string(),
3133
+ results: import_zod9.z.array(import_zod9.z.object({
3134
+ key: import_zod9.z.string(),
3135
+ value: import_zod9.z.unknown(),
3136
+ score: import_zod9.z.number(),
3137
+ matchedTerms: import_zod9.z.array(import_zod9.z.string())
3138
+ })),
3139
+ nextCursor: import_zod9.z.string().optional(),
3140
+ hasMore: import_zod9.z.boolean().optional(),
3141
+ cursorStatus: CursorStatusSchema.optional()
2862
3142
  });
2863
- var ListResolversRequestSchema = import_zod3.z.object({
2864
- type: import_zod3.z.literal("LIST_RESOLVERS"),
2865
- requestId: import_zod3.z.string(),
2866
- mapName: import_zod3.z.string().optional()
3143
+ var HybridQueryDeltaPayloadSchema = import_zod9.z.object({
3144
+ subscriptionId: import_zod9.z.string(),
3145
+ key: import_zod9.z.string(),
3146
+ value: import_zod9.z.unknown().nullable(),
3147
+ score: import_zod9.z.number().optional(),
3148
+ matchedTerms: import_zod9.z.array(import_zod9.z.string()).optional(),
3149
+ type: import_zod9.z.enum(["ENTER", "UPDATE", "LEAVE"])
2867
3150
  });
2868
- var ListResolversResponseSchema = import_zod3.z.object({
2869
- type: import_zod3.z.literal("LIST_RESOLVERS_RESPONSE"),
2870
- requestId: import_zod3.z.string(),
2871
- resolvers: import_zod3.z.array(import_zod3.z.object({
2872
- mapName: import_zod3.z.string(),
2873
- name: import_zod3.z.string(),
2874
- priority: import_zod3.z.number().optional(),
2875
- keyPattern: import_zod3.z.string().optional()
2876
- }))
3151
+ var LockGrantedPayloadSchema = import_zod9.z.object({
3152
+ requestId: import_zod9.z.string(),
3153
+ fencingToken: import_zod9.z.number()
2877
3154
  });
2878
- var OpResultSchema = import_zod3.z.object({
2879
- opId: import_zod3.z.string(),
2880
- success: import_zod3.z.boolean(),
2881
- achievedLevel: WriteConcernSchema,
2882
- error: import_zod3.z.string().optional()
3155
+ var LockReleasedPayloadSchema = import_zod9.z.object({
3156
+ requestId: import_zod9.z.string(),
3157
+ success: import_zod9.z.boolean()
2883
3158
  });
2884
- var OpAckMessageSchema = import_zod3.z.object({
2885
- type: import_zod3.z.literal("OP_ACK"),
2886
- payload: import_zod3.z.object({
2887
- /** ID of the last operation in the batch (for backwards compatibility) */
2888
- lastId: import_zod3.z.string(),
2889
- /** Write Concern level achieved (for simple ACKs) */
2890
- achievedLevel: WriteConcernSchema.optional(),
2891
- /** Per-operation results (for batch operations with mixed Write Concern) */
2892
- results: import_zod3.z.array(OpResultSchema).optional()
2893
- })
3159
+ var SyncResetRequiredPayloadSchema = import_zod9.z.object({
3160
+ mapName: import_zod9.z.string(),
3161
+ reason: import_zod9.z.string()
2894
3162
  });
2895
- var OpRejectedMessageSchema = import_zod3.z.object({
2896
- type: import_zod3.z.literal("OP_REJECTED"),
2897
- payload: import_zod3.z.object({
2898
- /** Operation ID that was rejected */
2899
- opId: import_zod3.z.string(),
2900
- /** Reason for rejection */
2901
- reason: import_zod3.z.string(),
2902
- /** Error code */
2903
- code: import_zod3.z.number().optional()
2904
- })
3163
+
3164
+ // src/schemas/http-sync-schemas.ts
3165
+ var import_zod10 = require("zod");
3166
+ var SyncMapEntrySchema = import_zod10.z.object({
3167
+ mapName: import_zod10.z.string(),
3168
+ lastSyncTimestamp: TimestampSchema
2905
3169
  });
2906
- var ClusterSubRegisterPayloadSchema = import_zod3.z.object({
2907
- /** Unique subscription ID */
2908
- subscriptionId: import_zod3.z.string(),
2909
- /** Node ID of the coordinator (receives updates) */
2910
- coordinatorNodeId: import_zod3.z.string(),
2911
- /** Map name to subscribe to */
2912
- mapName: import_zod3.z.string(),
2913
- /** Subscription type */
2914
- type: import_zod3.z.enum(["SEARCH", "QUERY"]),
2915
- // For FTS subscriptions
2916
- /** Search query string (for SEARCH type) */
2917
- searchQuery: import_zod3.z.string().optional(),
2918
- /** Search options (for SEARCH type) */
2919
- searchOptions: import_zod3.z.object({
2920
- limit: import_zod3.z.number().int().positive().optional(),
2921
- minScore: import_zod3.z.number().optional(),
2922
- boost: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number()).optional()
2923
- }).optional(),
2924
- // For Query subscriptions
2925
- /** Query predicate (for QUERY type) */
2926
- queryPredicate: import_zod3.z.any().optional(),
2927
- /** Query sort order (for QUERY type) */
2928
- querySort: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.enum(["asc", "desc"])).optional()
3170
+ var HttpQueryRequestSchema = import_zod10.z.object({
3171
+ queryId: import_zod10.z.string(),
3172
+ mapName: import_zod10.z.string(),
3173
+ filter: import_zod10.z.any(),
3174
+ limit: import_zod10.z.number().optional(),
3175
+ offset: import_zod10.z.number().optional()
2929
3176
  });
2930
- var ClusterSubRegisterMessageSchema = import_zod3.z.object({
2931
- type: import_zod3.z.literal("CLUSTER_SUB_REGISTER"),
2932
- payload: ClusterSubRegisterPayloadSchema
3177
+ var HttpSearchRequestSchema = import_zod10.z.object({
3178
+ searchId: import_zod10.z.string(),
3179
+ mapName: import_zod10.z.string(),
3180
+ query: import_zod10.z.string(),
3181
+ options: import_zod10.z.any().optional()
2933
3182
  });
2934
- var ClusterSubAckPayloadSchema = import_zod3.z.object({
2935
- /** Correlates to subscriptionId */
2936
- subscriptionId: import_zod3.z.string(),
2937
- /** Node that registered this subscription */
2938
- nodeId: import_zod3.z.string(),
2939
- /** Registration success status */
2940
- success: import_zod3.z.boolean(),
2941
- /** Error message if failed */
2942
- error: import_zod3.z.string().optional(),
2943
- /** Initial results from this node */
2944
- initialResults: import_zod3.z.array(import_zod3.z.object({
2945
- key: import_zod3.z.string(),
2946
- value: import_zod3.z.unknown(),
2947
- score: import_zod3.z.number().optional(),
2948
- matchedTerms: import_zod3.z.array(import_zod3.z.string()).optional()
2949
- })).optional(),
2950
- /** Total matching documents on this node */
2951
- totalHits: import_zod3.z.number().int().nonnegative().optional()
3183
+ var HttpSyncRequestSchema = import_zod10.z.object({
3184
+ // Client identification
3185
+ clientId: import_zod10.z.string(),
3186
+ // Client's current HLC for causality tracking
3187
+ clientHlc: TimestampSchema,
3188
+ // Batch of operations to push (optional)
3189
+ operations: import_zod10.z.array(ClientOpSchema).optional(),
3190
+ // Maps the client wants deltas for, with their last known sync HLC timestamp
3191
+ syncMaps: import_zod10.z.array(SyncMapEntrySchema).optional(),
3192
+ // One-shot queries to execute (optional)
3193
+ queries: import_zod10.z.array(HttpQueryRequestSchema).optional(),
3194
+ // One-shot search requests (optional)
3195
+ searches: import_zod10.z.array(HttpSearchRequestSchema).optional()
2952
3196
  });
2953
- var ClusterSubAckMessageSchema = import_zod3.z.object({
2954
- type: import_zod3.z.literal("CLUSTER_SUB_ACK"),
2955
- payload: ClusterSubAckPayloadSchema
3197
+ var DeltaRecordSchema = import_zod10.z.object({
3198
+ key: import_zod10.z.string(),
3199
+ record: LWWRecordSchema,
3200
+ eventType: import_zod10.z.enum(["PUT", "REMOVE"])
2956
3201
  });
2957
- var ClusterSubUpdatePayloadSchema = import_zod3.z.object({
2958
- /** Subscription ID this update belongs to */
2959
- subscriptionId: import_zod3.z.string(),
2960
- /** Node that produced this update */
2961
- sourceNodeId: import_zod3.z.string(),
2962
- /** Document key */
2963
- key: import_zod3.z.string(),
2964
- /** Document value (null for LEAVE) */
2965
- value: import_zod3.z.unknown(),
2966
- /** Search score (for SEARCH type) */
2967
- score: import_zod3.z.number().optional(),
2968
- /** Matched terms (for SEARCH type) */
2969
- matchedTerms: import_zod3.z.array(import_zod3.z.string()).optional(),
2970
- /** Change type: ENTER (new match), UPDATE (still matches), LEAVE (no longer matches) */
2971
- changeType: import_zod3.z.enum(["ENTER", "UPDATE", "LEAVE"]),
2972
- /** Timestamp for ordering */
2973
- timestamp: import_zod3.z.number()
3202
+ var MapDeltaSchema = import_zod10.z.object({
3203
+ mapName: import_zod10.z.string(),
3204
+ records: import_zod10.z.array(DeltaRecordSchema),
3205
+ serverSyncTimestamp: TimestampSchema
2974
3206
  });
2975
- var ClusterSubUpdateMessageSchema = import_zod3.z.object({
2976
- type: import_zod3.z.literal("CLUSTER_SUB_UPDATE"),
2977
- payload: ClusterSubUpdatePayloadSchema
3207
+ var HttpQueryResultSchema = import_zod10.z.object({
3208
+ queryId: import_zod10.z.string(),
3209
+ results: import_zod10.z.array(import_zod10.z.any()),
3210
+ hasMore: import_zod10.z.boolean().optional(),
3211
+ nextCursor: import_zod10.z.string().optional()
2978
3212
  });
2979
- var ClusterSubUnregisterPayloadSchema = import_zod3.z.object({
2980
- /** Subscription ID to remove */
2981
- subscriptionId: import_zod3.z.string()
3213
+ var HttpSearchResultSchema = import_zod10.z.object({
3214
+ searchId: import_zod10.z.string(),
3215
+ results: import_zod10.z.array(import_zod10.z.any()),
3216
+ totalCount: import_zod10.z.number().optional()
2982
3217
  });
2983
- var ClusterSubUnregisterMessageSchema = import_zod3.z.object({
2984
- type: import_zod3.z.literal("CLUSTER_SUB_UNREGISTER"),
2985
- payload: ClusterSubUnregisterPayloadSchema
3218
+ var HttpSyncErrorSchema = import_zod10.z.object({
3219
+ code: import_zod10.z.number(),
3220
+ message: import_zod10.z.string(),
3221
+ context: import_zod10.z.string().optional()
3222
+ });
3223
+ var HttpSyncResponseSchema = import_zod10.z.object({
3224
+ // Server's current HLC
3225
+ serverHlc: TimestampSchema,
3226
+ // Acknowledgment of received operations
3227
+ ack: import_zod10.z.object({
3228
+ lastId: import_zod10.z.string(),
3229
+ results: import_zod10.z.array(OpResultSchema).optional()
3230
+ }).optional(),
3231
+ // Delta records for requested maps (new/changed since lastSyncTimestamp)
3232
+ deltas: import_zod10.z.array(MapDeltaSchema).optional(),
3233
+ // Query results
3234
+ queryResults: import_zod10.z.array(HttpQueryResultSchema).optional(),
3235
+ // Search results
3236
+ searchResults: import_zod10.z.array(HttpSearchResultSchema).optional(),
3237
+ // Errors for individual operations
3238
+ errors: import_zod10.z.array(HttpSyncErrorSchema).optional()
2986
3239
  });
2987
- var MessageSchema = import_zod3.z.discriminatedUnion("type", [
3240
+
3241
+ // src/schemas/index.ts
3242
+ var import_zod11 = require("zod");
3243
+ var MessageSchema = import_zod11.z.discriminatedUnion("type", [
2988
3244
  AuthMessageSchema,
2989
3245
  QuerySubMessageSchema,
2990
3246
  QueryUnsubMessageSchema,
@@ -3002,7 +3258,6 @@ var MessageSchema = import_zod3.z.discriminatedUnion("type", [
3002
3258
  TopicPubSchema,
3003
3259
  PingMessageSchema,
3004
3260
  PongMessageSchema,
3005
- // ORMap Sync Messages
3006
3261
  ORMapSyncInitSchema,
3007
3262
  ORMapSyncRespRootSchema,
3008
3263
  ORMapSyncRespBucketsSchema,
@@ -3011,23 +3266,18 @@ var MessageSchema = import_zod3.z.discriminatedUnion("type", [
3011
3266
  ORMapDiffRequestSchema,
3012
3267
  ORMapDiffResponseSchema,
3013
3268
  ORMapPushDiffSchema,
3014
- // Phase 4: Partition Map
3015
3269
  PartitionMapRequestSchema,
3016
- // Phase 5.2: PN Counter
3017
3270
  CounterRequestSchema,
3018
3271
  CounterSyncSchema,
3019
- // Phase 5.03: Entry Processor
3020
3272
  EntryProcessRequestSchema,
3021
3273
  EntryProcessBatchRequestSchema,
3022
3274
  EntryProcessResponseSchema,
3023
3275
  EntryProcessBatchResponseSchema,
3024
- // Phase 5.04: Event Journal
3025
3276
  JournalSubscribeRequestSchema,
3026
3277
  JournalUnsubscribeRequestSchema,
3027
3278
  JournalEventMessageSchema,
3028
3279
  JournalReadRequestSchema,
3029
3280
  JournalReadResponseSchema,
3030
- // Phase 5.05: Conflict Resolver
3031
3281
  RegisterResolverRequestSchema,
3032
3282
  RegisterResolverResponseSchema,
3033
3283
  UnregisterResolverRequestSchema,
@@ -3035,101 +3285,16 @@ var MessageSchema = import_zod3.z.discriminatedUnion("type", [
3035
3285
  MergeRejectedMessageSchema,
3036
3286
  ListResolversRequestSchema,
3037
3287
  ListResolversResponseSchema,
3038
- // Phase 11.1: Full-Text Search
3039
3288
  SearchMessageSchema,
3040
3289
  SearchRespMessageSchema,
3041
- // Phase 11.1b: Live Search Subscriptions
3042
3290
  SearchSubMessageSchema,
3043
3291
  SearchUpdateMessageSchema,
3044
3292
  SearchUnsubMessageSchema,
3045
- // Phase 14.2: Distributed Live Subscriptions (cluster-internal)
3046
3293
  ClusterSubRegisterMessageSchema,
3047
3294
  ClusterSubAckMessageSchema,
3048
3295
  ClusterSubUpdateMessageSchema,
3049
3296
  ClusterSubUnregisterMessageSchema
3050
3297
  ]);
3051
- var ClusterSearchReqPayloadSchema = import_zod3.z.object({
3052
- /** Unique request ID for correlation */
3053
- requestId: import_zod3.z.string(),
3054
- /** Map name to search */
3055
- mapName: import_zod3.z.string(),
3056
- /** Search query text */
3057
- query: import_zod3.z.string(),
3058
- /** Search options */
3059
- options: import_zod3.z.object({
3060
- /** Maximum results per node (for Top-K) */
3061
- limit: import_zod3.z.number().int().positive().max(1e3),
3062
- /** Minimum score threshold */
3063
- minScore: import_zod3.z.number().optional(),
3064
- /** Fields to boost */
3065
- boost: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number()).optional(),
3066
- /** Include matched terms in response */
3067
- includeMatchedTerms: import_zod3.z.boolean().optional(),
3068
- /** For cursor-based pagination: return results after this score */
3069
- afterScore: import_zod3.z.number().optional(),
3070
- /** For cursor-based pagination: return results after this key (tie-breaking) */
3071
- afterKey: import_zod3.z.string().optional()
3072
- }),
3073
- /** Timeout in milliseconds */
3074
- timeoutMs: import_zod3.z.number().int().positive().optional()
3075
- });
3076
- var ClusterSearchReqMessageSchema = import_zod3.z.object({
3077
- type: import_zod3.z.literal("CLUSTER_SEARCH_REQ"),
3078
- payload: ClusterSearchReqPayloadSchema
3079
- });
3080
- var ClusterSearchRespPayloadSchema = import_zod3.z.object({
3081
- /** Correlates to requestId */
3082
- requestId: import_zod3.z.string(),
3083
- /** Node that produced these results */
3084
- nodeId: import_zod3.z.string(),
3085
- /** Search results with scores */
3086
- results: import_zod3.z.array(import_zod3.z.object({
3087
- key: import_zod3.z.string(),
3088
- value: import_zod3.z.unknown(),
3089
- score: import_zod3.z.number(),
3090
- matchedTerms: import_zod3.z.array(import_zod3.z.string()).optional()
3091
- })),
3092
- /** Total matching documents on this node (for pagination) */
3093
- totalHits: import_zod3.z.number().int().nonnegative(),
3094
- /** Execution time on this node in ms (for monitoring) */
3095
- executionTimeMs: import_zod3.z.number().nonnegative(),
3096
- /** Error if search failed on this node */
3097
- error: import_zod3.z.string().optional()
3098
- });
3099
- var ClusterSearchRespMessageSchema = import_zod3.z.object({
3100
- type: import_zod3.z.literal("CLUSTER_SEARCH_RESP"),
3101
- payload: ClusterSearchRespPayloadSchema
3102
- });
3103
- var ClusterSearchSubscribePayloadSchema = import_zod3.z.object({
3104
- subscriptionId: import_zod3.z.string(),
3105
- mapName: import_zod3.z.string(),
3106
- query: import_zod3.z.string(),
3107
- options: SearchOptionsSchema.optional()
3108
- });
3109
- var ClusterSearchSubscribeMessageSchema = import_zod3.z.object({
3110
- type: import_zod3.z.literal("CLUSTER_SEARCH_SUBSCRIBE"),
3111
- payload: ClusterSearchSubscribePayloadSchema
3112
- });
3113
- var ClusterSearchUnsubscribePayloadSchema = import_zod3.z.object({
3114
- subscriptionId: import_zod3.z.string()
3115
- });
3116
- var ClusterSearchUnsubscribeMessageSchema = import_zod3.z.object({
3117
- type: import_zod3.z.literal("CLUSTER_SEARCH_UNSUBSCRIBE"),
3118
- payload: ClusterSearchUnsubscribePayloadSchema
3119
- });
3120
- var ClusterSearchUpdatePayloadSchema = import_zod3.z.object({
3121
- subscriptionId: import_zod3.z.string(),
3122
- nodeId: import_zod3.z.string(),
3123
- key: import_zod3.z.string(),
3124
- value: import_zod3.z.unknown(),
3125
- score: import_zod3.z.number(),
3126
- matchedTerms: import_zod3.z.array(import_zod3.z.string()).optional(),
3127
- type: SearchUpdateTypeSchema
3128
- });
3129
- var ClusterSearchUpdateMessageSchema = import_zod3.z.object({
3130
- type: import_zod3.z.literal("CLUSTER_SEARCH_UPDATE"),
3131
- payload: ClusterSearchUpdatePayloadSchema
3132
- });
3133
3298
 
3134
3299
  // src/types/WriteConcern.ts
3135
3300
  var WriteConcern = /* @__PURE__ */ ((WriteConcern2) => {
@@ -4088,6 +4253,18 @@ function createPredicateMatcher(getAttribute) {
4088
4253
  }
4089
4254
 
4090
4255
  // src/query/QueryTypes.ts
4256
+ var COST_WEIGHTS = {
4257
+ CPU: 1,
4258
+ NETWORK: 10,
4259
+ // Network is expensive (latency, bandwidth)
4260
+ IO: 5,
4261
+ // Disk I/O is moderately expensive
4262
+ ROWS: 1e-3
4263
+ // Row count factor
4264
+ };
4265
+ function calculateTotalCost(cost) {
4266
+ return cost.rows * COST_WEIGHTS.ROWS + cost.cpu * COST_WEIGHTS.CPU + cost.network * COST_WEIGHTS.NETWORK + cost.io * COST_WEIGHTS.IO;
4267
+ }
4091
4268
  function isSimpleQuery(query) {
4092
4269
  return [
4093
4270
  "eq",
@@ -6054,7 +6231,7 @@ var IndexRegistry = class {
6054
6231
  constructor() {
6055
6232
  /** Indexes grouped by attribute name */
6056
6233
  this.attributeIndexes = /* @__PURE__ */ new Map();
6057
- /** Compound indexes (Phase 9.03) - keyed by sorted attribute names */
6234
+ /** Compound indexes - keyed by sorted attribute names */
6058
6235
  this.compoundIndexes = /* @__PURE__ */ new Map();
6059
6236
  /** Fallback index for full scan (optional) */
6060
6237
  this.fallbackIndex = null;
@@ -6081,7 +6258,7 @@ var IndexRegistry = class {
6081
6258
  }
6082
6259
  }
6083
6260
  /**
6084
- * Register a compound index (Phase 9.03).
6261
+ * Register a compound index.
6085
6262
  *
6086
6263
  * @param index - Compound index to register
6087
6264
  */
@@ -6115,7 +6292,7 @@ var IndexRegistry = class {
6115
6292
  return true;
6116
6293
  }
6117
6294
  /**
6118
- * Remove a compound index (Phase 9.03).
6295
+ * Remove a compound index.
6119
6296
  *
6120
6297
  * @param index - Compound index to remove
6121
6298
  * @returns true if index was found and removed
@@ -6195,10 +6372,10 @@ var IndexRegistry = class {
6195
6372
  return indexes.filter((index) => index.supportsQuery(queryType)).sort((a, b) => a.getRetrievalCost() - b.getRetrievalCost());
6196
6373
  }
6197
6374
  // ========================================
6198
- // Phase 9.03: Compound Index Methods
6375
+ // Compound Index Methods
6199
6376
  // ========================================
6200
6377
  /**
6201
- * Find a compound index that covers the given attribute names (Phase 9.03).
6378
+ * Find a compound index that covers the given attribute names.
6202
6379
  * The compound index must cover ALL the attributes (exact match or superset).
6203
6380
  *
6204
6381
  * @param attributeNames - Array of attribute names to search for
@@ -6216,7 +6393,7 @@ var IndexRegistry = class {
6216
6393
  return null;
6217
6394
  }
6218
6395
  /**
6219
- * Check if a compound index exists for the given attributes (Phase 9.03).
6396
+ * Check if a compound index exists for the given attributes.
6220
6397
  *
6221
6398
  * @param attributeNames - Array of attribute names
6222
6399
  * @returns true if a compound index exists
@@ -6225,7 +6402,7 @@ var IndexRegistry = class {
6225
6402
  return this.findCompoundIndex(attributeNames) !== null;
6226
6403
  }
6227
6404
  /**
6228
- * Get all compound indexes (Phase 9.03).
6405
+ * Get all compound indexes.
6229
6406
  *
6230
6407
  * @returns Array of all compound indexes
6231
6408
  */
@@ -6363,22 +6540,15 @@ var QueryOptimizer = class {
6363
6540
  /**
6364
6541
  * Create a QueryOptimizer.
6365
6542
  *
6366
- * @param indexRegistryOrOptions - IndexRegistry or options object
6367
- * @param standingQueryRegistry - Optional StandingQueryRegistry (deprecated, use options)
6543
+ * @param options - QueryOptimizer options
6368
6544
  */
6369
- constructor(indexRegistryOrOptions, standingQueryRegistry) {
6370
- if ("indexRegistry" in indexRegistryOrOptions) {
6371
- this.indexRegistry = indexRegistryOrOptions.indexRegistry;
6372
- this.standingQueryRegistry = indexRegistryOrOptions.standingQueryRegistry;
6373
- this.fullTextIndexes = indexRegistryOrOptions.fullTextIndexes ?? /* @__PURE__ */ new Map();
6374
- } else {
6375
- this.indexRegistry = indexRegistryOrOptions;
6376
- this.standingQueryRegistry = standingQueryRegistry;
6377
- this.fullTextIndexes = /* @__PURE__ */ new Map();
6378
- }
6545
+ constructor(options) {
6546
+ this.indexRegistry = options.indexRegistry;
6547
+ this.standingQueryRegistry = options.standingQueryRegistry;
6548
+ this.fullTextIndexes = options.fullTextIndexes ?? /* @__PURE__ */ new Map();
6379
6549
  }
6380
6550
  /**
6381
- * Register a full-text index for a field (Phase 12).
6551
+ * Register a full-text index for a field.
6382
6552
  *
6383
6553
  * @param field - Field name
6384
6554
  * @param index - FullTextIndex instance
@@ -6387,7 +6557,7 @@ var QueryOptimizer = class {
6387
6557
  this.fullTextIndexes.set(field, index);
6388
6558
  }
6389
6559
  /**
6390
- * Unregister a full-text index (Phase 12).
6560
+ * Unregister a full-text index.
6391
6561
  *
6392
6562
  * @param field - Field name
6393
6563
  */
@@ -6395,7 +6565,7 @@ var QueryOptimizer = class {
6395
6565
  this.fullTextIndexes.delete(field);
6396
6566
  }
6397
6567
  /**
6398
- * Get registered full-text index for a field (Phase 12).
6568
+ * Get registered full-text index for a field.
6399
6569
  *
6400
6570
  * @param field - Field name
6401
6571
  * @returns FullTextIndex or undefined
@@ -6404,7 +6574,7 @@ var QueryOptimizer = class {
6404
6574
  return this.fullTextIndexes.get(field);
6405
6575
  }
6406
6576
  /**
6407
- * Check if a full-text index exists for a field (Phase 12).
6577
+ * Check if a full-text index exists for a field.
6408
6578
  *
6409
6579
  * @param field - Field name
6410
6580
  * @returns True if FTS index exists
@@ -6416,13 +6586,22 @@ var QueryOptimizer = class {
6416
6586
  * Optimize a query and return an execution plan.
6417
6587
  *
6418
6588
  * Optimization order (by cost):
6419
- * 1. StandingQueryIndex (cost: 10) - pre-computed results
6420
- * 2. Other indexes via optimizeNode
6589
+ * 1. Point lookup (cost: 1) - direct primary key access
6590
+ * 2. StandingQueryIndex (cost: 10) - pre-computed results
6591
+ * 3. Other indexes via optimizeNode
6421
6592
  *
6422
6593
  * @param query - Query to optimize
6423
6594
  * @returns Query execution plan
6424
6595
  */
6425
6596
  optimize(query) {
6597
+ const pointLookupStep = this.tryPointLookup(query);
6598
+ if (pointLookupStep) {
6599
+ return {
6600
+ root: pointLookupStep,
6601
+ estimatedCost: this.estimateCost(pointLookupStep),
6602
+ usesIndexes: this.usesIndexes(pointLookupStep)
6603
+ };
6604
+ }
6426
6605
  if (this.standingQueryRegistry) {
6427
6606
  const standingIndex = this.standingQueryRegistry.getIndex(query);
6428
6607
  if (standingIndex) {
@@ -6446,16 +6625,68 @@ var QueryOptimizer = class {
6446
6625
  };
6447
6626
  }
6448
6627
  /**
6449
- * Optimize a query with sort/limit/offset options.
6628
+ * Optimize a query with sort/limit/offset options and index hints.
6629
+ *
6630
+ * Hint precedence: disableOptimization > useIndex > forceIndexScan.
6450
6631
  *
6451
6632
  * @param query - Query to optimize
6452
- * @param options - Query options (sort, limit, offset)
6633
+ * @param options - Query options (sort, limit, cursor, hints)
6453
6634
  * @returns Query execution plan with options
6454
6635
  */
6455
6636
  optimizeWithOptions(query, options) {
6637
+ if (options.disableOptimization) {
6638
+ return {
6639
+ root: { type: "full-scan", predicate: query },
6640
+ estimatedCost: Number.MAX_SAFE_INTEGER,
6641
+ usesIndexes: false
6642
+ };
6643
+ }
6644
+ if (options.useIndex) {
6645
+ const indexes = this.indexRegistry.getIndexes(options.useIndex);
6646
+ if (indexes.length === 0) {
6647
+ throw new Error(
6648
+ `Index hint: no index found for attribute "${options.useIndex}"`
6649
+ );
6650
+ }
6651
+ let best = indexes[0];
6652
+ for (let i = 1; i < indexes.length; i++) {
6653
+ if (indexes[i].getRetrievalCost() < best.getRetrievalCost()) {
6654
+ best = indexes[i];
6655
+ }
6656
+ }
6657
+ const step = {
6658
+ type: "index-scan",
6659
+ index: best,
6660
+ query: this.buildHintedIndexQuery(query, options.useIndex)
6661
+ };
6662
+ return this.applyPlanOptions(
6663
+ {
6664
+ root: step,
6665
+ estimatedCost: best.getRetrievalCost(),
6666
+ usesIndexes: true,
6667
+ hint: options.useIndex
6668
+ },
6669
+ options
6670
+ );
6671
+ }
6456
6672
  const basePlan = this.optimize(query);
6673
+ if (options.forceIndexScan && !basePlan.usesIndexes) {
6674
+ throw new Error(
6675
+ "No suitable index found and forceIndexScan is enabled"
6676
+ );
6677
+ }
6678
+ return this.applyPlanOptions(basePlan, options);
6679
+ }
6680
+ /**
6681
+ * Apply sort/limit/cursor options to a query plan.
6682
+ *
6683
+ * @param plan - Base query plan
6684
+ * @param options - Query options with sort/limit/cursor
6685
+ * @returns Plan with options applied
6686
+ */
6687
+ applyPlanOptions(plan, options) {
6457
6688
  if (!options.sort && options.limit === void 0 && options.cursor === void 0) {
6458
- return basePlan;
6689
+ return plan;
6459
6690
  }
6460
6691
  let indexedSort = false;
6461
6692
  let sortField;
@@ -6472,14 +6703,73 @@ var QueryOptimizer = class {
6472
6703
  }
6473
6704
  }
6474
6705
  return {
6475
- ...basePlan,
6706
+ ...plan,
6476
6707
  indexedSort,
6477
6708
  sort: sortField && sortDirection ? { field: sortField, direction: sortDirection } : void 0,
6478
6709
  limit: options.limit,
6479
6710
  cursor: options.cursor
6480
- // Phase 14.1: replaces offset
6481
6711
  };
6482
6712
  }
6713
+ /**
6714
+ * Extract the relevant index query for a hinted attribute from the query tree.
6715
+ * If the query directly references the attribute, build an index query from it.
6716
+ * For compound (logical) queries, extract the matching child predicate.
6717
+ * Falls back to { type: 'has' } when no matching predicate is found,
6718
+ * retrieving all entries from the index for post-filtering.
6719
+ * FTS query nodes also fall back to { type: 'has' } since full-text search
6720
+ * queries are not compatible with regular index lookups.
6721
+ *
6722
+ * @param query - Original query tree
6723
+ * @param attributeName - Hinted attribute name
6724
+ * @returns Index query for the hinted attribute
6725
+ */
6726
+ buildHintedIndexQuery(query, attributeName) {
6727
+ if (isSimpleQuery(query) && query.attribute === attributeName) {
6728
+ return this.buildIndexQuery(query);
6729
+ }
6730
+ if (isFTSQuery(query)) {
6731
+ return { type: "has" };
6732
+ }
6733
+ if (isLogicalQuery(query) && query.children) {
6734
+ for (const child of query.children) {
6735
+ if (isSimpleQuery(child) && child.attribute === attributeName) {
6736
+ return this.buildIndexQuery(child);
6737
+ }
6738
+ }
6739
+ }
6740
+ return { type: "has" };
6741
+ }
6742
+ /**
6743
+ * Try to optimize query as a point lookup.
6744
+ * Returns a point lookup step if query is an equality or IN query on primary key.
6745
+ *
6746
+ * @param query - Query to check
6747
+ * @returns Point lookup step or null
6748
+ */
6749
+ tryPointLookup(query) {
6750
+ if (!isSimpleQuery(query)) {
6751
+ return null;
6752
+ }
6753
+ const primaryKeyFields = ["_key", "key", "id"];
6754
+ if (!primaryKeyFields.includes(query.attribute)) {
6755
+ return null;
6756
+ }
6757
+ if (query.type === "eq") {
6758
+ return {
6759
+ type: "point-lookup",
6760
+ key: query.value,
6761
+ cost: 1
6762
+ };
6763
+ }
6764
+ if (query.type === "in" && query.values) {
6765
+ return {
6766
+ type: "multi-point-lookup",
6767
+ keys: query.values,
6768
+ cost: query.values.length
6769
+ };
6770
+ }
6771
+ return null;
6772
+ }
6483
6773
  /**
6484
6774
  * Optimize a single query node.
6485
6775
  */
@@ -6495,7 +6785,7 @@ var QueryOptimizer = class {
6495
6785
  }
6496
6786
  }
6497
6787
  /**
6498
- * Optimize a full-text search query (Phase 12).
6788
+ * Optimize a full-text search query.
6499
6789
  */
6500
6790
  optimizeFTS(query) {
6501
6791
  const field = query.attribute;
@@ -6505,7 +6795,7 @@ var QueryOptimizer = class {
6505
6795
  return this.buildFTSScanStep(query);
6506
6796
  }
6507
6797
  /**
6508
- * Build an FTS scan step from a query node (Phase 12).
6798
+ * Build an FTS scan step from a query node.
6509
6799
  */
6510
6800
  buildFTSScanStep(query) {
6511
6801
  const field = query.attribute;
@@ -6545,7 +6835,7 @@ var QueryOptimizer = class {
6545
6835
  }
6546
6836
  }
6547
6837
  /**
6548
- * Estimate cost of FTS query based on index size (Phase 12).
6838
+ * Estimate cost of FTS query based on index size.
6549
6839
  */
6550
6840
  estimateFTSCost(field) {
6551
6841
  const index = this.fullTextIndexes.get(field);
@@ -6556,7 +6846,7 @@ var QueryOptimizer = class {
6556
6846
  return 50 + Math.log2(docCount + 1) * 10;
6557
6847
  }
6558
6848
  /**
6559
- * Classify predicates by type for hybrid query planning (Phase 12).
6849
+ * Classify predicates by type for hybrid query planning.
6560
6850
  *
6561
6851
  * @param predicates - Array of predicates to classify
6562
6852
  * @returns Classified predicates
@@ -6597,7 +6887,7 @@ var QueryOptimizer = class {
6597
6887
  return result;
6598
6888
  }
6599
6889
  /**
6600
- * Determine fusion strategy based on step types (Phase 12).
6890
+ * Determine fusion strategy based on step types.
6601
6891
  *
6602
6892
  * Strategy selection:
6603
6893
  * - All binary (exact/range with no scores) → 'intersection'
@@ -6619,7 +6909,7 @@ var QueryOptimizer = class {
6619
6909
  }
6620
6910
  }
6621
6911
  /**
6622
- * Check if a plan step returns scored results (Phase 12).
6912
+ * Check if a plan step returns scored results.
6623
6913
  */
6624
6914
  stepReturnsScored(step) {
6625
6915
  switch (step.type) {
@@ -6663,7 +6953,7 @@ var QueryOptimizer = class {
6663
6953
  * Strategy: Find child with lowest cost, use as base, filter with rest.
6664
6954
  *
6665
6955
  * CQEngine "smallest first" strategy:
6666
- * 1. Check for CompoundIndex covering all eq children (Phase 9.03)
6956
+ * 1. Check for CompoundIndex covering all eq children
6667
6957
  * 2. Sort children by merge cost
6668
6958
  * 3. Use intersection if multiple indexes available
6669
6959
  * 4. Apply remaining predicates as filters
@@ -6704,7 +6994,7 @@ var QueryOptimizer = class {
6704
6994
  return { type: "intersection", steps: indexedSteps };
6705
6995
  }
6706
6996
  /**
6707
- * Try to use a CompoundIndex for an AND query (Phase 9.03).
6997
+ * Try to use a CompoundIndex for an AND query.
6708
6998
  *
6709
6999
  * Returns a compound index scan step if:
6710
7000
  * 1. All children are simple 'eq' queries
@@ -6868,6 +7158,9 @@ var QueryOptimizer = class {
6868
7158
  */
6869
7159
  estimateCost(step) {
6870
7160
  switch (step.type) {
7161
+ case "point-lookup":
7162
+ case "multi-point-lookup":
7163
+ return step.cost;
6871
7164
  case "index-scan":
6872
7165
  return step.index.getRetrievalCost();
6873
7166
  case "full-scan":
@@ -6886,7 +7179,7 @@ var QueryOptimizer = class {
6886
7179
  return this.estimateCost(step.source) + 10;
6887
7180
  case "not":
6888
7181
  return this.estimateCost(step.source) + 100;
6889
- // Phase 12: FTS step types
7182
+ // FTS step types
6890
7183
  case "fts-scan":
6891
7184
  return step.estimatedCost;
6892
7185
  case "fusion":
@@ -6903,22 +7196,100 @@ var QueryOptimizer = class {
6903
7196
  }
6904
7197
  }
6905
7198
  /**
6906
- * Check if a plan step uses any indexes.
7199
+ * Estimate distributed cost including network overhead.
7200
+ *
7201
+ * Network cost is assigned based on step type:
7202
+ * - full-scan: broadcast to all nodes (highest cost)
7203
+ * - index-scan: 0 if local partition, 5 if remote
7204
+ * - point-lookup: 0 if local key, 5 if remote
7205
+ * - intersection/union: aggregating results from multiple sources
7206
+ *
7207
+ * @param step - Plan step to estimate
7208
+ * @param context - Distributed query context (optional)
7209
+ * @returns Distributed cost breakdown
6907
7210
  */
6908
- usesIndexes(step) {
7211
+ estimateDistributedCost(step, context) {
7212
+ const baseCost = this.estimateCost(step);
7213
+ if (!context?.isDistributed || context.nodeCount <= 1) {
7214
+ return {
7215
+ rows: baseCost,
7216
+ cpu: baseCost,
7217
+ network: 0,
7218
+ io: 0
7219
+ };
7220
+ }
7221
+ let networkCost = 0;
6909
7222
  switch (step.type) {
6910
- case "index-scan":
6911
- return true;
6912
7223
  case "full-scan":
6913
- return false;
7224
+ networkCost = context.nodeCount * 10;
7225
+ break;
7226
+ case "index-scan":
7227
+ networkCost = 5;
7228
+ break;
7229
+ case "point-lookup":
7230
+ networkCost = 5;
7231
+ break;
7232
+ case "multi-point-lookup":
7233
+ networkCost = Math.min(step.keys.length, context.nodeCount) * 5;
7234
+ break;
6914
7235
  case "intersection":
6915
7236
  case "union":
6916
- return step.steps.some((s) => this.usesIndexes(s));
7237
+ networkCost = step.steps.length * 5;
7238
+ break;
6917
7239
  case "filter":
6918
- return this.usesIndexes(step.source);
7240
+ return this.estimateDistributedCost(step.source, context);
6919
7241
  case "not":
6920
- return this.usesIndexes(step.source);
6921
- // Phase 12: FTS step types
7242
+ networkCost = context.nodeCount * 5;
7243
+ break;
7244
+ case "fts-scan":
7245
+ networkCost = Math.ceil(context.nodeCount / 2) * 5;
7246
+ break;
7247
+ case "fusion":
7248
+ networkCost = step.steps.reduce(
7249
+ (sum, s) => sum + this.estimateDistributedCost(s, context).network,
7250
+ 0
7251
+ );
7252
+ break;
7253
+ }
7254
+ return {
7255
+ rows: baseCost,
7256
+ cpu: baseCost,
7257
+ network: networkCost,
7258
+ io: context.usesStorage ? baseCost * 0.5 : 0
7259
+ };
7260
+ }
7261
+ /**
7262
+ * Get total distributed cost for a plan step.
7263
+ * Convenience method combining estimateDistributedCost and calculateTotalCost.
7264
+ *
7265
+ * @param step - Plan step to estimate
7266
+ * @param context - Distributed query context (optional)
7267
+ * @returns Weighted total cost
7268
+ */
7269
+ getTotalDistributedCost(step, context) {
7270
+ const distributedCost = this.estimateDistributedCost(step, context);
7271
+ return calculateTotalCost(distributedCost);
7272
+ }
7273
+ /**
7274
+ * Check if a plan step uses any indexes.
7275
+ */
7276
+ usesIndexes(step) {
7277
+ switch (step.type) {
7278
+ case "point-lookup":
7279
+ case "multi-point-lookup":
7280
+ return true;
7281
+ case "index-scan":
7282
+ return true;
7283
+ case "full-scan":
7284
+ return false;
7285
+ case "intersection":
7286
+ case "union":
7287
+ return step.steps.some((s) => this.usesIndexes(s));
7288
+ case "filter":
7289
+ return this.usesIndexes(step.source);
7290
+ case "not":
7291
+ return this.usesIndexes(step.source);
7292
+ // FTS step types
6922
7293
  case "fts-scan":
6923
7294
  return true;
6924
7295
  // FTS uses FullTextIndex
@@ -7175,7 +7546,7 @@ var LiveQueryManager = class {
7175
7546
  results: initialResults
7176
7547
  });
7177
7548
  } catch (error) {
7178
- console.error("LiveQueryManager initial callback error:", error);
7549
+ logger.error({ err: error, query, context: "initial_callback" }, "LiveQueryManager initial callback error");
7179
7550
  }
7180
7551
  return () => {
7181
7552
  callbacks?.delete(callback);
@@ -7274,7 +7645,7 @@ var LiveQueryManager = class {
7274
7645
  newResultCount: index.getResultCount()
7275
7646
  });
7276
7647
  } catch (error) {
7277
- console.error("LiveQueryManager callback error:", error);
7648
+ logger.error({ err: error, operation, context: "delta_callback" }, "LiveQueryManager callback error");
7278
7649
  }
7279
7650
  }
7280
7651
  }
@@ -7409,7 +7780,7 @@ var QueryPatternTracker = class {
7409
7780
  }
7410
7781
  }
7411
7782
  /**
7412
- * Record a compound (AND) query execution for pattern tracking (Phase 9.03).
7783
+ * Record a compound (AND) query execution for pattern tracking.
7413
7784
  *
7414
7785
  * @param attributes - Array of attribute names being queried together
7415
7786
  * @param executionTime - Query execution time in milliseconds
@@ -7449,7 +7820,7 @@ var QueryPatternTracker = class {
7449
7820
  }
7450
7821
  }
7451
7822
  /**
7452
- * Get all compound query statistics (Phase 9.03).
7823
+ * Get all compound query statistics.
7453
7824
  *
7454
7825
  * @returns Array of compound query statistics, sorted by query count descending
7455
7826
  */
@@ -7639,7 +8010,7 @@ var QueryPatternTracker = class {
7639
8010
  }
7640
8011
  }
7641
8012
  /**
7642
- * Evict the oldest compound query entry (Phase 9.03).
8013
+ * Evict the oldest compound query entry.
7643
8014
  */
7644
8015
  evictOldestCompound() {
7645
8016
  let oldestKey = null;
@@ -7655,7 +8026,7 @@ var QueryPatternTracker = class {
7655
8026
  }
7656
8027
  }
7657
8028
  /**
7658
- * Prune stale compound statistics (Phase 9.03).
8029
+ * Prune stale compound statistics.
7659
8030
  */
7660
8031
  pruneStaleCompound() {
7661
8032
  const cutoff = Date.now() - this.statsTtl;
@@ -7904,7 +8275,7 @@ var IndexAdvisor = class {
7904
8275
  return reason;
7905
8276
  }
7906
8277
  // ========================================
7907
- // Phase 9.03: Compound Index Suggestions
8278
+ // Compound Index Suggestions
7908
8279
  // ========================================
7909
8280
  /**
7910
8281
  * Get compound index suggestions based on AND query patterns.
@@ -8225,7 +8596,7 @@ var AutoIndexManager = class {
8225
8596
  this.tracker.updateIndexStatus(attributeName, true);
8226
8597
  this.config.onIndexCreated(attributeName, indexType);
8227
8598
  } catch (error) {
8228
- console.error(`AutoIndexManager: Failed to create ${indexType} index on '${attributeName}':`, error);
8599
+ logger.error({ err: error, attributeName, indexType, context: "index_creation" }, `AutoIndexManager: Failed to create ${indexType} index on '${attributeName}'`);
8229
8600
  }
8230
8601
  }
8231
8602
  };
@@ -9023,7 +9394,7 @@ var IndexedLWWMap = class extends LWWMap {
9023
9394
  * Execute a query using indexes.
9024
9395
  * Returns lazy ResultSet of matching keys.
9025
9396
  *
9026
- * Also tracks query patterns for adaptive indexing (Phase 8.02).
9397
+ * Also tracks query patterns for adaptive indexing.
9027
9398
  *
9028
9399
  * @param query - Query to execute
9029
9400
  * @returns ResultSet of matching keys
@@ -9087,6 +9458,24 @@ var IndexedLWWMap = class extends LWWMap {
9087
9458
  */
9088
9459
  executePlan(step) {
9089
9460
  switch (step.type) {
9461
+ case "point-lookup": {
9462
+ const key = step.key;
9463
+ const result = /* @__PURE__ */ new Set();
9464
+ if (this.get(key) !== void 0) {
9465
+ result.add(key);
9466
+ }
9467
+ return new SetResultSet(result, 1);
9468
+ }
9469
+ case "multi-point-lookup": {
9470
+ const result = /* @__PURE__ */ new Set();
9471
+ for (const key of step.keys) {
9472
+ const k = key;
9473
+ if (this.get(k) !== void 0) {
9474
+ result.add(k);
9475
+ }
9476
+ }
9477
+ return new SetResultSet(result, step.keys.length);
9478
+ }
9090
9479
  case "index-scan":
9091
9480
  return step.index.retrieve(step.query);
9092
9481
  case "full-scan": {
@@ -9392,7 +9781,7 @@ var IndexedLWWMap = class extends LWWMap {
9392
9781
  explainQuery(query) {
9393
9782
  return this.queryOptimizer.optimize(query);
9394
9783
  }
9395
- // ==================== Adaptive Indexing (Phase 8.02) ====================
9784
+ // ==================== Adaptive Indexing ====================
9396
9785
  /**
9397
9786
  * Register an attribute for auto-indexing.
9398
9787
  * Required before auto-index can create indexes on this attribute.
@@ -9474,7 +9863,7 @@ var IndexedLWWMap = class extends LWWMap {
9474
9863
  isAutoIndexingEnabled() {
9475
9864
  return this.autoIndexManager !== null;
9476
9865
  }
9477
- // ==================== Lazy Indexing (Phase 9.01) ====================
9866
+ // ==================== Lazy Indexing ====================
9478
9867
  /**
9479
9868
  * Check if lazy index building is enabled.
9480
9869
  */
@@ -10679,7 +11068,7 @@ var FullTextIndex = class {
10679
11068
  var IndexedORMap = class extends ORMap {
10680
11069
  constructor(hlc, options = {}) {
10681
11070
  super(hlc);
10682
- // Full-Text Search (Phase 11)
11071
+ // Full-Text Search
10683
11072
  this.fullTextIndex = null;
10684
11073
  this.options = options;
10685
11074
  this.indexRegistry = new IndexRegistry();
@@ -10761,7 +11150,7 @@ var IndexedORMap = class extends ORMap {
10761
11150
  this.indexRegistry.addIndex(index);
10762
11151
  this.buildIndexFromExisting(index);
10763
11152
  }
10764
- // ==================== Full-Text Search (Phase 11) ====================
11153
+ // ==================== Full-Text Search ====================
10765
11154
  /**
10766
11155
  * Enable BM25-based full-text search on specified fields.
10767
11156
  * This creates a FullTextIndex for relevance-ranked search.
@@ -10904,7 +11293,7 @@ var IndexedORMap = class extends ORMap {
10904
11293
  * Execute a query across all records.
10905
11294
  * Returns array of matching results with key, tag, and value.
10906
11295
  *
10907
- * Also tracks query patterns for adaptive indexing (Phase 8.02).
11296
+ * Also tracks query patterns for adaptive indexing.
10908
11297
  *
10909
11298
  * @param query - Query to execute
10910
11299
  * @returns Array of query results
@@ -11270,7 +11659,7 @@ var IndexedORMap = class extends ORMap {
11270
11659
  explainQuery(query) {
11271
11660
  return this.queryOptimizer.optimize(query);
11272
11661
  }
11273
- // ==================== Adaptive Indexing (Phase 8.02) ====================
11662
+ // ==================== Adaptive Indexing ====================
11274
11663
  /**
11275
11664
  * Register an attribute for auto-indexing.
11276
11665
  * Required before auto-index can create indexes on this attribute.
@@ -11603,13 +11992,1057 @@ var SearchCursor = class {
11603
11992
  };
11604
11993
  }
11605
11994
  };
11995
+
11996
+ // src/debug/CRDTDebugger.ts
11997
+ var CRDTDebugger = class {
11998
+ constructor(options = {}) {
11999
+ this.snapshots = [];
12000
+ this.conflicts = [];
12001
+ this.idCounter = 0;
12002
+ this.maxSnapshots = options.maxSnapshots || 1e4;
12003
+ this.enabled = options.enabled ?? process.env.TOPGUN_DEBUG === "true";
12004
+ }
12005
+ // ============================================================================
12006
+ // Recording Control
12007
+ // ============================================================================
12008
+ isEnabled() {
12009
+ return this.enabled;
12010
+ }
12011
+ enable() {
12012
+ this.enabled = true;
12013
+ }
12014
+ disable() {
12015
+ this.enabled = false;
12016
+ }
12017
+ // ============================================================================
12018
+ // Operation Recording
12019
+ // ============================================================================
12020
+ recordOperation(snapshot) {
12021
+ if (!this.enabled) return;
12022
+ this.snapshots.push({
12023
+ ...snapshot,
12024
+ id: `op-${++this.idCounter}`
12025
+ });
12026
+ if (this.snapshots.length > this.maxSnapshots) {
12027
+ this.snapshots = this.snapshots.slice(-this.maxSnapshots);
12028
+ }
12029
+ }
12030
+ recordSet(mapId, key, value, timestamp, nodeId, oldValue, merkleRoot) {
12031
+ this.recordOperation({
12032
+ timestamp,
12033
+ operation: "set",
12034
+ mapId,
12035
+ key,
12036
+ value,
12037
+ oldValue,
12038
+ nodeId,
12039
+ merkleRoot
12040
+ });
12041
+ }
12042
+ recordDelete(mapId, key, timestamp, nodeId, oldValue, merkleRoot) {
12043
+ this.recordOperation({
12044
+ timestamp,
12045
+ operation: "delete",
12046
+ mapId,
12047
+ key,
12048
+ oldValue,
12049
+ nodeId,
12050
+ merkleRoot
12051
+ });
12052
+ }
12053
+ recordMerge(mapId, key, value, timestamp, nodeId, wasUpdated, oldValue, merkleRoot) {
12054
+ this.recordOperation({
12055
+ timestamp,
12056
+ operation: "merge",
12057
+ mapId,
12058
+ key,
12059
+ value,
12060
+ oldValue,
12061
+ nodeId,
12062
+ merkleRoot,
12063
+ metadata: { wasUpdated }
12064
+ });
12065
+ }
12066
+ recordConflict(conflict) {
12067
+ if (!this.enabled) return;
12068
+ this.conflicts.push(conflict);
12069
+ }
12070
+ // ============================================================================
12071
+ // Querying
12072
+ // ============================================================================
12073
+ getOperations(options = {}) {
12074
+ let results = this.snapshots;
12075
+ if (options.mapId) {
12076
+ results = results.filter((s) => s.mapId === options.mapId);
12077
+ }
12078
+ if (options.nodeId) {
12079
+ results = results.filter((s) => s.nodeId === options.nodeId);
12080
+ }
12081
+ if (options.operation) {
12082
+ results = results.filter((s) => s.operation === options.operation);
12083
+ }
12084
+ if (options.since) {
12085
+ results = results.filter(
12086
+ (s) => this.compareTimestamp(s.timestamp, options.since) >= 0
12087
+ );
12088
+ }
12089
+ if (options.until) {
12090
+ results = results.filter(
12091
+ (s) => this.compareTimestamp(s.timestamp, options.until) <= 0
12092
+ );
12093
+ }
12094
+ if (options.limit) {
12095
+ results = results.slice(-options.limit);
12096
+ }
12097
+ return results;
12098
+ }
12099
+ getConflicts(mapId) {
12100
+ if (mapId) {
12101
+ return this.conflicts.filter((c) => c.mapId === mapId);
12102
+ }
12103
+ return this.conflicts;
12104
+ }
12105
+ getLastOperation() {
12106
+ return this.snapshots[this.snapshots.length - 1];
12107
+ }
12108
+ getOperationsForKey(mapId, key) {
12109
+ return this.snapshots.filter((s) => s.mapId === mapId && s.key === key);
12110
+ }
12111
+ // ============================================================================
12112
+ // Statistics
12113
+ // ============================================================================
12114
+ getStatistics(mapId) {
12115
+ const ops = mapId ? this.snapshots.filter((s) => s.mapId === mapId) : this.snapshots;
12116
+ const operationsByType = {};
12117
+ const operationsByNode = {};
12118
+ const uniqueKeys = /* @__PURE__ */ new Set();
12119
+ for (const op of ops) {
12120
+ operationsByType[op.operation] = (operationsByType[op.operation] || 0) + 1;
12121
+ operationsByNode[op.nodeId] = (operationsByNode[op.nodeId] || 0) + 1;
12122
+ if (op.key) uniqueKeys.add(op.key);
12123
+ }
12124
+ const timeRange = {
12125
+ start: ops.length > 0 ? ops[0].timestamp : null,
12126
+ end: ops.length > 0 ? ops[ops.length - 1].timestamp : null
12127
+ };
12128
+ let avgOpsPerSecond = 0;
12129
+ if (timeRange.start && timeRange.end) {
12130
+ const durationMs = timeRange.end.millis - timeRange.start.millis;
12131
+ if (durationMs > 0) {
12132
+ avgOpsPerSecond = ops.length / durationMs * 1e3;
12133
+ }
12134
+ }
12135
+ return {
12136
+ totalOperations: ops.length,
12137
+ operationsByType,
12138
+ operationsByNode,
12139
+ conflictsResolved: this.conflicts.length,
12140
+ timeRange,
12141
+ uniqueKeys: uniqueKeys.size,
12142
+ averageOpsPerSecond: avgOpsPerSecond
12143
+ };
12144
+ }
12145
+ // ============================================================================
12146
+ // Replay
12147
+ // ============================================================================
12148
+ /**
12149
+ * Replays operations up to the target timestamp and returns the map state.
12150
+ */
12151
+ replayUntil(targetTimestamp, mapId, hlc) {
12152
+ const map = new LWWMap(hlc || new HLC("replay-node"));
12153
+ const ops = this.getOperations({ mapId, until: targetTimestamp });
12154
+ for (const op of ops) {
12155
+ if (op.operation === "set" && op.key !== void 0) {
12156
+ const record = {
12157
+ value: op.value,
12158
+ timestamp: op.timestamp
12159
+ };
12160
+ map.merge(op.key, record);
12161
+ } else if (op.operation === "delete" && op.key !== void 0) {
12162
+ const record = {
12163
+ value: null,
12164
+ timestamp: op.timestamp
12165
+ };
12166
+ map.merge(op.key, record);
12167
+ } else if (op.operation === "merge" && op.key !== void 0) {
12168
+ const record = {
12169
+ value: op.value,
12170
+ timestamp: op.timestamp
12171
+ };
12172
+ map.merge(op.key, record);
12173
+ }
12174
+ }
12175
+ return map;
12176
+ }
12177
+ /**
12178
+ * Creates a timeline of operations grouped by time intervals.
12179
+ */
12180
+ getTimeline(intervalMs = 1e3, mapId) {
12181
+ const ops = mapId ? this.snapshots.filter((s) => s.mapId === mapId) : this.snapshots;
12182
+ if (ops.length === 0) return [];
12183
+ const timeline = [];
12184
+ let currentBucket = [];
12185
+ let bucketStart = Math.floor(ops[0].timestamp.millis / intervalMs) * intervalMs;
12186
+ for (const op of ops) {
12187
+ const opBucket = Math.floor(op.timestamp.millis / intervalMs) * intervalMs;
12188
+ if (opBucket !== bucketStart) {
12189
+ if (currentBucket.length > 0) {
12190
+ timeline.push({ timestamp: bucketStart, operations: currentBucket });
12191
+ }
12192
+ currentBucket = [];
12193
+ bucketStart = opBucket;
12194
+ }
12195
+ currentBucket.push(op);
12196
+ }
12197
+ if (currentBucket.length > 0) {
12198
+ timeline.push({ timestamp: bucketStart, operations: currentBucket });
12199
+ }
12200
+ return timeline;
12201
+ }
12202
+ // ============================================================================
12203
+ // Export / Import
12204
+ // ============================================================================
12205
+ exportHistory(format = "json") {
12206
+ switch (format) {
12207
+ case "csv":
12208
+ return this.toCSV();
12209
+ case "ndjson":
12210
+ return this.snapshots.map((s) => JSON.stringify(s)).join("\n");
12211
+ default:
12212
+ return JSON.stringify(
12213
+ {
12214
+ version: "1.0",
12215
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
12216
+ statistics: this.getStatistics(),
12217
+ operations: this.snapshots,
12218
+ conflicts: this.conflicts
12219
+ },
12220
+ null,
12221
+ 2
12222
+ );
12223
+ }
12224
+ }
12225
+ toCSV() {
12226
+ const header = "id,timestamp_millis,timestamp_counter,operation,map_id,key,node_id,merkle_root\n";
12227
+ const rows = this.snapshots.map(
12228
+ (s) => `${s.id},${s.timestamp.millis},${s.timestamp.counter},${s.operation},${s.mapId},${s.key || ""},${s.nodeId},${s.merkleRoot || ""}`
12229
+ ).join("\n");
12230
+ return header + rows;
12231
+ }
12232
+ importHistory(json) {
12233
+ const data = JSON.parse(json);
12234
+ if (data.version === "1.0") {
12235
+ this.snapshots = data.operations || [];
12236
+ this.conflicts = data.conflicts || [];
12237
+ const maxId = this.snapshots.reduce((max, s) => {
12238
+ const num = parseInt(s.id.replace("op-", ""), 10);
12239
+ return isNaN(num) ? max : Math.max(max, num);
12240
+ }, 0);
12241
+ this.idCounter = maxId;
12242
+ } else {
12243
+ throw new Error(
12244
+ 'Unsupported history format. Expected v1.0 format with { version: "1.0", operations: [...], conflicts: [...] }. Legacy array format is no longer supported.'
12245
+ );
12246
+ }
12247
+ }
12248
+ // ============================================================================
12249
+ // Diff
12250
+ // ============================================================================
12251
+ /**
12252
+ * Compares two points in time and returns the differences.
12253
+ */
12254
+ diff(fromTimestamp, toTimestamp, mapId) {
12255
+ const fromOps = this.getOperations({ mapId, until: fromTimestamp });
12256
+ const toOps = this.getOperations({ mapId, until: toTimestamp });
12257
+ const fromState = /* @__PURE__ */ new Map();
12258
+ const toState = /* @__PURE__ */ new Map();
12259
+ for (const op of fromOps) {
12260
+ if (op.key) {
12261
+ fromState.set(`${op.mapId}:${op.key}`, op);
12262
+ }
12263
+ }
12264
+ for (const op of toOps) {
12265
+ if (op.key) {
12266
+ toState.set(`${op.mapId}:${op.key}`, op);
12267
+ }
12268
+ }
12269
+ const added = [];
12270
+ const modified = [];
12271
+ const deleted = [];
12272
+ for (const [key, toOp] of toState) {
12273
+ const fromOp = fromState.get(key);
12274
+ if (!fromOp) {
12275
+ if (toOp.operation !== "delete") {
12276
+ added.push(toOp);
12277
+ }
12278
+ } else if (toOp.operation === "delete" && fromOp.operation !== "delete") {
12279
+ deleted.push(toOp);
12280
+ } else if (toOp.operation !== "delete" && JSON.stringify(toOp.value) !== JSON.stringify(fromOp.value)) {
12281
+ modified.push(toOp);
12282
+ }
12283
+ }
12284
+ return { added, modified, deleted };
12285
+ }
12286
+ // ============================================================================
12287
+ // Utilities
12288
+ // ============================================================================
12289
+ clear() {
12290
+ this.snapshots = [];
12291
+ this.conflicts = [];
12292
+ this.idCounter = 0;
12293
+ }
12294
+ compareTimestamp(a, b) {
12295
+ if (a.millis !== b.millis) return a.millis - b.millis;
12296
+ if (a.counter !== b.counter) return a.counter - b.counter;
12297
+ return a.nodeId.localeCompare(b.nodeId);
12298
+ }
12299
+ };
12300
+ var globalDebugger = null;
12301
+ function getCRDTDebugger() {
12302
+ if (!globalDebugger) {
12303
+ globalDebugger = new CRDTDebugger();
12304
+ }
12305
+ return globalDebugger;
12306
+ }
12307
+ function resetCRDTDebugger() {
12308
+ globalDebugger = null;
12309
+ }
12310
+
12311
+ // src/debug/SearchDebugger.ts
12312
+ var SearchDebugger = class {
12313
+ constructor(options = {}) {
12314
+ this.lastQuery = null;
12315
+ this.history = [];
12316
+ this.enabled = options.enabled ?? process.env.TOPGUN_DEBUG === "true";
12317
+ this.maxHistory = options.maxHistory || 100;
12318
+ }
12319
+ // ============================================================================
12320
+ // Control
12321
+ // ============================================================================
12322
+ isEnabled() {
12323
+ return this.enabled;
12324
+ }
12325
+ enable() {
12326
+ this.enabled = true;
12327
+ }
12328
+ disable() {
12329
+ this.enabled = false;
12330
+ }
12331
+ // ============================================================================
12332
+ // Recording
12333
+ // ============================================================================
12334
+ recordSearch(debugInfo) {
12335
+ if (!this.enabled) return;
12336
+ this.lastQuery = debugInfo;
12337
+ this.history.push(debugInfo);
12338
+ if (this.history.length > this.maxHistory) {
12339
+ this.history = this.history.slice(-this.maxHistory);
12340
+ }
12341
+ }
12342
+ // ============================================================================
12343
+ // Querying
12344
+ // ============================================================================
12345
+ getLastQuery() {
12346
+ return this.lastQuery;
12347
+ }
12348
+ getHistory() {
12349
+ return this.history;
12350
+ }
12351
+ getHistoryByMap(mapId) {
12352
+ return this.history.filter((q) => q.mapId === mapId);
12353
+ }
12354
+ explainResult(docId) {
12355
+ return this.lastQuery?.results.find((r) => r.docId === docId);
12356
+ }
12357
+ // ============================================================================
12358
+ // Formatting
12359
+ // ============================================================================
12360
+ formatExplanation(docId) {
12361
+ const result = this.explainResult(docId);
12362
+ if (!result) return "No debug info available for this document.";
12363
+ const lines = [];
12364
+ lines.push(`Score Breakdown for ${docId}`);
12365
+ lines.push(`Final Score: ${result.finalScore.toFixed(4)}`);
12366
+ lines.push("");
12367
+ if (result.scoreBreakdown.bm25) {
12368
+ const bm25 = result.scoreBreakdown.bm25;
12369
+ lines.push("BM25 Full-Text Search:");
12370
+ lines.push(` Score: ${bm25.score.toFixed(4)}`);
12371
+ lines.push(
12372
+ ` Document length: ${bm25.docLength} (avg: ${bm25.avgDocLength.toFixed(1)})`
12373
+ );
12374
+ lines.push(` Parameters: k1=${bm25.k1}, b=${bm25.b}`);
12375
+ lines.push(" Term contributions:");
12376
+ for (const term of bm25.matchedTerms) {
12377
+ const tf = bm25.tf[term] || 0;
12378
+ const idf = bm25.idf[term] || 0;
12379
+ const contribution = tf * idf;
12380
+ lines.push(
12381
+ ` "${term}": TF=${tf.toFixed(3)}, IDF=${idf.toFixed(3)}, contribution=${contribution.toFixed(4)}`
12382
+ );
12383
+ }
12384
+ lines.push("");
12385
+ }
12386
+ if (result.scoreBreakdown.exact) {
12387
+ const exact = result.scoreBreakdown.exact;
12388
+ lines.push("Exact Match:");
12389
+ lines.push(` Score: ${exact.score.toFixed(4)}`);
12390
+ lines.push(` Matched fields: ${exact.matchedFields.join(", ")}`);
12391
+ lines.push(` Boost applied: ${exact.boostApplied}x`);
12392
+ lines.push("");
12393
+ }
12394
+ if (result.scoreBreakdown.rrf) {
12395
+ const rrf = result.scoreBreakdown.rrf;
12396
+ lines.push("Reciprocal Rank Fusion (RRF):");
12397
+ lines.push(` Final rank: ${rrf.rank}`);
12398
+ lines.push(` RRF score: ${rrf.score.toFixed(4)}`);
12399
+ lines.push(` k parameter: ${rrf.k}`);
12400
+ lines.push(" Contributing ranks:");
12401
+ for (const contrib of rrf.contributingRanks) {
12402
+ lines.push(` ${contrib.source}: rank ${contrib.rank}`);
12403
+ }
12404
+ lines.push("");
12405
+ }
12406
+ if (result.scoreBreakdown.vector) {
12407
+ const vector = result.scoreBreakdown.vector;
12408
+ lines.push("Vector Similarity:");
12409
+ lines.push(` Score: ${vector.score.toFixed(4)}`);
12410
+ lines.push(` Distance: ${vector.distance.toFixed(4)}`);
12411
+ lines.push(` Metric: ${vector.similarity}`);
12412
+ lines.push("");
12413
+ }
12414
+ return lines.join("\n");
12415
+ }
12416
+ formatQuerySummary() {
12417
+ if (!this.lastQuery) return "No query recorded.";
12418
+ const q = this.lastQuery;
12419
+ const lines = [];
12420
+ lines.push(`Query: "${q.query}"`);
12421
+ lines.push(`Tokens: ${q.queryTokens.join(", ")}`);
12422
+ lines.push(`Type: ${q.searchType}`);
12423
+ lines.push(`Results: ${q.matchingDocuments} of ${q.totalDocuments} documents`);
12424
+ lines.push("");
12425
+ lines.push("Timing:");
12426
+ lines.push(` Tokenization: ${q.timing.tokenization.toFixed(2)}ms`);
12427
+ lines.push(` Index lookup: ${q.timing.indexLookup.toFixed(2)}ms`);
12428
+ lines.push(` Scoring: ${q.timing.scoring.toFixed(2)}ms`);
12429
+ lines.push(` Ranking: ${q.timing.ranking.toFixed(2)}ms`);
12430
+ if (q.timing.fusion !== void 0) {
12431
+ lines.push(` Fusion: ${q.timing.fusion.toFixed(2)}ms`);
12432
+ }
12433
+ lines.push(` Total: ${q.timing.total.toFixed(2)}ms`);
12434
+ lines.push("");
12435
+ lines.push("Index stats:");
12436
+ lines.push(` Type: ${q.indexStats.indexType}`);
12437
+ lines.push(` Size: ${q.indexStats.indexSize} entries`);
12438
+ lines.push(` Terms searched: ${q.indexStats.termsSearched}`);
12439
+ return lines.join("\n");
12440
+ }
12441
+ formatAllResults() {
12442
+ if (!this.lastQuery) return "No query recorded.";
12443
+ const lines = [];
12444
+ lines.push(this.formatQuerySummary());
12445
+ lines.push("");
12446
+ lines.push("Results:");
12447
+ lines.push("");
12448
+ for (let i = 0; i < this.lastQuery.results.length; i++) {
12449
+ const result = this.lastQuery.results[i];
12450
+ lines.push(`${i + 1}. ${result.docId}`);
12451
+ lines.push(` Final score: ${result.finalScore.toFixed(4)}`);
12452
+ if (result.scoreBreakdown.bm25) {
12453
+ const bm25 = result.scoreBreakdown.bm25;
12454
+ lines.push(` BM25: ${bm25.score.toFixed(4)}`);
12455
+ const topTerms = bm25.matchedTerms.slice(0, 3);
12456
+ for (const term of topTerms) {
12457
+ lines.push(
12458
+ ` - "${term}": TF=${bm25.tf[term]?.toFixed(3)}, IDF=${bm25.idf[term]?.toFixed(3)}`
12459
+ );
12460
+ }
12461
+ }
12462
+ if (result.scoreBreakdown.exact) {
12463
+ lines.push(
12464
+ ` Exact: ${result.scoreBreakdown.exact.score.toFixed(4)} (${result.scoreBreakdown.exact.matchedFields.join(", ")})`
12465
+ );
12466
+ }
12467
+ if (result.scoreBreakdown.rrf) {
12468
+ lines.push(` RRF rank: ${result.scoreBreakdown.rrf.rank}`);
12469
+ }
12470
+ lines.push("");
12471
+ }
12472
+ return lines.join("\n");
12473
+ }
12474
+ // ============================================================================
12475
+ // Export
12476
+ // ============================================================================
12477
+ exportDebugInfo() {
12478
+ return JSON.stringify(this.lastQuery, null, 2);
12479
+ }
12480
+ exportHistory() {
12481
+ return JSON.stringify(
12482
+ {
12483
+ version: "1.0",
12484
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
12485
+ queryCount: this.history.length,
12486
+ queries: this.history
12487
+ },
12488
+ null,
12489
+ 2
12490
+ );
12491
+ }
12492
+ // ============================================================================
12493
+ // Analysis
12494
+ // ============================================================================
12495
+ getSearchStats() {
12496
+ if (this.history.length === 0) {
12497
+ return {
12498
+ totalQueries: 0,
12499
+ averageResultCount: 0,
12500
+ averageLatencyMs: 0,
12501
+ queryTypeBreakdown: {}
12502
+ };
12503
+ }
12504
+ const queryTypeBreakdown = {};
12505
+ let totalResults = 0;
12506
+ let totalLatency = 0;
12507
+ for (const q of this.history) {
12508
+ queryTypeBreakdown[q.searchType] = (queryTypeBreakdown[q.searchType] || 0) + 1;
12509
+ totalResults += q.matchingDocuments;
12510
+ totalLatency += q.timing.total;
12511
+ }
12512
+ return {
12513
+ totalQueries: this.history.length,
12514
+ averageResultCount: totalResults / this.history.length,
12515
+ averageLatencyMs: totalLatency / this.history.length,
12516
+ queryTypeBreakdown
12517
+ };
12518
+ }
12519
+ // ============================================================================
12520
+ // Utilities
12521
+ // ============================================================================
12522
+ clear() {
12523
+ this.lastQuery = null;
12524
+ this.history = [];
12525
+ }
12526
+ };
12527
+ var globalSearchDebugger = null;
12528
+ function getSearchDebugger() {
12529
+ if (!globalSearchDebugger) {
12530
+ globalSearchDebugger = new SearchDebugger();
12531
+ }
12532
+ return globalSearchDebugger;
12533
+ }
12534
+ function resetSearchDebugger() {
12535
+ globalSearchDebugger = null;
12536
+ }
12537
+
12538
+ // src/testing/VirtualClock.ts
12539
+ var RealClock = {
12540
+ now: () => Date.now()
12541
+ };
12542
+ var VirtualClock = class {
12543
+ /**
12544
+ * @param initialTime Starting timestamp in milliseconds (default: 0)
12545
+ */
12546
+ constructor(initialTime = 0) {
12547
+ if (!Number.isFinite(initialTime) || initialTime < 0) {
12548
+ throw new Error("Initial time must be a non-negative finite number");
12549
+ }
12550
+ this.currentTime = initialTime;
12551
+ }
12552
+ /**
12553
+ * Returns the current virtual time.
12554
+ * Time remains frozen until advance() or set() is called.
12555
+ */
12556
+ now() {
12557
+ return this.currentTime;
12558
+ }
12559
+ /**
12560
+ * Advances time forward by the specified milliseconds.
12561
+ * @param ms Milliseconds to advance (must be non-negative)
12562
+ */
12563
+ advance(ms) {
12564
+ if (!Number.isFinite(ms) || ms < 0) {
12565
+ throw new Error("Advance amount must be a non-negative finite number");
12566
+ }
12567
+ this.currentTime += ms;
12568
+ }
12569
+ /**
12570
+ * Sets the clock to a specific time.
12571
+ * Allows moving time forward or backward (useful for testing).
12572
+ * @param time Absolute timestamp in milliseconds
12573
+ */
12574
+ set(time) {
12575
+ if (!Number.isFinite(time) || time < 0) {
12576
+ throw new Error("Time must be a non-negative finite number");
12577
+ }
12578
+ this.currentTime = time;
12579
+ }
12580
+ /**
12581
+ * Resets the clock to zero.
12582
+ */
12583
+ reset() {
12584
+ this.currentTime = 0;
12585
+ }
12586
+ };
12587
+
12588
+ // src/testing/SeededRNG.ts
12589
+ var SeededRNG = class {
12590
+ /**
12591
+ * @param seed Integer seed value. Same seed = same sequence.
12592
+ */
12593
+ constructor(seed) {
12594
+ if (!Number.isInteger(seed)) {
12595
+ throw new Error("Seed must be an integer");
12596
+ }
12597
+ this.state = seed >>> 0;
12598
+ this.originalSeed = this.state;
12599
+ }
12600
+ /**
12601
+ * Returns the original seed used to construct this RNG.
12602
+ */
12603
+ getSeed() {
12604
+ return this.originalSeed;
12605
+ }
12606
+ /**
12607
+ * Generates the next random number in [0, 1).
12608
+ * Uses mulberry32 algorithm for deterministic, high-quality randomness.
12609
+ */
12610
+ random() {
12611
+ let t = this.state += 1831565813;
12612
+ t = Math.imul(t ^ t >>> 15, t | 1);
12613
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
12614
+ this.state = t;
12615
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
12616
+ }
12617
+ /**
12618
+ * Generates a random integer in [min, max] (inclusive).
12619
+ * @param min Minimum value (inclusive)
12620
+ * @param max Maximum value (inclusive)
12621
+ */
12622
+ randomInt(min, max) {
12623
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
12624
+ throw new Error("Min and max must be integers");
12625
+ }
12626
+ if (min > max) {
12627
+ throw new Error("Min must be less than or equal to max");
12628
+ }
12629
+ const range = max - min + 1;
12630
+ return Math.floor(this.random() * range) + min;
12631
+ }
12632
+ /**
12633
+ * Generates a random boolean value.
12634
+ * @param probability Probability of returning true (default: 0.5)
12635
+ */
12636
+ randomBool(probability = 0.5) {
12637
+ if (probability < 0 || probability > 1) {
12638
+ throw new Error("Probability must be between 0 and 1");
12639
+ }
12640
+ return this.random() < probability;
12641
+ }
12642
+ /**
12643
+ * Shuffles an array in place using Fisher-Yates algorithm.
12644
+ * Returns the shuffled array.
12645
+ * @param array Array to shuffle
12646
+ */
12647
+ shuffle(array) {
12648
+ for (let i = array.length - 1; i > 0; i--) {
12649
+ const j = this.randomInt(0, i);
12650
+ [array[i], array[j]] = [array[j], array[i]];
12651
+ }
12652
+ return array;
12653
+ }
12654
+ /**
12655
+ * Picks a random element from an array.
12656
+ * @param array Array to pick from
12657
+ * @returns Random element, or undefined if array is empty
12658
+ */
12659
+ pick(array) {
12660
+ if (array.length === 0) return void 0;
12661
+ return array[this.randomInt(0, array.length - 1)];
12662
+ }
12663
+ /**
12664
+ * Resets the RNG to its original seed.
12665
+ * Useful for reproducing a sequence from the start.
12666
+ */
12667
+ reset() {
12668
+ this.state = this.originalSeed;
12669
+ }
12670
+ };
12671
+
12672
+ // src/testing/VirtualNetwork.ts
12673
+ var VirtualNetwork = class {
12674
+ constructor(rng, clock) {
12675
+ this.pendingMessages = [];
12676
+ this.rng = rng;
12677
+ this.clock = clock;
12678
+ this.config = {
12679
+ latencyMs: { min: 0, max: 0 },
12680
+ packetLossRate: 0,
12681
+ partitions: []
12682
+ };
12683
+ }
12684
+ /**
12685
+ * Updates network configuration.
12686
+ * Partially updates existing config with provided values.
12687
+ */
12688
+ configure(config) {
12689
+ if (config.latencyMs !== void 0) {
12690
+ const { min, max } = config.latencyMs;
12691
+ if (min < 0 || max < 0 || min > max) {
12692
+ throw new Error("Invalid latency range");
12693
+ }
12694
+ this.config.latencyMs = config.latencyMs;
12695
+ }
12696
+ if (config.packetLossRate !== void 0) {
12697
+ if (config.packetLossRate < 0 || config.packetLossRate > 1) {
12698
+ throw new Error("Packet loss rate must be between 0 and 1");
12699
+ }
12700
+ this.config.packetLossRate = config.packetLossRate;
12701
+ }
12702
+ if (config.partitions !== void 0) {
12703
+ this.config.partitions = config.partitions;
12704
+ }
12705
+ }
12706
+ /**
12707
+ * Sends a message through the network.
12708
+ * Subject to packet loss, latency, and partition rules.
12709
+ */
12710
+ send(from, to, payload) {
12711
+ if (this.rng.random() < this.config.packetLossRate) {
12712
+ return;
12713
+ }
12714
+ if (this.isPartitioned(from, to)) {
12715
+ return;
12716
+ }
12717
+ const latency = this.rng.randomInt(
12718
+ this.config.latencyMs.min,
12719
+ this.config.latencyMs.max
12720
+ );
12721
+ const scheduledTime = this.clock.now() + latency;
12722
+ this.pendingMessages.push({
12723
+ from,
12724
+ to,
12725
+ payload,
12726
+ scheduledTime
12727
+ });
12728
+ }
12729
+ /**
12730
+ * Creates a network partition between two groups.
12731
+ * Nodes in groupA cannot communicate with nodes in groupB.
12732
+ */
12733
+ partition(groupA, groupB) {
12734
+ this.config.partitions.push(groupA, groupB);
12735
+ }
12736
+ /**
12737
+ * Removes all network partitions.
12738
+ */
12739
+ heal() {
12740
+ this.config.partitions = [];
12741
+ }
12742
+ /**
12743
+ * Delivers all messages scheduled at or before the current time.
12744
+ * @returns Array of delivered messages
12745
+ */
12746
+ tick() {
12747
+ const currentTime = this.clock.now();
12748
+ const delivered = [];
12749
+ const remaining = [];
12750
+ for (const msg of this.pendingMessages) {
12751
+ if (msg.scheduledTime <= currentTime) {
12752
+ delivered.push(msg);
12753
+ } else {
12754
+ remaining.push(msg);
12755
+ }
12756
+ }
12757
+ this.pendingMessages = remaining;
12758
+ return delivered;
12759
+ }
12760
+ /**
12761
+ * Returns the number of messages currently in flight.
12762
+ */
12763
+ getPendingCount() {
12764
+ return this.pendingMessages.length;
12765
+ }
12766
+ /**
12767
+ * Clears all pending messages.
12768
+ */
12769
+ clear() {
12770
+ this.pendingMessages = [];
12771
+ }
12772
+ /**
12773
+ * Checks if two nodes are partitioned from each other.
12774
+ */
12775
+ isPartitioned(from, to) {
12776
+ for (let i = 0; i < this.config.partitions.length; i += 2) {
12777
+ const groupA = this.config.partitions[i];
12778
+ const groupB = this.config.partitions[i + 1];
12779
+ if (groupA.includes(from) && groupB.includes(to) || groupB.includes(from) && groupA.includes(to)) {
12780
+ return true;
12781
+ }
12782
+ }
12783
+ return false;
12784
+ }
12785
+ /**
12786
+ * Returns all pending messages (useful for debugging).
12787
+ */
12788
+ getPendingMessages() {
12789
+ return [...this.pendingMessages];
12790
+ }
12791
+ };
12792
+
12793
+ // src/testing/InvariantChecker.ts
12794
+ var InvariantChecker = class {
12795
+ constructor() {
12796
+ this.invariants = /* @__PURE__ */ new Map();
12797
+ }
12798
+ /**
12799
+ * Adds an invariant to be checked.
12800
+ * @param name Unique name for this invariant
12801
+ * @param check Function that returns true if invariant holds
12802
+ */
12803
+ addInvariant(name, check) {
12804
+ if (this.invariants.has(name)) {
12805
+ throw new Error(`Invariant '${name}' already exists`);
12806
+ }
12807
+ this.invariants.set(name, check);
12808
+ }
12809
+ /**
12810
+ * Removes an invariant by name.
12811
+ */
12812
+ removeInvariant(name) {
12813
+ return this.invariants.delete(name);
12814
+ }
12815
+ /**
12816
+ * Verifies all invariants against the provided state.
12817
+ * @returns Result with pass/fail status and list of failed invariants
12818
+ */
12819
+ verify(state) {
12820
+ const failures = [];
12821
+ for (const [name, check] of this.invariants.entries()) {
12822
+ try {
12823
+ if (!check(state)) {
12824
+ failures.push(name);
12825
+ }
12826
+ } catch (error) {
12827
+ failures.push(`${name} (exception: ${error instanceof Error ? error.message : String(error)})`);
12828
+ }
12829
+ }
12830
+ return {
12831
+ passed: failures.length === 0,
12832
+ failures
12833
+ };
12834
+ }
12835
+ /**
12836
+ * Returns the number of registered invariants.
12837
+ */
12838
+ get count() {
12839
+ return this.invariants.size;
12840
+ }
12841
+ /**
12842
+ * Clears all invariants.
12843
+ */
12844
+ clear() {
12845
+ this.invariants.clear();
12846
+ }
12847
+ };
12848
+ var CRDTInvariants = {
12849
+ /**
12850
+ * Verifies LWW-Map convergence: all maps contain the same values for same keys.
12851
+ */
12852
+ lwwConvergence: (maps) => {
12853
+ if (maps.length < 2) return true;
12854
+ const reference = maps[0];
12855
+ const refKeys = new Set(reference.allKeys());
12856
+ for (let i = 1; i < maps.length; i++) {
12857
+ const other = maps[i];
12858
+ const otherKeys = new Set(other.allKeys());
12859
+ if (refKeys.size !== otherKeys.size) return false;
12860
+ for (const key of refKeys) {
12861
+ if (!otherKeys.has(key)) return false;
12862
+ }
12863
+ for (const key of refKeys) {
12864
+ const refRecord = reference.getRecord(key);
12865
+ const otherRecord = other.getRecord(key);
12866
+ if (!refRecord || !otherRecord) {
12867
+ if (refRecord !== otherRecord) return false;
12868
+ continue;
12869
+ }
12870
+ if (refRecord.value !== otherRecord.value) return false;
12871
+ if (HLC.compare(refRecord.timestamp, otherRecord.timestamp) !== 0) {
12872
+ return false;
12873
+ }
12874
+ }
12875
+ }
12876
+ return true;
12877
+ },
12878
+ /**
12879
+ * Verifies OR-Map convergence: all maps contain the same values for same keys.
12880
+ */
12881
+ orMapConvergence: (maps) => {
12882
+ if (maps.length < 2) return true;
12883
+ const reference = maps[0];
12884
+ const refKeys = reference.allKeys();
12885
+ for (let i = 1; i < maps.length; i++) {
12886
+ const other = maps[i];
12887
+ const otherKeys = new Set(other.allKeys());
12888
+ if (refKeys.length !== otherKeys.size) return false;
12889
+ for (const key of refKeys) {
12890
+ if (!otherKeys.has(key)) return false;
12891
+ }
12892
+ for (const key of refKeys) {
12893
+ const refRecords = reference.getRecords(key);
12894
+ const otherRecords = other.getRecords(key);
12895
+ if (refRecords.length !== otherRecords.length) return false;
12896
+ const refSorted = [...refRecords].sort((a, b) => a.tag.localeCompare(b.tag));
12897
+ const otherSorted = [...otherRecords].sort((a, b) => a.tag.localeCompare(b.tag));
12898
+ for (let j = 0; j < refSorted.length; j++) {
12899
+ if (refSorted[j].tag !== otherSorted[j].tag) return false;
12900
+ if (refSorted[j].value !== otherSorted[j].value) return false;
12901
+ if (HLC.compare(refSorted[j].timestamp, otherSorted[j].timestamp) !== 0) {
12902
+ return false;
12903
+ }
12904
+ }
12905
+ }
12906
+ const refTombstones = new Set(reference.getTombstones());
12907
+ const otherTombstones = new Set(other.getTombstones());
12908
+ if (refTombstones.size !== otherTombstones.size) return false;
12909
+ for (const tag of refTombstones) {
12910
+ if (!otherTombstones.has(tag)) return false;
12911
+ }
12912
+ }
12913
+ return true;
12914
+ },
12915
+ /**
12916
+ * Verifies HLC monotonicity: timestamps are strictly increasing.
12917
+ */
12918
+ hlcMonotonicity: (timestamps) => {
12919
+ for (let i = 1; i < timestamps.length; i++) {
12920
+ if (HLC.compare(timestamps[i - 1], timestamps[i]) >= 0) {
12921
+ return false;
12922
+ }
12923
+ }
12924
+ return true;
12925
+ },
12926
+ /**
12927
+ * Verifies Merkle tree consistency: trees with same data have same root hash.
12928
+ */
12929
+ merkleConsistency: (trees) => {
12930
+ if (trees.length < 2) return true;
12931
+ const referenceHash = trees[0].getRootHash();
12932
+ for (let i = 1; i < trees.length; i++) {
12933
+ if (trees[i].getRootHash() !== referenceHash) {
12934
+ return false;
12935
+ }
12936
+ }
12937
+ return true;
12938
+ }
12939
+ };
12940
+
12941
+ // src/testing/ScenarioRunner.ts
12942
+ var ScenarioRunner = class {
12943
+ constructor(config) {
12944
+ if (!config.nodes || config.nodes.length === 0) {
12945
+ throw new Error("Scenario must have at least one node");
12946
+ }
12947
+ if (config.duration <= 0) {
12948
+ throw new Error("Duration must be positive");
12949
+ }
12950
+ this.seed = config.seed ?? Math.floor(Math.random() * 2147483647);
12951
+ this.config = {
12952
+ ...config,
12953
+ seed: this.seed,
12954
+ tickInterval: config.tickInterval ?? 1
12955
+ };
12956
+ this.clock = new VirtualClock(0);
12957
+ this.rng = new SeededRNG(this.seed);
12958
+ this.network = new VirtualNetwork(this.rng, this.clock);
12959
+ }
12960
+ /**
12961
+ * Returns the seed used for this scenario.
12962
+ */
12963
+ getSeed() {
12964
+ return this.seed;
12965
+ }
12966
+ /**
12967
+ * Returns the virtual clock instance.
12968
+ */
12969
+ getClock() {
12970
+ return this.clock;
12971
+ }
12972
+ /**
12973
+ * Returns the seeded RNG instance.
12974
+ */
12975
+ getRNG() {
12976
+ return this.rng;
12977
+ }
12978
+ /**
12979
+ * Returns the virtual network instance.
12980
+ */
12981
+ getNetwork() {
12982
+ return this.network;
12983
+ }
12984
+ /**
12985
+ * Returns the list of nodes in this scenario.
12986
+ */
12987
+ getNodes() {
12988
+ return [...this.config.nodes];
12989
+ }
12990
+ /**
12991
+ * Executes the simulation scenario.
12992
+ *
12993
+ * @param setup Called once before simulation starts. Initialize state here.
12994
+ * @param step Called on each tick. Perform operations and message delivery.
12995
+ * @param invariants Checker for verifying correctness throughout execution.
12996
+ * @returns Result with pass/fail status and captured state
12997
+ */
12998
+ run(setup, step, invariants) {
12999
+ const finalStates = /* @__PURE__ */ new Map();
13000
+ const invariantFailures = [];
13001
+ setup(this);
13002
+ let tickCount = 0;
13003
+ const tickInterval = this.config.tickInterval;
13004
+ const endTime = this.config.duration;
13005
+ while (this.clock.now() < endTime) {
13006
+ this.clock.advance(tickInterval);
13007
+ tickCount++;
13008
+ step(this, tickCount);
13009
+ const delivered = this.network.tick();
13010
+ if (delivered.length > 0) {
13011
+ finalStates.set(`_tick_${tickCount}_delivered`, delivered.length);
13012
+ }
13013
+ }
13014
+ const result = invariants.verify(null);
13015
+ if (!result.passed) {
13016
+ invariantFailures.push(...result.failures);
13017
+ }
13018
+ return {
13019
+ seed: this.seed,
13020
+ passed: invariantFailures.length === 0,
13021
+ ticks: tickCount,
13022
+ invariantFailures,
13023
+ finalStates
13024
+ };
13025
+ }
13026
+ /**
13027
+ * Stores state for a node (useful for capturing final state).
13028
+ */
13029
+ setState(nodeId, state) {
13030
+ if (!this.config.nodes.includes(nodeId)) {
13031
+ throw new Error(`Unknown node: ${nodeId}`);
13032
+ }
13033
+ }
13034
+ };
11606
13035
  // Annotate the CommonJS export names for ESM import in node:
11607
13036
  0 && (module.exports = {
13037
+ AuthFailMessageSchema,
11608
13038
  AuthMessageSchema,
11609
13039
  BM25Scorer,
11610
13040
  BatchMessageSchema,
11611
13041
  BuiltInProcessors,
11612
13042
  BuiltInResolvers,
13043
+ COST_WEIGHTS,
13044
+ CRDTDebugger,
13045
+ CRDTInvariants,
11613
13046
  ClientOpMessageSchema,
11614
13047
  ClientOpSchema,
11615
13048
  ClusterSearchReqMessageSchema,
@@ -11651,6 +13084,7 @@ var SearchCursor = class {
11651
13084
  DEFAULT_RESOLVER_RATE_LIMITS,
11652
13085
  DEFAULT_STOP_WORDS,
11653
13086
  DEFAULT_WRITE_CONCERN_TIMEOUT,
13087
+ DeltaRecordSchema,
11654
13088
  ENGLISH_STOPWORDS,
11655
13089
  EntryProcessBatchRequestSchema,
11656
13090
  EntryProcessBatchResponseSchema,
@@ -11666,12 +13100,24 @@ var SearchCursor = class {
11666
13100
  FallbackIndex,
11667
13101
  FilteringResultSet,
11668
13102
  FullTextIndex,
13103
+ GcPruneMessageSchema,
13104
+ GcPrunePayloadSchema,
11669
13105
  HLC,
11670
13106
  HashIndex,
13107
+ HttpQueryRequestSchema,
13108
+ HttpQueryResultSchema,
13109
+ HttpSearchRequestSchema,
13110
+ HttpSearchResultSchema,
13111
+ HttpSyncErrorSchema,
13112
+ HttpSyncRequestSchema,
13113
+ HttpSyncResponseSchema,
13114
+ HybridQueryDeltaPayloadSchema,
13115
+ HybridQueryRespPayloadSchema,
11671
13116
  IndexRegistry,
11672
13117
  IndexedLWWMap,
11673
13118
  IndexedORMap,
11674
13119
  IntersectionResultSet,
13120
+ InvariantChecker,
11675
13121
  InvertedIndex,
11676
13122
  JournalEventDataSchema,
11677
13123
  JournalEventMessageSchema,
@@ -11687,9 +13133,12 @@ var SearchCursor = class {
11687
13133
  ListResolversRequestSchema,
11688
13134
  ListResolversResponseSchema,
11689
13135
  LiveQueryManager,
13136
+ LockGrantedPayloadSchema,
11690
13137
  LockReleaseSchema,
13138
+ LockReleasedPayloadSchema,
11691
13139
  LockRequestSchema,
11692
13140
  LowercaseFilter,
13141
+ MapDeltaSchema,
11693
13142
  MaxLengthFilter,
11694
13143
  MergeRejectedMessageSchema,
11695
13144
  MerkleReqBucketMessageSchema,
@@ -11731,12 +13180,17 @@ var SearchCursor = class {
11731
13180
  QuerySchema,
11732
13181
  QuerySubMessageSchema,
11733
13182
  QueryUnsubMessageSchema,
13183
+ QueryUpdateMessageSchema,
13184
+ QueryUpdatePayloadSchema,
11734
13185
  RESOLVER_FORBIDDEN_PATTERNS,
13186
+ RealClock,
11735
13187
  ReciprocalRankFusion,
11736
13188
  RegisterResolverRequestSchema,
11737
13189
  RegisterResolverResponseSchema,
11738
13190
  Ringbuffer,
13191
+ ScenarioRunner,
11739
13192
  SearchCursor,
13193
+ SearchDebugger,
11740
13194
  SearchMessageSchema,
11741
13195
  SearchOptionsSchema,
11742
13196
  SearchPayloadSchema,
@@ -11749,6 +13203,10 @@ var SearchCursor = class {
11749
13203
  SearchUpdateMessageSchema,
11750
13204
  SearchUpdatePayloadSchema,
11751
13205
  SearchUpdateTypeSchema,
13206
+ SeededRNG,
13207
+ ServerBatchEventMessageSchema,
13208
+ ServerEventMessageSchema,
13209
+ ServerEventPayloadSchema,
11752
13210
  SetResultSet,
11753
13211
  SimpleAttribute,
11754
13212
  SortedMap,
@@ -11757,6 +13215,8 @@ var SearchCursor = class {
11757
13215
  StandingQueryRegistry,
11758
13216
  StopWordFilter,
11759
13217
  SyncInitMessageSchema,
13218
+ SyncMapEntrySchema,
13219
+ SyncResetRequiredPayloadSchema,
11760
13220
  SyncRespBucketsMessageSchema,
11761
13221
  SyncRespLeafMessageSchema,
11762
13222
  SyncRespRootMessageSchema,
@@ -11771,11 +13231,14 @@ var SearchCursor = class {
11771
13231
  UniqueFilter,
11772
13232
  UnregisterResolverRequestSchema,
11773
13233
  UnregisterResolverResponseSchema,
13234
+ VirtualClock,
13235
+ VirtualNetwork,
11774
13236
  WRITE_CONCERN_ORDER,
11775
13237
  WhitespaceTokenizer,
11776
13238
  WordBoundaryTokenizer,
11777
13239
  WriteConcern,
11778
13240
  WriteConcernSchema,
13241
+ calculateTotalCost,
11779
13242
  combineHashes,
11780
13243
  compareHLCTimestamps,
11781
13244
  compareTimestamps,
@@ -11788,7 +13251,9 @@ var SearchCursor = class {
11788
13251
  disableNativeHash,
11789
13252
  encodeBase64Url,
11790
13253
  evaluatePredicate,
13254
+ getCRDTDebugger,
11791
13255
  getHighestWriteConcernLevel,
13256
+ getSearchDebugger,
11792
13257
  hashORMapEntry,
11793
13258
  hashORMapRecord,
11794
13259
  hashObject,
@@ -11797,9 +13262,12 @@ var SearchCursor = class {
11797
13262
  isSimpleQuery,
11798
13263
  isUsingNativeHash,
11799
13264
  isWriteConcernAchieved,
13265
+ logger,
11800
13266
  multiAttribute,
11801
13267
  porterStem,
13268
+ resetCRDTDebugger,
11802
13269
  resetNativeHash,
13270
+ resetSearchDebugger,
11803
13271
  serialize,
11804
13272
  simpleAttribute,
11805
13273
  timestampToString,