@lark-sh/client 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -24,6 +24,7 @@ declare class OnDisconnect {
24
24
  cancel(): Promise<void>;
25
25
  /**
26
26
  * Set a value with priority when disconnected.
27
+ * Priority is injected as `.priority` into the value object.
27
28
  */
28
29
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
29
30
  }
@@ -126,10 +127,12 @@ declare class DatabaseReference {
126
127
  push(value?: unknown): DatabaseReference | Promise<DatabaseReference>;
127
128
  /**
128
129
  * Set the data with a priority value for ordering.
130
+ * Priority is injected as `.priority` into the value object.
129
131
  */
130
132
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
131
133
  /**
132
134
  * Set the priority of the data at this location.
135
+ * Fetches current value and sets it with the new priority.
133
136
  */
134
137
  setPriority(priority: number | string): Promise<void>;
135
138
  /**
@@ -224,6 +227,12 @@ declare class DatabaseReference {
224
227
  /**
225
228
  * DataSnapshot - an immutable snapshot of data at a location.
226
229
  * Received in event callbacks and from once() operations.
230
+ *
231
+ * Priority Handling:
232
+ * - Priority is stored as a regular child value `.priority` in the data
233
+ * - val() strips `.priority` from returned objects (so app code doesn't see it)
234
+ * - getPriority() reads from the data's `.priority` field
235
+ * - This matches Firebase behavior where priority is metadata, not user data
227
236
  */
228
237
 
229
238
  declare class DataSnapshot {
@@ -231,11 +240,9 @@ declare class DataSnapshot {
231
240
  private readonly _path;
232
241
  private readonly _db;
233
242
  private readonly _volatile;
234
- private readonly _priority;
235
243
  private readonly _serverTimestamp;
236
244
  constructor(data: unknown, path: string, db: LarkDatabase, options?: {
237
245
  volatile?: boolean;
238
- priority?: number | string | null;
239
246
  serverTimestamp?: number | null;
240
247
  });
241
248
  /**
@@ -247,7 +254,8 @@ declare class DataSnapshot {
247
254
  */
248
255
  get key(): string | null;
249
256
  /**
250
- * Get the raw data value.
257
+ * Get the data value, with `.priority` stripped if present.
258
+ * Priority is internal metadata and should not be visible to app code.
251
259
  */
252
260
  val(): unknown;
253
261
  /**
@@ -276,6 +284,7 @@ declare class DataSnapshot {
276
284
  forEach(callback: (child: DataSnapshot) => boolean | void): void;
277
285
  /**
278
286
  * Get the priority of the data at this location.
287
+ * Priority is stored as `.priority` in the data object.
279
288
  */
280
289
  getPriority(): number | string | null;
281
290
  /**
@@ -328,19 +337,21 @@ interface TxConditionOp {
328
337
  v: unknown;
329
338
  }
330
339
  type TxOperation = TxSetOp | TxUpdateOp | TxDeleteOp | TxConditionOp;
331
- interface MoveEntry {
332
- k: string;
333
- ak: string;
334
- }
335
340
 
336
341
  /**
337
- * SubscriptionManager - tracks active subscriptions and routes events to callbacks.
342
+ * View - represents a client's subscription to a database path.
338
343
  *
339
- * Handles the new delta-based protocol where server sends 'put' and 'patch' events.
340
- * Client generates child_added, child_changed, child_removed, child_moved events locally.
344
+ * Each View encapsulates all state for a single subscription:
345
+ * - Path and query parameters
346
+ * - Event callbacks by type
347
+ * - Ordered children (keys in sorted order, sorted by client)
348
+ * - Local cache of visible data
341
349
  *
342
- * Supports ordered queries: tracks child order from server's `k` (orderedKeys) and `ak` (afterKey)
343
- * fields, and fires child_moved when positions change via `mv` (moves) array.
350
+ * This mirrors the server's View concept, enabling:
351
+ * - Per-View caching (no shared global cache)
352
+ * - Client-side sorting (ignores server's ak/mv hints)
353
+ * - Local-first writes (future)
354
+ * - Independent reconnection per View
344
355
  */
345
356
 
346
357
  type SnapshotCallback = (snapshot: DataSnapshot, previousChildKey?: string | null) => void;
@@ -389,12 +400,18 @@ interface TransactionConditionOp {
389
400
  type TransactionOp = TransactionSetOp | TransactionUpdateOp | TransactionDeleteOp | TransactionConditionOp;
390
401
  /** Object syntax for transactions: path -> value (null = delete) */
391
402
  type TransactionObject = Record<string, unknown>;
403
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
392
404
  declare class LarkDatabase {
393
405
  private _state;
394
406
  private _auth;
395
407
  private _databaseId;
396
408
  private _coordinatorUrl;
397
409
  private _volatilePaths;
410
+ private _connectionId;
411
+ private _connectOptions;
412
+ private _intentionalDisconnect;
413
+ private _reconnectAttempt;
414
+ private _reconnectTimer;
398
415
  private ws;
399
416
  private messageQueue;
400
417
  private subscriptionManager;
@@ -402,11 +419,20 @@ declare class LarkDatabase {
402
419
  private connectCallbacks;
403
420
  private disconnectCallbacks;
404
421
  private errorCallbacks;
422
+ private reconnectingCallbacks;
405
423
  constructor();
406
424
  /**
407
425
  * Whether the database is currently connected.
408
426
  */
409
427
  get connected(): boolean;
428
+ /**
429
+ * Whether the database is currently attempting to reconnect.
430
+ */
431
+ get reconnecting(): boolean;
432
+ /**
433
+ * Current connection state.
434
+ */
435
+ get state(): ConnectionState;
410
436
  /**
411
437
  * Current auth info, or null if not connected.
412
438
  */
@@ -442,15 +468,41 @@ declare class LarkDatabase {
442
468
  * @param options - Connection options (token, anonymous, coordinator URL)
443
469
  */
444
470
  connect(databaseId: string, options?: ConnectOptions): Promise<void>;
471
+ /**
472
+ * Internal connect implementation used by both initial connect and reconnect.
473
+ */
474
+ private performConnect;
445
475
  /**
446
476
  * Disconnect from the database.
447
477
  * This triggers onDisconnect hooks on the server.
448
478
  */
449
479
  disconnect(): Promise<void>;
450
480
  /**
451
- * Clean up connection state.
481
+ * Full cleanup - clears all state including subscriptions.
482
+ * Used for intentional disconnect.
483
+ */
484
+ private cleanupFull;
485
+ /**
486
+ * Partial cleanup - preserves state needed for reconnect.
487
+ * Used for unexpected disconnect.
488
+ */
489
+ private cleanupForReconnect;
490
+ /**
491
+ * Schedule a reconnection attempt with exponential backoff.
452
492
  */
453
- private cleanup;
493
+ private scheduleReconnect;
494
+ /**
495
+ * Attempt to reconnect to the database.
496
+ */
497
+ private attemptReconnect;
498
+ /**
499
+ * Restore subscriptions and retry pending writes after reconnect.
500
+ */
501
+ private restoreAfterReconnect;
502
+ /**
503
+ * Retry all pending writes after reconnect.
504
+ */
505
+ private retryPendingWrites;
454
506
  /**
455
507
  * Get a reference to a path in the database.
456
508
  */
@@ -512,14 +564,21 @@ declare class LarkDatabase {
512
564
  * Returns an unsubscribe function.
513
565
  */
514
566
  onError(callback: (error: Error) => void): () => void;
567
+ /**
568
+ * Register a callback for when reconnection attempts begin.
569
+ * This fires when an unexpected disconnect occurs and auto-reconnect starts.
570
+ * Returns an unsubscribe function.
571
+ */
572
+ onReconnecting(callback: () => void): () => void;
515
573
  private handleMessage;
516
574
  private handleClose;
517
575
  private handleError;
518
576
  private send;
519
577
  /**
520
578
  * @internal Send a set operation.
579
+ * Note: Priority is now part of the value (as .priority), not a separate field.
521
580
  */
522
- _sendSet(path: string, value: unknown, priority?: number | string): Promise<void>;
581
+ _sendSet(path: string, value: unknown): Promise<void>;
523
582
  /**
524
583
  * @internal Send an update operation.
525
584
  */
@@ -528,10 +587,6 @@ declare class LarkDatabase {
528
587
  * @internal Send a delete operation.
529
588
  */
530
589
  _sendDelete(path: string): Promise<void>;
531
- /**
532
- * @internal Send a push operation. Returns the generated key.
533
- */
534
- _sendPush(path: string, value: unknown): Promise<string>;
535
590
  /**
536
591
  * @internal Send a once (read) operation.
537
592
  *
@@ -548,7 +603,7 @@ declare class LarkDatabase {
548
603
  /**
549
604
  * @internal Send an onDisconnect operation.
550
605
  */
551
- _sendOnDisconnect(path: string, action: string, value?: unknown, priority?: number | string): Promise<void>;
606
+ _sendOnDisconnect(path: string, action: string, value?: unknown): Promise<void>;
552
607
  /**
553
608
  * @internal Send a subscribe message to server.
554
609
  */
@@ -577,6 +632,18 @@ declare class LarkDatabase {
577
632
 
578
633
  /**
579
634
  * LarkError - custom error class for Lark operations.
635
+ *
636
+ * Standard error codes:
637
+ * - `permission_denied` - Security rules rejected operation
638
+ * - `invalid_data` - Malformed data
639
+ * - `not_found` - Path doesn't exist
640
+ * - `invalid_path` - Invalid path format
641
+ * - `timeout` - Request timed out
642
+ * - `not_connected` - Operation attempted while disconnected
643
+ * - `condition_failed` - Transaction condition check failed (CAS mismatch)
644
+ * - `max_retries_exceeded` - Optimistic transaction exceeded retry limit
645
+ * - `write_tainted` - Write rejected locally because it depended on a failed write
646
+ * - `view_recovering` - Write rejected because View is recovering from failed write
580
647
  */
581
648
  declare class LarkError extends Error {
582
649
  readonly code: string;
@@ -590,7 +657,7 @@ declare class LarkError extends Error {
590
657
  * pending writes until they are acknowledged by the server. On reconnect, pending
591
658
  * writes can be retried to ensure data consistency.
592
659
  */
593
- type WriteOperation = 'set' | 'update' | 'delete' | 'push' | 'transaction';
660
+ type WriteOperation = 'set' | 'update' | 'delete' | 'transaction';
594
661
  interface PendingWrite {
595
662
  oid: string;
596
663
  operation: WriteOperation;
@@ -675,4 +742,4 @@ declare function generatePushId(): string;
675
742
  */
676
743
  declare function isVolatilePath(path: string, patterns: string[] | null | undefined): boolean;
677
744
 
678
- export { type AuthInfo, type ConnectOptions, DataSnapshot, DatabaseReference, type EventType, LarkDatabase, LarkError, type MoveEntry, OnDisconnect, type PendingWrite, PendingWriteManager, type QueryParams, type QueryState, type SnapshotCallback$1 as SnapshotCallback, type TransactionConditionOp, type TransactionDeleteOp, type TransactionObject, type TransactionOp, type TransactionResult, type TransactionSetOp, type TransactionUpdateOp, type WriteOperation, generatePushId, isVolatilePath };
745
+ export { type AuthInfo, type ConnectOptions, DataSnapshot, DatabaseReference, type EventType, LarkDatabase, LarkError, OnDisconnect, type PendingWrite, PendingWriteManager, type QueryParams, type QueryState, type SnapshotCallback$1 as SnapshotCallback, type TransactionConditionOp, type TransactionDeleteOp, type TransactionObject, type TransactionOp, type TransactionResult, type TransactionSetOp, type TransactionUpdateOp, type WriteOperation, generatePushId, isVolatilePath };
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ declare class OnDisconnect {
24
24
  cancel(): Promise<void>;
25
25
  /**
26
26
  * Set a value with priority when disconnected.
27
+ * Priority is injected as `.priority` into the value object.
27
28
  */
28
29
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
29
30
  }
@@ -126,10 +127,12 @@ declare class DatabaseReference {
126
127
  push(value?: unknown): DatabaseReference | Promise<DatabaseReference>;
127
128
  /**
128
129
  * Set the data with a priority value for ordering.
130
+ * Priority is injected as `.priority` into the value object.
129
131
  */
130
132
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
131
133
  /**
132
134
  * Set the priority of the data at this location.
135
+ * Fetches current value and sets it with the new priority.
133
136
  */
134
137
  setPriority(priority: number | string): Promise<void>;
135
138
  /**
@@ -224,6 +227,12 @@ declare class DatabaseReference {
224
227
  /**
225
228
  * DataSnapshot - an immutable snapshot of data at a location.
226
229
  * Received in event callbacks and from once() operations.
230
+ *
231
+ * Priority Handling:
232
+ * - Priority is stored as a regular child value `.priority` in the data
233
+ * - val() strips `.priority` from returned objects (so app code doesn't see it)
234
+ * - getPriority() reads from the data's `.priority` field
235
+ * - This matches Firebase behavior where priority is metadata, not user data
227
236
  */
228
237
 
229
238
  declare class DataSnapshot {
@@ -231,11 +240,9 @@ declare class DataSnapshot {
231
240
  private readonly _path;
232
241
  private readonly _db;
233
242
  private readonly _volatile;
234
- private readonly _priority;
235
243
  private readonly _serverTimestamp;
236
244
  constructor(data: unknown, path: string, db: LarkDatabase, options?: {
237
245
  volatile?: boolean;
238
- priority?: number | string | null;
239
246
  serverTimestamp?: number | null;
240
247
  });
241
248
  /**
@@ -247,7 +254,8 @@ declare class DataSnapshot {
247
254
  */
248
255
  get key(): string | null;
249
256
  /**
250
- * Get the raw data value.
257
+ * Get the data value, with `.priority` stripped if present.
258
+ * Priority is internal metadata and should not be visible to app code.
251
259
  */
252
260
  val(): unknown;
253
261
  /**
@@ -276,6 +284,7 @@ declare class DataSnapshot {
276
284
  forEach(callback: (child: DataSnapshot) => boolean | void): void;
277
285
  /**
278
286
  * Get the priority of the data at this location.
287
+ * Priority is stored as `.priority` in the data object.
279
288
  */
280
289
  getPriority(): number | string | null;
281
290
  /**
@@ -328,19 +337,21 @@ interface TxConditionOp {
328
337
  v: unknown;
329
338
  }
330
339
  type TxOperation = TxSetOp | TxUpdateOp | TxDeleteOp | TxConditionOp;
331
- interface MoveEntry {
332
- k: string;
333
- ak: string;
334
- }
335
340
 
336
341
  /**
337
- * SubscriptionManager - tracks active subscriptions and routes events to callbacks.
342
+ * View - represents a client's subscription to a database path.
338
343
  *
339
- * Handles the new delta-based protocol where server sends 'put' and 'patch' events.
340
- * Client generates child_added, child_changed, child_removed, child_moved events locally.
344
+ * Each View encapsulates all state for a single subscription:
345
+ * - Path and query parameters
346
+ * - Event callbacks by type
347
+ * - Ordered children (keys in sorted order, sorted by client)
348
+ * - Local cache of visible data
341
349
  *
342
- * Supports ordered queries: tracks child order from server's `k` (orderedKeys) and `ak` (afterKey)
343
- * fields, and fires child_moved when positions change via `mv` (moves) array.
350
+ * This mirrors the server's View concept, enabling:
351
+ * - Per-View caching (no shared global cache)
352
+ * - Client-side sorting (ignores server's ak/mv hints)
353
+ * - Local-first writes (future)
354
+ * - Independent reconnection per View
344
355
  */
345
356
 
346
357
  type SnapshotCallback = (snapshot: DataSnapshot, previousChildKey?: string | null) => void;
@@ -389,12 +400,18 @@ interface TransactionConditionOp {
389
400
  type TransactionOp = TransactionSetOp | TransactionUpdateOp | TransactionDeleteOp | TransactionConditionOp;
390
401
  /** Object syntax for transactions: path -> value (null = delete) */
391
402
  type TransactionObject = Record<string, unknown>;
403
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
392
404
  declare class LarkDatabase {
393
405
  private _state;
394
406
  private _auth;
395
407
  private _databaseId;
396
408
  private _coordinatorUrl;
397
409
  private _volatilePaths;
410
+ private _connectionId;
411
+ private _connectOptions;
412
+ private _intentionalDisconnect;
413
+ private _reconnectAttempt;
414
+ private _reconnectTimer;
398
415
  private ws;
399
416
  private messageQueue;
400
417
  private subscriptionManager;
@@ -402,11 +419,20 @@ declare class LarkDatabase {
402
419
  private connectCallbacks;
403
420
  private disconnectCallbacks;
404
421
  private errorCallbacks;
422
+ private reconnectingCallbacks;
405
423
  constructor();
406
424
  /**
407
425
  * Whether the database is currently connected.
408
426
  */
409
427
  get connected(): boolean;
428
+ /**
429
+ * Whether the database is currently attempting to reconnect.
430
+ */
431
+ get reconnecting(): boolean;
432
+ /**
433
+ * Current connection state.
434
+ */
435
+ get state(): ConnectionState;
410
436
  /**
411
437
  * Current auth info, or null if not connected.
412
438
  */
@@ -442,15 +468,41 @@ declare class LarkDatabase {
442
468
  * @param options - Connection options (token, anonymous, coordinator URL)
443
469
  */
444
470
  connect(databaseId: string, options?: ConnectOptions): Promise<void>;
471
+ /**
472
+ * Internal connect implementation used by both initial connect and reconnect.
473
+ */
474
+ private performConnect;
445
475
  /**
446
476
  * Disconnect from the database.
447
477
  * This triggers onDisconnect hooks on the server.
448
478
  */
449
479
  disconnect(): Promise<void>;
450
480
  /**
451
- * Clean up connection state.
481
+ * Full cleanup - clears all state including subscriptions.
482
+ * Used for intentional disconnect.
483
+ */
484
+ private cleanupFull;
485
+ /**
486
+ * Partial cleanup - preserves state needed for reconnect.
487
+ * Used for unexpected disconnect.
488
+ */
489
+ private cleanupForReconnect;
490
+ /**
491
+ * Schedule a reconnection attempt with exponential backoff.
452
492
  */
453
- private cleanup;
493
+ private scheduleReconnect;
494
+ /**
495
+ * Attempt to reconnect to the database.
496
+ */
497
+ private attemptReconnect;
498
+ /**
499
+ * Restore subscriptions and retry pending writes after reconnect.
500
+ */
501
+ private restoreAfterReconnect;
502
+ /**
503
+ * Retry all pending writes after reconnect.
504
+ */
505
+ private retryPendingWrites;
454
506
  /**
455
507
  * Get a reference to a path in the database.
456
508
  */
@@ -512,14 +564,21 @@ declare class LarkDatabase {
512
564
  * Returns an unsubscribe function.
513
565
  */
514
566
  onError(callback: (error: Error) => void): () => void;
567
+ /**
568
+ * Register a callback for when reconnection attempts begin.
569
+ * This fires when an unexpected disconnect occurs and auto-reconnect starts.
570
+ * Returns an unsubscribe function.
571
+ */
572
+ onReconnecting(callback: () => void): () => void;
515
573
  private handleMessage;
516
574
  private handleClose;
517
575
  private handleError;
518
576
  private send;
519
577
  /**
520
578
  * @internal Send a set operation.
579
+ * Note: Priority is now part of the value (as .priority), not a separate field.
521
580
  */
522
- _sendSet(path: string, value: unknown, priority?: number | string): Promise<void>;
581
+ _sendSet(path: string, value: unknown): Promise<void>;
523
582
  /**
524
583
  * @internal Send an update operation.
525
584
  */
@@ -528,10 +587,6 @@ declare class LarkDatabase {
528
587
  * @internal Send a delete operation.
529
588
  */
530
589
  _sendDelete(path: string): Promise<void>;
531
- /**
532
- * @internal Send a push operation. Returns the generated key.
533
- */
534
- _sendPush(path: string, value: unknown): Promise<string>;
535
590
  /**
536
591
  * @internal Send a once (read) operation.
537
592
  *
@@ -548,7 +603,7 @@ declare class LarkDatabase {
548
603
  /**
549
604
  * @internal Send an onDisconnect operation.
550
605
  */
551
- _sendOnDisconnect(path: string, action: string, value?: unknown, priority?: number | string): Promise<void>;
606
+ _sendOnDisconnect(path: string, action: string, value?: unknown): Promise<void>;
552
607
  /**
553
608
  * @internal Send a subscribe message to server.
554
609
  */
@@ -577,6 +632,18 @@ declare class LarkDatabase {
577
632
 
578
633
  /**
579
634
  * LarkError - custom error class for Lark operations.
635
+ *
636
+ * Standard error codes:
637
+ * - `permission_denied` - Security rules rejected operation
638
+ * - `invalid_data` - Malformed data
639
+ * - `not_found` - Path doesn't exist
640
+ * - `invalid_path` - Invalid path format
641
+ * - `timeout` - Request timed out
642
+ * - `not_connected` - Operation attempted while disconnected
643
+ * - `condition_failed` - Transaction condition check failed (CAS mismatch)
644
+ * - `max_retries_exceeded` - Optimistic transaction exceeded retry limit
645
+ * - `write_tainted` - Write rejected locally because it depended on a failed write
646
+ * - `view_recovering` - Write rejected because View is recovering from failed write
580
647
  */
581
648
  declare class LarkError extends Error {
582
649
  readonly code: string;
@@ -590,7 +657,7 @@ declare class LarkError extends Error {
590
657
  * pending writes until they are acknowledged by the server. On reconnect, pending
591
658
  * writes can be retried to ensure data consistency.
592
659
  */
593
- type WriteOperation = 'set' | 'update' | 'delete' | 'push' | 'transaction';
660
+ type WriteOperation = 'set' | 'update' | 'delete' | 'transaction';
594
661
  interface PendingWrite {
595
662
  oid: string;
596
663
  operation: WriteOperation;
@@ -675,4 +742,4 @@ declare function generatePushId(): string;
675
742
  */
676
743
  declare function isVolatilePath(path: string, patterns: string[] | null | undefined): boolean;
677
744
 
678
- export { type AuthInfo, type ConnectOptions, DataSnapshot, DatabaseReference, type EventType, LarkDatabase, LarkError, type MoveEntry, OnDisconnect, type PendingWrite, PendingWriteManager, type QueryParams, type QueryState, type SnapshotCallback$1 as SnapshotCallback, type TransactionConditionOp, type TransactionDeleteOp, type TransactionObject, type TransactionOp, type TransactionResult, type TransactionSetOp, type TransactionUpdateOp, type WriteOperation, generatePushId, isVolatilePath };
745
+ export { type AuthInfo, type ConnectOptions, DataSnapshot, DatabaseReference, type EventType, LarkDatabase, LarkError, OnDisconnect, type PendingWrite, PendingWriteManager, type QueryParams, type QueryState, type SnapshotCallback$1 as SnapshotCallback, type TransactionConditionOp, type TransactionDeleteOp, type TransactionObject, type TransactionOp, type TransactionResult, type TransactionSetOp, type TransactionUpdateOp, type WriteOperation, generatePushId, isVolatilePath };