@powersync/shared-internals 0.0.0-dev-20260827080125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,441 @@
1
+ import {
2
+ BaseObserver,
3
+ LogLevels,
4
+ PowerSyncLogger,
5
+ SyncStatus,
6
+ BaseListener,
7
+ PowerSyncBackendConnector,
8
+ SyncStream,
9
+ SyncStreamDescription,
10
+ SyncStreamSubscribeOptions,
11
+ SyncStreamSubscription,
12
+ SyncOptions,
13
+ SyncStreamConnectionMethod
14
+ } from '@powersync/common';
15
+
16
+ import { StreamingSyncImplementation, SubscribedStream } from './sync/stream/AbstractStreamingSyncImplementation.js';
17
+ import { ResolvedSyncOptions, resolveSyncOptions } from './sync/options.js';
18
+
19
+ /**
20
+ * @internal
21
+ */
22
+ export interface ConnectionManagerSyncImplementationResult {
23
+ sync: StreamingSyncImplementation;
24
+ /**
25
+ * Additional cleanup function which is called after the sync stream implementation
26
+ * is disposed.
27
+ */
28
+ onDispose: () => Promise<void> | void;
29
+ }
30
+
31
+ /**
32
+ * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
33
+ *
34
+ * @internal
35
+ */
36
+ export interface CreateSyncImplementationOptions {
37
+ subscriptions: SubscribedStream[];
38
+ serializedSchema: any;
39
+ }
40
+
41
+ /**
42
+ * @internal
43
+ */
44
+ export interface InternalSubscriptionAdapter {
45
+ firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
46
+ resolveOfflineSyncStatus(): Promise<void>;
47
+ rustSubscriptionsCommand(payload: any): Promise<void>;
48
+ }
49
+
50
+ /**
51
+ * @internal
52
+ */
53
+ export interface ConnectionManagerOptions {
54
+ createSyncImplementation(
55
+ connector: PowerSyncBackendConnector,
56
+ options: CreateSyncImplementationOptions
57
+ ): Promise<ConnectionManagerSyncImplementationResult>;
58
+ readonly defaultConnectionMethod: SyncStreamConnectionMethod;
59
+
60
+ logger: PowerSyncLogger;
61
+ }
62
+
63
+ type StoredConnectionOptions = {
64
+ connector: PowerSyncBackendConnector;
65
+ options: ResolvedSyncOptions;
66
+ schema: any;
67
+ };
68
+
69
+ /**
70
+ * @internal
71
+ */
72
+ export interface ConnectionManagerListener extends BaseListener {
73
+ syncStreamCreated: (sync: StreamingSyncImplementation) => void;
74
+ }
75
+
76
+ /**
77
+ * @internal
78
+ */
79
+ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
80
+ /**
81
+ * Tracks active connection attempts
82
+ */
83
+ protected connectingPromise: Promise<void> | null;
84
+ /**
85
+ * Tracks actively instantiating a streaming sync implementation.
86
+ */
87
+ protected syncStreamInitPromise: Promise<void> | null;
88
+ /**
89
+ * Active disconnect operation. Calling disconnect multiple times
90
+ * will resolve to the same operation.
91
+ */
92
+ protected disconnectingPromise: Promise<void> | null;
93
+ /**
94
+ * Tracks the last parameters supplied to `connect` calls.
95
+ * Calling `connect` multiple times in succession will result in:
96
+ * - 1 pending connection operation which will be aborted.
97
+ * - updating the last set of parameters while waiting for the pending
98
+ * attempt to be aborted
99
+ * - internally connecting with the last set of parameters
100
+ */
101
+ protected pendingConnectionOptions: StoredConnectionOptions | null;
102
+
103
+ private currentOptions: ResolvedSyncOptions | null;
104
+
105
+ syncStreamImplementation: StreamingSyncImplementation | null;
106
+
107
+ /**
108
+ * Additional cleanup function which is called after the sync stream implementation
109
+ * is disposed.
110
+ */
111
+ protected syncDisposer: (() => Promise<void> | void) | null;
112
+
113
+ /**
114
+ * Subscriptions managed in this connection manager.
115
+ *
116
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
117
+ */
118
+ private locallyActiveSubscriptions = new Map<string, ActiveSubscription>();
119
+
120
+ constructor(protected options: ConnectionManagerOptions) {
121
+ super();
122
+ this.connectingPromise = null;
123
+ this.syncStreamInitPromise = null;
124
+ this.disconnectingPromise = null;
125
+ this.pendingConnectionOptions = null;
126
+ this.syncStreamImplementation = null;
127
+ this.currentOptions = null;
128
+ this.syncDisposer = null;
129
+ }
130
+
131
+ get connector() {
132
+ return this.pendingConnectionOptions?.connector ?? null;
133
+ }
134
+
135
+ get connectionOptions() {
136
+ return this.currentOptions ?? this.pendingConnectionOptions?.options ?? null;
137
+ }
138
+
139
+ get logger() {
140
+ return this.options.logger;
141
+ }
142
+
143
+ async close() {
144
+ await this.syncStreamImplementation?.dispose();
145
+ await this.syncDisposer?.();
146
+ }
147
+
148
+ async connect(connector: PowerSyncBackendConnector, options: SyncOptions, serializedSchema: any) {
149
+ // Keep track if there were pending operations before this call
150
+ const hadPendingOptions = !!this.pendingConnectionOptions;
151
+
152
+ // Update pending options to the latest values
153
+ const resolvedOptions = resolveSyncOptions(options, this.options.defaultConnectionMethod);
154
+ this.pendingConnectionOptions = {
155
+ connector,
156
+ options: resolvedOptions,
157
+ schema: serializedSchema
158
+ };
159
+
160
+ if (connector.postCheckpointRequest && resolvedOptions.checkpointMode == 'legacy') {
161
+ this.logger.log({
162
+ level: LogLevels.warn,
163
+ message:
164
+ 'The backend connector implements postCheckpointRequest, but connect() was called without checkpoint requests enabled.'
165
+ });
166
+ }
167
+
168
+ // Disconnecting here provides aborting in progress connection attempts.
169
+ // The connectInternal method will clear pending options once it starts connecting (with the options).
170
+ // We only need to trigger a disconnect here if we have already reached the point of connecting.
171
+ // If we do already have pending options, a disconnect has already been performed.
172
+ // The connectInternal method also does a sanity disconnect to prevent straggler connections.
173
+ // We should also disconnect if we have already completed a connection attempt.
174
+ if (!hadPendingOptions || this.syncStreamImplementation) {
175
+ await this.disconnectInternal();
176
+ }
177
+
178
+ // Triggers a connect which checks if pending options are available after the connect completes.
179
+ // The completion can be for a successful, unsuccessful or aborted connection attempt.
180
+ // If pending options are available another connection will be triggered.
181
+ const checkConnection = async (): Promise<void> => {
182
+ if (this.pendingConnectionOptions) {
183
+ // Pending options have been placed while connecting.
184
+ // Need to reconnect.
185
+ this.connectingPromise = this.connectInternal()
186
+ .catch(() => {})
187
+ .finally(checkConnection);
188
+ return this.connectingPromise;
189
+ } else {
190
+ // Clear the connecting promise, done.
191
+ this.connectingPromise = null;
192
+ return;
193
+ }
194
+ };
195
+
196
+ this.connectingPromise ??= this.connectInternal()
197
+ .catch(() => {})
198
+ .finally(checkConnection);
199
+ return this.connectingPromise;
200
+ }
201
+
202
+ protected async connectInternal() {
203
+ let appliedOptions: ResolvedSyncOptions | null = null;
204
+
205
+ // This method ensures a disconnect before any connection attempt
206
+ await this.disconnectInternal();
207
+
208
+ /**
209
+ * This portion creates a sync implementation which can be racy when disconnecting or
210
+ * if multiple tabs on web are in use.
211
+ * This is protected in an exclusive lock.
212
+ * The promise tracks the creation which is used to synchronize disconnect attempts.
213
+ */
214
+ this.syncStreamInitPromise = new Promise(async (resolve, reject) => {
215
+ try {
216
+ if (!this.pendingConnectionOptions) {
217
+ this.logger.log({
218
+ level: LogLevels.debug,
219
+ message: 'No pending connection options found, not creating sync stream implementation'
220
+ });
221
+ // A disconnect could have cleared this.
222
+ resolve();
223
+ return;
224
+ }
225
+
226
+ if (this.disconnectingPromise) {
227
+ resolve();
228
+ return;
229
+ }
230
+
231
+ const { connector, options, schema } = this.pendingConnectionOptions;
232
+ appliedOptions = options;
233
+ this.currentOptions = options;
234
+
235
+ this.pendingConnectionOptions = null;
236
+
237
+ const subscriptionsAtStart = this.subscriptionIdentity;
238
+ const { sync, onDispose } = await this.options.createSyncImplementation(connector, {
239
+ subscriptions: this.activeStreams,
240
+ serializedSchema: schema
241
+ });
242
+ this.iterateListeners((l) => l.syncStreamCreated?.(sync));
243
+ this.syncStreamImplementation = sync;
244
+ this.syncDisposer = onDispose;
245
+ await this.syncStreamImplementation.waitForReady();
246
+
247
+ // Subscriptions changed while creating the sync stream implementation, update it now.
248
+ if (this.subscriptionIdentity !== subscriptionsAtStart) {
249
+ this.syncStreamImplementation.updateSubscriptions(this.activeStreams);
250
+ }
251
+ resolve();
252
+ } catch (error) {
253
+ reject(error);
254
+ }
255
+ });
256
+
257
+ await this.syncStreamInitPromise;
258
+ this.syncStreamInitPromise = null;
259
+
260
+ if (!appliedOptions) {
261
+ // A disconnect could have cleared the options which did not create a syncStreamImplementation
262
+ return;
263
+ }
264
+
265
+ // It might be possible that a disconnect triggered between the last check
266
+ // and this point. Awaiting here allows the sync stream to be cleared if disconnected.
267
+ await this.disconnectingPromise;
268
+
269
+ this.logger.log({ level: LogLevels.debug, message: 'Attempting to connect to PowerSync instance' });
270
+ await this.syncStreamImplementation?.connect(appliedOptions!);
271
+ }
272
+
273
+ /**
274
+ * Close the sync connection.
275
+ *
276
+ * Use {@link ConnectionManager.connect} to connect again.
277
+ */
278
+ async disconnect() {
279
+ // This will help abort pending connects
280
+ this.pendingConnectionOptions = null;
281
+ this.currentOptions = null;
282
+ await this.disconnectInternal();
283
+ }
284
+
285
+ protected async disconnectInternal(): Promise<void> {
286
+ if (this.disconnectingPromise) {
287
+ // A disconnect is already in progress
288
+ return this.disconnectingPromise;
289
+ }
290
+
291
+ this.disconnectingPromise = this.performDisconnect();
292
+
293
+ await this.disconnectingPromise;
294
+ this.disconnectingPromise = null;
295
+ }
296
+
297
+ protected async performDisconnect() {
298
+ // Wait if a sync stream implementation is being created before closing it
299
+ // (syncStreamImplementation must be assigned before we can properly dispose it)
300
+ await this.syncStreamInitPromise;
301
+
302
+ // Keep reference to the sync stream implementation and disposer
303
+ // The class members will be cleared before we trigger the disconnect
304
+ // to prevent any further calls to the sync stream implementation.
305
+ const sync = this.syncStreamImplementation;
306
+ this.syncStreamImplementation = null;
307
+ const disposer = this.syncDisposer;
308
+ this.syncDisposer = null;
309
+
310
+ await sync?.disconnect();
311
+ await sync?.dispose();
312
+ await disposer?.();
313
+ }
314
+
315
+ stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream {
316
+ const desc = { name, parameters } satisfies SyncStreamDescription;
317
+
318
+ const waitForFirstSync = (abort?: AbortSignal) => {
319
+ return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);
320
+ };
321
+
322
+ return {
323
+ ...desc,
324
+ subscribe: async (options?: SyncStreamSubscribeOptions) => {
325
+ // NOTE: We also run this command if a subscription already exists, because this increases the expiry date
326
+ // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).
327
+ await adapter.rustSubscriptionsCommand({
328
+ subscribe: {
329
+ stream: {
330
+ name,
331
+ params: parameters
332
+ },
333
+ ttl: options?.ttl,
334
+ priority: options?.priority
335
+ }
336
+ });
337
+
338
+ if (!this.syncStreamImplementation) {
339
+ // We're not connected. So, update the offline sync status to reflect the new subscription.
340
+ // (With an active iteration, the sync client would include it in its state).
341
+ await adapter.resolveOfflineSyncStatus();
342
+ }
343
+
344
+ const key = `${name}|${JSON.stringify(parameters)}`;
345
+ let subscription = this.locallyActiveSubscriptions.get(key);
346
+ if (subscription == null) {
347
+ const clearSubscription = () => {
348
+ this.locallyActiveSubscriptions.delete(key);
349
+ this.subscriptionsMayHaveChanged();
350
+ };
351
+
352
+ subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);
353
+ this.locallyActiveSubscriptions.set(key, subscription);
354
+ this.subscriptionsMayHaveChanged();
355
+ }
356
+
357
+ return new SyncStreamSubscriptionHandle(subscription);
358
+ },
359
+ unsubscribeAll: async () => {
360
+ await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });
361
+ this.subscriptionsMayHaveChanged();
362
+ }
363
+ };
364
+ }
365
+
366
+ /**
367
+ * @internal exposed for testing
368
+ */
369
+ get activeStreams() {
370
+ return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));
371
+ }
372
+
373
+ /**
374
+ * Identifies the current set of subscriptions, for detecting a change across an await.
375
+ */
376
+ private get subscriptionIdentity() {
377
+ return [...this.locallyActiveSubscriptions.keys()].join('\n');
378
+ }
379
+
380
+ private subscriptionsMayHaveChanged() {
381
+ this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);
382
+ }
383
+ }
384
+
385
+ class ActiveSubscription {
386
+ refcount: number = 0;
387
+
388
+ constructor(
389
+ readonly name: string,
390
+ readonly parameters: Record<string, any> | null,
391
+ readonly logger: PowerSyncLogger,
392
+ readonly waitForFirstSync: (abort?: AbortSignal) => Promise<void>,
393
+ private clearSubscription: () => void
394
+ ) {}
395
+
396
+ decrementRefCount() {
397
+ this.refcount--;
398
+ if (this.refcount == 0) {
399
+ this.clearSubscription();
400
+ }
401
+ }
402
+ }
403
+
404
+ class SyncStreamSubscriptionHandle implements SyncStreamSubscription {
405
+ private active: boolean = true;
406
+
407
+ constructor(readonly subscription: ActiveSubscription) {
408
+ subscription.refcount++;
409
+ _finalizer?.register(this, subscription, this);
410
+ }
411
+
412
+ get name() {
413
+ return this.subscription.name;
414
+ }
415
+
416
+ get parameters() {
417
+ return this.subscription.parameters;
418
+ }
419
+
420
+ waitForFirstSync(abort?: AbortSignal): Promise<void> {
421
+ return this.subscription.waitForFirstSync(abort);
422
+ }
423
+
424
+ unsubscribe(): void {
425
+ if (this.active) {
426
+ this.active = false;
427
+ _finalizer?.unregister(this);
428
+ this.subscription.decrementRefCount();
429
+ }
430
+ }
431
+ }
432
+
433
+ const _finalizer =
434
+ 'FinalizationRegistry' in globalThis
435
+ ? new FinalizationRegistry<ActiveSubscription>((sub) => {
436
+ sub.logger.log({
437
+ level: LogLevels.warn,
438
+ message: `A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`
439
+ });
440
+ })
441
+ : null;
@@ -0,0 +1,60 @@
1
+ import {
2
+ Query,
3
+ StandardWatchedQueryOptions,
4
+ FalsyComparator,
5
+ WatchCompatibleQuery,
6
+ WatchedQueryOptions,
7
+ DifferentialWatchedQueryOptions
8
+ } from '@powersync/common';
9
+
10
+ import { BasePowerSyncDatabase } from './BasePowerSyncDatabase.js';
11
+ import { DifferentialQueryProcessor } from './watched/DifferentialQueryProcessor.js';
12
+ import { OnChangeQueryProcessor } from './watched/OnChangeQueryProcessor.js';
13
+ import { DEFAULT_WATCH_QUERY_OPTIONS } from './watched/WatchedQuery.js';
14
+
15
+ /**
16
+ * @internal
17
+ */
18
+ export interface CustomQueryOptions<RowType> {
19
+ db: BasePowerSyncDatabase;
20
+ query: WatchCompatibleQuery<RowType[]>;
21
+ }
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export class CustomQuery<RowType> implements Query<RowType> {
27
+ constructor(protected options: CustomQueryOptions<RowType>) {}
28
+
29
+ protected resolveOptions(options: WatchedQueryOptions): WatchedQueryOptions {
30
+ return {
31
+ reportFetching: options?.reportFetching ?? DEFAULT_WATCH_QUERY_OPTIONS.reportFetching,
32
+ throttleMs: options?.throttleMs ?? DEFAULT_WATCH_QUERY_OPTIONS.throttleMs,
33
+ triggerOnTables: options?.triggerOnTables
34
+ };
35
+ }
36
+
37
+ watch(watchOptions: StandardWatchedQueryOptions<RowType>) {
38
+ return new OnChangeQueryProcessor<RowType[]>({
39
+ db: this.options.db,
40
+ comparator: watchOptions?.comparator ?? FalsyComparator,
41
+ placeholderData: watchOptions?.placeholderData ?? [],
42
+ watchOptions: {
43
+ ...this.resolveOptions(watchOptions),
44
+ query: this.options.query
45
+ }
46
+ });
47
+ }
48
+
49
+ differentialWatch(differentialWatchOptions: DifferentialWatchedQueryOptions<RowType>) {
50
+ return new DifferentialQueryProcessor<RowType>({
51
+ db: this.options.db,
52
+ rowComparator: differentialWatchOptions?.rowComparator,
53
+ placeholderData: differentialWatchOptions?.placeholderData ?? [],
54
+ watchOptions: {
55
+ ...this.resolveOptions(differentialWatchOptions),
56
+ query: this.options.query
57
+ }
58
+ });
59
+ }
60
+ }
@@ -0,0 +1,54 @@
1
+ import { CheckpointRequest } from '@powersync/common';
2
+ import { BasePowerSyncDatabase } from '../BasePowerSyncDatabase.js';
3
+ import {
4
+ cannotRequestDueToDisconnectedError,
5
+ checkpointRequestsNotEnabledError,
6
+ isCheckpointRequestApplied
7
+ } from './stream/CheckpointState.js';
8
+ import { SyncStatusSnapshot } from '../../db/crud/SyncStatus.js';
9
+
10
+ export class CheckpointRequestImpl implements CheckpointRequest {
11
+ constructor(
12
+ private readonly requestId: bigint,
13
+ private readonly database: BasePowerSyncDatabase
14
+ ) {}
15
+
16
+ get hasSynced(): boolean {
17
+ const status = this.database.currentStatus.core;
18
+ return isCheckpointRequestApplied(status, this.requestId);
19
+ }
20
+
21
+ async waitForSync(options?: { signal?: AbortSignal }): Promise<void> {
22
+ if (this.hasSynced) return;
23
+
24
+ const signal = options?.signal;
25
+ const manager = this.database.connectionManager;
26
+ if (manager.syncStreamImplementation == null) {
27
+ throw cannotRequestDueToDisconnectedError();
28
+ }
29
+ if (manager.connectionOptions?.checkpointMode == 'legacy') {
30
+ throw checkpointRequestsNotEnabledError();
31
+ }
32
+
33
+ await this.database.waitForStatus((status) => {
34
+ if (isCheckpointRequestApplied((status as SyncStatusSnapshot).core, this.requestId)) {
35
+ return true;
36
+ }
37
+
38
+ const anyError = status.downloadError ?? status.uploadError;
39
+ if (anyError) {
40
+ throw new Error('Sync error while waiting for checkpoint request', { cause: anyError });
41
+ }
42
+
43
+ if (!status.connected && !status.connecting) {
44
+ throw cannotRequestDueToDisconnectedError();
45
+ }
46
+
47
+ return false;
48
+ }, signal);
49
+
50
+ if (signal?.aborted) {
51
+ throw signal.reason;
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,85 @@
1
+ import {
2
+ BaseListener,
3
+ BaseObserverInterface,
4
+ Disposable,
5
+ CrudBatch,
6
+ CrudEntry,
7
+ Transaction,
8
+ SqliteValue
9
+ } from '@powersync/common';
10
+ import { MAX_OP_ID } from '../../../constants.js';
11
+
12
+ export enum PSInternalTable {
13
+ DATA = 'ps_data',
14
+ CRUD = 'ps_crud',
15
+ BUCKETS = 'ps_buckets',
16
+ OPLOG = 'ps_oplog',
17
+ UNTYPED = 'ps_untyped'
18
+ }
19
+
20
+ export enum PowerSyncControlCommand {
21
+ PROCESS_TEXT_LINE = 'line_text',
22
+ PROCESS_BSON_LINE = 'line_binary',
23
+ STOP = 'stop',
24
+ START = 'start',
25
+ NOTIFY_TOKEN_REFRESHED = 'refreshed_token',
26
+ NOTIFY_CRUD_UPLOAD_COMPLETED = 'completed_upload',
27
+ UPDATE_SUBSCRIPTIONS = 'update_subscriptions',
28
+ /**
29
+ * An `established` or `end` event for response streams.
30
+ */
31
+ CONNECTION_STATE = 'connection'
32
+ }
33
+
34
+ export interface BucketStorageListener extends BaseListener {
35
+ crudUpdate: () => void;
36
+ }
37
+
38
+ export interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListener>, Disposable {
39
+ hasMigratedSubkeys(): Promise<boolean>;
40
+ migrateToFixedSubkeys(): Promise<void>;
41
+
42
+ nextCrudItem(): Promise<CrudEntry | undefined>;
43
+ hasCrud(): Promise<boolean>;
44
+ getCrudBatch(limit?: number): Promise<CrudBatch | null>;
45
+
46
+ updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
47
+ handleCrudCheckpoint(lastClientId: number, writeCheckpoint?: string): Promise<void>;
48
+ readCheckpointRequestId(variant: 'next' | 'current' | 'seed', payload?: string): Promise<string>;
49
+
50
+ /**
51
+ * Get an unique client id.
52
+ */
53
+ getClientId(): Promise<string>;
54
+
55
+ /**
56
+ * Invokes the `powersync_control` function for the sync client.
57
+ */
58
+ control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
59
+ }
60
+
61
+ /**
62
+ * Invokes `powersync_control` from the core extension, casting the result to text.
63
+ */
64
+ export async function rawPowerSyncControl(tx: Transaction, op: string, payload: SqliteValue): Promise<string | null> {
65
+ // For some calls, notably on target_checkpoint_request_id, powersync_control returns a 64-bit integer we want to
66
+ // represent as text. Instead of dealing with bigints which may or may not be supported across different sqlite
67
+ // libraries, play it safe and cast to text before mapping to JavaScript.
68
+ const { rawRows } = await tx.executeRaw('SELECT CAST(powersync_control(?, ?) AS TEXT)', [op, payload]);
69
+ return rawRows[0][0] as string | null;
70
+ }
71
+
72
+ /**
73
+ * Reads the current target checkpoint request id, or updates it when the update parameter is set.
74
+ *
75
+ * After requesting a checkpoint, the service needs to include that checkpoint id (or a subsequent one) in a
76
+ * `checkpoint_complete` message before we apply any subsequent sync lines. This guards against uploaded changes that
77
+ * have not yet been synced to flicker if we apply an intermediate checkpoint.
78
+ *
79
+ * @param update An optional value to update the stored target checkpoint request. {@link MAX_OP_ID} can be used as a
80
+ * sentinel for pending changes that have been uploaded, but for which no checkpoint request has been created yet.
81
+ * @returns The previous checkpoint request.
82
+ */
83
+ export function targetCheckpointRequestId(tx: Transaction, update: string | null = null): Promise<string | null> {
84
+ return rawPowerSyncControl(tx, 'target_checkpoint_request_id', update);
85
+ }