@topgunbuild/core 0.1.0 → 0.2.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/HLC.ts","../src/utils/hash.ts","../src/MerkleTree.ts","../src/LWWMap.ts","../src/ORMap.ts","../src/serializer.ts","../src/predicate.ts","../src/schemas.ts"],"sourcesContent":["import { HLC, Timestamp } from './HLC';\nimport { LWWMap, LWWRecord } from './LWWMap';\nimport { ORMap, ORMapRecord } from './ORMap';\nimport { MerkleTree } from './MerkleTree';\n\nexport { HLC, LWWMap, ORMap, MerkleTree };\nexport * from './utils/hash';\nexport * from './serializer';\nexport * from './predicate';\nexport * from './security';\nexport * from './schemas';\nexport type { Timestamp, LWWRecord, ORMapRecord };\n","export interface Timestamp {\n millis: number;\n counter: number;\n nodeId: string;\n}\n\nexport class HLC {\n private lastMillis: number;\n private lastCounter: number;\n private readonly nodeId: string;\n\n // Max allowable drift in milliseconds (1 minute)\n private static readonly MAX_DRIFT = 60000;\n\n constructor(nodeId: string) {\n this.nodeId = nodeId;\n this.lastMillis = 0;\n this.lastCounter = 0;\n }\n\n public get getNodeId(): string {\n return this.nodeId;\n }\n\n /**\n * Generates a new unique timestamp for a local event.\n * Ensures monotonicity: always greater than any previously generated or received timestamp.\n */\n public now(): Timestamp {\n const systemTime = Date.now();\n \n // If local physical time catches up to logical time, reset counter\n if (systemTime > this.lastMillis) {\n this.lastMillis = systemTime;\n this.lastCounter = 0;\n } else {\n // Else, just increment the logical counter\n this.lastCounter++;\n }\n\n return {\n millis: this.lastMillis,\n counter: this.lastCounter,\n nodeId: this.nodeId\n };\n }\n\n /**\n * Updates the local clock based on a received remote timestamp.\n * Must be called whenever a message/event is received from another node.\n */\n public update(remote: Timestamp): void {\n const systemTime = Date.now();\n\n // Validate drift (optional but good practice)\n if (remote.millis > systemTime + HLC.MAX_DRIFT) {\n console.warn(`Clock drift detected: Remote time ${remote.millis} is far ahead of local ${systemTime}`);\n // In strict systems we might reject, but in AP systems we usually accept and fast-forward\n }\n\n const maxMillis = Math.max(this.lastMillis, systemTime, remote.millis);\n\n if (maxMillis === this.lastMillis && maxMillis === remote.millis) {\n // Both clocks are on the same millisecond, take max counter\n this.lastCounter = Math.max(this.lastCounter, remote.counter) + 1;\n } else if (maxMillis === this.lastMillis) {\n // Local logical clock is ahead in millis (or same as remote but remote millis < local)\n this.lastCounter++;\n } else if (maxMillis === remote.millis) {\n // Remote clock is ahead, fast-forward local\n this.lastCounter = remote.counter + 1;\n } else {\n // System time is ahead of both\n this.lastCounter = 0;\n }\n\n this.lastMillis = maxMillis;\n }\n\n /**\n * Compares two timestamps.\n * Returns -1 if a < b, 1 if a > b, 0 if equal.\n */\n public static compare(a: Timestamp, b: Timestamp): number {\n if (a.millis !== b.millis) {\n return a.millis - b.millis;\n }\n if (a.counter !== b.counter) {\n return a.counter - b.counter;\n }\n return a.nodeId.localeCompare(b.nodeId);\n }\n\n /**\n * Serializes timestamp to a string representation (e.g., for storage/network).\n * Format: \"<millis>:<counter>:<nodeId>\"\n */\n public static toString(ts: Timestamp): string {\n return `${ts.millis}:${ts.counter}:${ts.nodeId}`;\n }\n\n /**\n * Parses a string representation back to a Timestamp object.\n */\n public static parse(str: string): Timestamp {\n const parts = str.split(':');\n if (parts.length !== 3) {\n throw new Error(`Invalid timestamp format: ${str}`);\n }\n return {\n millis: parseInt(parts[0], 10),\n counter: parseInt(parts[1], 10),\n nodeId: parts[2]\n };\n }\n}\n","/**\n * FNV-1a Hash implementation for strings.\n * Fast, non-cryptographic, synchronous.\n * Good enough for data synchronization checks.\n */\nexport function hashString(str: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0; // Ensure positive 32-bit integer\n}\n\n/**\n * Combines multiple hash numbers into one order-independent hash.\n * Used for combining bucket hashes.\n * XOR is simple and effective for order-independent combination, \n * but for Merkle trees we usually want position dependence if it's a Trie, \n * or order-independence if it's a Set.\n * Here we simply sum or XOR.\n */\nexport function combineHashes(hashes: number[]): number {\n let result = 0;\n for (const h of hashes) {\n result = (result + h) | 0; // Simple sum\n }\n return result >>> 0;\n}\n\n","import { LWWRecord } from './LWWMap';\nimport { hashString } from './utils/hash';\n\nexport interface MerkleNode {\n hash: number;\n children?: { [key: string]: MerkleNode }; // Keyed by bucket index (hex char)\n entries?: Map<string, number>; // Leaf node: Key -> ContentHash\n}\n\n/**\n * A specific implementation of Merkle Tree for syncing LWW-Maps.\n * It uses a Prefix Trie structure based on the hash of the Record Key.\n * \n * Structure:\n * - Level 0: Root\n * - Level 1..N: Buckets based on hex digits of Key Hash.\n * \n * This allows us to quickly identify which \"bucket\" of keys is out of sync.\n */\nexport class MerkleTree {\n private root: MerkleNode;\n private readonly depth: number;\n\n constructor(records: Map<string, LWWRecord<any>> = new Map(), depth: number = 3) {\n this.depth = depth;\n this.root = { hash: 0, children: {} };\n // Build initial tree\n for (const [key, record] of records) {\n this.update(key, record);\n }\n }\n\n /**\n * Incrementally updates the Merkle Tree with a single record.\n * @param key The key of the record\n * @param record The record (value + timestamp)\n */\n public update(key: string, record: LWWRecord<any>) {\n const itemHash = hashString(`${key}:${record.timestamp.millis}:${record.timestamp.counter}:${record.timestamp.nodeId}`);\n // We use the hash of the KEY for routing, so the record stays in the same bucket\n // regardless of timestamp changes.\n const pathHash = hashString(key).toString(16).padStart(8, '0'); \n \n this.updateNode(this.root, key, itemHash, pathHash, 0);\n }\n\n /**\n * Removes a key from the Merkle Tree.\n * Necessary for Garbage Collection of tombstones.\n */\n public remove(key: string) {\n const pathHash = hashString(key).toString(16).padStart(8, '0');\n this.removeNode(this.root, key, pathHash, 0);\n }\n\n private removeNode(node: MerkleNode, key: string, pathHash: string, level: number): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (node.entries) {\n node.entries.delete(key);\n \n // Recalculate leaf hash\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n }\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (node.children && node.children[bucketChar]) {\n const childHash = this.removeNode(node.children[bucketChar], key, pathHash, level + 1);\n \n // Optimization: if child is empty/zero, we might want to remove it, but for now just recalc.\n }\n \n // Recalculate this node's hash from children\n let h = 0;\n if (node.children) {\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n private updateNode(node: MerkleNode, key: string, itemHash: number, pathHash: string, level: number): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (!node.entries) node.entries = new Map();\n node.entries.set(key, itemHash);\n \n // Recalculate leaf hash (Sum of item hashes)\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (!node.children) node.children = {};\n \n if (!node.children[bucketChar]) {\n node.children[bucketChar] = { hash: 0 };\n }\n \n this.updateNode(node.children[bucketChar], key, itemHash, pathHash, level + 1);\n \n // Recalculate this node's hash from children\n let h = 0;\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n public getRootHash(): number {\n return this.root.hash;\n }\n\n public getNode(path: string): MerkleNode | undefined {\n let current = this.root;\n for (const char of path) {\n if (!current.children || !current.children[char]) {\n return undefined;\n }\n current = current.children[char];\n }\n return current;\n }\n\n /**\n * Returns the hashes of the children at the given path.\n * Used by the client/server to compare buckets.\n */\n public getBuckets(path: string): Record<string, number> {\n const node = this.getNode(path);\n if (!node || !node.children) return {};\n \n const result: Record<string, number> = {};\n for (const [key, child] of Object.entries(node.children)) {\n result[key] = child.hash;\n }\n return result;\n }\n\n /**\n * For a leaf node (bucket), returns the actual keys it contains.\n * Used to request specific keys when a bucket differs.\n */\n public getKeysInBucket(path: string): string[] {\n const node = this.getNode(path);\n if (!node || !node.entries) return [];\n return Array.from(node.entries.keys());\n }\n}\n","import { HLC, Timestamp } from './HLC';\nimport { MerkleTree } from './MerkleTree';\n\n/**\n * A record in the LWW-Map.\n * Can represent a value or a deletion (tombstone).\n */\nexport interface LWWRecord<V> {\n value: V | null;\n timestamp: Timestamp;\n ttlMs?: number;\n}\n\n/**\n * Last-Write-Wins Map Implementation.\n * This structure guarantees convergence by always keeping the entry with the highest timestamp.\n */\nexport class LWWMap<K, V> {\n private data: Map<K, LWWRecord<V>>;\n private readonly hlc: HLC;\n private listeners: Array<() => void> = [];\n private merkleTree: MerkleTree;\n\n constructor(hlc: HLC) {\n this.hlc = hlc;\n this.data = new Map();\n this.merkleTree = new MerkleTree();\n }\n\n public onChange(callback: () => void): () => void {\n this.listeners.push(callback);\n return () => {\n this.listeners = this.listeners.filter(cb => cb !== callback);\n };\n }\n\n private notify(): void {\n this.listeners.forEach(cb => cb());\n }\n\n public getMerkleTree(): MerkleTree {\n return this.merkleTree;\n }\n\n public get size(): number {\n return this.data.size;\n }\n\n /**\n * Sets a value for a key.\n * Generates a new timestamp using the local HLC.\n */\n public set(key: K, value: V, ttlMs?: number): LWWRecord<V> {\n const timestamp = this.hlc.now();\n const record: LWWRecord<V> = { value, timestamp };\n \n if (ttlMs !== undefined) {\n if (typeof ttlMs !== 'number' || ttlMs <= 0 || !Number.isFinite(ttlMs)) {\n // We could throw, but to be resilient we might just ignore invalid TTL or log warning.\n // Given this is core lib, throwing is safer to alert dev.\n throw new Error('TTL must be a positive finite number');\n }\n record.ttlMs = ttlMs;\n }\n \n // We assume K is string for MerkleTree compatibility in this system\n // If K is not string, we might need to stringify it.\n // The project seems to use string keys for maps.\n this.data.set(key, record);\n this.merkleTree.update(String(key), record);\n \n this.notify();\n return record;\n }\n\n /**\n * Retrieves the value for a key.\n * Returns undefined if key doesn't exist, is a tombstone, or is expired.\n */\n public get(key: K): V | undefined {\n const record = this.data.get(key);\n if (!record || record.value === null) {\n return undefined;\n }\n\n // Check for expiration\n if (record.ttlMs) {\n const now = Date.now();\n if (record.timestamp.millis + record.ttlMs < now) {\n return undefined;\n }\n }\n\n return record.value;\n }\n\n /**\n * Returns the full record (including timestamp).\n * Useful for synchronization.\n */\n public getRecord(key: K): LWWRecord<V> | undefined {\n return this.data.get(key);\n }\n\n /**\n * Removes a key (creates a tombstone).\n */\n public remove(key: K): LWWRecord<V> {\n const timestamp = this.hlc.now();\n const tombstone: LWWRecord<V> = { value: null, timestamp };\n \n this.data.set(key, tombstone);\n this.merkleTree.update(String(key), tombstone);\n \n this.notify();\n return tombstone;\n }\n\n /**\n * Merges a record from a remote source.\n * Returns true if the local state was updated.\n */\n public merge(key: K, remoteRecord: LWWRecord<V>): boolean {\n // Update our clock to ensure causality for future events\n this.hlc.update(remoteRecord.timestamp);\n\n const localRecord = this.data.get(key);\n\n // LWW Logic:\n // 1. If no local record, accept remote.\n // 2. If remote is strictly greater than local, accept remote.\n // 3. If equal, we can arbitrarily choose (e.g. by NodeID) to ensure convergence, \n // but HLC.compare handles nodeId tie-breaking already.\n \n if (!localRecord || HLC.compare(remoteRecord.timestamp, localRecord.timestamp) > 0) {\n this.data.set(key, remoteRecord);\n this.merkleTree.update(String(key), remoteRecord);\n \n this.notify();\n return true;\n }\n\n return false;\n }\n\n /**\n * Garbage Collection: Prunes tombstones older than the specified timestamp.\n * Only removes records that are tombstones (deleted) AND older than the threshold.\n * \n * @param olderThan The timestamp threshold. Tombstones older than this will be removed.\n * @returns The number of tombstones removed.\n */\n public prune(olderThan: Timestamp): K[] {\n const removedKeys: K[] = [];\n \n for (const [key, record] of this.data.entries()) {\n // Only prune tombstones (value === null)\n if (record.value === null) {\n // Check if timestamp is strictly older than the threshold\n // HLC.compare(a, b) returns < 0 if a < b\n if (HLC.compare(record.timestamp, olderThan) < 0) {\n this.data.delete(key);\n this.merkleTree.remove(String(key));\n removedKeys.push(key);\n }\n }\n }\n\n if (removedKeys.length > 0) {\n this.notify();\n }\n\n return removedKeys;\n }\n\n /**\n * Clears all data and tombstones.\n * Resets the MerkleTree.\n */\n public clear(): void {\n this.data.clear();\n this.merkleTree = new MerkleTree();\n this.notify();\n }\n\n /**\n * Returns an iterator over all non-deleted entries.\n */\n public entries(): IterableIterator<[K, V]> {\n const iterator = this.data.entries();\n const now = Date.now();\n \n return {\n [Symbol.iterator]() { return this; },\n next: () => {\n let result = iterator.next();\n while (!result.done) {\n const [key, record] = result.value;\n if (record.value !== null) {\n // Check TTL\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n result = iterator.next();\n continue;\n }\n return { value: [key, record.value], done: false };\n }\n result = iterator.next();\n }\n return { value: undefined, done: true };\n }\n };\n }\n\n /**\n * Returns all keys (including tombstones).\n */\n public allKeys(): IterableIterator<K> {\n return this.data.keys();\n }\n}\n","import { HLC, Timestamp } from './HLC';\n\n/**\n * A record in the OR-Map (Observed-Remove Map).\n * Represents a single value instance with a unique tag.\n */\nexport interface ORMapRecord<V> {\n value: V;\n timestamp: Timestamp;\n tag: string; // Unique identifier (UUID + Timestamp)\n ttlMs?: number;\n}\n\n/**\n * OR-Map (Observed-Remove Map) Implementation.\n * \n * Acts as a Multimap where each Key holds a Set of Values.\n * Supports concurrent additions to the same key without data loss.\n * \n * Logic:\n * - Add(K, V): Generates a unique tag. Stores (V, tag) under K.\n * - Remove(K, V): Finds all *currently observed* tags for V under K, and moves them to a Remove Set (Tombstones).\n * - Merge: Union of items minus Union of tombstones.\n */\nexport class ORMap<K, V> {\n // Key -> Map<Tag, Record>\n // Stores active records.\n private items: Map<K, Map<string, ORMapRecord<V>>>;\n\n // Set of removed tags (Tombstones).\n private tombstones: Set<string>;\n\n // Set of expired tags (Local only cache for fast filtering)\n // Note: We don't persist this directly, but rely on filtering. \n // For now, we will just filter on get()\n\n private readonly hlc: HLC;\n\n constructor(hlc: HLC) {\n this.hlc = hlc;\n this.items = new Map();\n this.tombstones = new Set();\n }\n\n private listeners: Array<() => void> = [];\n\n public onChange(callback: () => void): () => void {\n this.listeners.push(callback);\n return () => {\n this.listeners = this.listeners.filter(cb => cb !== callback);\n };\n }\n\n private notify(): void {\n this.listeners.forEach(cb => cb());\n }\n\n public get size(): number {\n return this.items.size;\n }\n\n public get totalRecords(): number {\n let count = 0;\n for (const keyMap of this.items.values()) {\n count += keyMap.size;\n }\n return count;\n }\n\n /**\n * Adds a value to the set associated with the key.\n * Generates a unique tag for this specific addition.\n */\n public add(key: K, value: V, ttlMs?: number): ORMapRecord<V> {\n const timestamp = this.hlc.now();\n // Tag must be unique globally. HLC.toString() provides unique string per node+time.\n const tag = HLC.toString(timestamp);\n\n const record: ORMapRecord<V> = {\n value,\n timestamp,\n tag\n };\n\n if (ttlMs !== undefined) {\n if (typeof ttlMs !== 'number' || ttlMs <= 0 || !Number.isFinite(ttlMs)) {\n throw new Error('TTL must be a positive finite number');\n }\n record.ttlMs = ttlMs;\n }\n\n let keyMap = this.items.get(key);\n if (!keyMap) {\n keyMap = new Map();\n this.items.set(key, keyMap);\n }\n\n keyMap.set(tag, record);\n this.notify();\n return record;\n }\n\n /**\n * Removes a specific value from the set associated with the key.\n * Marks all *currently observed* instances of this value as removed (tombstones).\n * Returns the list of tags that were removed (useful for sync).\n */\n public remove(key: K, value: V): string[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n // Find all tags for this value\n const tagsToRemove: string[] = [];\n\n for (const [tag, record] of keyMap.entries()) {\n // Using strict equality. For objects, this requires the exact instance.\n if (record.value === value) {\n tagsToRemove.push(tag);\n }\n }\n\n for (const tag of tagsToRemove) {\n this.tombstones.add(tag);\n keyMap.delete(tag);\n }\n\n if (keyMap.size === 0) {\n this.items.delete(key);\n }\n\n this.notify();\n return tagsToRemove;\n }\n\n /**\n * Clears all data and tombstones.\n */\n public clear(): void {\n this.items.clear();\n this.tombstones.clear();\n this.notify();\n }\n\n /**\n * Returns all active values for a key.\n * Filters out expired records.\n */\n public get(key: K): V[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n const values: V[] = [];\n const now = Date.now();\n\n for (const [tag, record] of keyMap.entries()) {\n if (!this.tombstones.has(tag)) {\n // Check expiration\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n continue;\n }\n values.push(record.value);\n }\n }\n return values;\n }\n\n /**\n * Returns all active records for a key.\n * Useful for persistence and sync.\n * Filters out expired records.\n */\n public getRecords(key: K): ORMapRecord<V>[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n const records: ORMapRecord<V>[] = [];\n const now = Date.now();\n\n for (const [tag, record] of keyMap.entries()) {\n if (!this.tombstones.has(tag)) {\n // Check expiration\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n continue;\n }\n records.push(record);\n }\n }\n return records;\n }\n\n /**\n * Returns all tombstone tags.\n */\n public getTombstones(): string[] {\n return Array.from(this.tombstones);\n }\n\n /**\n * Applies a record from a remote source (Sync).\n */\n public apply(key: K, record: ORMapRecord<V>): void {\n if (this.tombstones.has(record.tag)) return;\n\n let keyMap = this.items.get(key);\n if (!keyMap) {\n keyMap = new Map();\n this.items.set(key, keyMap);\n }\n keyMap.set(record.tag, record);\n this.hlc.update(record.timestamp);\n this.notify();\n }\n\n /**\n * Applies a tombstone (deletion) from a remote source.\n */\n public applyTombstone(tag: string): void {\n this.tombstones.add(tag);\n // Cleanup active items if present\n for (const [key, keyMap] of this.items) {\n if (keyMap.has(tag)) {\n keyMap.delete(tag);\n if (keyMap.size === 0) this.items.delete(key);\n // We found it, so we can stop searching (tag is unique globally)\n break;\n }\n }\n this.notify();\n }\n\n /**\n * Merges state from another ORMap.\n * - Adds all new tombstones from 'other'.\n * - Adds all new items from 'other' that are not in tombstones.\n * - Updates HLC with observed timestamps.\n */\n public merge(other: ORMap<K, V>): void {\n // 1. Merge tombstones\n for (const tag of other.tombstones) {\n this.tombstones.add(tag);\n }\n\n // 2. Merge items\n for (const [key, otherKeyMap] of other.items) {\n let localKeyMap = this.items.get(key);\n if (!localKeyMap) {\n localKeyMap = new Map();\n this.items.set(key, localKeyMap);\n }\n\n for (const [tag, record] of otherKeyMap) {\n // Only accept if not deleted\n if (!this.tombstones.has(tag)) {\n if (!localKeyMap.has(tag)) {\n localKeyMap.set(tag, record);\n }\n // Always update causality\n this.hlc.update(record.timestamp);\n }\n }\n }\n\n // 3. Cleanup: Remove any local items that are now in the merged tombstones\n for (const [key, localKeyMap] of this.items) {\n for (const tag of localKeyMap.keys()) {\n if (this.tombstones.has(tag)) {\n localKeyMap.delete(tag);\n }\n }\n if (localKeyMap.size === 0) {\n this.items.delete(key);\n }\n }\n this.notify();\n }\n\n /**\n * Garbage Collection: Prunes tombstones older than the specified timestamp.\n */\n public prune(olderThan: Timestamp): string[] {\n const removedTags: string[] = [];\n\n for (const tag of this.tombstones) {\n try {\n const timestamp = HLC.parse(tag);\n if (HLC.compare(timestamp, olderThan) < 0) {\n this.tombstones.delete(tag);\n removedTags.push(tag);\n }\n } catch (e) {\n // Ignore invalid tags\n }\n }\n\n return removedTags;\n }\n}\n","import { encode, decode } from '@msgpack/msgpack';\n\n/**\n * Serializes a JavaScript object to MessagePack binary format.\n * @param data The data to serialize.\n * @returns A Uint8Array containing the serialized data.\n */\nexport function serialize(data: unknown): Uint8Array {\n return encode(data);\n}\n\n/**\n * Deserializes MessagePack binary data to a JavaScript object.\n * @param data The binary data to deserialize (Uint8Array or ArrayBuffer).\n * @returns The deserialized object.\n */\nexport function deserialize<T = unknown>(data: Uint8Array | ArrayBuffer): T {\n // @msgpack/msgpack decode accepts Uint8Array, ArrayBuffer, etc.\n return decode(data) as T;\n}\n\n","\nexport type PredicateOp = \n | 'eq' | 'neq' \n | 'gt' | 'gte' \n | 'lt' | 'lte' \n | 'like' | 'regex' \n | 'and' | 'or' | 'not';\n\nexport interface PredicateNode {\n op: PredicateOp;\n attribute?: string;\n value?: any;\n children?: PredicateNode[];\n}\n\nexport class Predicates {\n static equal(attribute: string, value: any): PredicateNode { \n return { op: 'eq', attribute, value }; \n }\n \n static notEqual(attribute: string, value: any): PredicateNode { \n return { op: 'neq', attribute, value }; \n }\n \n static greaterThan(attribute: string, value: any): PredicateNode { \n return { op: 'gt', attribute, value }; \n }\n \n static greaterThanOrEqual(attribute: string, value: any): PredicateNode { \n return { op: 'gte', attribute, value }; \n }\n \n static lessThan(attribute: string, value: any): PredicateNode { \n return { op: 'lt', attribute, value }; \n }\n \n static lessThanOrEqual(attribute: string, value: any): PredicateNode { \n return { op: 'lte', attribute, value }; \n }\n \n static like(attribute: string, pattern: string): PredicateNode { \n return { op: 'like', attribute, value: pattern }; \n }\n \n static regex(attribute: string, pattern: string): PredicateNode { \n return { op: 'regex', attribute, value: pattern }; \n }\n\n static between(attribute: string, from: any, to: any): PredicateNode {\n return {\n op: 'and',\n children: [\n { op: 'gte', attribute, value: from },\n { op: 'lte', attribute, value: to }\n ]\n };\n }\n\n static and(...predicates: PredicateNode[]): PredicateNode { \n return { op: 'and', children: predicates }; \n }\n \n static or(...predicates: PredicateNode[]): PredicateNode { \n return { op: 'or', children: predicates }; \n }\n \n static not(predicate: PredicateNode): PredicateNode { \n return { op: 'not', children: [predicate] }; \n }\n}\n\nexport function evaluatePredicate(predicate: PredicateNode, data: any): boolean {\n if (!data) return false;\n \n switch (predicate.op) {\n case 'and':\n return (predicate.children || []).every(p => evaluatePredicate(p, data));\n case 'or':\n return (predicate.children || []).some(p => evaluatePredicate(p, data));\n case 'not': {\n const child = (predicate.children || [])[0];\n if (!child) return true; // NOT of nothing is true (vacuous)\n return !evaluatePredicate(child, data);\n }\n }\n\n // Leaf nodes require an attribute\n if (!predicate.attribute) return false;\n \n const value = data[predicate.attribute];\n const target = predicate.value;\n\n switch (predicate.op) {\n case 'eq':\n return value === target;\n case 'neq':\n return value !== target;\n case 'gt':\n return value > target;\n case 'gte':\n return value >= target;\n case 'lt':\n return value < target;\n case 'lte':\n return value <= target;\n case 'like':\n if (typeof value !== 'string' || typeof target !== 'string') return false;\n const pattern = target\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/%/g, '.*')\n .replace(/_/g, '.');\n return new RegExp(`^${pattern}$`, 'i').test(value);\n case 'regex':\n if (typeof value !== 'string' || typeof target !== 'string') return false;\n return new RegExp(target).test(value);\n default:\n return false;\n }\n}\n","import { z } from 'zod';\n\n// --- Basic Types ---\n\nexport const TimestampSchema = z.object({\n millis: z.number(),\n counter: z.number(),\n nodeId: z.string(),\n});\n\nexport const LWWRecordSchema = z.object({\n value: z.any().nullable(),\n timestamp: TimestampSchema,\n ttlMs: z.number().optional(),\n});\n\nexport const ORMapRecordSchema = z.object({\n value: z.any(),\n timestamp: TimestampSchema,\n tag: z.string(),\n ttlMs: z.number().optional(),\n});\n\n// --- Predicate Types ---\n\nexport const PredicateOpSchema = z.enum([\n 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'regex', 'and', 'or', 'not'\n]);\n\n// Recursive schema for PredicateNode\nexport const PredicateNodeSchema: z.ZodType<any> = z.lazy(() => z.object({\n op: PredicateOpSchema,\n attribute: z.string().optional(),\n value: z.any().optional(),\n children: z.array(PredicateNodeSchema).optional(),\n}));\n\n// --- Query Types ---\n\nexport const QuerySchema = z.object({\n where: z.record(z.string(), z.any()).optional(),\n predicate: PredicateNodeSchema.optional(),\n sort: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n});\n\n// --- Client Operation Types ---\n\nexport const ClientOpSchema = z.object({\n id: z.string().optional(),\n mapName: z.string(),\n key: z.string(),\n // Permissive opType to match ServerCoordinator behavior logic\n // It can be 'REMOVE', 'OR_ADD', 'OR_REMOVE' or undefined/other (implies PUT/LWW)\n opType: z.string().optional(), \n record: LWWRecordSchema.nullable().optional(),\n orRecord: ORMapRecordSchema.nullable().optional(),\n orTag: z.string().nullable().optional(),\n});\n\n// --- Message Schemas ---\n\nexport const AuthMessageSchema = z.object({\n type: z.literal('AUTH'),\n token: z.string(),\n});\n\nexport const QuerySubMessageSchema = z.object({\n type: z.literal('QUERY_SUB'),\n payload: z.object({\n queryId: z.string(),\n mapName: z.string(),\n query: QuerySchema,\n }),\n});\n\nexport const QueryUnsubMessageSchema = z.object({\n type: z.literal('QUERY_UNSUB'),\n payload: z.object({\n queryId: z.string(),\n }),\n});\n\nexport const ClientOpMessageSchema = z.object({\n type: z.literal('CLIENT_OP'),\n payload: ClientOpSchema,\n});\n\nexport const OpBatchMessageSchema = z.object({\n type: z.literal('OP_BATCH'),\n payload: z.object({\n ops: z.array(ClientOpSchema),\n }),\n});\n\nexport const SyncInitMessageSchema = z.object({\n type: z.literal('SYNC_INIT'),\n mapName: z.string(),\n lastSyncTimestamp: z.number().optional(),\n});\n\nexport const SyncRespRootMessageSchema = z.object({\n type: z.literal('SYNC_RESP_ROOT'),\n payload: z.object({\n mapName: z.string(),\n rootHash: z.number(),\n timestamp: TimestampSchema,\n }),\n});\n\nexport const SyncRespBucketsMessageSchema = z.object({\n type: z.literal('SYNC_RESP_BUCKETS'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n buckets: z.record(z.string(), z.number()),\n }),\n});\n\nexport const SyncRespLeafMessageSchema = z.object({\n type: z.literal('SYNC_RESP_LEAF'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n records: z.array(z.object({\n key: z.string(),\n record: LWWRecordSchema,\n })),\n }),\n});\n\nexport const MerkleReqBucketMessageSchema = z.object({\n type: z.literal('MERKLE_REQ_BUCKET'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n }),\n});\n\nexport const LockRequestSchema = z.object({\n type: z.literal('LOCK_REQUEST'),\n payload: z.object({\n requestId: z.string(),\n name: z.string(),\n ttl: z.number().optional(),\n }),\n});\n\nexport const LockReleaseSchema = z.object({\n type: z.literal('LOCK_RELEASE'),\n payload: z.object({\n requestId: z.string().optional(),\n name: z.string(),\n fencingToken: z.number(),\n }),\n});\n\n// --- Topic Messages ---\n\nexport const TopicSubSchema = z.object({\n type: z.literal('TOPIC_SUB'),\n payload: z.object({\n topic: z.string(),\n }),\n});\n\nexport const TopicUnsubSchema = z.object({\n type: z.literal('TOPIC_UNSUB'),\n payload: z.object({\n topic: z.string(),\n }),\n});\n\nexport const TopicPubSchema = z.object({\n type: z.literal('TOPIC_PUB'),\n payload: z.object({\n topic: z.string(),\n data: z.any(),\n }),\n});\n\nexport const TopicMessageEventSchema = z.object({\n type: z.literal('TOPIC_MESSAGE'),\n payload: z.object({\n topic: z.string(),\n data: z.any(),\n publisherId: z.string().optional(),\n timestamp: z.number(),\n }),\n});\n\n// --- Union Schema ---\n\nexport const MessageSchema = z.discriminatedUnion('type', [\n AuthMessageSchema,\n QuerySubMessageSchema,\n QueryUnsubMessageSchema,\n ClientOpMessageSchema,\n OpBatchMessageSchema,\n SyncInitMessageSchema,\n SyncRespRootMessageSchema,\n SyncRespBucketsMessageSchema,\n SyncRespLeafMessageSchema,\n MerkleReqBucketMessageSchema,\n LockRequestSchema,\n LockReleaseSchema,\n TopicSubSchema,\n TopicUnsubSchema,\n TopicPubSchema,\n]);\n\n// --- Type Inference ---\n\nexport type Timestamp = z.infer<typeof TimestampSchema>;\nexport type LWWRecord<V = any> = z.infer<typeof LWWRecordSchema>; // Generic placeholder\nexport type ORMapRecord<V = any> = z.infer<typeof ORMapRecordSchema>; // Generic placeholder\n// export type PredicateNode = z.infer<typeof PredicateNodeSchema>; // Conflict with predicate.ts\nexport type Query = z.infer<typeof QuerySchema>;\nexport type ClientOp = z.infer<typeof ClientOpSchema>;\nexport type Message = z.infer<typeof MessageSchema>;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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EM,IAAM,mBAAmB,aAAE,OAAO;AAAA,EACvC,MAAM,aAAE,QAAQ,aAAa;AAAA,EAC7B,SAAS,aAAE,OAAO;AAAA,IAChB,OAAO,aAAE,OAAO;AAAA,EAClB,CAAC;AACH,CAAC;AAEM,IAAM,iBAAiB,aAAE,OAAO;AAAA,EACrC,MAAM,aAAE,QAAQ,WAAW;AAAA,EAC3B,SAAS,aAAE,OAAO;AAAA,IAChB,OAAO,aAAE,OAAO;AAAA,IAChB,MAAM,aAAE,IAAI;AAAA,EACd,CAAC;AACH,CAAC;AAEM,IAAM,0BAA0B,aAAE,OAAO;AAAA,EAC9C,MAAM,aAAE,QAAQ,eAAe;AAAA,EAC/B,SAAS,aAAE,OAAO;AAAA,IAChB,OAAO,aAAE,OAAO;AAAA,IAChB,MAAM,aAAE,IAAI;AAAA,IACZ,aAAa,aAAE,OAAO,EAAE,SAAS;AAAA,IACjC,WAAW,aAAE,OAAO;AAAA,EACtB,CAAC;AACH,CAAC;AAIM,IAAM,gBAAgB,aAAE,mBAAmB,QAAQ;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;","names":["h"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/HLC.ts","../src/utils/hash.ts","../src/MerkleTree.ts","../src/LWWMap.ts","../src/ORMapMerkle.ts","../src/ORMapMerkleTree.ts","../src/ORMap.ts","../src/serializer.ts","../src/predicate.ts","../src/schemas.ts"],"sourcesContent":["import { HLC, Timestamp } from './HLC';\nimport { LWWMap, LWWRecord } from './LWWMap';\nimport { ORMap, ORMapRecord, MergeKeyResult, ORMapSnapshot } from './ORMap';\nimport { MerkleTree } from './MerkleTree';\nimport { ORMapMerkleTree, ORMapMerkleNode } from './ORMapMerkleTree';\nimport { hashORMapEntry, hashORMapRecord, timestampToString, compareTimestamps } from './ORMapMerkle';\n\nexport { HLC, LWWMap, ORMap, MerkleTree, ORMapMerkleTree };\nexport { hashORMapEntry, hashORMapRecord, timestampToString, compareTimestamps };\nexport * from './utils/hash';\nexport * from './serializer';\nexport * from './predicate';\nexport * from './security';\nexport * from './schemas';\nexport type { Timestamp, LWWRecord, ORMapRecord, MergeKeyResult, ORMapSnapshot, ORMapMerkleNode };\n\n// Re-export heartbeat types for convenience\nexport type { PingMessage, PongMessage } from './schemas';\n","export interface Timestamp {\n millis: number;\n counter: number;\n nodeId: string;\n}\n\nexport class HLC {\n private lastMillis: number;\n private lastCounter: number;\n private readonly nodeId: string;\n\n // Max allowable drift in milliseconds (1 minute)\n private static readonly MAX_DRIFT = 60000;\n\n constructor(nodeId: string) {\n this.nodeId = nodeId;\n this.lastMillis = 0;\n this.lastCounter = 0;\n }\n\n public get getNodeId(): string {\n return this.nodeId;\n }\n\n /**\n * Generates a new unique timestamp for a local event.\n * Ensures monotonicity: always greater than any previously generated or received timestamp.\n */\n public now(): Timestamp {\n const systemTime = Date.now();\n \n // If local physical time catches up to logical time, reset counter\n if (systemTime > this.lastMillis) {\n this.lastMillis = systemTime;\n this.lastCounter = 0;\n } else {\n // Else, just increment the logical counter\n this.lastCounter++;\n }\n\n return {\n millis: this.lastMillis,\n counter: this.lastCounter,\n nodeId: this.nodeId\n };\n }\n\n /**\n * Updates the local clock based on a received remote timestamp.\n * Must be called whenever a message/event is received from another node.\n */\n public update(remote: Timestamp): void {\n const systemTime = Date.now();\n\n // Validate drift (optional but good practice)\n if (remote.millis > systemTime + HLC.MAX_DRIFT) {\n console.warn(`Clock drift detected: Remote time ${remote.millis} is far ahead of local ${systemTime}`);\n // In strict systems we might reject, but in AP systems we usually accept and fast-forward\n }\n\n const maxMillis = Math.max(this.lastMillis, systemTime, remote.millis);\n\n if (maxMillis === this.lastMillis && maxMillis === remote.millis) {\n // Both clocks are on the same millisecond, take max counter\n this.lastCounter = Math.max(this.lastCounter, remote.counter) + 1;\n } else if (maxMillis === this.lastMillis) {\n // Local logical clock is ahead in millis (or same as remote but remote millis < local)\n this.lastCounter++;\n } else if (maxMillis === remote.millis) {\n // Remote clock is ahead, fast-forward local\n this.lastCounter = remote.counter + 1;\n } else {\n // System time is ahead of both\n this.lastCounter = 0;\n }\n\n this.lastMillis = maxMillis;\n }\n\n /**\n * Compares two timestamps.\n * Returns -1 if a < b, 1 if a > b, 0 if equal.\n */\n public static compare(a: Timestamp, b: Timestamp): number {\n if (a.millis !== b.millis) {\n return a.millis - b.millis;\n }\n if (a.counter !== b.counter) {\n return a.counter - b.counter;\n }\n return a.nodeId.localeCompare(b.nodeId);\n }\n\n /**\n * Serializes timestamp to a string representation (e.g., for storage/network).\n * Format: \"<millis>:<counter>:<nodeId>\"\n */\n public static toString(ts: Timestamp): string {\n return `${ts.millis}:${ts.counter}:${ts.nodeId}`;\n }\n\n /**\n * Parses a string representation back to a Timestamp object.\n */\n public static parse(str: string): Timestamp {\n const parts = str.split(':');\n if (parts.length !== 3) {\n throw new Error(`Invalid timestamp format: ${str}`);\n }\n return {\n millis: parseInt(parts[0], 10),\n counter: parseInt(parts[1], 10),\n nodeId: parts[2]\n };\n }\n}\n","/**\n * FNV-1a Hash implementation for strings.\n * Fast, non-cryptographic, synchronous.\n * Good enough for data synchronization checks.\n */\nexport function hashString(str: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0; // Ensure positive 32-bit integer\n}\n\n/**\n * Combines multiple hash numbers into one order-independent hash.\n * Used for combining bucket hashes.\n * XOR is simple and effective for order-independent combination, \n * but for Merkle trees we usually want position dependence if it's a Trie, \n * or order-independence if it's a Set.\n * Here we simply sum or XOR.\n */\nexport function combineHashes(hashes: number[]): number {\n let result = 0;\n for (const h of hashes) {\n result = (result + h) | 0; // Simple sum\n }\n return result >>> 0;\n}\n\n","import { LWWRecord } from './LWWMap';\nimport { hashString } from './utils/hash';\n\nexport interface MerkleNode {\n hash: number;\n children?: { [key: string]: MerkleNode }; // Keyed by bucket index (hex char)\n entries?: Map<string, number>; // Leaf node: Key -> ContentHash\n}\n\n/**\n * A specific implementation of Merkle Tree for syncing LWW-Maps.\n * It uses a Prefix Trie structure based on the hash of the Record Key.\n * \n * Structure:\n * - Level 0: Root\n * - Level 1..N: Buckets based on hex digits of Key Hash.\n * \n * This allows us to quickly identify which \"bucket\" of keys is out of sync.\n */\nexport class MerkleTree {\n private root: MerkleNode;\n private readonly depth: number;\n\n constructor(records: Map<string, LWWRecord<any>> = new Map(), depth: number = 3) {\n this.depth = depth;\n this.root = { hash: 0, children: {} };\n // Build initial tree\n for (const [key, record] of records) {\n this.update(key, record);\n }\n }\n\n /**\n * Incrementally updates the Merkle Tree with a single record.\n * @param key The key of the record\n * @param record The record (value + timestamp)\n */\n public update(key: string, record: LWWRecord<any>) {\n const itemHash = hashString(`${key}:${record.timestamp.millis}:${record.timestamp.counter}:${record.timestamp.nodeId}`);\n // We use the hash of the KEY for routing, so the record stays in the same bucket\n // regardless of timestamp changes.\n const pathHash = hashString(key).toString(16).padStart(8, '0'); \n \n this.updateNode(this.root, key, itemHash, pathHash, 0);\n }\n\n /**\n * Removes a key from the Merkle Tree.\n * Necessary for Garbage Collection of tombstones.\n */\n public remove(key: string) {\n const pathHash = hashString(key).toString(16).padStart(8, '0');\n this.removeNode(this.root, key, pathHash, 0);\n }\n\n private removeNode(node: MerkleNode, key: string, pathHash: string, level: number): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (node.entries) {\n node.entries.delete(key);\n \n // Recalculate leaf hash\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n }\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (node.children && node.children[bucketChar]) {\n const childHash = this.removeNode(node.children[bucketChar], key, pathHash, level + 1);\n \n // Optimization: if child is empty/zero, we might want to remove it, but for now just recalc.\n }\n \n // Recalculate this node's hash from children\n let h = 0;\n if (node.children) {\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n private updateNode(node: MerkleNode, key: string, itemHash: number, pathHash: string, level: number): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (!node.entries) node.entries = new Map();\n node.entries.set(key, itemHash);\n \n // Recalculate leaf hash (Sum of item hashes)\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (!node.children) node.children = {};\n \n if (!node.children[bucketChar]) {\n node.children[bucketChar] = { hash: 0 };\n }\n \n this.updateNode(node.children[bucketChar], key, itemHash, pathHash, level + 1);\n \n // Recalculate this node's hash from children\n let h = 0;\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n public getRootHash(): number {\n return this.root.hash;\n }\n\n public getNode(path: string): MerkleNode | undefined {\n let current = this.root;\n for (const char of path) {\n if (!current.children || !current.children[char]) {\n return undefined;\n }\n current = current.children[char];\n }\n return current;\n }\n\n /**\n * Returns the hashes of the children at the given path.\n * Used by the client/server to compare buckets.\n */\n public getBuckets(path: string): Record<string, number> {\n const node = this.getNode(path);\n if (!node || !node.children) return {};\n \n const result: Record<string, number> = {};\n for (const [key, child] of Object.entries(node.children)) {\n result[key] = child.hash;\n }\n return result;\n }\n\n /**\n * For a leaf node (bucket), returns the actual keys it contains.\n * Used to request specific keys when a bucket differs.\n */\n public getKeysInBucket(path: string): string[] {\n const node = this.getNode(path);\n if (!node || !node.entries) return [];\n return Array.from(node.entries.keys());\n }\n}\n","import { HLC, Timestamp } from './HLC';\nimport { MerkleTree } from './MerkleTree';\n\n/**\n * A record in the LWW-Map.\n * Can represent a value or a deletion (tombstone).\n */\nexport interface LWWRecord<V> {\n value: V | null;\n timestamp: Timestamp;\n ttlMs?: number;\n}\n\n/**\n * Last-Write-Wins Map Implementation.\n * This structure guarantees convergence by always keeping the entry with the highest timestamp.\n */\nexport class LWWMap<K, V> {\n private data: Map<K, LWWRecord<V>>;\n private readonly hlc: HLC;\n private listeners: Array<() => void> = [];\n private merkleTree: MerkleTree;\n\n constructor(hlc: HLC) {\n this.hlc = hlc;\n this.data = new Map();\n this.merkleTree = new MerkleTree();\n }\n\n public onChange(callback: () => void): () => void {\n this.listeners.push(callback);\n return () => {\n this.listeners = this.listeners.filter(cb => cb !== callback);\n };\n }\n\n private notify(): void {\n this.listeners.forEach(cb => cb());\n }\n\n public getMerkleTree(): MerkleTree {\n return this.merkleTree;\n }\n\n public get size(): number {\n return this.data.size;\n }\n\n /**\n * Sets a value for a key.\n * Generates a new timestamp using the local HLC.\n */\n public set(key: K, value: V, ttlMs?: number): LWWRecord<V> {\n const timestamp = this.hlc.now();\n const record: LWWRecord<V> = { value, timestamp };\n \n if (ttlMs !== undefined) {\n if (typeof ttlMs !== 'number' || ttlMs <= 0 || !Number.isFinite(ttlMs)) {\n // We could throw, but to be resilient we might just ignore invalid TTL or log warning.\n // Given this is core lib, throwing is safer to alert dev.\n throw new Error('TTL must be a positive finite number');\n }\n record.ttlMs = ttlMs;\n }\n \n // We assume K is string for MerkleTree compatibility in this system\n // If K is not string, we might need to stringify it.\n // The project seems to use string keys for maps.\n this.data.set(key, record);\n this.merkleTree.update(String(key), record);\n \n this.notify();\n return record;\n }\n\n /**\n * Retrieves the value for a key.\n * Returns undefined if key doesn't exist, is a tombstone, or is expired.\n */\n public get(key: K): V | undefined {\n const record = this.data.get(key);\n if (!record || record.value === null) {\n return undefined;\n }\n\n // Check for expiration\n if (record.ttlMs) {\n const now = Date.now();\n if (record.timestamp.millis + record.ttlMs < now) {\n return undefined;\n }\n }\n\n return record.value;\n }\n\n /**\n * Returns the full record (including timestamp).\n * Useful for synchronization.\n */\n public getRecord(key: K): LWWRecord<V> | undefined {\n return this.data.get(key);\n }\n\n /**\n * Removes a key (creates a tombstone).\n */\n public remove(key: K): LWWRecord<V> {\n const timestamp = this.hlc.now();\n const tombstone: LWWRecord<V> = { value: null, timestamp };\n \n this.data.set(key, tombstone);\n this.merkleTree.update(String(key), tombstone);\n \n this.notify();\n return tombstone;\n }\n\n /**\n * Merges a record from a remote source.\n * Returns true if the local state was updated.\n */\n public merge(key: K, remoteRecord: LWWRecord<V>): boolean {\n // Update our clock to ensure causality for future events\n this.hlc.update(remoteRecord.timestamp);\n\n const localRecord = this.data.get(key);\n\n // LWW Logic:\n // 1. If no local record, accept remote.\n // 2. If remote is strictly greater than local, accept remote.\n // 3. If equal, we can arbitrarily choose (e.g. by NodeID) to ensure convergence, \n // but HLC.compare handles nodeId tie-breaking already.\n \n if (!localRecord || HLC.compare(remoteRecord.timestamp, localRecord.timestamp) > 0) {\n this.data.set(key, remoteRecord);\n this.merkleTree.update(String(key), remoteRecord);\n \n this.notify();\n return true;\n }\n\n return false;\n }\n\n /**\n * Garbage Collection: Prunes tombstones older than the specified timestamp.\n * Only removes records that are tombstones (deleted) AND older than the threshold.\n * \n * @param olderThan The timestamp threshold. Tombstones older than this will be removed.\n * @returns The number of tombstones removed.\n */\n public prune(olderThan: Timestamp): K[] {\n const removedKeys: K[] = [];\n \n for (const [key, record] of this.data.entries()) {\n // Only prune tombstones (value === null)\n if (record.value === null) {\n // Check if timestamp is strictly older than the threshold\n // HLC.compare(a, b) returns < 0 if a < b\n if (HLC.compare(record.timestamp, olderThan) < 0) {\n this.data.delete(key);\n this.merkleTree.remove(String(key));\n removedKeys.push(key);\n }\n }\n }\n\n if (removedKeys.length > 0) {\n this.notify();\n }\n\n return removedKeys;\n }\n\n /**\n * Clears all data and tombstones.\n * Resets the MerkleTree.\n */\n public clear(): void {\n this.data.clear();\n this.merkleTree = new MerkleTree();\n this.notify();\n }\n\n /**\n * Returns an iterator over all non-deleted entries.\n */\n public entries(): IterableIterator<[K, V]> {\n const iterator = this.data.entries();\n const now = Date.now();\n \n return {\n [Symbol.iterator]() { return this; },\n next: () => {\n let result = iterator.next();\n while (!result.done) {\n const [key, record] = result.value;\n if (record.value !== null) {\n // Check TTL\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n result = iterator.next();\n continue;\n }\n return { value: [key, record.value], done: false };\n }\n result = iterator.next();\n }\n return { value: undefined, done: true };\n }\n };\n }\n\n /**\n * Returns all keys (including tombstones).\n */\n public allKeys(): IterableIterator<K> {\n return this.data.keys();\n }\n}\n","import { ORMapRecord } from './ORMap';\nimport { Timestamp } from './HLC';\nimport { hashString } from './utils/hash';\n\n/**\n * Convert Timestamp to deterministic string for hashing.\n * Format: millis:counter:nodeId\n */\nexport function timestampToString(ts: Timestamp): string {\n return `${ts.millis}:${ts.counter}:${ts.nodeId}`;\n}\n\n/**\n * Stringify a value in a deterministic way for hashing.\n */\nfunction stringifyValue(value: unknown): string {\n if (value === null || value === undefined) {\n return String(value);\n }\n if (typeof value === 'object') {\n // Sort object keys for deterministic JSON\n return JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort());\n }\n return String(value);\n}\n\n/**\n * Hash an ORMap entry (key + all its records).\n * Must be deterministic regardless of insertion order.\n *\n * @param key The key of the entry\n * @param records Map of tag -> record for this key\n * @returns Hash as a number (FNV-1a hash)\n */\nexport function hashORMapEntry<V>(\n key: string,\n records: Map<string, ORMapRecord<V>>\n): number {\n // Sort records by tag for deterministic ordering\n const sortedTags = Array.from(records.keys()).sort();\n\n // Build deterministic string representation\n const parts: string[] = [`key:${key}`];\n\n for (const tag of sortedTags) {\n const record = records.get(tag)!;\n // Include tag, value (JSON-stringified), timestamp, and ttl if present\n const valuePart = stringifyValue(record.value);\n\n let recordStr = `${tag}:${valuePart}:${timestampToString(record.timestamp)}`;\n if (record.ttlMs !== undefined) {\n recordStr += `:ttl=${record.ttlMs}`;\n }\n parts.push(recordStr);\n }\n\n return hashString(parts.join('|'));\n}\n\n/**\n * Hash a single ORMapRecord for comparison.\n * Used when comparing individual records during merge.\n */\nexport function hashORMapRecord<V>(record: ORMapRecord<V>): number {\n const valuePart = stringifyValue(record.value);\n\n let str = `${record.tag}:${valuePart}:${timestampToString(record.timestamp)}`;\n if (record.ttlMs !== undefined) {\n str += `:ttl=${record.ttlMs}`;\n }\n\n return hashString(str);\n}\n\n/**\n * Compare two timestamps.\n * Returns:\n * < 0 if a < b\n * > 0 if a > b\n * = 0 if a == b\n */\nexport function compareTimestamps(a: Timestamp, b: Timestamp): number {\n if (a.millis !== b.millis) {\n return a.millis - b.millis;\n }\n if (a.counter !== b.counter) {\n return a.counter - b.counter;\n }\n return a.nodeId.localeCompare(b.nodeId);\n}\n","import { ORMap, ORMapRecord } from './ORMap';\nimport { hashString, combineHashes } from './utils/hash';\nimport { hashORMapEntry } from './ORMapMerkle';\n\n/**\n * Merkle Node for ORMap.\n * Uses a prefix trie structure based on key hash (similar to LWWMap MerkleTree).\n */\nexport interface ORMapMerkleNode {\n hash: number;\n children?: { [key: string]: ORMapMerkleNode }; // Keyed by bucket index (hex char)\n entries?: Map<string, number>; // Leaf node: Key -> ContentHash\n}\n\n/**\n * A Merkle Tree implementation specifically for ORMap synchronization.\n * Uses a Prefix Trie structure based on the hash of the Record Key.\n *\n * Structure:\n * - Level 0: Root\n * - Level 1..N: Buckets based on hex digits of Key Hash.\n *\n * Key difference from LWWMap MerkleTree:\n * - Each key can have multiple records (tags), so the entry hash includes all records for that key.\n */\nexport class ORMapMerkleTree {\n private root: ORMapMerkleNode;\n private readonly depth: number;\n\n constructor(depth: number = 3) {\n this.depth = depth;\n this.root = { hash: 0, children: {} };\n }\n\n /**\n * Update tree from ORMap data.\n * Rebuilds hashes for all entries in the map.\n */\n updateFromORMap<K, V>(map: ORMap<K, V>): void {\n // Clear and rebuild\n this.root = { hash: 0, children: {} };\n\n // Access internal items through available methods\n // We need to iterate over all keys and get their records\n const snapshot = map.getSnapshot();\n\n for (const [key, records] of snapshot.items) {\n if (records.size > 0) {\n const keyStr = String(key);\n const entryHash = hashORMapEntry(keyStr, records);\n const pathHash = hashString(keyStr).toString(16).padStart(8, '0');\n this.updateNode(this.root, keyStr, entryHash, pathHash, 0);\n }\n }\n }\n\n /**\n * Incrementally update a single key's hash.\n * Call this when records for a key change.\n */\n update<V>(key: string, records: Map<string, ORMapRecord<V>>): void {\n const pathHash = hashString(key).toString(16).padStart(8, '0');\n\n if (records.size === 0) {\n // Key has no records, remove from tree\n this.removeNode(this.root, key, pathHash, 0);\n } else {\n const entryHash = hashORMapEntry(key, records);\n this.updateNode(this.root, key, entryHash, pathHash, 0);\n }\n }\n\n /**\n * Remove a key from the tree.\n * Called when all records for a key are removed.\n */\n remove(key: string): void {\n const pathHash = hashString(key).toString(16).padStart(8, '0');\n this.removeNode(this.root, key, pathHash, 0);\n }\n\n private updateNode(\n node: ORMapMerkleNode,\n key: string,\n entryHash: number,\n pathHash: string,\n level: number\n ): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (!node.entries) node.entries = new Map();\n node.entries.set(key, entryHash);\n\n // Recalculate leaf hash (Sum of entry hashes)\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (!node.children) node.children = {};\n\n if (!node.children[bucketChar]) {\n node.children[bucketChar] = { hash: 0 };\n }\n\n this.updateNode(node.children[bucketChar], key, entryHash, pathHash, level + 1);\n\n // Recalculate this node's hash from children\n let h = 0;\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n private removeNode(\n node: ORMapMerkleNode,\n key: string,\n pathHash: string,\n level: number\n ): number {\n // Leaf Node Logic\n if (level >= this.depth) {\n if (node.entries) {\n node.entries.delete(key);\n\n // Recalculate leaf hash\n let h = 0;\n for (const val of node.entries.values()) {\n h = (h + val) | 0;\n }\n node.hash = h >>> 0;\n }\n return node.hash;\n }\n\n // Intermediate Node Logic\n const bucketChar = pathHash[level];\n if (node.children && node.children[bucketChar]) {\n this.removeNode(node.children[bucketChar], key, pathHash, level + 1);\n }\n\n // Recalculate this node's hash from children\n let h = 0;\n if (node.children) {\n for (const child of Object.values(node.children)) {\n h = (h + child.hash) | 0;\n }\n }\n node.hash = h >>> 0;\n return node.hash;\n }\n\n /**\n * Get the root hash for quick comparison.\n */\n getRootHash(): number {\n return this.root.hash;\n }\n\n /**\n * Get node at a specific path.\n */\n getNode(path: string): ORMapMerkleNode | undefined {\n let current = this.root;\n for (const char of path) {\n if (!current.children || !current.children[char]) {\n return undefined;\n }\n current = current.children[char];\n }\n return current;\n }\n\n /**\n * Returns the hashes of the children at the given path.\n * Used by the client/server to compare buckets.\n */\n getBuckets(path: string): Record<string, number> {\n const node = this.getNode(path);\n if (!node || !node.children) return {};\n\n const result: Record<string, number> = {};\n for (const [key, child] of Object.entries(node.children)) {\n result[key] = child.hash;\n }\n return result;\n }\n\n /**\n * For a leaf node (bucket), returns the actual keys it contains.\n * Used to request specific keys when a bucket differs.\n */\n getKeysInBucket(path: string): string[] {\n const node = this.getNode(path);\n if (!node || !node.entries) return [];\n return Array.from(node.entries.keys());\n }\n\n /**\n * Find keys that differ between this tree and bucket info from remote.\n * Returns keys that:\n * - Exist locally but have different hash on remote\n * - Exist on remote but not locally\n * - Exist locally but not on remote\n */\n findDiffKeys(path: string, remoteEntries: Map<string, number>): Set<string> {\n const diffKeys = new Set<string>();\n const node = this.getNode(path);\n const localEntries = node?.entries || new Map();\n\n // Keys in local but not remote, or different hash\n for (const [key, hash] of localEntries) {\n const remoteHash = remoteEntries.get(key);\n if (remoteHash === undefined || remoteHash !== hash) {\n diffKeys.add(key);\n }\n }\n\n // Keys in remote but not local\n for (const key of remoteEntries.keys()) {\n if (!localEntries.has(key)) {\n diffKeys.add(key);\n }\n }\n\n return diffKeys;\n }\n\n /**\n * Get all entry hashes at a leaf path.\n * Used when sending bucket details to remote.\n */\n getEntryHashes(path: string): Map<string, number> {\n const node = this.getNode(path);\n return node?.entries || new Map();\n }\n\n /**\n * Check if a path leads to a leaf node.\n */\n isLeaf(path: string): boolean {\n const node = this.getNode(path);\n return node !== undefined && node.entries !== undefined && node.entries.size > 0;\n }\n}\n","import { HLC, Timestamp } from './HLC';\nimport { ORMapMerkleTree } from './ORMapMerkleTree';\nimport { compareTimestamps } from './ORMapMerkle';\n\n/**\n * A record in the OR-Map (Observed-Remove Map).\n * Represents a single value instance with a unique tag.\n */\nexport interface ORMapRecord<V> {\n value: V;\n timestamp: Timestamp;\n tag: string; // Unique identifier (UUID + Timestamp)\n ttlMs?: number;\n}\n\n/**\n * Result of merging records for a key.\n */\nexport interface MergeKeyResult {\n added: number;\n updated: number;\n}\n\n/**\n * Snapshot of ORMap internal state for Merkle Tree synchronization.\n */\nexport interface ORMapSnapshot<K, V> {\n items: Map<K, Map<string, ORMapRecord<V>>>;\n tombstones: Set<string>;\n}\n\n/**\n * OR-Map (Observed-Remove Map) Implementation.\n * \n * Acts as a Multimap where each Key holds a Set of Values.\n * Supports concurrent additions to the same key without data loss.\n * \n * Logic:\n * - Add(K, V): Generates a unique tag. Stores (V, tag) under K.\n * - Remove(K, V): Finds all *currently observed* tags for V under K, and moves them to a Remove Set (Tombstones).\n * - Merge: Union of items minus Union of tombstones.\n */\nexport class ORMap<K, V> {\n // Key -> Map<Tag, Record>\n // Stores active records.\n private items: Map<K, Map<string, ORMapRecord<V>>>;\n\n // Set of removed tags (Tombstones).\n private tombstones: Set<string>;\n\n // Set of expired tags (Local only cache for fast filtering)\n // Note: We don't persist this directly, but rely on filtering.\n // For now, we will just filter on get()\n\n private readonly hlc: HLC;\n\n // Merkle Tree for efficient sync\n private merkleTree: ORMapMerkleTree;\n\n constructor(hlc: HLC) {\n this.hlc = hlc;\n this.items = new Map();\n this.tombstones = new Set();\n this.merkleTree = new ORMapMerkleTree();\n }\n\n private listeners: Array<() => void> = [];\n\n public onChange(callback: () => void): () => void {\n this.listeners.push(callback);\n return () => {\n this.listeners = this.listeners.filter(cb => cb !== callback);\n };\n }\n\n private notify(): void {\n this.listeners.forEach(cb => cb());\n }\n\n public get size(): number {\n return this.items.size;\n }\n\n public get totalRecords(): number {\n let count = 0;\n for (const keyMap of this.items.values()) {\n count += keyMap.size;\n }\n return count;\n }\n\n /**\n * Adds a value to the set associated with the key.\n * Generates a unique tag for this specific addition.\n */\n public add(key: K, value: V, ttlMs?: number): ORMapRecord<V> {\n const timestamp = this.hlc.now();\n // Tag must be unique globally. HLC.toString() provides unique string per node+time.\n const tag = HLC.toString(timestamp);\n\n const record: ORMapRecord<V> = {\n value,\n timestamp,\n tag\n };\n\n if (ttlMs !== undefined) {\n if (typeof ttlMs !== 'number' || ttlMs <= 0 || !Number.isFinite(ttlMs)) {\n throw new Error('TTL must be a positive finite number');\n }\n record.ttlMs = ttlMs;\n }\n\n let keyMap = this.items.get(key);\n if (!keyMap) {\n keyMap = new Map();\n this.items.set(key, keyMap);\n }\n\n keyMap.set(tag, record);\n this.updateMerkleTree(key);\n this.notify();\n return record;\n }\n\n /**\n * Removes a specific value from the set associated with the key.\n * Marks all *currently observed* instances of this value as removed (tombstones).\n * Returns the list of tags that were removed (useful for sync).\n */\n public remove(key: K, value: V): string[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n // Find all tags for this value\n const tagsToRemove: string[] = [];\n\n for (const [tag, record] of keyMap.entries()) {\n // Using strict equality. For objects, this requires the exact instance.\n if (record.value === value) {\n tagsToRemove.push(tag);\n }\n }\n\n for (const tag of tagsToRemove) {\n this.tombstones.add(tag);\n keyMap.delete(tag);\n }\n\n if (keyMap.size === 0) {\n this.items.delete(key);\n }\n\n this.updateMerkleTree(key);\n this.notify();\n return tagsToRemove;\n }\n\n /**\n * Clears all data and tombstones.\n */\n public clear(): void {\n this.items.clear();\n this.tombstones.clear();\n this.merkleTree = new ORMapMerkleTree();\n this.notify();\n }\n\n /**\n * Returns all active values for a key.\n * Filters out expired records.\n */\n public get(key: K): V[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n const values: V[] = [];\n const now = Date.now();\n\n for (const [tag, record] of keyMap.entries()) {\n if (!this.tombstones.has(tag)) {\n // Check expiration\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n continue;\n }\n values.push(record.value);\n }\n }\n return values;\n }\n\n /**\n * Returns all active records for a key.\n * Useful for persistence and sync.\n * Filters out expired records.\n */\n public getRecords(key: K): ORMapRecord<V>[] {\n const keyMap = this.items.get(key);\n if (!keyMap) return [];\n\n const records: ORMapRecord<V>[] = [];\n const now = Date.now();\n\n for (const [tag, record] of keyMap.entries()) {\n if (!this.tombstones.has(tag)) {\n // Check expiration\n if (record.ttlMs && record.timestamp.millis + record.ttlMs < now) {\n continue;\n }\n records.push(record);\n }\n }\n return records;\n }\n\n /**\n * Returns all tombstone tags.\n */\n public getTombstones(): string[] {\n return Array.from(this.tombstones);\n }\n\n /**\n * Applies a record from a remote source (Sync).\n * Returns true if the record was applied (not tombstoned).\n */\n public apply(key: K, record: ORMapRecord<V>): boolean {\n if (this.tombstones.has(record.tag)) return false;\n\n let keyMap = this.items.get(key);\n if (!keyMap) {\n keyMap = new Map();\n this.items.set(key, keyMap);\n }\n keyMap.set(record.tag, record);\n this.hlc.update(record.timestamp);\n this.updateMerkleTree(key);\n this.notify();\n return true;\n }\n\n /**\n * Applies a tombstone (deletion) from a remote source.\n */\n public applyTombstone(tag: string): void {\n this.tombstones.add(tag);\n // Cleanup active items if present\n for (const [key, keyMap] of this.items) {\n if (keyMap.has(tag)) {\n keyMap.delete(tag);\n if (keyMap.size === 0) this.items.delete(key);\n this.updateMerkleTree(key);\n // We found it, so we can stop searching (tag is unique globally)\n break;\n }\n }\n this.notify();\n }\n\n /**\n * Merges state from another ORMap.\n * - Adds all new tombstones from 'other'.\n * - Adds all new items from 'other' that are not in tombstones.\n * - Updates HLC with observed timestamps.\n */\n public merge(other: ORMap<K, V>): void {\n const changedKeys = new Set<K>();\n\n // 1. Merge tombstones\n for (const tag of other.tombstones) {\n this.tombstones.add(tag);\n }\n\n // 2. Merge items\n for (const [key, otherKeyMap] of other.items) {\n let localKeyMap = this.items.get(key);\n if (!localKeyMap) {\n localKeyMap = new Map();\n this.items.set(key, localKeyMap);\n }\n\n for (const [tag, record] of otherKeyMap) {\n // Only accept if not deleted\n if (!this.tombstones.has(tag)) {\n if (!localKeyMap.has(tag)) {\n localKeyMap.set(tag, record);\n changedKeys.add(key);\n }\n // Always update causality\n this.hlc.update(record.timestamp);\n }\n }\n }\n\n // 3. Cleanup: Remove any local items that are now in the merged tombstones\n for (const [key, localKeyMap] of this.items) {\n for (const tag of localKeyMap.keys()) {\n if (this.tombstones.has(tag)) {\n localKeyMap.delete(tag);\n changedKeys.add(key);\n }\n }\n if (localKeyMap.size === 0) {\n this.items.delete(key);\n }\n }\n\n // Update Merkle Tree for changed keys\n for (const key of changedKeys) {\n this.updateMerkleTree(key);\n }\n\n this.notify();\n }\n\n /**\n * Garbage Collection: Prunes tombstones older than the specified timestamp.\n */\n public prune(olderThan: Timestamp): string[] {\n const removedTags: string[] = [];\n\n for (const tag of this.tombstones) {\n try {\n const timestamp = HLC.parse(tag);\n if (HLC.compare(timestamp, olderThan) < 0) {\n this.tombstones.delete(tag);\n removedTags.push(tag);\n }\n } catch (e) {\n // Ignore invalid tags\n }\n }\n\n return removedTags;\n }\n\n // ============ Merkle Sync Methods ============\n\n /**\n * Get the Merkle Tree for this ORMap.\n * Used for efficient synchronization.\n */\n public getMerkleTree(): ORMapMerkleTree {\n return this.merkleTree;\n }\n\n /**\n * Get a snapshot of internal state for Merkle Tree synchronization.\n * Returns references to internal structures - do not modify!\n */\n public getSnapshot(): ORMapSnapshot<K, V> {\n return {\n items: this.items,\n tombstones: this.tombstones\n };\n }\n\n /**\n * Get all keys in this ORMap.\n */\n public allKeys(): K[] {\n return Array.from(this.items.keys());\n }\n\n /**\n * Get the internal records map for a key.\n * Returns Map<tag, record> or undefined if key doesn't exist.\n * Used for Merkle sync.\n */\n public getRecordsMap(key: K): Map<string, ORMapRecord<V>> | undefined {\n return this.items.get(key);\n }\n\n /**\n * Merge remote records for a specific key into local state.\n * Implements Observed-Remove CRDT semantics.\n * Used during Merkle Tree synchronization.\n *\n * @param key The key to merge\n * @param remoteRecords Array of records from remote\n * @param remoteTombstones Array of tombstone tags from remote\n * @returns Result with count of added and updated records\n */\n public mergeKey(\n key: K,\n remoteRecords: ORMapRecord<V>[],\n remoteTombstones: string[] = []\n ): MergeKeyResult {\n let added = 0;\n let updated = 0;\n\n // First apply remote tombstones\n for (const tag of remoteTombstones) {\n if (!this.tombstones.has(tag)) {\n this.tombstones.add(tag);\n }\n }\n\n // Get or create local key map\n let localKeyMap = this.items.get(key);\n if (!localKeyMap) {\n localKeyMap = new Map();\n this.items.set(key, localKeyMap);\n }\n\n // Remove any local records that are now tombstoned\n for (const tag of localKeyMap.keys()) {\n if (this.tombstones.has(tag)) {\n localKeyMap.delete(tag);\n }\n }\n\n // Merge remote records\n for (const remoteRecord of remoteRecords) {\n // Skip if tombstoned\n if (this.tombstones.has(remoteRecord.tag)) {\n continue;\n }\n\n const localRecord = localKeyMap.get(remoteRecord.tag);\n\n if (!localRecord) {\n // New record - add it\n localKeyMap.set(remoteRecord.tag, remoteRecord);\n added++;\n } else if (compareTimestamps(remoteRecord.timestamp, localRecord.timestamp) > 0) {\n // Remote is newer - update\n localKeyMap.set(remoteRecord.tag, remoteRecord);\n updated++;\n }\n // Else: local is newer or equal, keep local\n\n // Always update causality\n this.hlc.update(remoteRecord.timestamp);\n }\n\n // Cleanup empty key map\n if (localKeyMap.size === 0) {\n this.items.delete(key);\n }\n\n // Update Merkle Tree\n this.updateMerkleTree(key);\n\n if (added > 0 || updated > 0) {\n this.notify();\n }\n\n return { added, updated };\n }\n\n /**\n * Check if a tag is tombstoned.\n */\n public isTombstoned(tag: string): boolean {\n return this.tombstones.has(tag);\n }\n\n /**\n * Update the Merkle Tree for a specific key.\n * Called internally after any modification.\n */\n private updateMerkleTree(key: K): void {\n const keyStr = String(key);\n const keyMap = this.items.get(key);\n\n if (!keyMap || keyMap.size === 0) {\n this.merkleTree.remove(keyStr);\n } else {\n this.merkleTree.update(keyStr, keyMap);\n }\n }\n}\n","import { encode, decode } from '@msgpack/msgpack';\n\n/**\n * Serializes a JavaScript object to MessagePack binary format.\n * @param data The data to serialize.\n * @returns A Uint8Array containing the serialized data.\n */\nexport function serialize(data: unknown): Uint8Array {\n return encode(data);\n}\n\n/**\n * Deserializes MessagePack binary data to a JavaScript object.\n * @param data The binary data to deserialize (Uint8Array or ArrayBuffer).\n * @returns The deserialized object.\n */\nexport function deserialize<T = unknown>(data: Uint8Array | ArrayBuffer): T {\n // @msgpack/msgpack decode accepts Uint8Array, ArrayBuffer, etc.\n return decode(data) as T;\n}\n\n","\nexport type PredicateOp = \n | 'eq' | 'neq' \n | 'gt' | 'gte' \n | 'lt' | 'lte' \n | 'like' | 'regex' \n | 'and' | 'or' | 'not';\n\nexport interface PredicateNode {\n op: PredicateOp;\n attribute?: string;\n value?: any;\n children?: PredicateNode[];\n}\n\nexport class Predicates {\n static equal(attribute: string, value: any): PredicateNode { \n return { op: 'eq', attribute, value }; \n }\n \n static notEqual(attribute: string, value: any): PredicateNode { \n return { op: 'neq', attribute, value }; \n }\n \n static greaterThan(attribute: string, value: any): PredicateNode { \n return { op: 'gt', attribute, value }; \n }\n \n static greaterThanOrEqual(attribute: string, value: any): PredicateNode { \n return { op: 'gte', attribute, value }; \n }\n \n static lessThan(attribute: string, value: any): PredicateNode { \n return { op: 'lt', attribute, value }; \n }\n \n static lessThanOrEqual(attribute: string, value: any): PredicateNode { \n return { op: 'lte', attribute, value }; \n }\n \n static like(attribute: string, pattern: string): PredicateNode { \n return { op: 'like', attribute, value: pattern }; \n }\n \n static regex(attribute: string, pattern: string): PredicateNode { \n return { op: 'regex', attribute, value: pattern }; \n }\n\n static between(attribute: string, from: any, to: any): PredicateNode {\n return {\n op: 'and',\n children: [\n { op: 'gte', attribute, value: from },\n { op: 'lte', attribute, value: to }\n ]\n };\n }\n\n static and(...predicates: PredicateNode[]): PredicateNode { \n return { op: 'and', children: predicates }; \n }\n \n static or(...predicates: PredicateNode[]): PredicateNode { \n return { op: 'or', children: predicates }; \n }\n \n static not(predicate: PredicateNode): PredicateNode { \n return { op: 'not', children: [predicate] }; \n }\n}\n\nexport function evaluatePredicate(predicate: PredicateNode, data: any): boolean {\n if (!data) return false;\n \n switch (predicate.op) {\n case 'and':\n return (predicate.children || []).every(p => evaluatePredicate(p, data));\n case 'or':\n return (predicate.children || []).some(p => evaluatePredicate(p, data));\n case 'not': {\n const child = (predicate.children || [])[0];\n if (!child) return true; // NOT of nothing is true (vacuous)\n return !evaluatePredicate(child, data);\n }\n }\n\n // Leaf nodes require an attribute\n if (!predicate.attribute) return false;\n \n const value = data[predicate.attribute];\n const target = predicate.value;\n\n switch (predicate.op) {\n case 'eq':\n return value === target;\n case 'neq':\n return value !== target;\n case 'gt':\n return value > target;\n case 'gte':\n return value >= target;\n case 'lt':\n return value < target;\n case 'lte':\n return value <= target;\n case 'like':\n if (typeof value !== 'string' || typeof target !== 'string') return false;\n const pattern = target\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/%/g, '.*')\n .replace(/_/g, '.');\n return new RegExp(`^${pattern}$`, 'i').test(value);\n case 'regex':\n if (typeof value !== 'string' || typeof target !== 'string') return false;\n return new RegExp(target).test(value);\n default:\n return false;\n }\n}\n","import { z } from 'zod';\n\n// --- Basic Types ---\n\nexport const TimestampSchema = z.object({\n millis: z.number(),\n counter: z.number(),\n nodeId: z.string(),\n});\n\nexport const LWWRecordSchema = z.object({\n value: z.any().nullable(),\n timestamp: TimestampSchema,\n ttlMs: z.number().optional(),\n});\n\nexport const ORMapRecordSchema = z.object({\n value: z.any(),\n timestamp: TimestampSchema,\n tag: z.string(),\n ttlMs: z.number().optional(),\n});\n\n// --- Predicate Types ---\n\nexport const PredicateOpSchema = z.enum([\n 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'regex', 'and', 'or', 'not'\n]);\n\n// Recursive schema for PredicateNode\nexport const PredicateNodeSchema: z.ZodType<any> = z.lazy(() => z.object({\n op: PredicateOpSchema,\n attribute: z.string().optional(),\n value: z.any().optional(),\n children: z.array(PredicateNodeSchema).optional(),\n}));\n\n// --- Query Types ---\n\nexport const QuerySchema = z.object({\n where: z.record(z.string(), z.any()).optional(),\n predicate: PredicateNodeSchema.optional(),\n sort: z.record(z.string(), z.enum(['asc', 'desc'])).optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n});\n\n// --- Client Operation Types ---\n\nexport const ClientOpSchema = z.object({\n id: z.string().optional(),\n mapName: z.string(),\n key: z.string(),\n // Permissive opType to match ServerCoordinator behavior logic\n // It can be 'REMOVE', 'OR_ADD', 'OR_REMOVE' or undefined/other (implies PUT/LWW)\n opType: z.string().optional(), \n record: LWWRecordSchema.nullable().optional(),\n orRecord: ORMapRecordSchema.nullable().optional(),\n orTag: z.string().nullable().optional(),\n});\n\n// --- Message Schemas ---\n\nexport const AuthMessageSchema = z.object({\n type: z.literal('AUTH'),\n token: z.string(),\n});\n\nexport const QuerySubMessageSchema = z.object({\n type: z.literal('QUERY_SUB'),\n payload: z.object({\n queryId: z.string(),\n mapName: z.string(),\n query: QuerySchema,\n }),\n});\n\nexport const QueryUnsubMessageSchema = z.object({\n type: z.literal('QUERY_UNSUB'),\n payload: z.object({\n queryId: z.string(),\n }),\n});\n\nexport const ClientOpMessageSchema = z.object({\n type: z.literal('CLIENT_OP'),\n payload: ClientOpSchema,\n});\n\nexport const OpBatchMessageSchema = z.object({\n type: z.literal('OP_BATCH'),\n payload: z.object({\n ops: z.array(ClientOpSchema),\n }),\n});\n\nexport const SyncInitMessageSchema = z.object({\n type: z.literal('SYNC_INIT'),\n mapName: z.string(),\n lastSyncTimestamp: z.number().optional(),\n});\n\nexport const SyncRespRootMessageSchema = z.object({\n type: z.literal('SYNC_RESP_ROOT'),\n payload: z.object({\n mapName: z.string(),\n rootHash: z.number(),\n timestamp: TimestampSchema,\n }),\n});\n\nexport const SyncRespBucketsMessageSchema = z.object({\n type: z.literal('SYNC_RESP_BUCKETS'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n buckets: z.record(z.string(), z.number()),\n }),\n});\n\nexport const SyncRespLeafMessageSchema = z.object({\n type: z.literal('SYNC_RESP_LEAF'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n records: z.array(z.object({\n key: z.string(),\n record: LWWRecordSchema,\n })),\n }),\n});\n\nexport const MerkleReqBucketMessageSchema = z.object({\n type: z.literal('MERKLE_REQ_BUCKET'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n }),\n});\n\nexport const LockRequestSchema = z.object({\n type: z.literal('LOCK_REQUEST'),\n payload: z.object({\n requestId: z.string(),\n name: z.string(),\n ttl: z.number().optional(),\n }),\n});\n\nexport const LockReleaseSchema = z.object({\n type: z.literal('LOCK_RELEASE'),\n payload: z.object({\n requestId: z.string().optional(),\n name: z.string(),\n fencingToken: z.number(),\n }),\n});\n\n// --- Topic Messages ---\n\nexport const TopicSubSchema = z.object({\n type: z.literal('TOPIC_SUB'),\n payload: z.object({\n topic: z.string(),\n }),\n});\n\nexport const TopicUnsubSchema = z.object({\n type: z.literal('TOPIC_UNSUB'),\n payload: z.object({\n topic: z.string(),\n }),\n});\n\nexport const TopicPubSchema = z.object({\n type: z.literal('TOPIC_PUB'),\n payload: z.object({\n topic: z.string(),\n data: z.any(),\n }),\n});\n\nexport const TopicMessageEventSchema = z.object({\n type: z.literal('TOPIC_MESSAGE'),\n payload: z.object({\n topic: z.string(),\n data: z.any(),\n publisherId: z.string().optional(),\n timestamp: z.number(),\n }),\n});\n\n// --- Heartbeat Messages ---\n\nexport const PingMessageSchema = z.object({\n type: z.literal('PING'),\n timestamp: z.number(), // Client's Date.now()\n});\n\nexport const PongMessageSchema = z.object({\n type: z.literal('PONG'),\n timestamp: z.number(), // Echo back client's timestamp\n serverTime: z.number(), // Server's Date.now() (for clock skew detection)\n});\n\n// --- ORMap Sync Messages ---\n\n/**\n * ORMAP_SYNC_INIT: Client initiates ORMap sync\n * Sends root hash and bucket hashes to server\n */\nexport const ORMapSyncInitSchema = z.object({\n type: z.literal('ORMAP_SYNC_INIT'),\n mapName: z.string(),\n rootHash: z.number(),\n bucketHashes: z.record(z.string(), z.number()), // path -> hash\n lastSyncTimestamp: z.number().optional(),\n});\n\n/**\n * ORMAP_SYNC_RESP_ROOT: Server responds with its root hash\n */\nexport const ORMapSyncRespRootSchema = z.object({\n type: z.literal('ORMAP_SYNC_RESP_ROOT'),\n payload: z.object({\n mapName: z.string(),\n rootHash: z.number(),\n timestamp: TimestampSchema,\n }),\n});\n\n/**\n * ORMAP_SYNC_RESP_BUCKETS: Server sends bucket hashes for comparison\n */\nexport const ORMapSyncRespBucketsSchema = z.object({\n type: z.literal('ORMAP_SYNC_RESP_BUCKETS'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n buckets: z.record(z.string(), z.number()),\n }),\n});\n\n/**\n * ORMAP_MERKLE_REQ_BUCKET: Client requests bucket details\n */\nexport const ORMapMerkleReqBucketSchema = z.object({\n type: z.literal('ORMAP_MERKLE_REQ_BUCKET'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n }),\n});\n\n/**\n * ORMAP_SYNC_RESP_LEAF: Server sends actual records for differing keys\n */\nexport const ORMapSyncRespLeafSchema = z.object({\n type: z.literal('ORMAP_SYNC_RESP_LEAF'),\n payload: z.object({\n mapName: z.string(),\n path: z.string(),\n entries: z.array(z.object({\n key: z.string(),\n records: z.array(ORMapRecordSchema),\n tombstones: z.array(z.string()), // Tombstone tags for this key's records\n })),\n }),\n});\n\n/**\n * ORMAP_DIFF_REQUEST: Client requests data for specific keys\n */\nexport const ORMapDiffRequestSchema = z.object({\n type: z.literal('ORMAP_DIFF_REQUEST'),\n payload: z.object({\n mapName: z.string(),\n keys: z.array(z.string()),\n }),\n});\n\n/**\n * ORMAP_DIFF_RESPONSE: Server responds with data for requested keys\n */\nexport const ORMapDiffResponseSchema = z.object({\n type: z.literal('ORMAP_DIFF_RESPONSE'),\n payload: z.object({\n mapName: z.string(),\n entries: z.array(z.object({\n key: z.string(),\n records: z.array(ORMapRecordSchema),\n tombstones: z.array(z.string()),\n })),\n }),\n});\n\n/**\n * ORMAP_PUSH_DIFF: Client pushes local diffs to server\n */\nexport const ORMapPushDiffSchema = z.object({\n type: z.literal('ORMAP_PUSH_DIFF'),\n payload: z.object({\n mapName: z.string(),\n entries: z.array(z.object({\n key: z.string(),\n records: z.array(ORMapRecordSchema),\n tombstones: z.array(z.string()),\n })),\n }),\n});\n\n// --- Union Schema ---\n\nexport const MessageSchema = z.discriminatedUnion('type', [\n AuthMessageSchema,\n QuerySubMessageSchema,\n QueryUnsubMessageSchema,\n ClientOpMessageSchema,\n OpBatchMessageSchema,\n SyncInitMessageSchema,\n SyncRespRootMessageSchema,\n SyncRespBucketsMessageSchema,\n SyncRespLeafMessageSchema,\n MerkleReqBucketMessageSchema,\n LockRequestSchema,\n LockReleaseSchema,\n TopicSubSchema,\n TopicUnsubSchema,\n TopicPubSchema,\n PingMessageSchema,\n PongMessageSchema,\n // ORMap Sync Messages\n ORMapSyncInitSchema,\n ORMapSyncRespRootSchema,\n ORMapSyncRespBucketsSchema,\n ORMapMerkleReqBucketSchema,\n ORMapSyncRespLeafSchema,\n ORMapDiffRequestSchema,\n ORMapDiffResponseSchema,\n ORMapPushDiffSchema,\n]);\n\n// --- Type Inference ---\n\nexport type Timestamp = z.infer<typeof TimestampSchema>;\nexport type LWWRecord<V = any> = z.infer<typeof LWWRecordSchema>; // Generic placeholder\nexport type ORMapRecord<V = any> = z.infer<typeof ORMapRecordSchema>; // Generic placeholder\n// export type PredicateNode = z.infer<typeof PredicateNodeSchema>; // Conflict with predicate.ts\nexport type Query = z.infer<typeof QuerySchema>;\nexport type ClientOp = z.infer<typeof ClientOpSchema>;\nexport type Message = z.infer<typeof MessageS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