@spacelr/sdk 0.10.11 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -372,6 +372,12 @@ interface UploadProgress {
372
372
  }
373
373
 
374
374
  type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
375
+ /**
376
+ * Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
377
+ * A transient refresh failure (network/transport OR a 5xx) is NOT reported
378
+ * (#759/#762).
379
+ * See the `onAuthLost` JSDoc in `client.ts` for the full contract.
380
+ */
375
381
  type AuthLostReason = 'refresh-failed' | 'unauthorized';
376
382
  type TokenRefreshedListener = (tokens: StoredTokens) => void;
377
383
  type AuthLostListener = (reason: AuthLostReason) => void;
@@ -384,6 +390,7 @@ declare class TokenManager {
384
390
  private tokenRefreshedListeners;
385
391
  private authLostListeners;
386
392
  private authLostEmitted;
393
+ private pendingClear;
387
394
  constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
388
395
  setRefreshCallback(callback: RefreshCallback): void;
389
396
  getAccessToken(): Promise<string | null>;
@@ -398,9 +405,52 @@ declare class TokenManager {
398
405
  * rather than an exception that would get wrapped as a network error.
399
406
  */
400
407
  forceRefresh(): Promise<string | null>;
408
+ /**
409
+ * Whether the stored session currently carries a refresh token. Used by the
410
+ * 401-recovery path to decide whether a refresh was even possible, so it can
411
+ * let `doRefresh` own the auth-loss classification instead of second-guessing
412
+ * it. A rejecting storage backend reads as "no refresh token".
413
+ */
414
+ hasRefreshToken(): Promise<boolean>;
401
415
  onTokenRefreshed(listener: TokenRefreshedListener): () => void;
402
416
  onAuthLost(listener: AuthLostListener): () => void;
403
417
  emitAuthLost(reason: AuthLostReason): void;
418
+ private dispatchAuthLost;
419
+ /**
420
+ * Handle a server-confirmed auth loss: drop the dead session, THEN notify.
421
+ *
422
+ * The stored tokens are cleared **before** listeners run (#759) so that a
423
+ * reload lands on the login screen and `hasStoredSession()` reads false — and,
424
+ * critically, so a listener that re-logs-in via `setTokens()` (synchronously
425
+ * OR after an await) writes its new session strictly AFTER the clear and can
426
+ * never be erased by it. The clear is a storage-only wipe: we do NOT reset
427
+ * `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
428
+ * this lost session. A rejecting storage backend is swallowed — best-effort,
429
+ * the consumer is routed to logout regardless. `refreshPromise` is left to
430
+ * `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
431
+ * refresh.
432
+ *
433
+ * The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
434
+ * via `refreshPromise`) on a server-confirmed refresh rejection, and from
435
+ * `HttpClient` only when a 401 could not be refreshed AND no refresh was even
436
+ * attempted (no refresh token) — these are mutually exclusive, so there is
437
+ * exactly one clear per loss and it runs BEFORE any listener. A re-login a
438
+ * listener performs is therefore never erased.
439
+ */
440
+ notifyAuthLost(reason: AuthLostReason): Promise<void>;
441
+ /**
442
+ * A refresh failure that is transient (retryable), not a server-confirmed auth
443
+ * loss — so it must NOT eject a local-first app; the next request retries.
444
+ * Covers:
445
+ * - a transport failure (offline, tunnel, captive portal, unreachable
446
+ * gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
447
+ * - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
448
+ * is momentarily down (#760/#762) — which is retryable infrastructure, not
449
+ * a token rejection.
450
+ * A real auth rejection (401/invalid_grant) or any other non-5xx server error
451
+ * is NOT transient and is treated as a server-confirmed loss.
452
+ */
453
+ private isTransientTransportError;
404
454
  private isTokenExpired;
405
455
  private shouldRefresh;
406
456
  private tryRefresh;
@@ -454,8 +504,16 @@ declare class HttpClient {
454
504
  * caller should retry with a refreshed token. 403 is never routed here —
455
505
  * it means "forbidden for this action" and must not trigger logout.
456
506
  *
457
- * `emitAuthLost('unauthorized')` is deduped inside TokenManager, so it's a
458
- * no-op if `executeRefresh` already emitted 'refresh-failed'.
507
+ * Auth-loss ownership (#759 review):
508
+ * - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
509
+ * the outcome: it clears + emits on a server-confirmed rejection, and stays
510
+ * silent on a transient transport failure. We must not second-guess it, so
511
+ * we do NOT emit here — that avoids a double clear/emit and stops a transient
512
+ * blip during a 401 retry from ejecting the user.
513
+ * - When no refresh was possible (no refresh token), this 401 IS the confirmed
514
+ * loss and we own it: `notifyAuthLost` clears the dead session then emits.
515
+ * The single clear always runs before any listener, so a listener that
516
+ * re-logs-in via `setTokens()` can never have its fresh session erased.
459
517
  */
460
518
  private recoverFromAuthFailure;
461
519
  private uploadFormOnce;
@@ -589,7 +647,7 @@ interface RealtimeConfig {
589
647
  */
590
648
  onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
591
649
  }
592
- type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated';
650
+ type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
593
651
  interface StreamGapInfo {
594
652
  projectId: string;
595
653
  collectionName: string;
@@ -601,6 +659,14 @@ interface StreamSubscriptionOptions {
601
659
  projectId: string;
602
660
  collectionName: string;
603
661
  sinceId?: string;
662
+ /**
663
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
664
+ * id). When set, the server keeps a durable delivery cursor for this consumer
665
+ * and RESUMES from it (overriding `sinceId`/`fromStart`), returns
666
+ * `{ generation, session, resumeCursor }`, and expects `ack-events`. Absent →
667
+ * legacy stateless behaviour.
668
+ */
669
+ consumerId?: string;
604
670
  /**
605
671
  * #685 — "replay from earliest retained". When true, a brand-new subscription
606
672
  * (no prior cursor) replays every retained stream entry from the earliest
@@ -624,7 +690,7 @@ interface StreamSubscriptionOptions {
624
690
  eventId: string;
625
691
  event: DatabaseChangeEvent;
626
692
  }) => void | Promise<void>;
627
- /** Called when the server emits an event-gap. See GapReason for the four codes. */
693
+ /** Called when the server emits an event-gap. See GapReason for the codes. */
628
694
  onGap?: (info: StreamGapInfo) => void;
629
695
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
630
696
  onError?: (error: Error) => void;
@@ -688,6 +754,10 @@ declare class RealtimeClient {
688
754
  unsubscribe: () => void;
689
755
  realtimeMode: 'pubsub' | 'stream';
690
756
  latestStreamId: string | null;
757
+ /** #768 — the durable position the server RESUMED from (null for a fresh
758
+ * consumer, or after a reset-to-'0' following eviction/log-reset/late-grant).
759
+ * Non-null ⇒ this is a resume; the caller should SKIP the snapshot. */
760
+ resumeCursor: string | null;
691
761
  }>;
692
762
  /**
693
763
  * Shared body for `subscribeWithCursor` and
@@ -794,6 +864,19 @@ declare class RealtimeClient {
794
864
  */
795
865
  private resubscribeRoom;
796
866
  private emitSubscribeEvents;
867
+ /** #768 — capture the durable fencing tokens from a successful handshake so
868
+ * `ack-events` echoes the (generation, session) the server expects. */
869
+ private captureDurableHandshake;
870
+ /**
871
+ * #768 — schedule a coalesced durable ack. Only durable subscriptions (a
872
+ * consumerId with a captured generation+session) ack. At most one ack per
873
+ * microtask drain, carrying the highest delivered seq — cumulative on the
874
+ * server, so a burst of N events costs one ack, not N.
875
+ */
876
+ private scheduleDurableAck;
877
+ /** #768 — emit `ack-events` for `seq`; a fenced/evicted response routes into
878
+ * the gap-recovery path so the caller re-snapshots (§12.5/§12.1). */
879
+ private emitDurableAck;
797
880
  private buildStreamPayload;
798
881
  private unsubscribeStream;
799
882
  private dispatchStreamEvent;
@@ -847,6 +930,28 @@ declare function memoryCursorStorage(): CursorStorage;
847
930
  */
848
931
  declare function localStorageCursorStorage(prefix?: string): CursorStorage;
849
932
 
933
+ /**
934
+ * Well-known storage key under which the SDK persists an auto-generated durable
935
+ * consumer id (one per device/app install).
936
+ */
937
+ declare const CONSUMER_ID_STORAGE_KEY = "spacelr:consumer-id";
938
+ /**
939
+ * Resolve the durable-subscription consumer id (#768 §12.2 / R7).
940
+ *
941
+ * A durable subscription's cursor is owned by a *consumer identity* — a stable
942
+ * per-device/app id — not by the user, so one device's ack never hides a row
943
+ * from another consumer of the same user.
944
+ *
945
+ * Precedence:
946
+ * 1. An explicit `consumerId` the app passes → used verbatim (the app owns
947
+ * identity, e.g. a device id it already has).
948
+ * 2. Else, if `storage` is provided, load a previously-persisted id, or generate
949
+ * one and persist it so it is stable across restarts/reconnects.
950
+ * 3. Else (no storage), an ephemeral id is generated — durable resume then only
951
+ * holds within the live session (a reload gets a new identity).
952
+ */
953
+ declare function resolveConsumerId(explicit: string | undefined, storage: CursorStorage | undefined, key?: string): Promise<string>;
954
+
850
955
  type AuthState = 'authenticated' | 'unauthenticated';
851
956
  type AuthStateListener = (state: AuthState) => void | Promise<void>;
852
957
  declare class AuthModule {
@@ -1329,6 +1434,14 @@ interface SubscribeWithSnapshotOptions<T> {
1329
1434
  * forget callback handlers don't need to also wrap the await.
1330
1435
  */
1331
1436
  onSnapshotError?: (err: Error) => void;
1437
+ /**
1438
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
1439
+ * id). When set, the server keeps a durable delivery cursor for this consumer
1440
+ * and resumes from it across reconnects; the SDK acks consumed events and, on
1441
+ * a void/reset gap, re-snapshots. Omit for legacy stateless behaviour. Use
1442
+ * `resolveConsumerId()` (exported) to auto-generate + persist one per device.
1443
+ */
1444
+ consumerId?: string;
1332
1445
  }
1333
1446
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1334
1447
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
@@ -1364,6 +1477,14 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1364
1477
  * `where` filters or per-user feeds) must persist independent cursors.
1365
1478
  */
1366
1479
  cursorKey?: string;
1480
+ /**
1481
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
1482
+ * id). When set, the server keeps a durable delivery cursor for this consumer
1483
+ * and resumes from it across reconnects; the SDK acks consumed events and, on
1484
+ * a void/reset gap, re-snapshots. Omit for legacy stateless behaviour. Use
1485
+ * `resolveConsumerId()` (exported) to auto-generate + persist one per device.
1486
+ */
1487
+ consumerId?: string;
1367
1488
  /** Called on inserts. Receives the document merged with `_eventId`. */
1368
1489
  onInsert?: (doc: T & {
1369
1490
  _id: string;
@@ -1385,7 +1506,7 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1385
1506
  * is tracked in #710. Document-bearing deletes are unaffected.
1386
1507
  */
1387
1508
  onDelete?: (documentId: string, eventId: string) => void | Promise<void>;
1388
- /** Called when the server emits an event-gap. See GapReason for the four codes. */
1509
+ /** Called when the server emits an event-gap. See GapReason for the codes. */
1389
1510
  onGap?: (info: StreamGapInfo) => void;
1390
1511
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
1391
1512
  onError?: (error: Error) => void;
@@ -1933,16 +2054,35 @@ interface SpacelrClient {
1933
2054
  /** Disconnect realtime WebSocket (if connected) */
1934
2055
  disconnect(): void;
1935
2056
  /**
1936
- * Subscribe to auth loss. Fires in three situations:
2057
+ * Subscribe to a **server-confirmed** auth loss — a genuine, durable session
2058
+ * invalidation (refresh token revoked/expired, or a 401 that no refresh could
2059
+ * recover). Fires in two situations:
1937
2060
  * - `'refresh-failed'` — a refresh call was rejected by the server
1938
2061
  * (refresh token revoked or expired). Note: this can also fire from a
1939
2062
  * *background* refresh triggered inside the expiry buffer window, at
1940
2063
  * which point the current access token may still be valid for up to
1941
2064
  * `refreshBufferSeconds` (default 60). Treat the session as over anyway;
1942
2065
  * the refresh token is dead.
1943
- * - `'unauthorized'` — an authenticated request came back 401 and no
1944
- * fresh token could be produced (no refresh token, or the retry after
1945
- * a successful refresh was itself 401).
2066
+ * - `'unauthorized'` — an authenticated request came back 401 and the
2067
+ * session genuinely cannot be recovered: there was no refresh token to
2068
+ * try, or the retry after a successful refresh was itself 401. A 401 whose
2069
+ * refresh merely failed *transiently* (network) does NOT fire this — see
2070
+ * below.
2071
+ *
2072
+ * A **transient refresh failure does NOT fire this** — the SDK keeps the
2073
+ * session and the next request retries. That covers a network/transport
2074
+ * failure (offline, tunnel, captive portal, unreachable gateway; #759) AND a
2075
+ * **5xx** server response, e.g. a `503` the gateway returns while
2076
+ * oauth-service is momentarily down (#760/#762). This lets a local-first app
2077
+ * stay signed in through an outage instead of ejecting the user. Only a
2078
+ * server-confirmed rejection (a 401/invalid_grant, or another non-5xx server
2079
+ * error) fires.
2080
+ *
2081
+ * On a confirmed loss the SDK **clears the stored tokens itself**, so
2082
+ * `hasStoredSession()` reads `false` afterwards and a reload lands on the
2083
+ * login screen — you no longer need to call `clearTokens()` from the handler.
2084
+ * A `setTokens()` issued while that wipe is in flight (e.g. an external
2085
+ * re-login racing the loss) is applied **after** the wipe and is never lost.
1946
2086
  *
1947
2087
  * Typical consumer reaction: clear UI state and show the login screen.
1948
2088
  * The event is deduped until `setTokens`/`clearTokens` is called again.
@@ -1979,4 +2119,4 @@ interface SpacelrClient {
1979
2119
  }
1980
2120
  declare function createClient(config: SpacelrClientConfig): SpacelrClient;
1981
2121
 
1982
- export { type ApiResponse, type AuthLostReason, type AuthState, type AuthStateListener, type AuthorizationUrlParams, BrowserTokenStorage, CodeChallengeMethod, type ConnectionState, CursorInvalidError, type CursorStorage, type DatabaseChangeEvent, type DownloadUrlResponse, type ExchangeCodeParams, type FileInfo, type FileListResponse, FileVisibility, ForbiddenError, type FunctionInvokeOptions, type FunctionInvokeResult, type GapReason, GrantType, type InitMultipartUploadParams, type InitMultipartUploadResponse, type JWK, type JWKSResponse, type ListFilesParams, type LoginParams, type LoginResponse, MemoryTokenStorage, NotFoundError, type OpenIDConfiguration, type PKCEChallenge, type PartEtag, type PasskeyAuthenticationOptionsJSON, type PasskeyAuthenticationResponseJSON, type PasskeyCredential, type PasskeyCredentialDescriptorJSON, type PasskeyLoginResponse, type PasskeyRegistrationOptionsJSON, type PasskeyRegistrationResponseJSON, type PasskeyRegistrationResult, type PushSubscriptionInfo, type QuotaInfo, type RegisterParams, type RegisterResponse, type Schedule, type ScheduleInvokeOptions, type ScheduleListOptions, type ScheduleStatus, type SearchOptions, ServerConfigError, type ShareFileParams, SharePermission, SpacelrAuthError, type SpacelrClient, type SpacelrClientConfig, SpacelrEmailVerificationRequiredError, SpacelrError, SpacelrNetworkError, SpacelrScanLimitExceededError, SpacelrSearchFilterRequiredError, SpacelrTimeoutError, SpacelrTwoFactorRequiredError, type StoredTokens, type StreamGapInfo, type StreamSubscription, type SubscribeEventsHandlers, type SubscribeHandlers, type SubscribeWithSnapshotOptions, type TimelineAndFilter, TimelineError, type TimelineFieldFilter, type TimelineFilter, type TimelineLeafFilter, TimelineModule, type TimelineOrderBy, type TimelineQueryOptions, type TimelineQueryResponse, type TimelineScalar, type TimelineSourceStats, TimeoutError, type TokenResponse, type TokenStorage, type TwoFactorResponse, type TwoFactorVerifyParams, type UnshareFileParams, type UploadFileParams, type UploadLargeFileParams, type UploadProgress, type UserInfo, type UserProfile, ValidationError, type VapidKeyResponse, type WhereFilter, type WhereOperator, type WhereScalar, type WhereValue, createClient, generatePKCEChallenge, localStorageCursorStorage, memoryCursorStorage };
2122
+ export { type ApiResponse, type AuthLostReason, type AuthState, type AuthStateListener, type AuthorizationUrlParams, BrowserTokenStorage, CONSUMER_ID_STORAGE_KEY, CodeChallengeMethod, type ConnectionState, CursorInvalidError, type CursorStorage, type DatabaseChangeEvent, type DownloadUrlResponse, type ExchangeCodeParams, type FileInfo, type FileListResponse, FileVisibility, ForbiddenError, type FunctionInvokeOptions, type FunctionInvokeResult, type GapReason, GrantType, type InitMultipartUploadParams, type InitMultipartUploadResponse, type JWK, type JWKSResponse, type ListFilesParams, type LoginParams, type LoginResponse, MemoryTokenStorage, NotFoundError, type OpenIDConfiguration, type PKCEChallenge, type PartEtag, type PasskeyAuthenticationOptionsJSON, type PasskeyAuthenticationResponseJSON, type PasskeyCredential, type PasskeyCredentialDescriptorJSON, type PasskeyLoginResponse, type PasskeyRegistrationOptionsJSON, type PasskeyRegistrationResponseJSON, type PasskeyRegistrationResult, type PushSubscriptionInfo, type QuotaInfo, type RegisterParams, type RegisterResponse, type Schedule, type ScheduleInvokeOptions, type ScheduleListOptions, type ScheduleStatus, type SearchOptions, ServerConfigError, type ShareFileParams, SharePermission, SpacelrAuthError, type SpacelrClient, type SpacelrClientConfig, SpacelrEmailVerificationRequiredError, SpacelrError, SpacelrNetworkError, SpacelrScanLimitExceededError, SpacelrSearchFilterRequiredError, SpacelrTimeoutError, SpacelrTwoFactorRequiredError, type StoredTokens, type StreamGapInfo, type StreamSubscription, type SubscribeEventsHandlers, type SubscribeHandlers, type SubscribeWithSnapshotOptions, type TimelineAndFilter, TimelineError, type TimelineFieldFilter, type TimelineFilter, type TimelineLeafFilter, TimelineModule, type TimelineOrderBy, type TimelineQueryOptions, type TimelineQueryResponse, type TimelineScalar, type TimelineSourceStats, TimeoutError, type TokenResponse, type TokenStorage, type TwoFactorResponse, type TwoFactorVerifyParams, type UnshareFileParams, type UploadFileParams, type UploadLargeFileParams, type UploadProgress, type UserInfo, type UserProfile, ValidationError, type VapidKeyResponse, type WhereFilter, type WhereOperator, type WhereScalar, type WhereValue, createClient, generatePKCEChallenge, localStorageCursorStorage, memoryCursorStorage, resolveConsumerId };
package/dist/index.d.ts CHANGED
@@ -372,6 +372,12 @@ interface UploadProgress {
372
372
  }
373
373
 
374
374
  type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
375
+ /**
376
+ * Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
377
+ * A transient refresh failure (network/transport OR a 5xx) is NOT reported
378
+ * (#759/#762).
379
+ * See the `onAuthLost` JSDoc in `client.ts` for the full contract.
380
+ */
375
381
  type AuthLostReason = 'refresh-failed' | 'unauthorized';
376
382
  type TokenRefreshedListener = (tokens: StoredTokens) => void;
377
383
  type AuthLostListener = (reason: AuthLostReason) => void;
@@ -384,6 +390,7 @@ declare class TokenManager {
384
390
  private tokenRefreshedListeners;
385
391
  private authLostListeners;
386
392
  private authLostEmitted;
393
+ private pendingClear;
387
394
  constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
388
395
  setRefreshCallback(callback: RefreshCallback): void;
389
396
  getAccessToken(): Promise<string | null>;
@@ -398,9 +405,52 @@ declare class TokenManager {
398
405
  * rather than an exception that would get wrapped as a network error.
399
406
  */
400
407
  forceRefresh(): Promise<string | null>;
408
+ /**
409
+ * Whether the stored session currently carries a refresh token. Used by the
410
+ * 401-recovery path to decide whether a refresh was even possible, so it can
411
+ * let `doRefresh` own the auth-loss classification instead of second-guessing
412
+ * it. A rejecting storage backend reads as "no refresh token".
413
+ */
414
+ hasRefreshToken(): Promise<boolean>;
401
415
  onTokenRefreshed(listener: TokenRefreshedListener): () => void;
402
416
  onAuthLost(listener: AuthLostListener): () => void;
403
417
  emitAuthLost(reason: AuthLostReason): void;
418
+ private dispatchAuthLost;
419
+ /**
420
+ * Handle a server-confirmed auth loss: drop the dead session, THEN notify.
421
+ *
422
+ * The stored tokens are cleared **before** listeners run (#759) so that a
423
+ * reload lands on the login screen and `hasStoredSession()` reads false — and,
424
+ * critically, so a listener that re-logs-in via `setTokens()` (synchronously
425
+ * OR after an await) writes its new session strictly AFTER the clear and can
426
+ * never be erased by it. The clear is a storage-only wipe: we do NOT reset
427
+ * `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
428
+ * this lost session. A rejecting storage backend is swallowed — best-effort,
429
+ * the consumer is routed to logout regardless. `refreshPromise` is left to
430
+ * `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
431
+ * refresh.
432
+ *
433
+ * The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
434
+ * via `refreshPromise`) on a server-confirmed refresh rejection, and from
435
+ * `HttpClient` only when a 401 could not be refreshed AND no refresh was even
436
+ * attempted (no refresh token) — these are mutually exclusive, so there is
437
+ * exactly one clear per loss and it runs BEFORE any listener. A re-login a
438
+ * listener performs is therefore never erased.
439
+ */
440
+ notifyAuthLost(reason: AuthLostReason): Promise<void>;
441
+ /**
442
+ * A refresh failure that is transient (retryable), not a server-confirmed auth
443
+ * loss — so it must NOT eject a local-first app; the next request retries.
444
+ * Covers:
445
+ * - a transport failure (offline, tunnel, captive portal, unreachable
446
+ * gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
447
+ * - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
448
+ * is momentarily down (#760/#762) — which is retryable infrastructure, not
449
+ * a token rejection.
450
+ * A real auth rejection (401/invalid_grant) or any other non-5xx server error
451
+ * is NOT transient and is treated as a server-confirmed loss.
452
+ */
453
+ private isTransientTransportError;
404
454
  private isTokenExpired;
405
455
  private shouldRefresh;
406
456
  private tryRefresh;
@@ -454,8 +504,16 @@ declare class HttpClient {
454
504
  * caller should retry with a refreshed token. 403 is never routed here —
455
505
  * it means "forbidden for this action" and must not trigger logout.
456
506
  *
457
- * `emitAuthLost('unauthorized')` is deduped inside TokenManager, so it's a
458
- * no-op if `executeRefresh` already emitted 'refresh-failed'.
507
+ * Auth-loss ownership (#759 review):
508
+ * - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
509
+ * the outcome: it clears + emits on a server-confirmed rejection, and stays
510
+ * silent on a transient transport failure. We must not second-guess it, so
511
+ * we do NOT emit here — that avoids a double clear/emit and stops a transient
512
+ * blip during a 401 retry from ejecting the user.
513
+ * - When no refresh was possible (no refresh token), this 401 IS the confirmed
514
+ * loss and we own it: `notifyAuthLost` clears the dead session then emits.
515
+ * The single clear always runs before any listener, so a listener that
516
+ * re-logs-in via `setTokens()` can never have its fresh session erased.
459
517
  */
460
518
  private recoverFromAuthFailure;
461
519
  private uploadFormOnce;
@@ -589,7 +647,7 @@ interface RealtimeConfig {
589
647
  */
590
648
  onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
591
649
  }
592
- type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated';
650
+ type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
593
651
  interface StreamGapInfo {
594
652
  projectId: string;
595
653
  collectionName: string;
@@ -601,6 +659,14 @@ interface StreamSubscriptionOptions {
601
659
  projectId: string;
602
660
  collectionName: string;
603
661
  sinceId?: string;
662
+ /**
663
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
664
+ * id). When set, the server keeps a durable delivery cursor for this consumer
665
+ * and RESUMES from it (overriding `sinceId`/`fromStart`), returns
666
+ * `{ generation, session, resumeCursor }`, and expects `ack-events`. Absent →
667
+ * legacy stateless behaviour.
668
+ */
669
+ consumerId?: string;
604
670
  /**
605
671
  * #685 — "replay from earliest retained". When true, a brand-new subscription
606
672
  * (no prior cursor) replays every retained stream entry from the earliest
@@ -624,7 +690,7 @@ interface StreamSubscriptionOptions {
624
690
  eventId: string;
625
691
  event: DatabaseChangeEvent;
626
692
  }) => void | Promise<void>;
627
- /** Called when the server emits an event-gap. See GapReason for the four codes. */
693
+ /** Called when the server emits an event-gap. See GapReason for the codes. */
628
694
  onGap?: (info: StreamGapInfo) => void;
629
695
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
630
696
  onError?: (error: Error) => void;
@@ -688,6 +754,10 @@ declare class RealtimeClient {
688
754
  unsubscribe: () => void;
689
755
  realtimeMode: 'pubsub' | 'stream';
690
756
  latestStreamId: string | null;
757
+ /** #768 — the durable position the server RESUMED from (null for a fresh
758
+ * consumer, or after a reset-to-'0' following eviction/log-reset/late-grant).
759
+ * Non-null ⇒ this is a resume; the caller should SKIP the snapshot. */
760
+ resumeCursor: string | null;
691
761
  }>;
692
762
  /**
693
763
  * Shared body for `subscribeWithCursor` and
@@ -794,6 +864,19 @@ declare class RealtimeClient {
794
864
  */
795
865
  private resubscribeRoom;
796
866
  private emitSubscribeEvents;
867
+ /** #768 — capture the durable fencing tokens from a successful handshake so
868
+ * `ack-events` echoes the (generation, session) the server expects. */
869
+ private captureDurableHandshake;
870
+ /**
871
+ * #768 — schedule a coalesced durable ack. Only durable subscriptions (a
872
+ * consumerId with a captured generation+session) ack. At most one ack per
873
+ * microtask drain, carrying the highest delivered seq — cumulative on the
874
+ * server, so a burst of N events costs one ack, not N.
875
+ */
876
+ private scheduleDurableAck;
877
+ /** #768 — emit `ack-events` for `seq`; a fenced/evicted response routes into
878
+ * the gap-recovery path so the caller re-snapshots (§12.5/§12.1). */
879
+ private emitDurableAck;
797
880
  private buildStreamPayload;
798
881
  private unsubscribeStream;
799
882
  private dispatchStreamEvent;
@@ -847,6 +930,28 @@ declare function memoryCursorStorage(): CursorStorage;
847
930
  */
848
931
  declare function localStorageCursorStorage(prefix?: string): CursorStorage;
849
932
 
933
+ /**
934
+ * Well-known storage key under which the SDK persists an auto-generated durable
935
+ * consumer id (one per device/app install).
936
+ */
937
+ declare const CONSUMER_ID_STORAGE_KEY = "spacelr:consumer-id";
938
+ /**
939
+ * Resolve the durable-subscription consumer id (#768 §12.2 / R7).
940
+ *
941
+ * A durable subscription's cursor is owned by a *consumer identity* — a stable
942
+ * per-device/app id — not by the user, so one device's ack never hides a row
943
+ * from another consumer of the same user.
944
+ *
945
+ * Precedence:
946
+ * 1. An explicit `consumerId` the app passes → used verbatim (the app owns
947
+ * identity, e.g. a device id it already has).
948
+ * 2. Else, if `storage` is provided, load a previously-persisted id, or generate
949
+ * one and persist it so it is stable across restarts/reconnects.
950
+ * 3. Else (no storage), an ephemeral id is generated — durable resume then only
951
+ * holds within the live session (a reload gets a new identity).
952
+ */
953
+ declare function resolveConsumerId(explicit: string | undefined, storage: CursorStorage | undefined, key?: string): Promise<string>;
954
+
850
955
  type AuthState = 'authenticated' | 'unauthenticated';
851
956
  type AuthStateListener = (state: AuthState) => void | Promise<void>;
852
957
  declare class AuthModule {
@@ -1329,6 +1434,14 @@ interface SubscribeWithSnapshotOptions<T> {
1329
1434
  * forget callback handlers don't need to also wrap the await.
1330
1435
  */
1331
1436
  onSnapshotError?: (err: Error) => void;
1437
+ /**
1438
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
1439
+ * id). When set, the server keeps a durable delivery cursor for this consumer
1440
+ * and resumes from it across reconnects; the SDK acks consumed events and, on
1441
+ * a void/reset gap, re-snapshots. Omit for legacy stateless behaviour. Use
1442
+ * `resolveConsumerId()` (exported) to auto-generate + persist one per device.
1443
+ */
1444
+ consumerId?: string;
1332
1445
  }
1333
1446
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1334
1447
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
@@ -1364,6 +1477,14 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1364
1477
  * `where` filters or per-user feeds) must persist independent cursors.
1365
1478
  */
1366
1479
  cursorKey?: string;
1480
+ /**
1481
+ * #768 — durable-subscription consumer identity (opaque; a stable per-device
1482
+ * id). When set, the server keeps a durable delivery cursor for this consumer
1483
+ * and resumes from it across reconnects; the SDK acks consumed events and, on
1484
+ * a void/reset gap, re-snapshots. Omit for legacy stateless behaviour. Use
1485
+ * `resolveConsumerId()` (exported) to auto-generate + persist one per device.
1486
+ */
1487
+ consumerId?: string;
1367
1488
  /** Called on inserts. Receives the document merged with `_eventId`. */
1368
1489
  onInsert?: (doc: T & {
1369
1490
  _id: string;
@@ -1385,7 +1506,7 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1385
1506
  * is tracked in #710. Document-bearing deletes are unaffected.
1386
1507
  */
1387
1508
  onDelete?: (documentId: string, eventId: string) => void | Promise<void>;
1388
- /** Called when the server emits an event-gap. See GapReason for the four codes. */
1509
+ /** Called when the server emits an event-gap. See GapReason for the codes. */
1389
1510
  onGap?: (info: StreamGapInfo) => void;
1390
1511
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
1391
1512
  onError?: (error: Error) => void;
@@ -1933,16 +2054,35 @@ interface SpacelrClient {
1933
2054
  /** Disconnect realtime WebSocket (if connected) */
1934
2055
  disconnect(): void;
1935
2056
  /**
1936
- * Subscribe to auth loss. Fires in three situations:
2057
+ * Subscribe to a **server-confirmed** auth loss — a genuine, durable session
2058
+ * invalidation (refresh token revoked/expired, or a 401 that no refresh could
2059
+ * recover). Fires in two situations:
1937
2060
  * - `'refresh-failed'` — a refresh call was rejected by the server
1938
2061
  * (refresh token revoked or expired). Note: this can also fire from a
1939
2062
  * *background* refresh triggered inside the expiry buffer window, at
1940
2063
  * which point the current access token may still be valid for up to
1941
2064
  * `refreshBufferSeconds` (default 60). Treat the session as over anyway;
1942
2065
  * the refresh token is dead.
1943
- * - `'unauthorized'` — an authenticated request came back 401 and no
1944
- * fresh token could be produced (no refresh token, or the retry after
1945
- * a successful refresh was itself 401).
2066
+ * - `'unauthorized'` — an authenticated request came back 401 and the
2067
+ * session genuinely cannot be recovered: there was no refresh token to
2068
+ * try, or the retry after a successful refresh was itself 401. A 401 whose
2069
+ * refresh merely failed *transiently* (network) does NOT fire this — see
2070
+ * below.
2071
+ *
2072
+ * A **transient refresh failure does NOT fire this** — the SDK keeps the
2073
+ * session and the next request retries. That covers a network/transport
2074
+ * failure (offline, tunnel, captive portal, unreachable gateway; #759) AND a
2075
+ * **5xx** server response, e.g. a `503` the gateway returns while
2076
+ * oauth-service is momentarily down (#760/#762). This lets a local-first app
2077
+ * stay signed in through an outage instead of ejecting the user. Only a
2078
+ * server-confirmed rejection (a 401/invalid_grant, or another non-5xx server
2079
+ * error) fires.
2080
+ *
2081
+ * On a confirmed loss the SDK **clears the stored tokens itself**, so
2082
+ * `hasStoredSession()` reads `false` afterwards and a reload lands on the
2083
+ * login screen — you no longer need to call `clearTokens()` from the handler.
2084
+ * A `setTokens()` issued while that wipe is in flight (e.g. an external
2085
+ * re-login racing the loss) is applied **after** the wipe and is never lost.
1946
2086
  *
1947
2087
  * Typical consumer reaction: clear UI state and show the login screen.
1948
2088
  * The event is deduped until `setTokens`/`clearTokens` is called again.
@@ -1979,4 +2119,4 @@ interface SpacelrClient {
1979
2119
  }
1980
2120
  declare function createClient(config: SpacelrClientConfig): SpacelrClient;
1981
2121
 
1982
- export { type ApiResponse, type AuthLostReason, type AuthState, type AuthStateListener, type AuthorizationUrlParams, BrowserTokenStorage, CodeChallengeMethod, type ConnectionState, CursorInvalidError, type CursorStorage, type DatabaseChangeEvent, type DownloadUrlResponse, type ExchangeCodeParams, type FileInfo, type FileListResponse, FileVisibility, ForbiddenError, type FunctionInvokeOptions, type FunctionInvokeResult, type GapReason, GrantType, type InitMultipartUploadParams, type InitMultipartUploadResponse, type JWK, type JWKSResponse, type ListFilesParams, type LoginParams, type LoginResponse, MemoryTokenStorage, NotFoundError, type OpenIDConfiguration, type PKCEChallenge, type PartEtag, type PasskeyAuthenticationOptionsJSON, type PasskeyAuthenticationResponseJSON, type PasskeyCredential, type PasskeyCredentialDescriptorJSON, type PasskeyLoginResponse, type PasskeyRegistrationOptionsJSON, type PasskeyRegistrationResponseJSON, type PasskeyRegistrationResult, type PushSubscriptionInfo, type QuotaInfo, type RegisterParams, type RegisterResponse, type Schedule, type ScheduleInvokeOptions, type ScheduleListOptions, type ScheduleStatus, type SearchOptions, ServerConfigError, type ShareFileParams, SharePermission, SpacelrAuthError, type SpacelrClient, type SpacelrClientConfig, SpacelrEmailVerificationRequiredError, SpacelrError, SpacelrNetworkError, SpacelrScanLimitExceededError, SpacelrSearchFilterRequiredError, SpacelrTimeoutError, SpacelrTwoFactorRequiredError, type StoredTokens, type StreamGapInfo, type StreamSubscription, type SubscribeEventsHandlers, type SubscribeHandlers, type SubscribeWithSnapshotOptions, type TimelineAndFilter, TimelineError, type TimelineFieldFilter, type TimelineFilter, type TimelineLeafFilter, TimelineModule, type TimelineOrderBy, type TimelineQueryOptions, type TimelineQueryResponse, type TimelineScalar, type TimelineSourceStats, TimeoutError, type TokenResponse, type TokenStorage, type TwoFactorResponse, type TwoFactorVerifyParams, type UnshareFileParams, type UploadFileParams, type UploadLargeFileParams, type UploadProgress, type UserInfo, type UserProfile, ValidationError, type VapidKeyResponse, type WhereFilter, type WhereOperator, type WhereScalar, type WhereValue, createClient, generatePKCEChallenge, localStorageCursorStorage, memoryCursorStorage };
2122
+ export { type ApiResponse, type AuthLostReason, type AuthState, type AuthStateListener, type AuthorizationUrlParams, BrowserTokenStorage, CONSUMER_ID_STORAGE_KEY, CodeChallengeMethod, type ConnectionState, CursorInvalidError, type CursorStorage, type DatabaseChangeEvent, type DownloadUrlResponse, type ExchangeCodeParams, type FileInfo, type FileListResponse, FileVisibility, ForbiddenError, type FunctionInvokeOptions, type FunctionInvokeResult, type GapReason, GrantType, type InitMultipartUploadParams, type InitMultipartUploadResponse, type JWK, type JWKSResponse, type ListFilesParams, type LoginParams, type LoginResponse, MemoryTokenStorage, NotFoundError, type OpenIDConfiguration, type PKCEChallenge, type PartEtag, type PasskeyAuthenticationOptionsJSON, type PasskeyAuthenticationResponseJSON, type PasskeyCredential, type PasskeyCredentialDescriptorJSON, type PasskeyLoginResponse, type PasskeyRegistrationOptionsJSON, type PasskeyRegistrationResponseJSON, type PasskeyRegistrationResult, type PushSubscriptionInfo, type QuotaInfo, type RegisterParams, type RegisterResponse, type Schedule, type ScheduleInvokeOptions, type ScheduleListOptions, type ScheduleStatus, type SearchOptions, ServerConfigError, type ShareFileParams, SharePermission, SpacelrAuthError, type SpacelrClient, type SpacelrClientConfig, SpacelrEmailVerificationRequiredError, SpacelrError, SpacelrNetworkError, SpacelrScanLimitExceededError, SpacelrSearchFilterRequiredError, SpacelrTimeoutError, SpacelrTwoFactorRequiredError, type StoredTokens, type StreamGapInfo, type StreamSubscription, type SubscribeEventsHandlers, type SubscribeHandlers, type SubscribeWithSnapshotOptions, type TimelineAndFilter, TimelineError, type TimelineFieldFilter, type TimelineFilter, type TimelineLeafFilter, TimelineModule, type TimelineOrderBy, type TimelineQueryOptions, type TimelineQueryResponse, type TimelineScalar, type TimelineSourceStats, TimeoutError, type TokenResponse, type TokenStorage, type TwoFactorResponse, type TwoFactorVerifyParams, type UnshareFileParams, type UploadFileParams, type UploadLargeFileParams, type UploadProgress, type UserInfo, type UserProfile, ValidationError, type VapidKeyResponse, type WhereFilter, type WhereOperator, type WhereScalar, type WhereValue, createClient, generatePKCEChallenge, localStorageCursorStorage, memoryCursorStorage, resolveConsumerId };