@spacelr/sdk 0.11.0 → 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
@@ -647,7 +647,7 @@ interface RealtimeConfig {
647
647
  */
648
648
  onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
649
649
  }
650
- 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';
651
651
  interface StreamGapInfo {
652
652
  projectId: string;
653
653
  collectionName: string;
@@ -659,6 +659,14 @@ interface StreamSubscriptionOptions {
659
659
  projectId: string;
660
660
  collectionName: string;
661
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;
662
670
  /**
663
671
  * #685 — "replay from earliest retained". When true, a brand-new subscription
664
672
  * (no prior cursor) replays every retained stream entry from the earliest
@@ -682,7 +690,7 @@ interface StreamSubscriptionOptions {
682
690
  eventId: string;
683
691
  event: DatabaseChangeEvent;
684
692
  }) => void | Promise<void>;
685
- /** 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. */
686
694
  onGap?: (info: StreamGapInfo) => void;
687
695
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
688
696
  onError?: (error: Error) => void;
@@ -746,6 +754,10 @@ declare class RealtimeClient {
746
754
  unsubscribe: () => void;
747
755
  realtimeMode: 'pubsub' | 'stream';
748
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;
749
761
  }>;
750
762
  /**
751
763
  * Shared body for `subscribeWithCursor` and
@@ -852,6 +864,19 @@ declare class RealtimeClient {
852
864
  */
853
865
  private resubscribeRoom;
854
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;
855
880
  private buildStreamPayload;
856
881
  private unsubscribeStream;
857
882
  private dispatchStreamEvent;
@@ -905,6 +930,28 @@ declare function memoryCursorStorage(): CursorStorage;
905
930
  */
906
931
  declare function localStorageCursorStorage(prefix?: string): CursorStorage;
907
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
+
908
955
  type AuthState = 'authenticated' | 'unauthenticated';
909
956
  type AuthStateListener = (state: AuthState) => void | Promise<void>;
910
957
  declare class AuthModule {
@@ -1387,6 +1434,14 @@ interface SubscribeWithSnapshotOptions<T> {
1387
1434
  * forget callback handlers don't need to also wrap the await.
1388
1435
  */
1389
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;
1390
1445
  }
1391
1446
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1392
1447
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
@@ -1422,6 +1477,14 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1422
1477
  * `where` filters or per-user feeds) must persist independent cursors.
1423
1478
  */
1424
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;
1425
1488
  /** Called on inserts. Receives the document merged with `_eventId`. */
1426
1489
  onInsert?: (doc: T & {
1427
1490
  _id: string;
@@ -1443,7 +1506,7 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1443
1506
  * is tracked in #710. Document-bearing deletes are unaffected.
1444
1507
  */
1445
1508
  onDelete?: (documentId: string, eventId: string) => void | Promise<void>;
1446
- /** 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. */
1447
1510
  onGap?: (info: StreamGapInfo) => void;
1448
1511
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
1449
1512
  onError?: (error: Error) => void;
@@ -2056,4 +2119,4 @@ interface SpacelrClient {
2056
2119
  }
2057
2120
  declare function createClient(config: SpacelrClientConfig): SpacelrClient;
2058
2121
 
2059
- 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
@@ -647,7 +647,7 @@ interface RealtimeConfig {
647
647
  */
648
648
  onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
649
649
  }
650
- 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';
651
651
  interface StreamGapInfo {
652
652
  projectId: string;
653
653
  collectionName: string;
@@ -659,6 +659,14 @@ interface StreamSubscriptionOptions {
659
659
  projectId: string;
660
660
  collectionName: string;
661
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;
662
670
  /**
663
671
  * #685 — "replay from earliest retained". When true, a brand-new subscription
664
672
  * (no prior cursor) replays every retained stream entry from the earliest
@@ -682,7 +690,7 @@ interface StreamSubscriptionOptions {
682
690
  eventId: string;
683
691
  event: DatabaseChangeEvent;
684
692
  }) => void | Promise<void>;
685
- /** 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. */
686
694
  onGap?: (info: StreamGapInfo) => void;
687
695
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
688
696
  onError?: (error: Error) => void;
@@ -746,6 +754,10 @@ declare class RealtimeClient {
746
754
  unsubscribe: () => void;
747
755
  realtimeMode: 'pubsub' | 'stream';
748
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;
749
761
  }>;
750
762
  /**
751
763
  * Shared body for `subscribeWithCursor` and
@@ -852,6 +864,19 @@ declare class RealtimeClient {
852
864
  */
853
865
  private resubscribeRoom;
854
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;
855
880
  private buildStreamPayload;
856
881
  private unsubscribeStream;
857
882
  private dispatchStreamEvent;
@@ -905,6 +930,28 @@ declare function memoryCursorStorage(): CursorStorage;
905
930
  */
906
931
  declare function localStorageCursorStorage(prefix?: string): CursorStorage;
907
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
+
908
955
  type AuthState = 'authenticated' | 'unauthenticated';
909
956
  type AuthStateListener = (state: AuthState) => void | Promise<void>;
910
957
  declare class AuthModule {
@@ -1387,6 +1434,14 @@ interface SubscribeWithSnapshotOptions<T> {
1387
1434
  * forget callback handlers don't need to also wrap the await.
1388
1435
  */
1389
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;
1390
1445
  }
1391
1446
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1392
1447
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
@@ -1422,6 +1477,14 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1422
1477
  * `where` filters or per-user feeds) must persist independent cursors.
1423
1478
  */
1424
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;
1425
1488
  /** Called on inserts. Receives the document merged with `_eventId`. */
1426
1489
  onInsert?: (doc: T & {
1427
1490
  _id: string;
@@ -1443,7 +1506,7 @@ interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1443
1506
  * is tracked in #710. Document-bearing deletes are unaffected.
1444
1507
  */
1445
1508
  onDelete?: (documentId: string, eventId: string) => void | Promise<void>;
1446
- /** 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. */
1447
1510
  onGap?: (info: StreamGapInfo) => void;
1448
1511
  /** Called on handshake rejection (not-stream-collection, invalid sinceId, etc.) and handler failures. */
1449
1512
  onError?: (error: Error) => void;
@@ -2056,4 +2119,4 @@ interface SpacelrClient {
2056
2119
  }
2057
2120
  declare function createClient(config: SpacelrClientConfig): SpacelrClient;
2058
2121
 
2059
- 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.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  BrowserTokenStorage: () => BrowserTokenStorage,
24
+ CONSUMER_ID_STORAGE_KEY: () => CONSUMER_ID_STORAGE_KEY,
24
25
  CodeChallengeMethod: () => CodeChallengeMethod,
25
26
  CursorInvalidError: () => CursorInvalidError,
26
27
  FileVisibility: () => FileVisibility,
@@ -45,7 +46,8 @@ __export(index_exports, {
45
46
  createClient: () => createClient,
46
47
  generatePKCEChallenge: () => generatePKCEChallenge,
47
48
  localStorageCursorStorage: () => localStorageCursorStorage,
48
- memoryCursorStorage: () => memoryCursorStorage
49
+ memoryCursorStorage: () => memoryCursorStorage,
50
+ resolveConsumerId: () => resolveConsumerId
49
51
  });
50
52
  module.exports = __toCommonJS(index_exports);
51
53
 
@@ -1051,7 +1053,8 @@ var RealtimeClient = class {
1051
1053
  // gateways that haven't been updated yet are treated as pubsub-mode
1052
1054
  // so the SDK helper's fail-fast still fires correctly.
1053
1055
  realtimeMode: ack.realtimeMode ?? "pubsub",
1054
- latestStreamId: ack.latestStreamId ?? null
1056
+ latestStreamId: ack.latestStreamId ?? null,
1057
+ resumeCursor: ack.resumeCursor ?? null
1055
1058
  };
1056
1059
  }
1057
1060
  /**
@@ -1085,7 +1088,23 @@ var RealtimeClient = class {
1085
1088
  }
1086
1089
  await this.ensureConnected();
1087
1090
  const streamKey = `stream:${options.projectId}:${options.collectionName}`;
1088
- const subscriptionKey = this.streamSubscriptionKey(streamKey, options.where);
1091
+ const subscriptionKey = this.streamSubscriptionKey(
1092
+ streamKey,
1093
+ options.where,
1094
+ options.consumerId
1095
+ );
1096
+ if (options.consumerId) {
1097
+ const base = this.streamSubscriptionKey(streamKey, options.where);
1098
+ const mine = `${base}#${options.consumerId}`;
1099
+ for (const key of this.streamSubscriptions.keys()) {
1100
+ if (key.startsWith(`${base}#`) && key !== mine) {
1101
+ throw new SpacelrError(
1102
+ `A durable subscription for ${base} already exists on this client under a different consumerId. Use one consumerId per (collection, filter) per client.`,
1103
+ "DURABLE_CONSUMER_CONFLICT"
1104
+ );
1105
+ }
1106
+ }
1107
+ }
1089
1108
  const state = {
1090
1109
  options,
1091
1110
  lastDeliveredId: options.sinceId ?? null,
@@ -1118,6 +1137,7 @@ var RealtimeClient = class {
1118
1137
  options.onError?.(err);
1119
1138
  throw err;
1120
1139
  }
1140
+ this.captureDurableHandshake(state, ack);
1121
1141
  return {
1122
1142
  unsubscribe: () => this.unsubscribeStream(state),
1123
1143
  ack
@@ -1191,10 +1211,14 @@ var RealtimeClient = class {
1191
1211
  * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
1192
1212
  * client-local Map key only (never sent — the gateway derives its own).
1193
1213
  */
1194
- streamSubscriptionKey(streamKey, where) {
1195
- if (!where || Object.keys(where).length === 0) return streamKey;
1196
- const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1197
- return `${streamKey}?${filterStr}`;
1214
+ streamSubscriptionKey(streamKey, where, consumerId) {
1215
+ let key = streamKey;
1216
+ if (where && Object.keys(where).length > 0) {
1217
+ const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1218
+ key = `${streamKey}?${filterStr}`;
1219
+ }
1220
+ if (consumerId) key = `${key}#${consumerId}`;
1221
+ return key;
1198
1222
  }
1199
1223
  /**
1200
1224
  * All per-filter subscription sets registered for one collection's stream
@@ -1204,9 +1228,12 @@ var RealtimeClient = class {
1204
1228
  */
1205
1229
  streamSetsForStreamKey(streamKey) {
1206
1230
  const sets = [];
1207
- const prefix = `${streamKey}?`;
1231
+ const wherePrefix = `${streamKey}?`;
1232
+ const consumerPrefix = `${streamKey}#`;
1208
1233
  for (const [key, set] of this.streamSubscriptions) {
1209
- if (key === streamKey || key.startsWith(prefix)) sets.push(set);
1234
+ if (key === streamKey || key.startsWith(wherePrefix) || key.startsWith(consumerPrefix)) {
1235
+ sets.push(set);
1236
+ }
1210
1237
  }
1211
1238
  return sets;
1212
1239
  }
@@ -1374,6 +1401,21 @@ var RealtimeClient = class {
1374
1401
  }
1375
1402
  }
1376
1403
  });
1404
+ this.socket.on("subscription-reset", (info) => {
1405
+ if (!info || typeof info.projectId !== "string") return;
1406
+ for (const set of this.streamSubscriptions.values()) {
1407
+ for (const state of set) {
1408
+ if (state.options.consumerId && state.options.projectId === info.projectId) {
1409
+ state.options.onGap?.({
1410
+ projectId: info.projectId,
1411
+ collectionName: state.options.collectionName,
1412
+ retentionWindow: "unknown",
1413
+ reason: "evicted"
1414
+ });
1415
+ }
1416
+ }
1417
+ }
1418
+ });
1377
1419
  this.socket.on("disconnect", () => {
1378
1420
  if (this.disposed) return;
1379
1421
  if (initialConnect) return;
@@ -1569,9 +1611,66 @@ var RealtimeClient = class {
1569
1611
  );
1570
1612
  });
1571
1613
  }
1614
+ /** #768 — capture the durable fencing tokens from a successful handshake so
1615
+ * `ack-events` echoes the (generation, session) the server expects. */
1616
+ captureDurableHandshake(state, ack) {
1617
+ if (ack.generation !== void 0) state.generation = ack.generation;
1618
+ if (ack.session !== void 0) state.session = ack.session;
1619
+ }
1620
+ /**
1621
+ * #768 — schedule a coalesced durable ack. Only durable subscriptions (a
1622
+ * consumerId with a captured generation+session) ack. At most one ack per
1623
+ * microtask drain, carrying the highest delivered seq — cumulative on the
1624
+ * server, so a burst of N events costs one ack, not N.
1625
+ */
1626
+ scheduleDurableAck(state) {
1627
+ if (!state.options.consumerId || state.generation === void 0 || state.session === void 0 || state.ackFlushScheduled) {
1628
+ return;
1629
+ }
1630
+ state.ackFlushScheduled = true;
1631
+ queueMicrotask(() => {
1632
+ state.ackFlushScheduled = false;
1633
+ const seq = state.lastDeliveredId;
1634
+ if (seq) this.emitDurableAck(state, seq);
1635
+ });
1636
+ }
1637
+ /** #768 — emit `ack-events` for `seq`; a fenced/evicted response routes into
1638
+ * the gap-recovery path so the caller re-snapshots (§12.5/§12.1). */
1639
+ emitDurableAck(state, seq) {
1640
+ const socket = this.socket;
1641
+ if (!socket) return;
1642
+ const { projectId, collectionName, where, consumerId } = state.options;
1643
+ if (consumerId === void 0 || state.generation === void 0 || state.session === void 0) {
1644
+ return;
1645
+ }
1646
+ const payload = {
1647
+ projectId,
1648
+ collectionName,
1649
+ consumerId,
1650
+ generation: state.generation,
1651
+ session: state.session,
1652
+ seq
1653
+ };
1654
+ if (where && Object.keys(where).length > 0) payload["where"] = where;
1655
+ socket.emit(
1656
+ "ack-events",
1657
+ payload,
1658
+ (res) => {
1659
+ if (!res?.gap) return;
1660
+ if (!this.streamSubscriptions.get(state.subscriptionKey)?.has(state)) return;
1661
+ state.options.onGap?.({
1662
+ projectId,
1663
+ collectionName,
1664
+ retentionWindow: "unknown",
1665
+ reason: res.gap
1666
+ });
1667
+ }
1668
+ );
1669
+ }
1572
1670
  buildStreamPayload(state) {
1573
1671
  const { projectId, collectionName, where } = state.options;
1574
1672
  const payload = { projectId, collectionName };
1673
+ if (state.options.consumerId) payload["consumerId"] = state.options.consumerId;
1575
1674
  if (state.lastDeliveredId) {
1576
1675
  payload["sinceId"] = state.lastDeliveredId;
1577
1676
  } else if (state.options.fromStart) {
@@ -1612,6 +1711,7 @@ var RealtimeClient = class {
1612
1711
  try {
1613
1712
  await state.options.onEvent({ eventId: entryId, event: payload });
1614
1713
  state.lastDeliveredId = entryId;
1714
+ this.scheduleDurableAck(state);
1615
1715
  } catch (err) {
1616
1716
  const error = err instanceof Error ? err : new Error(String(err));
1617
1717
  try {
@@ -1650,6 +1750,11 @@ var RealtimeClient = class {
1650
1750
  }
1651
1751
  return;
1652
1752
  }
1753
+ for (const s of set) {
1754
+ s.generation = void 0;
1755
+ s.session = void 0;
1756
+ }
1757
+ this.captureDurableHandshake(primary, ack);
1653
1758
  if (!this.streamSubscriptions.has(primary.subscriptionKey)) {
1654
1759
  const payload = {
1655
1760
  projectId: primary.options.projectId,
@@ -1743,6 +1848,23 @@ function localStorageCursorStorage(prefix = "spacelr:cursor:") {
1743
1848
  };
1744
1849
  }
1745
1850
 
1851
+ // libs/sdk/src/core/consumer-id.ts
1852
+ var CONSUMER_ID_STORAGE_KEY = "spacelr:consumer-id";
1853
+ function generateConsumerId() {
1854
+ const c = globalThis.crypto;
1855
+ if (c?.randomUUID) return c.randomUUID();
1856
+ return (Math.random().toString(36).slice(2) + "-" + Date.now().toString(36)).slice(0, 128);
1857
+ }
1858
+ async function resolveConsumerId(explicit, storage, key = CONSUMER_ID_STORAGE_KEY) {
1859
+ if (explicit) return explicit;
1860
+ if (!storage) return generateConsumerId();
1861
+ const existing = await Promise.resolve(storage.load(key));
1862
+ if (existing) return existing;
1863
+ const generated = generateConsumerId();
1864
+ await Promise.resolve(storage.save(key, generated));
1865
+ return generated;
1866
+ }
1867
+
1746
1868
  // libs/sdk/src/modules/auth.module.ts
1747
1869
  function mapProfile(u) {
1748
1870
  const name = u.name ?? ([u.firstName, u.lastName].filter(Boolean).join(" ") || void 0) ?? u.displayName;
@@ -2761,6 +2883,13 @@ function compileMatcher(where, plan) {
2761
2883
  }
2762
2884
 
2763
2885
  // libs/sdk/src/modules/database.module.ts
2886
+ var RESNAPSHOT_GAP_REASONS = /* @__PURE__ */ new Set([
2887
+ "outside-retention-window",
2888
+ "replay-truncated",
2889
+ "evicted",
2890
+ "log-reset",
2891
+ "auth-unavailable"
2892
+ ]);
2764
2893
  var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
2765
2894
  var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
2766
2895
  var DEFAULT_CATCHUP_PAGE_SIZE = 100;
@@ -3154,6 +3283,7 @@ var CollectionRef = class {
3154
3283
  projectId: this.projectId,
3155
3284
  collectionName: this.collectionName,
3156
3285
  sinceId,
3286
+ consumerId: handlers.consumerId,
3157
3287
  // #685 — only meaningful on a fresh subscription (no sinceId/cursor);
3158
3288
  // buildStreamPayload ignores it once a cursor exists.
3159
3289
  fromStart: handlers.fromStart,
@@ -3270,6 +3400,11 @@ var CollectionRef = class {
3270
3400
  if (!this.realtime) {
3271
3401
  throw new Error("Realtime not available: no RealtimeClient configured");
3272
3402
  }
3403
+ if (opts.consumerId !== void 0 && !/^[A-Za-z0-9._-]{1,128}$/.test(opts.consumerId)) {
3404
+ throw new Error(
3405
+ `Invalid consumerId ${JSON.stringify(opts.consumerId)}: must match [A-Za-z0-9._-]{1,128}. Use resolveConsumerId() to generate one, or omit it for a stateless subscription.`
3406
+ );
3407
+ }
3273
3408
  let isActive = true;
3274
3409
  let currentUnsubscribe = null;
3275
3410
  let snapshotAbort = new AbortController();
@@ -3334,6 +3469,7 @@ var CollectionRef = class {
3334
3469
  projectId: this.projectId,
3335
3470
  collectionName: this.collectionName,
3336
3471
  sinceId: void 0,
3472
+ consumerId: opts.consumerId,
3337
3473
  where: streamWhere,
3338
3474
  onEvent: async ({ event }) => {
3339
3475
  if (!isActive) return;
@@ -3464,8 +3600,7 @@ var CollectionRef = class {
3464
3600
  };
3465
3601
  const handleGap = (info) => {
3466
3602
  if (!isActive) return;
3467
- if (info.reason !== "outside-retention-window" && info.reason !== "replay-truncated")
3468
- return;
3603
+ if (!RESNAPSHOT_GAP_REASONS.has(info.reason)) return;
3469
3604
  dispatchRecovery();
3470
3605
  };
3471
3606
  let subscribeAckResolved = false;
@@ -3478,6 +3613,7 @@ var CollectionRef = class {
3478
3613
  projectId: this.projectId,
3479
3614
  collectionName: this.collectionName,
3480
3615
  sinceId: void 0,
3616
+ consumerId: opts.consumerId,
3481
3617
  where: streamWhere,
3482
3618
  onEvent: async ({ event }) => {
3483
3619
  if (!isActive) return;
@@ -3526,11 +3662,10 @@ var CollectionRef = class {
3526
3662
  );
3527
3663
  }
3528
3664
  currentUnsubscribe = initial.unsubscribe;
3529
- let snapshotDocs;
3530
- try {
3531
- const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3532
- snapshotDocs = snapshotResult.documents;
3533
- recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3665
+ const isDurableResume = initial.resumeCursor !== null;
3666
+ let snapshotDocs = [];
3667
+ if (isDurableResume) {
3668
+ recomputeTypedMatcherPlan(void 0);
3534
3669
  initialPlanReady = true;
3535
3670
  for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3536
3671
  if (!passesLiveGate(pendingInitialEvents[i])) {
@@ -3538,29 +3673,44 @@ var CollectionRef = class {
3538
3673
  }
3539
3674
  }
3540
3675
  warnIfNoGateAvailable();
3541
- } catch (err) {
3542
- currentUnsubscribe?.();
3543
- isActive = false;
3544
- const isAbort = err instanceof DOMException && err.name === "AbortError";
3545
- if (isAbort) throw err;
3546
- const error = err instanceof Error ? err : new Error(String(err));
3547
- if (opts.onSnapshotError) opts.onSnapshotError(error);
3548
- else opts.onError?.(error);
3549
- throw error;
3676
+ } else {
3677
+ try {
3678
+ const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3679
+ snapshotDocs = snapshotResult.documents;
3680
+ recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3681
+ initialPlanReady = true;
3682
+ for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3683
+ if (!passesLiveGate(pendingInitialEvents[i])) {
3684
+ pendingInitialEvents.splice(i, 1);
3685
+ }
3686
+ }
3687
+ warnIfNoGateAvailable();
3688
+ } catch (err) {
3689
+ currentUnsubscribe?.();
3690
+ isActive = false;
3691
+ const isAbort = err instanceof DOMException && err.name === "AbortError";
3692
+ if (isAbort) throw err;
3693
+ const error = err instanceof Error ? err : new Error(String(err));
3694
+ if (opts.onSnapshotError) opts.onSnapshotError(error);
3695
+ else opts.onError?.(error);
3696
+ throw error;
3697
+ }
3550
3698
  }
3551
3699
  if (!isActive) {
3552
3700
  currentUnsubscribe?.();
3553
3701
  return () => void 0;
3554
3702
  }
3555
- try {
3556
- await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3557
- } catch (err) {
3558
- currentUnsubscribe?.();
3559
- currentUnsubscribe = null;
3560
- isActive = false;
3561
- const error = err instanceof Error ? err : new Error(String(err));
3562
- opts.onError?.(error);
3563
- throw error;
3703
+ if (!isDurableResume) {
3704
+ try {
3705
+ await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3706
+ } catch (err) {
3707
+ currentUnsubscribe?.();
3708
+ currentUnsubscribe = null;
3709
+ isActive = false;
3710
+ const error = err instanceof Error ? err : new Error(String(err));
3711
+ opts.onError?.(error);
3712
+ throw error;
3713
+ }
3564
3714
  }
3565
3715
  while (true) {
3566
3716
  if (!isActive) return () => void 0;
@@ -3948,6 +4098,7 @@ function createClient(config) {
3948
4098
  // Annotate the CommonJS export names for ESM import in node:
3949
4099
  0 && (module.exports = {
3950
4100
  BrowserTokenStorage,
4101
+ CONSUMER_ID_STORAGE_KEY,
3951
4102
  CodeChallengeMethod,
3952
4103
  CursorInvalidError,
3953
4104
  FileVisibility,
@@ -3972,6 +4123,7 @@ function createClient(config) {
3972
4123
  createClient,
3973
4124
  generatePKCEChallenge,
3974
4125
  localStorageCursorStorage,
3975
- memoryCursorStorage
4126
+ memoryCursorStorage,
4127
+ resolveConsumerId
3976
4128
  });
3977
4129
  //# sourceMappingURL=index.js.map