@a0n/aeon 5.0.1

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.
Files changed (73) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +199 -0
  3. package/dist/CryptoProvider-SLWjqByk.d.cts +407 -0
  4. package/dist/CryptoProvider-SLWjqByk.d.ts +407 -0
  5. package/dist/compression/index.cjs +1445 -0
  6. package/dist/compression/index.cjs.map +1 -0
  7. package/dist/compression/index.d.cts +451 -0
  8. package/dist/compression/index.d.ts +451 -0
  9. package/dist/compression/index.js +1426 -0
  10. package/dist/compression/index.js.map +1 -0
  11. package/dist/core/index.cjs +4 -0
  12. package/dist/core/index.cjs.map +1 -0
  13. package/dist/core/index.d.cts +212 -0
  14. package/dist/core/index.d.ts +212 -0
  15. package/dist/core/index.js +3 -0
  16. package/dist/core/index.js.map +1 -0
  17. package/dist/crypto/index.cjs +130 -0
  18. package/dist/crypto/index.cjs.map +1 -0
  19. package/dist/crypto/index.d.cts +56 -0
  20. package/dist/crypto/index.d.ts +56 -0
  21. package/dist/crypto/index.js +124 -0
  22. package/dist/crypto/index.js.map +1 -0
  23. package/dist/distributed/index.cjs +2586 -0
  24. package/dist/distributed/index.cjs.map +1 -0
  25. package/dist/distributed/index.d.cts +1005 -0
  26. package/dist/distributed/index.d.ts +1005 -0
  27. package/dist/distributed/index.js +2580 -0
  28. package/dist/distributed/index.js.map +1 -0
  29. package/dist/index.cjs +10953 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +1953 -0
  32. package/dist/index.d.ts +1953 -0
  33. package/dist/index.js +10828 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/offline/index.cjs +419 -0
  36. package/dist/offline/index.cjs.map +1 -0
  37. package/dist/offline/index.d.cts +148 -0
  38. package/dist/offline/index.d.ts +148 -0
  39. package/dist/offline/index.js +415 -0
  40. package/dist/offline/index.js.map +1 -0
  41. package/dist/optimization/index.cjs +800 -0
  42. package/dist/optimization/index.cjs.map +1 -0
  43. package/dist/optimization/index.d.cts +347 -0
  44. package/dist/optimization/index.d.ts +347 -0
  45. package/dist/optimization/index.js +790 -0
  46. package/dist/optimization/index.js.map +1 -0
  47. package/dist/persistence/index.cjs +207 -0
  48. package/dist/persistence/index.cjs.map +1 -0
  49. package/dist/persistence/index.d.cts +95 -0
  50. package/dist/persistence/index.d.ts +95 -0
  51. package/dist/persistence/index.js +204 -0
  52. package/dist/persistence/index.js.map +1 -0
  53. package/dist/presence/index.cjs +489 -0
  54. package/dist/presence/index.cjs.map +1 -0
  55. package/dist/presence/index.d.cts +283 -0
  56. package/dist/presence/index.d.ts +283 -0
  57. package/dist/presence/index.js +485 -0
  58. package/dist/presence/index.js.map +1 -0
  59. package/dist/types-CMxO7QF0.d.cts +33 -0
  60. package/dist/types-CMxO7QF0.d.ts +33 -0
  61. package/dist/utils/index.cjs +64 -0
  62. package/dist/utils/index.cjs.map +1 -0
  63. package/dist/utils/index.d.cts +38 -0
  64. package/dist/utils/index.d.ts +38 -0
  65. package/dist/utils/index.js +57 -0
  66. package/dist/utils/index.js.map +1 -0
  67. package/dist/versioning/index.cjs +1164 -0
  68. package/dist/versioning/index.cjs.map +1 -0
  69. package/dist/versioning/index.d.cts +537 -0
  70. package/dist/versioning/index.d.ts +537 -0
  71. package/dist/versioning/index.js +1159 -0
  72. package/dist/versioning/index.js.map +1 -0
  73. package/package.json +194 -0
