@powersync/common 1.38.1 → 1.40.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.cts CHANGED
@@ -357,6 +357,7 @@ interface Checkpoint {
357
357
  last_op_id: OpId;
358
358
  buckets: BucketChecksum[];
359
359
  write_checkpoint?: string;
360
+ streams?: any[];
360
361
  }
361
362
  interface BucketState {
362
363
  bucket: string;
@@ -390,6 +391,12 @@ interface BucketChecksum {
390
391
  * Count of operations - informational only.
391
392
  */
392
393
  count?: number;
394
+ /**
395
+ * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
396
+ * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
397
+ * present.
398
+ */
399
+ subscriptions?: any;
393
400
  }
394
401
  declare enum PSInternalTable {
395
402
  DATA = "ps_data",
@@ -404,7 +411,8 @@ declare enum PowerSyncControlCommand {
404
411
  STOP = "stop",
405
412
  START = "start",
406
413
  NOTIFY_TOKEN_REFRESHED = "refreshed_token",
407
- NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload"
414
+ NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload",
415
+ UPDATE_SUBSCRIPTIONS = "update_subscriptions"
408
416
  }
409
417
  interface BucketStorageListener extends BaseListener {
410
418
  crudUpdate: () => void;
@@ -440,73 +448,6 @@ interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListen
440
448
  control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
441
449
  }
442
450
 
443
- type DataStreamOptions<ParsedData, SourceData> = {
444
- mapLine?: (line: SourceData) => ParsedData;
445
- /**
446
- * Close the stream if any consumer throws an error
447
- */
448
- closeOnError?: boolean;
449
- pressure?: {
450
- highWaterMark?: number;
451
- lowWaterMark?: number;
452
- };
453
- logger?: ILogger;
454
- };
455
- type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
456
- interface DataStreamListener<Data extends any = any> extends BaseListener {
457
- data: (data: Data) => Promise<void>;
458
- closed: () => void;
459
- error: (error: Error) => void;
460
- highWater: () => Promise<void>;
461
- lowWater: () => Promise<void>;
462
- }
463
- declare const DEFAULT_PRESSURE_LIMITS: {
464
- highWater: number;
465
- lowWater: number;
466
- };
467
- /**
468
- * A very basic implementation of a data stream with backpressure support which does not use
469
- * native JS streams or async iterators.
470
- * This is handy for environments such as React Native which need polyfills for the above.
471
- */
472
- declare class DataStream<ParsedData, SourceData = any> extends BaseObserver<DataStreamListener<ParsedData>> {
473
- protected options?: DataStreamOptions<ParsedData, SourceData> | undefined;
474
- dataQueue: SourceData[];
475
- protected isClosed: boolean;
476
- protected processingPromise: Promise<void> | null;
477
- protected notifyDataAdded: (() => void) | null;
478
- protected logger: ILogger;
479
- protected mapLine: (line: SourceData) => ParsedData;
480
- constructor(options?: DataStreamOptions<ParsedData, SourceData> | undefined);
481
- get highWatermark(): number;
482
- get lowWatermark(): number;
483
- get closed(): boolean;
484
- close(): Promise<void>;
485
- /**
486
- * Enqueues data for the consumers to read
487
- */
488
- enqueueData(data: SourceData): void;
489
- /**
490
- * Reads data once from the data stream
491
- * @returns a Data payload or Null if the stream closed.
492
- */
493
- read(): Promise<ParsedData | null>;
494
- /**
495
- * Executes a callback for each data item in the stream
496
- */
497
- forEach(callback: DataStreamCallback<ParsedData>): () => void;
498
- protected processQueue(): Promise<void> | undefined;
499
- protected hasDataReader(): boolean;
500
- protected _processQueue(): Promise<void>;
501
- protected iterateAsyncErrored(cb: (l: Partial<DataStreamListener<ParsedData>>) => Promise<void>): Promise<void>;
502
- }
503
-
504
- interface PowerSyncCredentials {
505
- endpoint: string;
506
- token: string;
507
- expiresAt?: Date;
508
- }
509
-
510
451
  /**
511
452
  * For sync2.json
512
453
  */
@@ -643,6 +584,94 @@ interface CrudResponse {
643
584
  checkpoint?: OpId;
644
585
  }
645
586
 
587
+ interface CoreStreamSubscription {
588
+ progress: {
589
+ total: number;
590
+ downloaded: number;
591
+ };
592
+ name: string;
593
+ parameters: any;
594
+ priority: number | null;
595
+ active: boolean;
596
+ is_default: boolean;
597
+ has_explicit_subscription: boolean;
598
+ expires_at: number | null;
599
+ last_synced_at: number | null;
600
+ }
601
+ interface BucketProgress {
602
+ priority: number;
603
+ at_last: number;
604
+ since_last: number;
605
+ target_count: number;
606
+ }
607
+
608
+ type DataStreamOptions<ParsedData, SourceData> = {
609
+ mapLine?: (line: SourceData) => ParsedData;
610
+ /**
611
+ * Close the stream if any consumer throws an error
612
+ */
613
+ closeOnError?: boolean;
614
+ pressure?: {
615
+ highWaterMark?: number;
616
+ lowWaterMark?: number;
617
+ };
618
+ logger?: ILogger;
619
+ };
620
+ type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
621
+ interface DataStreamListener<Data extends any = any> extends BaseListener {
622
+ data: (data: Data) => Promise<void>;
623
+ closed: () => void;
624
+ error: (error: Error) => void;
625
+ highWater: () => Promise<void>;
626
+ lowWater: () => Promise<void>;
627
+ }
628
+ declare const DEFAULT_PRESSURE_LIMITS: {
629
+ highWater: number;
630
+ lowWater: number;
631
+ };
632
+ /**
633
+ * A very basic implementation of a data stream with backpressure support which does not use
634
+ * native JS streams or async iterators.
635
+ * This is handy for environments such as React Native which need polyfills for the above.
636
+ */
637
+ declare class DataStream<ParsedData, SourceData = any> extends BaseObserver<DataStreamListener<ParsedData>> {
638
+ protected options?: DataStreamOptions<ParsedData, SourceData> | undefined;
639
+ dataQueue: SourceData[];
640
+ protected isClosed: boolean;
641
+ protected processingPromise: Promise<void> | null;
642
+ protected notifyDataAdded: (() => void) | null;
643
+ protected logger: ILogger;
644
+ protected mapLine: (line: SourceData) => ParsedData;
645
+ constructor(options?: DataStreamOptions<ParsedData, SourceData> | undefined);
646
+ get highWatermark(): number;
647
+ get lowWatermark(): number;
648
+ get closed(): boolean;
649
+ close(): Promise<void>;
650
+ /**
651
+ * Enqueues data for the consumers to read
652
+ */
653
+ enqueueData(data: SourceData): void;
654
+ /**
655
+ * Reads data once from the data stream
656
+ * @returns a Data payload or Null if the stream closed.
657
+ */
658
+ read(): Promise<ParsedData | null>;
659
+ /**
660
+ * Executes a callback for each data item in the stream
661
+ */
662
+ forEach(callback: DataStreamCallback<ParsedData>): () => void;
663
+ protected processQueue(): Promise<void> | undefined;
664
+ protected hasDataReader(): boolean;
665
+ protected _processQueue(): Promise<void>;
666
+ protected iterateAsyncErrored(cb: (l: Partial<DataStreamListener<ParsedData>>) => Promise<void>): Promise<void>;
667
+ }
668
+
669
+ interface PowerSyncCredentials {
670
+ endpoint: string;
671
+ token: string;
672
+ expiresAt?: Date;
673
+ }
674
+
646
675
  type BSONImplementation = typeof BSON;
647
676
  type RemoteConnector = {
648
677
  fetchCredentials: () => Promise<PowerSyncCredentials | null>;
@@ -831,8 +860,9 @@ interface LockOptions<T> {
831
860
  type: LockType;
832
861
  signal?: AbortSignal;
833
862
  }
834
- interface AbstractStreamingSyncImplementationOptions extends AdditionalConnectionOptions {
863
+ interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
835
864
  adapter: BucketStorageAdapter;
865
+ subscriptions: SubscribedStream[];
836
866
  uploadCrud: () => Promise<void>;
837
867
  /**
838
868
  * An identifier for which PowerSync DB this sync implementation is
@@ -884,6 +914,12 @@ interface BaseConnectionOptions {
884
914
  * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
885
915
  */
886
916
  params?: Record<string, StreamingSyncRequestParameterType>;
917
+ /**
918
+ * Whether to include streams that have `auto_subscribe: true` in their definition.
919
+ *
920
+ * This defaults to `true`.
921
+ */
922
+ includeDefaultStreams?: boolean;
887
923
  /**
888
924
  * The serialized schema - mainly used to forward information about raw tables to the sync client.
889
925
  */
@@ -904,7 +940,9 @@ interface AdditionalConnectionOptions {
904
940
  crudUploadThrottleMs?: number;
905
941
  }
906
942
  /** @internal */
907
- type RequiredAdditionalConnectionOptions = Required<AdditionalConnectionOptions>;
943
+ interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
944
+ subscriptions: SubscribedStream[];
945
+ }
908
946
  interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
909
947
  /**
910
948
  * Connects to the sync service
@@ -924,6 +962,7 @@ interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyn
924
962
  waitForReady(): Promise<void>;
925
963
  waitForStatus(status: SyncStatusOptions): Promise<void>;
926
964
  waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
965
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
927
966
  }
928
967
  declare const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
929
968
  declare const DEFAULT_RETRY_DELAY_MS = 5000;
@@ -933,6 +972,10 @@ declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
933
972
  };
934
973
  type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
935
974
  declare const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;
975
+ type SubscribedStream = {
976
+ name: string;
977
+ params: Record<string, any> | null;
978
+ };
936
979
  declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
937
980
  protected _lastSyncedAt: Date | null;
938
981
  protected options: AbstractStreamingSyncImplementationOptions;
@@ -941,8 +984,10 @@ declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<
941
984
  protected crudUpdateListener?: () => void;
942
985
  protected streamingSyncPromise?: Promise<void>;
943
986
  protected logger: ILogger;
987
+ private activeStreams;
944
988
  private isUploadingCrud;
945
989
  private notifyCompletedUploads?;
990
+ private handleActiveStreamsChange?;
946
991
  syncStatus: SyncStatus;
947
992
  triggerCrudUpload: () => void;
948
993
  constructor(options: AbstractStreamingSyncImplementationOptions);
@@ -979,20 +1024,17 @@ declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<
979
1024
  * @returns Whether the database is now using the new, fixed subkey format.
980
1025
  */
981
1026
  private requireKeyFormat;
982
- protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
1027
+ protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<RustIterationResult | null>;
983
1028
  private legacyStreamingSyncIteration;
984
1029
  private rustSyncIteration;
985
1030
  private updateSyncStatusForStartingCheckpoint;
986
1031
  private applyCheckpoint;
987
1032
  protected updateSyncStatus(options: SyncStatusOptions): void;
988
1033
  private delayRetry;
1034
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
989
1035
  }
990
-
991
- interface BucketProgress {
992
- priority: number;
993
- at_last: number;
994
- since_last: number;
995
- target_count: number;
1036
+ interface RustIterationResult {
1037
+ immediateRestart: boolean;
996
1038
  }
997
1039
 
998
1040
  /** @internal */
@@ -1059,6 +1101,105 @@ declare class SyncProgress implements ProgressWithOperations {
1059
1101
  untilPriority(priority: number): ProgressWithOperations;
1060
1102
  }
1061
1103
 
1104
+ /**
1105
+ * A description of a sync stream, consisting of its {@link name} and the {@link parameters} used when subscribing.
1106
+ */
1107
+ interface SyncStreamDescription {
1108
+ /**
1109
+ * The name of the stream as it appears in the stream definition for the PowerSync service.
1110
+ */
1111
+ name: string;
1112
+ /**
1113
+ * The parameters used to subscribe to the stream, if any.
1114
+ *
1115
+ * The same stream can be subscribed to multiple times with different parameters.
1116
+ */
1117
+ parameters: Record<string, any> | null;
1118
+ }
1119
+ /**
1120
+ * Information about a subscribed sync stream.
1121
+ *
1122
+ * This includes the {@link SyncStreamDescription}, along with information about the current sync status.
1123
+ */
1124
+ interface SyncSubscriptionDescription extends SyncStreamDescription {
1125
+ active: boolean;
1126
+ /**
1127
+ * Whether this stream subscription is included by default, regardless of whether the stream has explicitly been
1128
+ * subscribed to or not.
1129
+ *
1130
+ * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1131
+ * happens when a default stream was subscribed explicitly.
1132
+ */
1133
+ isDefault: boolean;
1134
+ /**
1135
+ * Whether this stream has been subscribed to explicitly.
1136
+ *
1137
+ * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1138
+ * happens when a default stream was subscribed explicitly.
1139
+ */
1140
+ hasExplicitSubscription: boolean;
1141
+ /**
1142
+ * For sync streams that have a time-to-live, the current time at which the stream would expire if not subscribed to
1143
+ * again.
1144
+ */
1145
+ expiresAt: Date | null;
1146
+ /**
1147
+ * Whether this stream subscription has been synced at least once.
1148
+ */
1149
+ hasSynced: boolean;
1150
+ /**
1151
+ * If {@link hasSynced} is true, the last time data from this stream has been synced.
1152
+ */
1153
+ lastSyncedAt: Date | null;
1154
+ }
1155
+ interface SyncStreamSubscribeOptions {
1156
+ /**
1157
+ * A "time to live" for this stream subscription, in seconds.
1158
+ *
1159
+ * The TTL control when a stream gets evicted after not having an active {@link SyncStreamSubscription} object
1160
+ * attached to it.
1161
+ */
1162
+ ttl?: number;
1163
+ /**
1164
+ * A priority to assign to this subscription. This overrides the default priority that may have been set on streams.
1165
+ *
1166
+ * For details on priorities, see [priotized sync](https://docs.powersync.com/usage/use-case-examples/prioritized-sync).
1167
+ */
1168
+ priority?: 0 | 1 | 2 | 3;
1169
+ }
1170
+ /**
1171
+ * A handle to a {@link SyncStreamDescription} that allows subscribing to the stream.
1172
+ *
1173
+ * To obtain an instance of {@link SyncStream}, call {@link AbstractPowerSyncDatabase.syncStream}.
1174
+ */
1175
+ interface SyncStream extends SyncStreamDescription {
1176
+ /**
1177
+ * Adds a subscription to this stream, requesting it to be included when connecting to the sync service.
1178
+ *
1179
+ * You should keep a reference to the returned {@link SyncStreamSubscription} object along as you need data for that
1180
+ * stream. As soon as {@link SyncStreamSubscription.unsubscribe} is called for all subscriptions on this stream
1181
+ * (including subscriptions created on other tabs), the {@link SyncStreamSubscribeOptions.ttl} starts ticking and will
1182
+ * eventually evict the stream (unless {@link subscribe} is called again).
1183
+ */
1184
+ subscribe(options?: SyncStreamSubscribeOptions): Promise<SyncStreamSubscription>;
1185
+ /**
1186
+ * Clears all subscriptions attached to this stream and resets the TTL for the stream.
1187
+ *
1188
+ * This is a potentially dangerous operations, as it interferes with other stream subscriptions.
1189
+ */
1190
+ unsubscribeAll(): Promise<void>;
1191
+ }
1192
+ interface SyncStreamSubscription extends SyncStreamDescription {
1193
+ /**
1194
+ * A promise that resolves once data from in this sync stream has been synced and applied.
1195
+ */
1196
+ waitForFirstSync(abort?: AbortSignal): Promise<void>;
1197
+ /**
1198
+ * Removes this stream subscription.
1199
+ */
1200
+ unsubscribe(): void;
1201
+ }
1202
+
1062
1203
  type SyncDataFlowStatus = Partial<{
1063
1204
  downloading: boolean;
1064
1205
  uploading: boolean;
@@ -1079,6 +1220,7 @@ type SyncDataFlowStatus = Partial<{
1079
1220
  * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1080
1221
  */
1081
1222
  downloadProgress: InternalProgressInformation | null;
1223
+ internalStreamSubscriptions: CoreStreamSubscription[] | null;
1082
1224
  }>;
1083
1225
  interface SyncPriorityStatus {
1084
1226
  priority: number;
@@ -1158,7 +1300,23 @@ declare class SyncStatus {
1158
1300
  * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1159
1301
  */
1160
1302
  downloadProgress: InternalProgressInformation | null;
1303
+ internalStreamSubscriptions: CoreStreamSubscription[] | null;
1161
1304
  }>;
1305
+ /**
1306
+ * All sync streams currently being tracked in teh database.
1307
+ *
1308
+ * This returns null when the database is currently being opened and we don't have reliable information about all
1309
+ * included streams yet.
1310
+ *
1311
+ * @experimental Sync streams are currently in alpha.
1312
+ */
1313
+ get syncStreams(): SyncStreamStatus[] | undefined;
1314
+ /**
1315
+ * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
1316
+ *
1317
+ * @experimental Sync streams are currently in alpha.
1318
+ */
1319
+ forStream(stream: SyncStreamDescription): SyncStreamStatus | undefined;
1162
1320
  /**
1163
1321
  * Provides sync status information for all bucket priorities, sorted by priority (highest first).
1164
1322
  *
@@ -1216,6 +1374,14 @@ declare class SyncStatus {
1216
1374
  toJSON(): SyncStatusOptions;
1217
1375
  private static comparePriorities;
1218
1376
  }
1377
+ /**
1378
+ * Information about a sync stream subscription.
1379
+ */
1380
+ interface SyncStreamStatus {
1381
+ progress: ProgressWithOperations | null;
1382
+ subscription: SyncSubscriptionDescription;
1383
+ priority: number | null;
1384
+ }
1219
1385
 
1220
1386
  declare class UploadQueueStats {
1221
1387
  /**
@@ -1618,11 +1784,24 @@ interface ConnectionManagerSyncImplementationResult {
1618
1784
  */
1619
1785
  onDispose: () => Promise<void> | void;
1620
1786
  }
1787
+ /**
1788
+ * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
1789
+ *
1790
+ * @internal
1791
+ */
1792
+ interface CreateSyncImplementationOptions extends AdditionalConnectionOptions {
1793
+ subscriptions: SubscribedStream[];
1794
+ }
1795
+ interface InternalSubscriptionAdapter {
1796
+ firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
1797
+ resolveOfflineSyncStatus(): Promise<void>;
1798
+ rustSubscriptionsCommand(payload: any): Promise<void>;
1799
+ }
1621
1800
  /**
1622
1801
  * @internal
1623
1802
  */
1624
1803
  interface ConnectionManagerOptions {
1625
- createSyncImplementation(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<ConnectionManagerSyncImplementationResult>;
1804
+ createSyncImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions): Promise<ConnectionManagerSyncImplementationResult>;
1626
1805
  logger: ILogger;
1627
1806
  }
1628
1807
  type StoredConnectionOptions = {
@@ -1668,7 +1847,15 @@ declare class ConnectionManager extends BaseObserver<ConnectionManagerListener>
1668
1847
  * is disposed.
1669
1848
  */
1670
1849
  protected syncDisposer: (() => Promise<void> | void) | null;
1850
+ /**
1851
+ * Subscriptions managed in this connection manager.
1852
+ *
1853
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
1854
+ */
1855
+ private locallyActiveSubscriptions;
1671
1856
  constructor(options: ConnectionManagerOptions);
1857
+ get connector(): PowerSyncBackendConnector | null;
1858
+ get connectionOptions(): InternalConnectionOptions | null;
1672
1859
  get logger(): ILogger;
1673
1860
  close(): Promise<void>;
1674
1861
  connect(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<void>;
@@ -1681,6 +1868,15 @@ declare class ConnectionManager extends BaseObserver<ConnectionManagerListener>
1681
1868
  disconnect(): Promise<void>;
1682
1869
  protected disconnectInternal(): Promise<void>;
1683
1870
  protected performDisconnect(): Promise<void>;
1871
+ stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream;
1872
+ /**
1873
+ * @internal exposed for testing
1874
+ */
1875
+ get activeStreams(): {
1876
+ name: string;
1877
+ params: Record<string, any> | null;
1878
+ }[];
1879
+ private subscriptionsMayHaveChanged;
1684
1880
  }
1685
1881
 
1686
1882
  /**
@@ -2703,7 +2899,20 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2703
2899
  protected bucketStorageAdapter: BucketStorageAdapter;
2704
2900
  protected _isReadyPromise: Promise<void>;
2705
2901
  protected connectionManager: ConnectionManager;
2902
+ private subscriptions;
2706
2903
  get syncStreamImplementation(): StreamingSyncImplementation | null;
2904
+ /**
2905
+ * The connector used to connect to the PowerSync service.
2906
+ *
2907
+ * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
2908
+ */
2909
+ get connector(): PowerSyncBackendConnector | null;
2910
+ /**
2911
+ * The resolved connection options used to connect to the PowerSync service.
2912
+ *
2913
+ * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
2914
+ */
2915
+ get connectionOptions(): InternalConnectionOptions | null;
2707
2916
  protected _schema: Schema;
2708
2917
  private _database;
2709
2918
  protected runExclusiveMutex: Mutex;
@@ -2738,7 +2947,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2738
2947
  * Opens the DBAdapter given open options using a default open factory
2739
2948
  */
2740
2949
  protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
2741
- protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
2950
+ protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
2742
2951
  protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
2743
2952
  /**
2744
2953
  * @returns A promise which will resolve once initialization is completed.
@@ -2757,6 +2966,10 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2757
2966
  signal?: AbortSignal;
2758
2967
  priority?: number;
2759
2968
  }): Promise<void>;
2969
+ /**
2970
+ * Waits for the first sync status for which the `status` callback returns a truthy value.
2971
+ */
2972
+ waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
2760
2973
  /**
2761
2974
  * Allows for extended implementations to execute custom initialization
2762
2975
  * logic as part of the total init process
@@ -2768,7 +2981,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2768
2981
  */
2769
2982
  protected initialize(): Promise<void>;
2770
2983
  private _loadVersion;
2771
- protected updateHasSynced(): Promise<void>;
2984
+ protected resolveOfflineSyncStatus(): Promise<void>;
2772
2985
  /**
2773
2986
  * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
2774
2987
  *
@@ -2780,7 +2993,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2780
2993
  * While initializing is automatic, this helps to catch and report initialization errors.
2781
2994
  */
2782
2995
  init(): Promise<void>;
2783
- resolvedConnectionOptions(options?: PowerSyncConnectionOptions): RequiredAdditionalConnectionOptions;
2996
+ protected resolvedConnectionOptions(options: CreateSyncImplementationOptions): CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions;
2784
2997
  /**
2785
2998
  * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.
2786
2999
  * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.
@@ -2810,6 +3023,15 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2810
3023
  * To preserve data in local-only tables, set clearLocal to false.
2811
3024
  */
2812
3025
  disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
3026
+ /**
3027
+ * Create a sync stream to query its status or to subscribe to it.
3028
+ *
3029
+ * @param name The name of the stream to subscribe to.
3030
+ * @param params Optional parameters for the stream subscription.
3031
+ * @returns A {@link SyncStream} instance that can be subscribed to.
3032
+ * @experimental Sync streams are currently in alpha.
3033
+ */
3034
+ syncStream(name: string, params?: Record<string, any>): SyncStream;
2813
3035
  /**
2814
3036
  * Close the database, releasing resources.
2815
3037
  *
@@ -3376,4 +3598,4 @@ interface ParsedQuery {
3376
3598
  declare const parseQuery: <T>(query: string | CompilableQuery<T>, parameters: any[]) => ParsedQuery;
3377
3599
 
3378
3600
  export { AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, BaseObserver, Column, ColumnType, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, Table, TableV2, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
3379
- export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, LinkQueryOptions, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RemoteConnector, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStreamOptions, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState };
3601
+ export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RemoteConnector, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SubscribedStream, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState };
@@ -5,17 +5,18 @@ import { SyncStatus } from '../db/crud/SyncStatus.js';
5
5
  import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
6
6
  import { Schema } from '../db/schema/Schema.js';
7
7
  import { BaseObserver } from '../utils/BaseObserver.js';
8
- import { ConnectionManager } from './ConnectionManager.js';
8
+ import { ConnectionManager, CreateSyncImplementationOptions } from './ConnectionManager.js';
9
9
  import { ArrayQueryDefinition, Query } from './Query.js';
10
10
  import { SQLOpenFactory, SQLOpenOptions } from './SQLOpenFactory.js';
11
11
  import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
12
12
  import { BucketStorageAdapter } from './sync/bucket/BucketStorageAdapter.js';
13
13
  import { CrudBatch } from './sync/bucket/CrudBatch.js';
14
14
  import { CrudTransaction } from './sync/bucket/CrudTransaction.js';
15
- import { StreamingSyncImplementation, StreamingSyncImplementationListener, type AdditionalConnectionOptions, type PowerSyncConnectionOptions, type RequiredAdditionalConnectionOptions } from './sync/stream/AbstractStreamingSyncImplementation.js';
15
+ import { InternalConnectionOptions, StreamingSyncImplementation, StreamingSyncImplementationListener, type AdditionalConnectionOptions, type PowerSyncConnectionOptions, type RequiredAdditionalConnectionOptions } from './sync/stream/AbstractStreamingSyncImplementation.js';
16
16
  import { TriggerManager } from './triggers/TriggerManager.js';
17
17
  import { WatchCompatibleQuery } from './watched/WatchedQuery.js';
18
18
  import { WatchedQueryComparator } from './watched/processors/comparators.js';
19
+ import { SyncStream } from './sync/sync-streams.js';
19
20
  export interface DisconnectAndClearOptions {
20
21
  /** When set to false, data in local-only tables is preserved. */
21
22
  clearLocal?: boolean;
@@ -129,7 +130,20 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
129
130
  protected bucketStorageAdapter: BucketStorageAdapter;
130
131
  protected _isReadyPromise: Promise<void>;
131
132
  protected connectionManager: ConnectionManager;
133
+ private subscriptions;
132
134
  get syncStreamImplementation(): StreamingSyncImplementation | null;
135
+ /**
136
+ * The connector used to connect to the PowerSync service.
137
+ *
138
+ * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
139
+ */
140
+ get connector(): PowerSyncBackendConnector | null;
141
+ /**
142
+ * The resolved connection options used to connect to the PowerSync service.
143
+ *
144
+ * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
145
+ */
146
+ get connectionOptions(): InternalConnectionOptions | null;
133
147
  protected _schema: Schema;
134
148
  private _database;
135
149
  protected runExclusiveMutex: Mutex;
@@ -164,7 +178,7 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
164
178
  * Opens the DBAdapter given open options using a default open factory
165
179
  */
166
180
  protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
167
- protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
181
+ protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
168
182
  protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
169
183
  /**
170
184
  * @returns A promise which will resolve once initialization is completed.
@@ -183,6 +197,10 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
183
197
  signal?: AbortSignal;
184
198
  priority?: number;
185
199
  }): Promise<void>;
200
+ /**
201
+ * Waits for the first sync status for which the `status` callback returns a truthy value.
202
+ */
203
+ waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
186
204
  /**
187
205
  * Allows for extended implementations to execute custom initialization
188
206
  * logic as part of the total init process
@@ -194,7 +212,7 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
194
212
  */
195
213
  protected initialize(): Promise<void>;
196
214
  private _loadVersion;
197
- protected updateHasSynced(): Promise<void>;
215
+ protected resolveOfflineSyncStatus(): Promise<void>;
198
216
  /**
199
217
  * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
200
218
  *
@@ -206,7 +224,7 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
206
224
  * While initializing is automatic, this helps to catch and report initialization errors.
207
225
  */
208
226
  init(): Promise<void>;
209
- resolvedConnectionOptions(options?: PowerSyncConnectionOptions): RequiredAdditionalConnectionOptions;
227
+ protected resolvedConnectionOptions(options: CreateSyncImplementationOptions): CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions;
210
228
  /**
211
229
  * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.
212
230
  * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.
@@ -236,6 +254,15 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
236
254
  * To preserve data in local-only tables, set clearLocal to false.
237
255
  */
238
256
  disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
257
+ /**
258
+ * Create a sync stream to query its status or to subscribe to it.
259
+ *
260
+ * @param name The name of the stream to subscribe to.
261
+ * @param params Optional parameters for the stream subscription.
262
+ * @returns A {@link SyncStream} instance that can be subscribed to.
263
+ * @experimental Sync streams are currently in alpha.
264
+ */
265
+ syncStream(name: string, params?: Record<string, any>): SyncStream;
239
266
  /**
240
267
  * Close the database, releasing resources.
241
268
  *