@@ -0,0 +1,1005 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { I as ICryptoProvider, d as AeonEncryptionMode, e as AuthenticatedMessageFields } from '../CryptoProvider-SLWjqByk.js';
3
+ import { S as StorageAdapter, b as PersistenceSerializer, a as PersistenceDeserializer } from '../types-CMxO7QF0.js';
4
+
5
+ /**
6
+ * Sync Coordinator
7
+ *
8
+ * Coordinates synchronization between multiple nodes in a distributed system.
9
+ * Manages sync sessions, node registration, and synchronization workflows.
10
+ *
11
+ * Features:
12
+ * - Node registration and discovery
13
+ * - Sync session management
14
+ * - Synchronization workflow orchestration
15
+ * - Node health monitoring
16
+ * - Conflict detection and resolution coordination
17
+ * - DID-based node identification
18
+ * - Authenticated sync sessions
19
+ */
20
+
21
+ interface SyncNode {
22
+ id: string;
23
+ address: string;
24
+ port: number;
25
+ status: 'online' | 'offline' | 'syncing';
26
+ lastHeartbeat: string;
27
+ version: string;
28
+ capabilities: string[];
29
+ did?: string;
30
+ publicSigningKey?: JsonWebKey;
31
+ publicEncryptionKey?: JsonWebKey;
32
+ grantedCapabilities?: string[];
33
+ }
34
+ interface SyncSession {
35
+ id: string;
36
+ initiatorId: string;
37
+ participantIds: string[];
38
+ status: 'pending' | 'active' | 'completed' | 'failed';
39
+ startTime: string;
40
+ endTime?: string;
41
+ itemsSynced: number;
42
+ itemsFailed: number;
43
+ conflictsDetected: number;
44
+ initiatorDID?: string;
45
+ participantDIDs?: string[];
46
+ encryptionMode?: AeonEncryptionMode;
47
+ requiredCapabilities?: string[];
48
+ sessionToken?: string;
49
+ }
50
+ interface SyncEvent {
51
+ type: 'node-joined' | 'node-left' | 'sync-started' | 'sync-completed' | 'conflict-detected';
52
+ sessionId?: string;
53
+ nodeId: string;
54
+ timestamp: string;
55
+ data?: unknown;
56
+ }
57
+ /**
58
+ * Sync Coordinator
59
+ * Coordinates synchronization across distributed nodes
60
+ */
61
+ declare class SyncCoordinator extends EventEmitter {
62
+ private static readonly MAX_SYNC_EVENTS;
63
+ private nodes;
64
+ private sessions;
65
+ private syncEvents;
66
+ private nodeHeartbeats;
67
+ private heartbeatInterval;
68
+ private cryptoProvider;
69
+ private nodesByDID;
70
+ constructor();
71
+ private addSyncEvent;
72
+ /**
73
+ * Configure cryptographic provider for authenticated sync
74
+ */
75
+ configureCrypto(provider: ICryptoProvider): void;
76
+ /**
77
+ * Check if crypto is configured
78
+ */
79
+ isCryptoEnabled(): boolean;
80
+ /**
81
+ * Register a node with DID-based identity
82
+ */
83
+ registerAuthenticatedNode(nodeInfo: Omit<SyncNode, 'did' | 'publicSigningKey' | 'publicEncryptionKey'> & {
84
+ did: string;
85
+ publicSigningKey: JsonWebKey;
86
+ publicEncryptionKey?: JsonWebKey;
87
+ }): Promise<SyncNode>;
88
+ /**
89
+ * Get node by DID
90
+ */
91
+ getNodeByDID(did: string): SyncNode | undefined;
92
+ /**
93
+ * Get all authenticated nodes (nodes with DIDs)
94
+ */
95
+ getAuthenticatedNodes(): SyncNode[];
96
+ /**
97
+ * Create an authenticated sync session with UCAN-based authorization
98
+ */
99
+ createAuthenticatedSyncSession(initiatorDID: string, participantDIDs: string[], options?: {
100
+ encryptionMode?: AeonEncryptionMode;
101
+ requiredCapabilities?: string[];
102
+ }): Promise<SyncSession>;
103
+ /**
104
+ * Verify a node's UCAN capabilities for a session
105
+ */
106
+ verifyNodeCapabilities(sessionId: string, nodeDID: string, token: string): Promise<{
107
+ authorized: boolean;
108
+ error?: string;
109
+ }>;
110
+ /**
111
+ * Register a node in the cluster
112
+ */
113
+ registerNode(node: SyncNode): void;
114
+ /**
115
+ * Deregister a node from the cluster
116
+ */
117
+ deregisterNode(nodeId: string): void;
118
+ /**
119
+ * Create a new sync session
120
+ */
121
+ createSyncSession(initiatorId: string, participantIds: string[]): SyncSession;
122
+ /**
123
+ * Update sync session
124
+ */
125
+ updateSyncSession(sessionId: string, updates: Partial<SyncSession>): void;
126
+ /**
127
+ * Record a conflict during sync
128
+ */
129
+ recordConflict(sessionId: string, nodeId: string, conflictData?: unknown): void;
130
+ /**
131
+ * Update node status
132
+ */
133
+ updateNodeStatus(nodeId: string, status: SyncNode['status']): void;
134
+ /**
135
+ * Record heartbeat from node
136
+ */
137
+ recordHeartbeat(nodeId: string): void;
138
+ /**
139
+ * Get all nodes
140
+ */
141
+ getNodes(): SyncNode[];
142
+ /**
143
+ * Get node by ID
144
+ */
145
+ getNode(nodeId: string): SyncNode | undefined;
146
+ /**
147
+ * Get online nodes
148
+ */
149
+ getOnlineNodes(): SyncNode[];
150
+ /**
151
+ * Get nodes by capability
152
+ */
153
+ getNodesByCapability(capability: string): SyncNode[];
154
+ /**
155
+ * Get sync session
156
+ */
157
+ getSyncSession(sessionId: string): SyncSession | undefined;
158
+ /**
159
+ * Get all sync sessions
160
+ */
161
+ getAllSyncSessions(): SyncSession[];
162
+ /**
163
+ * Get active sync sessions
164
+ */
165
+ getActiveSyncSessions(): SyncSession[];
166
+ /**
167
+ * Get sessions for a node
168
+ */
169
+ getSessionsForNode(nodeId: string): SyncSession[];
170
+ /**
171
+ * Get sync statistics
172
+ */
173
+ getStatistics(): {
174
+ totalNodes: number;
175
+ onlineNodes: number;
176
+ offlineNodes: number;
177
+ totalSessions: number;
178
+ activeSessions: number;
179
+ completedSessions: number;
180
+ failedSessions: number;
181
+ successRate: number;
182
+ totalItemsSynced: number;
183
+ totalConflicts: number;
184
+ averageConflictsPerSession: number;
185
+ };
186
+ /**
187
+ * Get sync events
188
+ */
189
+ getSyncEvents(limit?: number): SyncEvent[];
190
+ /**
191
+ * Get sync events for session
192
+ */
193
+ getSessionEvents(sessionId: string): SyncEvent[];
194
+ /**
195
+ * Check node health
196
+ */
197
+ getNodeHealth(): Record<string, {
198
+ isHealthy: boolean;
199
+ downtime: number;
200
+ }>;
201
+ /**
202
+ * Start heartbeat monitoring
203
+ */
204
+ startHeartbeatMonitoring(interval?: number): void;
205
+ /**
206
+ * Stop heartbeat monitoring
207
+ */
208
+ stopHeartbeatMonitoring(): void;
209
+ /**
210
+ * Clear all state (for testing)
211
+ */
212
+ clear(): void;
213
+ /**
214
+ * Get the crypto provider (for advanced usage)
215
+ */
216
+ getCryptoProvider(): ICryptoProvider | null;
217
+ }
218
+
219
+ /**
220
+ * Replication Manager
221
+ *
222
+ * Manages data replication across multiple nodes.
223
+ * Handles replication policies, consistency levels, and replica coordination.
224
+ *
225
+ * Features:
226
+ * - Replica set management
227
+ * - Replication policy enforcement
228
+ * - Consistency level tracking
229
+ * - Replication health monitoring
230
+ * - Replica synchronization coordination
231
+ * - End-to-end encryption for replicated data
232
+ * - DID-based replica authentication
233
+ */
234
+
235
+ interface Replica {
236
+ id: string;
237
+ nodeId: string;
238
+ status: 'primary' | 'secondary' | 'syncing' | 'failed';
239
+ lastSyncTime: string;
240
+ lagBytes: number;
241
+ lagMillis: number;
242
+ did?: string;
243
+ encrypted?: boolean;
244
+ }
245
+ interface ReplicationPolicy {
246
+ id: string;
247
+ name: string;
248
+ replicationFactor: number;
249
+ consistencyLevel: 'eventual' | 'read-after-write' | 'strong';
250
+ syncInterval: number;
251
+ maxReplicationLag: number;
252
+ encryptionMode?: AeonEncryptionMode;
253
+ requiredCapabilities?: string[];
254
+ }
255
+ interface ReplicationEvent {
256
+ type: 'replica-added' | 'replica-removed' | 'replica-synced' | 'sync-failed';
257
+ replicaId: string;
258
+ nodeId: string;
259
+ timestamp: string;
260
+ details?: unknown;
261
+ }
262
+ /**
263
+ * Encrypted replication data envelope
264
+ */
265
+ interface EncryptedReplicationData {
266
+ /** Encrypted ciphertext (base64) */
267
+ ct: string;
268
+ /** Initialization vector (base64) */
269
+ iv: string;
270
+ /** Authentication tag (base64) */
271
+ tag: string;
272
+ /** Ephemeral public key for ECIES */
273
+ epk?: JsonWebKey;
274
+ /** Sender DID */
275
+ senderDID?: string;
276
+ /** Target replica DID */
277
+ targetDID?: string;
278
+ /** Encryption timestamp */
279
+ encryptedAt: number;
280
+ }
281
+ interface ReplicationPersistenceData {
282
+ replicas: Replica[];
283
+ policies: ReplicationPolicy[];
284
+ syncStatus: Array<{
285
+ nodeId: string;
286
+ synced: number;
287
+ failed: number;
288
+ }>;
289
+ }
290
+ interface ReplicationPersistenceConfig {
291
+ adapter: StorageAdapter;
292
+ key?: string;
293
+ autoPersist?: boolean;
294
+ autoLoad?: boolean;
295
+ persistDebounceMs?: number;
296
+ serializer?: PersistenceSerializer<ReplicationPersistenceData>;
297
+ deserializer?: PersistenceDeserializer<ReplicationPersistenceData>;
298
+ }
299
+ interface ReplicationManagerOptions {
300
+ persistence?: ReplicationPersistenceConfig;
301
+ }
302
+ /**
303
+ * Replication Manager
304
+ * Manages data replication across distributed nodes
305
+ */
306
+ declare class ReplicationManager {
307
+ private static readonly DEFAULT_PERSIST_KEY;
308
+ private replicas;
309
+ private policies;
310
+ private replicationEvents;
311
+ private syncStatus;
312
+ private cryptoProvider;
313
+ private replicasByDID;
314
+ private persistence;
315
+ private persistTimer;
316
+ private persistInFlight;
317
+ private persistPending;
318
+ constructor(options?: ReplicationManagerOptions);
319
+ /**
320
+ * Configure cryptographic provider for encrypted replication
321
+ */
322
+ configureCrypto(provider: ICryptoProvider): void;
323
+ /**
324
+ * Check if crypto is configured
325
+ */
326
+ isCryptoEnabled(): boolean;
327
+ /**
328
+ * Register an authenticated replica with DID
329
+ */
330
+ registerAuthenticatedReplica(replica: Omit<Replica, 'did' | 'encrypted'> & {
331
+ did: string;
332
+ publicSigningKey?: JsonWebKey;
333
+ publicEncryptionKey?: JsonWebKey;
334
+ }, encrypted?: boolean): Promise<Replica>;
335
+ /**
336
+ * Get replica by DID
337
+ */
338
+ getReplicaByDID(did: string): Replica | undefined;
339
+ /**
340
+ * Get all encrypted replicas
341
+ */
342
+ getEncryptedReplicas(): Replica[];
343
+ /**
344
+ * Encrypt data for replication to a specific replica
345
+ */
346
+ encryptForReplica(data: unknown, targetReplicaDID: string): Promise<EncryptedReplicationData>;
347
+ /**
348
+ * Decrypt data received from replication
349
+ */
350
+ decryptReplicationData<T>(encrypted: EncryptedReplicationData): Promise<T>;
351
+ /**
352
+ * Create an encrypted replication policy
353
+ */
354
+ createEncryptedPolicy(name: string, replicationFactor: number, consistencyLevel: 'eventual' | 'read-after-write' | 'strong', encryptionMode: AeonEncryptionMode, options?: {
355
+ syncInterval?: number;
356
+ maxReplicationLag?: number;
357
+ requiredCapabilities?: string[];
358
+ }): ReplicationPolicy;
359
+ /**
360
+ * Verify a replica's capabilities via UCAN
361
+ */
362
+ verifyReplicaCapabilities(replicaDID: string, token: string, policyId?: string): Promise<{
363
+ authorized: boolean;
364
+ error?: string;
365
+ }>;
366
+ /**
367
+ * Register a replica
368
+ */
369
+ registerReplica(replica: Replica): void;
370
+ /**
371
+ * Remove a replica
372
+ */
373
+ removeReplica(replicaId: string): void;
374
+ /**
375
+ * Create a replication policy
376
+ */
377
+ createPolicy(name: string, replicationFactor: number, consistencyLevel: 'eventual' | 'read-after-write' | 'strong', syncInterval?: number, maxReplicationLag?: number): ReplicationPolicy;
378
+ /**
379
+ * Update replica status
380
+ */
381
+ updateReplicaStatus(replicaId: string, status: Replica['status'], lagBytes?: number, lagMillis?: number): void;
382
+ /**
383
+ * Get replicas for node
384
+ */
385
+ getReplicasForNode(nodeId: string): Replica[];
386
+ /**
387
+ * Get healthy replicas
388
+ */
389
+ getHealthyReplicas(): Replica[];
390
+ /**
391
+ * Get syncing replicas
392
+ */
393
+ getSyncingReplicas(): Replica[];
394
+ /**
395
+ * Get failed replicas
396
+ */
397
+ getFailedReplicas(): Replica[];
398
+ /**
399
+ * Check replication health for policy
400
+ */
401
+ checkReplicationHealth(policyId: string): {
402
+ healthy: boolean;
403
+ replicasInPolicy: number;
404
+ healthyReplicas: number;
405
+ replicationLag: number;
406
+ };
407
+ /**
408
+ * Get consistency level
409
+ */
410
+ getConsistencyLevel(policyId: string): 'eventual' | 'read-after-write' | 'strong';
411
+ /**
412
+ * Get replica
413
+ */
414
+ getReplica(replicaId: string): Replica | undefined;
415
+ /**
416
+ * Get all replicas
417
+ */
418
+ getAllReplicas(): Replica[];
419
+ /**
420
+ * Get policy
421
+ */
422
+ getPolicy(policyId: string): ReplicationPolicy | undefined;
423
+ /**
424
+ * Get all policies
425
+ */
426
+ getAllPolicies(): ReplicationPolicy[];
427
+ /**
428
+ * Get replication statistics
429
+ */
430
+ getStatistics(): {
431
+ totalReplicas: number;
432
+ healthyReplicas: number;
433
+ syncingReplicas: number;
434
+ failedReplicas: number;
435
+ healthiness: number;
436
+ averageReplicationLagMs: number;
437
+ maxReplicationLagMs: number;
438
+ totalPolicies: number;
439
+ };
440
+ /**
441
+ * Get replication events
442
+ */
443
+ getReplicationEvents(limit?: number): ReplicationEvent[];
444
+ /**
445
+ * Get sync status for node
446
+ */
447
+ getSyncStatus(nodeId: string): {
448
+ synced: number;
449
+ failed: number;
450
+ };
451
+ /**
452
+ * Get replication lag distribution
453
+ */
454
+ getReplicationLagDistribution(): Record<string, number>;
455
+ /**
456
+ * Check if can satisfy consistency level
457
+ */
458
+ canSatisfyConsistency(policyId: string, _requiredAcks: number): boolean;
459
+ /**
460
+ * Persist current replication state snapshot.
461
+ */
462
+ saveToPersistence(): Promise<void>;
463
+ /**
464
+ * Load replication snapshot from persistence.
465
+ */
466
+ loadFromPersistence(): Promise<{
467
+ replicas: number;
468
+ policies: number;
469
+ syncStatus: number;
470
+ }>;
471
+ /**
472
+ * Remove persisted replication snapshot.
473
+ */
474
+ clearPersistence(): Promise<void>;
475
+ private schedulePersist;
476
+ private persistSafely;
477
+ private isValidReplica;
478
+ private isValidPolicy;
479
+ /**
480
+ * Clear all state (for testing)
481
+ */
482
+ clear(): void;
483
+ /**
484
+ * Get the crypto provider (for advanced usage)
485
+ */
486
+ getCryptoProvider(): ICryptoProvider | null;
487
+ }
488
+
489
+ /**
490
+ * Sync Protocol
491
+ *
492
+ * Handles synchronization protocol messages and handshaking.
493
+ * Manages message serialization, protocol versioning, and compatibility.
494
+ *
495
+ * Features:
496
+ * - Message serialization and deserialization
497
+ * - Protocol version management
498
+ * - Handshake handling
499
+ * - Message validation and error handling
500
+ * - Protocol state machine
501
+ * - Optional cryptographic authentication and encryption
502
+ */
503
+
504
+ interface SyncMessage {
505
+ type: 'handshake' | 'sync-request' | 'sync-response' | 'ack' | 'error';
506
+ version: string;
507
+ sender: string;
508
+ receiver: string;
509
+ messageId: string;
510
+ timestamp: string;
511
+ payload?: unknown;
512
+ auth?: AuthenticatedMessageFields;
513
+ }
514
+ interface Handshake {
515
+ protocolVersion: string;
516
+ nodeId: string;
517
+ capabilities: string[];
518
+ state: 'initiating' | 'responding' | 'completed';
519
+ did?: string;
520
+ publicSigningKey?: JsonWebKey;
521
+ publicEncryptionKey?: JsonWebKey;
522
+ ucan?: string;
523
+ }
524
+ /**
525
+ * Crypto configuration for sync protocol
526
+ */
527
+ interface SyncProtocolCryptoConfig {
528
+ /** Encryption mode for messages */
529
+ encryptionMode: AeonEncryptionMode;
530
+ /** Require all messages to be signed */
531
+ requireSignatures: boolean;
532
+ /** Require UCAN capability verification */
533
+ requireCapabilities: boolean;
534
+ /** Required capabilities for sync operations */
535
+ requiredCapabilities?: Array<{
536
+ can: string;
537
+ with: string;
538
+ }>;
539
+ }
540
+ interface SyncRequest {
541
+ sessionId: string;
542
+ fromVersion: string;
543
+ toVersion: string;
544
+ filter?: Record<string, unknown>;
545
+ }
546
+ interface SyncResponse {
547
+ sessionId: string;
548
+ fromVersion: string;
549
+ toVersion: string;
550
+ data: unknown[];
551
+ hasMore: boolean;
552
+ offset: number;
553
+ }
554
+ interface ProtocolError {
555
+ code: string;
556
+ message: string;
557
+ recoverable: boolean;
558
+ }
559
+ interface SyncProtocolPersistenceData {
560
+ protocolVersion: string;
561
+ messageCounter: number;
562
+ messageQueue: SyncMessage[];
563
+ handshakes: Array<{
564
+ nodeId: string;
565
+ handshake: Handshake;
566
+ }>;
567
+ protocolErrors: Array<{
568
+ error: ProtocolError;
569
+ timestamp: string;
570
+ }>;
571
+ }
572
+ interface SyncProtocolPersistenceConfig {
573
+ adapter: StorageAdapter;
574
+ key?: string;
575
+ autoPersist?: boolean;
576
+ autoLoad?: boolean;
577
+ persistDebounceMs?: number;
578
+ serializer?: PersistenceSerializer<SyncProtocolPersistenceData>;
579
+ deserializer?: PersistenceDeserializer<SyncProtocolPersistenceData>;
580
+ }
581
+ interface SyncProtocolOptions {
582
+ persistence?: SyncProtocolPersistenceConfig;
583
+ }
584
+ /**
585
+ * Sync Protocol
586
+ * Handles synchronization protocol messages and handshaking
587
+ */
588
+ declare class SyncProtocol {
589
+ private static readonly DEFAULT_PERSIST_KEY;
590
+ private version;
591
+ private messageQueue;
592
+ private messageMap;
593
+ private handshakes;
594
+ private protocolErrors;
595
+ private messageCounter;
596
+ private cryptoProvider;
597
+ private cryptoConfig;
598
+ private persistence;
599
+ private persistTimer;
600
+ private persistInFlight;
601
+ private persistPending;
602
+ constructor(options?: SyncProtocolOptions);
603
+ /**
604
+ * Configure cryptographic provider for authenticated/encrypted messages
605
+ */
606
+ configureCrypto(provider: ICryptoProvider, config?: Partial<SyncProtocolCryptoConfig>): void;
607
+ /**
608
+ * Check if crypto is configured
609
+ */
610
+ isCryptoEnabled(): boolean;
611
+ /**
612
+ * Get crypto configuration
613
+ */
614
+ getCryptoConfig(): SyncProtocolCryptoConfig | null;
615
+ /**
616
+ * Get protocol version
617
+ */
618
+ getVersion(): string;
619
+ /**
620
+ * Create authenticated handshake message with DID and keys
621
+ */
622
+ createAuthenticatedHandshake(capabilities: string[], targetDID?: string): Promise<SyncMessage>;
623
+ /**
624
+ * Verify and process an authenticated handshake
625
+ */
626
+ verifyAuthenticatedHandshake(message: SyncMessage): Promise<{
627
+ valid: boolean;
628
+ handshake?: Handshake;
629
+ error?: string;
630
+ }>;
631
+ /**
632
+ * Sign and optionally encrypt a message payload
633
+ */
634
+ signMessage<T>(message: SyncMessage, payload: T, encrypt?: boolean): Promise<SyncMessage>;
635
+ /**
636
+ * Verify signature and optionally decrypt a message
637
+ */
638
+ verifyMessage<T>(message: SyncMessage): Promise<{
639
+ valid: boolean;
640
+ payload?: T;
641
+ error?: string;
642
+ }>;
643
+ /**
644
+ * Create handshake message
645
+ */
646
+ createHandshakeMessage(nodeId: string, capabilities: string[]): SyncMessage;
647
+ /**
648
+ * Create sync request message
649
+ */
650
+ createSyncRequestMessage(sender: string, receiver: string, sessionId: string, fromVersion: string, toVersion: string, filter?: Record<string, unknown>): SyncMessage;
651
+ /**
652
+ * Create sync response message
653
+ */
654
+ createSyncResponseMessage(sender: string, receiver: string, sessionId: string, fromVersion: string, toVersion: string, data: unknown[], hasMore?: boolean, offset?: number): SyncMessage;
655
+ /**
656
+ * Create acknowledgement message
657
+ */
658
+ createAckMessage(sender: string, receiver: string, messageId: string): SyncMessage;
659
+ /**
660
+ * Create error message
661
+ */
662
+ createErrorMessage(sender: string, receiver: string, error: ProtocolError, relatedMessageId?: string): SyncMessage;
663
+ /**
664
+ * Validate message
665
+ */
666
+ validateMessage(message: SyncMessage): {
667
+ valid: boolean;
668
+ errors: string[];
669
+ };
670
+ /**
671
+ * Serialize message
672
+ */
673
+ serializeMessage(message: SyncMessage): string;
674
+ /**
675
+ * Deserialize message
676
+ */
677
+ deserializeMessage(data: string): SyncMessage;
678
+ /**
679
+ * Process handshake
680
+ */
681
+ processHandshake(message: SyncMessage): Handshake;
682
+ /**
683
+ * Get message
684
+ */
685
+ getMessage(messageId: string): SyncMessage | undefined;
686
+ /**
687
+ * Get all messages
688
+ */
689
+ getAllMessages(): SyncMessage[];
690
+ /**
691
+ * Get messages by type
692
+ */
693
+ getMessagesByType(type: SyncMessage['type']): SyncMessage[];
694
+ /**
695
+ * Get messages from sender
696
+ */
697
+ getMessagesFromSender(sender: string): SyncMessage[];
698
+ /**
699
+ * Get pending messages
700
+ */
701
+ getPendingMessages(receiver: string): SyncMessage[];
702
+ /**
703
+ * Get handshakes
704
+ */
705
+ getHandshakes(): Map<string, Handshake>;
706
+ /**
707
+ * Get protocol statistics
708
+ */
709
+ getStatistics(): {
710
+ totalMessages: number;
711
+ messagesByType: Record<string, number>;
712
+ totalHandshakes: number;
713
+ totalErrors: number;
714
+ recoverableErrors: number;
715
+ unrecoverableErrors: number;
716
+ };
717
+ /**
718
+ * Get protocol errors
719
+ */
720
+ getErrors(): Array<{
721
+ error: ProtocolError;
722
+ timestamp: string;
723
+ }>;
724
+ /**
725
+ * Persist protocol state for reconnect/replay.
726
+ */
727
+ saveToPersistence(): Promise<void>;
728
+ /**
729
+ * Load protocol state from persistence.
730
+ */
731
+ loadFromPersistence(): Promise<{
732
+ messages: number;
733
+ handshakes: number;
734
+ errors: number;
735
+ }>;
736
+ /**
737
+ * Clear persisted protocol checkpoint.
738
+ */
739
+ clearPersistence(): Promise<void>;
740
+ private schedulePersist;
741
+ private persistSafely;
742
+ private isValidHandshake;
743
+ private isValidProtocolErrorEntry;
744
+ /**
745
+ * Generate message ID
746
+ */
747
+ private generateMessageId;
748
+ /**
749
+ * Clear all state (for testing)
750
+ */
751
+ clear(): void;
752
+ /**
753
+ * Get the crypto provider (for advanced usage)
754
+ */
755
+ getCryptoProvider(): ICryptoProvider | null;
756
+ }
757
+
758
+ /**
759
+ * State Reconciler
760
+ *
761
+ * Reconciles conflicting state across multiple nodes in a distributed system.
762
+ * Applies merge strategies and resolves divergent state.
763
+ *
764
+ * Features:
765
+ * - State comparison and diff generation
766
+ * - Multiple merge strategies (last-write-wins, vector-clock based, custom)
767
+ * - Conflict detection and resolution
768
+ * - State validation and verification
769
+ * - Version tracking
770
+ * - Cryptographic verification of state versions
771
+ * - Signed state for tamper detection
772
+ */
773
+
774
+ interface StateVersion {
775
+ version: string;
776
+ timestamp: string;
777
+ nodeId: string;
778
+ hash: string;
779
+ data: unknown;
780
+ signerDID?: string;
781
+ signature?: string;
782
+ signedAt?: number;
783
+ }
784
+ interface StateDiff {
785
+ added: Record<string, unknown>;
786
+ modified: Record<string, {
787
+ old: unknown;
788
+ new: unknown;
789
+ }>;
790
+ removed: string[];
791
+ timestamp: string;
792
+ }
793
+ interface ReconciliationResult {
794
+ success: boolean;
795
+ mergedState: unknown;
796
+ conflictsResolved: number;
797
+ strategy: string;
798
+ timestamp: string;
799
+ }
800
+ type MergeStrategy = 'last-write-wins' | 'vector-clock' | 'majority-vote' | 'custom';
801
+ /**
802
+ * State Reconciler
803
+ * Reconciles state conflicts across distributed nodes
804
+ */
805
+ declare class StateReconciler {
806
+ private stateVersions;
807
+ private reconciliationHistory;
808
+ private cryptoProvider;
809
+ private requireSignedVersions;
810
+ /**
811
+ * Configure cryptographic provider for signed state versions
812
+ */
813
+ configureCrypto(provider: ICryptoProvider, requireSigned?: boolean): void;
814
+ /**
815
+ * Check if crypto is configured
816
+ */
817
+ isCryptoEnabled(): boolean;
818
+ /**
819
+ * Record a signed state version with cryptographic verification
820
+ */
821
+ recordSignedStateVersion(key: string, version: string, data: unknown): Promise<StateVersion>;
822
+ /**
823
+ * Verify a state version's signature
824
+ */
825
+ verifyStateVersion(version: StateVersion): Promise<{
826
+ valid: boolean;
827
+ error?: string;
828
+ }>;
829
+ /**
830
+ * Reconcile with verification - only accept verified versions
831
+ */
832
+ reconcileWithVerification(key: string, strategy?: MergeStrategy): Promise<ReconciliationResult & {
833
+ verificationErrors: string[];
834
+ }>;
835
+ /**
836
+ * Record a state version
837
+ */
838
+ recordStateVersion(key: string, version: string, timestamp: string, nodeId: string, hash: string, data: unknown): void;
839
+ /**
840
+ * Detect conflicts in state versions
841
+ */
842
+ detectConflicts(key: string): boolean;
843
+ /**
844
+ * Compare two states and generate diff
845
+ */
846
+ compareStates(state1: Record<string, unknown>, state2: Record<string, unknown>): StateDiff;
847
+ /**
848
+ * Reconcile states using last-write-wins strategy
849
+ */
850
+ reconcileLastWriteWins(versions: StateVersion[]): ReconciliationResult;
851
+ /**
852
+ * Reconcile states using vector clock strategy
853
+ */
854
+ reconcileVectorClock(versions: StateVersion[]): ReconciliationResult;
855
+ /**
856
+ * Reconcile states using majority vote strategy
857
+ */
858
+ reconcileMajorityVote(versions: StateVersion[]): ReconciliationResult;
859
+ /**
860
+ * Merge multiple states
861
+ */
862
+ mergeStates(states: Record<string, unknown>[]): unknown;
863
+ /**
864
+ * Validate state after reconciliation
865
+ */
866
+ validateState(state: unknown): {
867
+ valid: boolean;
868
+ errors: string[];
869
+ };
870
+ /**
871
+ * Get state versions for a key
872
+ */
873
+ getStateVersions(key: string): StateVersion[];
874
+ /**
875
+ * Get all state versions
876
+ */
877
+ getAllStateVersions(): Record<string, StateVersion[]>;
878
+ /**
879
+ * Get reconciliation history
880
+ */
881
+ getReconciliationHistory(): ReconciliationResult[];
882
+ /**
883
+ * Get reconciliation statistics
884
+ */
885
+ getStatistics(): {
886
+ totalReconciliations: number;
887
+ successfulReconciliations: number;
888
+ totalConflictsResolved: number;
889
+ averageConflictsPerReconciliation: number;
890
+ strategyUsage: Record<string, number>;
891
+ trackedKeys: number;
892
+ };
893
+ /**
894
+ * Clear all state (for testing)
895
+ */
896
+ clear(): void;
897
+ /**
898
+ * Get the crypto provider (for advanced usage)
899
+ */
900
+ getCryptoProvider(): ICryptoProvider | null;
901
+ }
902
+
903
+ type RecoveryShardRole = 'data' | 'parity';
904
+ type RecoveryPathStatus = 'succeeded' | 'failed';
905
+ interface RecoveryLedgerConfig {
906
+ readonly objectId: string;
907
+ readonly dataShardCount: number;
908
+ readonly parityShardCount?: number;
909
+ readonly recoveryThreshold?: number;
910
+ }
911
+ interface RecoveryPathObservation {
912
+ readonly pathId: string;
913
+ readonly status: RecoveryPathStatus;
914
+ readonly requestIds: readonly string[];
915
+ readonly observedBy: readonly string[];
916
+ readonly reasons: readonly string[];
917
+ readonly firstObservedAt: number;
918
+ readonly lastObservedAt: number;
919
+ }
920
+ interface RecoveryShardObservation {
921
+ readonly shardRole: RecoveryShardRole;
922
+ readonly shardIndex: number;
923
+ readonly digests: readonly string[];
924
+ readonly requestIds: readonly string[];
925
+ readonly observedBy: readonly string[];
926
+ readonly sources: readonly string[];
927
+ readonly firstObservedAt: number;
928
+ readonly lastObservedAt: number;
929
+ }
930
+ interface RecoveryLedgerSnapshot {
931
+ readonly objectId: string;
932
+ readonly dataShardCount: number;
933
+ readonly parityShardCount: number;
934
+ readonly recoveryThreshold: number;
935
+ readonly requestIds: readonly string[];
936
+ readonly shards: readonly RecoveryShardObservation[];
937
+ readonly paths: readonly RecoveryPathObservation[];
938
+ }
939
+ interface RecordShardObservationInput {
940
+ readonly shardRole: RecoveryShardRole;
941
+ readonly shardIndex: number;
942
+ readonly digest: string;
943
+ readonly requestId?: string;
944
+ readonly observedBy?: string;
945
+ readonly source?: string;
946
+ readonly observedAt?: number;
947
+ }
948
+ interface RecordPathObservationInput {
949
+ readonly pathId: string;
950
+ readonly status: RecoveryPathStatus;
951
+ readonly requestId?: string;
952
+ readonly observedBy?: string;
953
+ readonly reason?: string;
954
+ readonly observedAt?: number;
955
+ }
956
+ interface RecoveryConflict {
957
+ readonly shardRole: RecoveryShardRole;
958
+ readonly shardIndex: number;
959
+ readonly digests: readonly string[];
960
+ }
961
+ interface RecoveryStatus {
962
+ readonly objectId: string;
963
+ readonly requestIds: readonly string[];
964
+ readonly dataShardCount: number;
965
+ readonly parityShardCount: number;
966
+ readonly recoveryThreshold: number;
967
+ readonly availableDataShards: readonly number[];
968
+ readonly availableParityShards: readonly number[];
969
+ readonly missingDataShards: readonly number[];
970
+ readonly uniqueShardUnits: number;
971
+ readonly directDataComplete: boolean;
972
+ readonly canReconstruct: boolean;
973
+ readonly needsParityDecode: boolean;
974
+ readonly conflictingShards: readonly RecoveryConflict[];
975
+ readonly failedPaths: readonly string[];
976
+ readonly succeededPaths: readonly string[];
977
+ }
978
+ declare class RecoveryLedger {
979
+ private readonly objectId;
980
+ private readonly dataShardCount;
981
+ private readonly parityShardCount;
982
+ private readonly recoveryThreshold;
983
+ private readonly requestIds;
984
+ private readonly shards;
985
+ private readonly paths;
986
+ constructor(config: RecoveryLedgerConfig | RecoveryLedgerSnapshot);
987
+ static fromSnapshot(snapshot: RecoveryLedgerSnapshot): RecoveryLedger;
988
+ getObjectId(): string;
989
+ registerRequest(requestId: string): this;
990
+ recordShardObservation(input: RecordShardObservationInput): this;
991
+ recordPathObservation(input: RecordPathObservationInput): this;
992
+ merge(other: RecoveryLedger | RecoveryLedgerSnapshot): this;
993
+ getStatus(): RecoveryStatus;
994
+ snapshot(): RecoveryLedgerSnapshot;
995
+ private mergeShard;
996
+ private mergePath;
997
+ private getAvailableShardIndices;
998
+ private getMissingDataShardIndices;
999
+ private getPathsByStatus;
1000
+ private getConflicts;
1001
+ private assertCompatibleSnapshot;
1002
+ private assertShardIndex;
1003
+ }
1004
+
1005
+ export { type Handshake, type MergeStrategy, type ProtocolError, type ReconciliationResult, type RecordPathObservationInput, type RecordShardObservationInput, type RecoveryConflict, RecoveryLedger, type RecoveryLedgerConfig, type RecoveryLedgerSnapshot, type RecoveryPathObservation, type RecoveryPathStatus, type RecoveryShardObservation, type RecoveryShardRole, type RecoveryStatus, type Replica, type ReplicationEvent, ReplicationManager, type ReplicationManagerOptions, type ReplicationPersistenceConfig, type ReplicationPersistenceData, type ReplicationPolicy, type StateDiff, StateReconciler, type StateVersion, SyncCoordinator, type SyncEvent, type SyncMessage, type SyncNode, SyncProtocol, type SyncProtocolOptions, type SyncProtocolPersistenceConfig, type SyncProtocolPersistenceData, type SyncRequest, type SyncResponse, type SyncSession };