@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,234 @@
1
+ import {
2
+ SyncDataFlowStatus,
3
+ SyncPriorityStatus,
4
+ SyncProgress,
5
+ SyncStatus,
6
+ SyncStreamDescription,
7
+ SyncStreamStatus,
8
+ SyncSubscriptionDescription
9
+ } from '@powersync/common';
10
+ import { CoreStreamSubscription, CoreSyncStatus } from '../../client/sync/stream/core-instruction.js';
11
+ import { SyncPriorityStatus as CoreSyncPriorityStatus } from '../../client/sync/stream/core-instruction.js';
12
+ import { SyncProgressImpl } from './SyncProgress.js';
13
+ import { FULL_SYNC_PRIORITY } from '../../constants.js';
14
+
15
+ /**
16
+ * The {@link SyncStatus} subset not managed by the Rust client in {@link CoreSyncStatus}.
17
+ *
18
+ * This includes the upload state and JS errors.
19
+ */
20
+ export interface JavaScriptSyncState {
21
+ uploading?: boolean;
22
+ downloadError?: Error;
23
+ uploadError?: Error;
24
+ }
25
+
26
+ export class SyncStatusSnapshot implements SyncStatus {
27
+ constructor(
28
+ readonly core: CoreSyncStatus | null,
29
+ readonly jsState: JavaScriptSyncState
30
+ ) {}
31
+
32
+ get connected(): boolean {
33
+ return this.core?.connected ?? false;
34
+ }
35
+
36
+ get connecting(): boolean {
37
+ return this.core?.connecting ?? false;
38
+ }
39
+
40
+ get downloading(): boolean {
41
+ return this.core?.downloading != null;
42
+ }
43
+
44
+ get uploading(): boolean {
45
+ return this.jsState.uploading ?? false;
46
+ }
47
+
48
+ get downloadError(): Error | undefined {
49
+ return this.jsState.downloadError;
50
+ }
51
+
52
+ get uploadError(): Error | undefined {
53
+ return this.jsState.uploadError;
54
+ }
55
+
56
+ get dataFlowStatus(): SyncDataFlowStatus {
57
+ return {
58
+ downloading: this.downloading,
59
+ uploading: this.uploading,
60
+ downloadError: this.downloadError,
61
+ uploadError: this.uploadError
62
+ };
63
+ }
64
+
65
+ get lastSyncedAt(): Date | undefined {
66
+ return this.statusForPriority(FULL_SYNC_PRIORITY)?.lastSyncedAt;
67
+ }
68
+
69
+ get hasSynced(): boolean | undefined {
70
+ return this.statusForPriority(FULL_SYNC_PRIORITY)?.hasSynced;
71
+ }
72
+
73
+ get syncStreams(): SyncStreamStatus[] | undefined {
74
+ return this.core?.streams.map((core) => new SyncStreamStatusView(this, core));
75
+ }
76
+
77
+ forStream(stream: SyncStreamDescription): SyncStreamStatus | undefined {
78
+ const asJson = JSON.stringify(stream.parameters);
79
+ const raw = this.core?.streams?.find((r) => r.name == stream.name && asJson == JSON.stringify(r.parameters));
80
+
81
+ return raw && new SyncStreamStatusView(this, raw);
82
+ }
83
+
84
+ get priorityStatusEntries(): SyncPriorityStatus[] | undefined {
85
+ return this.core?.priority_status.map(priorityToJs);
86
+ }
87
+
88
+ get downloadProgress(): SyncProgress | null {
89
+ const internalProgress = this.core?.downloading;
90
+ if (internalProgress == null) {
91
+ return null;
92
+ }
93
+
94
+ return new SyncProgressImpl(internalProgress);
95
+ }
96
+
97
+ statusForPriority(priority: number): SyncPriorityStatus | undefined {
98
+ const coreStatus = this.core?.priority_status;
99
+ if (coreStatus == null) return undefined;
100
+
101
+ // priorityStatusEntries are sorted by ascending priorities (so higher numbers to lower numbers).
102
+ for (const known of coreStatus) {
103
+ // We look for the first entry that doesn't have a higher priority.
104
+ if (known.priority >= priority) {
105
+ return priorityToJs(known);
106
+ }
107
+ }
108
+
109
+ // If we get to this point, no priority entry exists so we never synced a priority that low.
110
+ return {
111
+ priority,
112
+ lastSyncedAt: undefined,
113
+ hasSynced: false
114
+ };
115
+ }
116
+
117
+ isEqual(status: SyncStatus) {
118
+ /**
119
+ * By default Error object are serialized to an empty object.
120
+ * This replaces Errors with more useful information before serialization.
121
+ */
122
+ const replacer = (_: string, value: any) => {
123
+ if (value instanceof Error) {
124
+ return this.serializeError(value);
125
+ }
126
+ return value;
127
+ };
128
+
129
+ const options = { core: this.core, jsState: this.jsState };
130
+ const otherStatus = status as unknown as SyncStatusSnapshot;
131
+ const otherOptions = {
132
+ core: otherStatus.core,
133
+ jsState: otherStatus.jsState
134
+ };
135
+
136
+ return JSON.stringify(options, replacer) == JSON.stringify(otherOptions, replacer);
137
+ }
138
+
139
+ getMessage() {
140
+ return `SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${this.downloading}. Uploading: ${this.uploading}. UploadError: ${this.uploadError}, DownloadError?: ${this.downloadError}>`;
141
+ }
142
+
143
+ /**
144
+ * Serializes the SyncStatus instance to a plain object.
145
+ *
146
+ * @returns A plain object representation of the sync status
147
+ */
148
+ toJSON(): SyncStatusJson {
149
+ return {
150
+ core: this.core,
151
+ dataFlow: {
152
+ uploading: this.uploading,
153
+ uploadError: this.serializeError(this.uploadError),
154
+ downloadError: this.serializeError(this.downloadError)
155
+ }
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
161
+ * This explicitly serializes errors in the SyncStatus.
162
+ */
163
+ serializeError(error?: Error) {
164
+ if (typeof error == 'undefined') {
165
+ return undefined;
166
+ }
167
+ const serialized: Error = {
168
+ name: error.name,
169
+ message: error.message,
170
+ stack: error.stack
171
+ };
172
+ // `Error.cause` can be any value (the spec types it as unknown). Preserve it
173
+ // so consumers reading uploadError/downloadError keep the failure context.
174
+ // Recurse for Error causes so the whole chain is flattened the same way.
175
+ if (typeof error.cause != 'undefined') {
176
+ serialized.cause = error.cause instanceof Error ? this.serializeError(error.cause) : error.cause;
177
+ }
178
+ return serialized;
179
+ }
180
+ }
181
+
182
+ function coreTimestampToDate(time: number | null): Date | undefined {
183
+ return time == null ? undefined : new Date(time / 1000);
184
+ }
185
+
186
+ function priorityToJs(status: CoreSyncPriorityStatus): SyncPriorityStatus {
187
+ return {
188
+ priority: status.priority,
189
+ hasSynced: status.has_synced ?? undefined,
190
+ lastSyncedAt: coreTimestampToDate(status.last_synced_at)
191
+ };
192
+ }
193
+
194
+ export interface SyncStatusJson {
195
+ // Note: When updating this, also update packages/tauri/src/database.rs
196
+ core: CoreSyncStatus | null;
197
+ dataFlow: JavaScriptSyncState;
198
+ }
199
+
200
+ class SyncStreamStatusView implements SyncStreamStatus {
201
+ subscription: SyncSubscriptionDescription;
202
+
203
+ constructor(
204
+ private status: SyncStatusSnapshot,
205
+ private core: CoreStreamSubscription
206
+ ) {
207
+ this.subscription = {
208
+ name: core.name,
209
+ parameters: core.parameters,
210
+ active: core.active,
211
+ isDefault: core.is_default,
212
+ hasExplicitSubscription: core.has_explicit_subscription,
213
+ expiresAt: core.expires_at != null ? new Date(core.expires_at * 1000) : null,
214
+ hasSynced: core.last_synced_at != null,
215
+ lastSyncedAt: core.last_synced_at != null ? new Date(core.last_synced_at * 1000) : null
216
+ };
217
+ }
218
+
219
+ get progress() {
220
+ if (this.status.core?.downloading == null) {
221
+ // Don't make download progress public if we're not currently downloading.
222
+ return null;
223
+ }
224
+
225
+ const { total, downloaded } = this.core.progress;
226
+ const progress = total == 0 ? 0.0 : downloaded / total;
227
+
228
+ return { totalOperations: total, downloadedOperations: downloaded, downloadedFraction: progress };
229
+ }
230
+
231
+ get priority() {
232
+ return this.core.priority;
233
+ }
234
+ }
@@ -0,0 +1,23 @@
1
+ import { DatabaseSource, DBAdapter, SQLOpenOptions } from '@powersync/common';
2
+
3
+ /**
4
+ * Internal helper to turn a {@link DatabaseSource} into an opened {@link DBAdapter}.
5
+ *
6
+ * @internal
7
+ */
8
+ export function openDatabase<T extends SQLOpenOptions>(
9
+ source: DatabaseSource<T>,
10
+ defaultFactory: (options: T) => DBAdapter
11
+ ): DBAdapter {
12
+ if ('opened' in source) {
13
+ return source.opened;
14
+ } else if ('factory' in source) {
15
+ return source.factory.openDB();
16
+ } else if ('database' in source && source.database?.dbFilename) {
17
+ return defaultFactory(source.database);
18
+ } else {
19
+ // This is dead code for well-typed programs, but JavaScript users might have forgotten to pass an option
20
+ // when creating a PowerSync database instance.
21
+ throw new Error('The provided `database` option is invalid.');
22
+ }
23
+ }
package/src/index.ts ADDED
@@ -0,0 +1,24 @@
1
+ export * from './client/BasePowerSyncDatabase.js';
2
+ export * from './client/sync/bucket/BucketStorageAdapter.js';
3
+ export * from './client/sync/bucket/CrudEntry.js';
4
+ export * from './client/sync/bucket/SqliteBucketStorage.js';
5
+ export * from './client/sync/stream/AbstractRemote.js';
6
+ export * from './client/sync/stream/AbstractStreamingSyncImplementation.js';
7
+ export * from './client/sync/stream/core-instruction.js';
8
+ export * from './db/ConnectionClosedError.js';
9
+ export * from './db/openDatabase.js';
10
+ export * from './db/crud/SyncStatus.js';
11
+ export * from './client/ConnectionManager.js';
12
+ export * from './client/sync/options.js';
13
+
14
+ export { MEMORY_TRIGGER_CLAIM_MANAGER } from './client/triggers/MemoryTriggerClaimManager.js';
15
+ export * from './client/triggers/TriggerManagerImpl.js';
16
+ export * from './client/watched/DifferentialQueryProcessor.js';
17
+ export * from './client/watched/OnChangeQueryProcessor.js';
18
+
19
+ export * from './utils/AbortOperation.js';
20
+ export * from './utils/compatibility.js';
21
+ export * from './utils/ControlledExecutor.js';
22
+ export * from './utils/mutex.js';
23
+ export * from './utils/parseQuery.js';
24
+ export type { SimpleAsyncIterator } from './utils/stream_transform.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Calls to Abortcontroller.abort(reason: any) will result in the
3
+ * `reason` being thrown. This is not necessarily an error,
4
+ * but extends error for better logging purposes.
5
+ *
6
+ * @internal
7
+ */
8
+ export class AbortOperation extends Error {
9
+ constructor(protected reason: string) {
10
+ super(reason);
11
+ // Set the prototype explicitly
12
+ Object.setPrototypeOf(this, AbortOperation.prototype);
13
+
14
+ // Capture stack trace
15
+ if (Error.captureStackTrace) {
16
+ Error.captureStackTrace(this, AbortOperation);
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ export interface ControlledExecutorOptions {
5
+ /**
6
+ * If throttling is enabled, it ensures only one task runs at a time,
7
+ * and only one additional task can be scheduled to run after the current task completes. The pending task will be overwritten by the latest task.
8
+ * Enabled by default.
9
+ */
10
+ throttleEnabled?: boolean;
11
+ }
12
+
13
+ /**
14
+ * @internal
15
+ */
16
+ export class ControlledExecutor<T> {
17
+ private task: (param: T) => Promise<void> | void;
18
+
19
+ /**
20
+ * Represents the currently running task, which could be a Promise or undefined if no task is running.
21
+ */
22
+ private runningTask: undefined | (Promise<void> | void);
23
+
24
+ private pendingTaskParam: T | undefined;
25
+
26
+ /**
27
+ * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.
28
+ */
29
+ private isThrottling: boolean;
30
+
31
+ private closed: boolean;
32
+
33
+ constructor(task: (param: T) => Promise<void> | void, options?: ControlledExecutorOptions) {
34
+ this.task = task;
35
+ const { throttleEnabled = true } = options ?? {};
36
+ this.isThrottling = throttleEnabled;
37
+ this.closed = false;
38
+ }
39
+
40
+ schedule(param: T) {
41
+ if (this.closed) {
42
+ return;
43
+ }
44
+ if (!this.isThrottling) {
45
+ this.task(param);
46
+ return;
47
+ }
48
+
49
+ if (this.runningTask) {
50
+ // set or replace the pending task param with latest one
51
+ this.pendingTaskParam = param;
52
+ return;
53
+ }
54
+
55
+ this.execute(param);
56
+ }
57
+
58
+ dispose() {
59
+ this.closed = true;
60
+
61
+ if (this.runningTask) {
62
+ this.runningTask = undefined;
63
+ }
64
+ }
65
+
66
+ private async execute(param: T) {
67
+ this.runningTask = this.task(param);
68
+ try {
69
+ await this.runningTask;
70
+ } finally {
71
+ this.runningTask = undefined;
72
+
73
+ if (this.pendingTaskParam) {
74
+ const pendingParam = this.pendingTaskParam;
75
+ this.pendingTaskParam = undefined;
76
+
77
+ this.execute(pendingParam);
78
+ }
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ BaseObserver,
3
+ BaseListener,
4
+ ListenerCounts,
5
+ ListenerMetaManager,
6
+ MetaBaseObserverInterface,
7
+ MetaListener
8
+ } from '@powersync/common';
9
+
10
+ /**
11
+ * A BaseObserver that tracks the counts of listeners for each event type.
12
+ */
13
+ export class MetaBaseObserver<Listener extends BaseListener>
14
+ extends BaseObserver<Listener>
15
+ implements MetaBaseObserverInterface<Listener>
16
+ {
17
+ protected get listenerCounts(): ListenerCounts<Listener> {
18
+ const counts = {} as Partial<Record<keyof Listener, number>>;
19
+ let total = 0;
20
+ for (const listener of this.listeners) {
21
+ for (const key in listener) {
22
+ if (listener[key]) {
23
+ counts[key] = (counts[key] ?? 0) + 1;
24
+ total++;
25
+ }
26
+ }
27
+ }
28
+ return {
29
+ ...counts,
30
+ total
31
+ };
32
+ }
33
+
34
+ get listenerMeta(): ListenerMetaManager<Listener> {
35
+ return {
36
+ counts: this.listenerCounts,
37
+ // Allows registering a meta listener that will be notified of changes in listener counts
38
+ registerListener: (listener: Partial<MetaListener<Listener>>) => {
39
+ return this.metaListener.registerListener(listener);
40
+ }
41
+ };
42
+ }
43
+
44
+ protected metaListener: BaseObserver<MetaListener<Listener>>;
45
+
46
+ constructor() {
47
+ super();
48
+ this.metaListener = new BaseObserver<MetaListener<Listener>>();
49
+ }
50
+
51
+ registerListener(listener: Partial<Listener>): () => void {
52
+ const dispose = super.registerListener(listener);
53
+ const updatedCount = this.listenerCounts;
54
+ this.metaListener.iterateListeners((l) => {
55
+ l.listenersChanged?.(updatedCount);
56
+ });
57
+ return () => {
58
+ dispose();
59
+ const updatedCount = this.listenerCounts;
60
+ this.metaListener.iterateListeners((l) => {
61
+ l.listenersChanged?.(updatedCount);
62
+ });
63
+ };
64
+ }
65
+ }
@@ -0,0 +1,185 @@
1
+ import { symbolAsyncIterator } from './compatibility.js';
2
+ import { doneResult, valueResult } from './stream_transform.js';
3
+
4
+ /**
5
+ * Throttle a function to be called at most once every "wait" milliseconds,
6
+ * on the trailing edge.
7
+ *
8
+ * Roughly equivalent to lodash/throttle with {leading: false, trailing: true}
9
+ */
10
+ export function throttleTrailing(func: () => void, wait: number) {
11
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
12
+
13
+ const later = () => {
14
+ func();
15
+ timeoutId = null;
16
+ };
17
+
18
+ return function () {
19
+ if (timeoutId == null) {
20
+ timeoutId = setTimeout(later, wait);
21
+ }
22
+ };
23
+ }
24
+
25
+ export interface AsyncNotifier {
26
+ /**
27
+ * @param signal Also resolve the promise once this signal completes.
28
+ * @returns A promise that resolves once {@link notify} is called after this promise was last resolved.
29
+ */
30
+ waitForNotification(signal: AbortSignal): Promise<void>;
31
+
32
+ /**
33
+ * Notifies a pending listener, or makes the next {@link waitForNotification} complete immediately if no listener
34
+ * is currently active.
35
+ */
36
+ notify(): void;
37
+ }
38
+
39
+ export function asyncNotifier(): AsyncNotifier {
40
+ const queue = new EventQueue<void>();
41
+
42
+ return {
43
+ notify() {
44
+ if (queue.countOutstandingEvents > 0) {
45
+ // Already has an outstanding event, no need to buffer another one.
46
+ } else {
47
+ queue.notify();
48
+ }
49
+ },
50
+ waitForNotification(signal: AbortSignal) {
51
+ return queue.waitForEvent(signal);
52
+ }
53
+ };
54
+ }
55
+
56
+ type QueueWaiter<T> = { resolve: (event: T) => void; reject: (error: unknown) => void };
57
+
58
+ export interface QueueOptions {
59
+ eventDelivered?: () => void;
60
+ }
61
+
62
+ export class EventQueue<T> {
63
+ private waitingConsumer: QueueWaiter<T> | undefined;
64
+ private readonly outstandingEvents: Array<(waiter: QueueWaiter<T>) => void>;
65
+
66
+ constructor(private readonly options: QueueOptions = {}) {
67
+ this.outstandingEvents = [];
68
+ }
69
+
70
+ /**
71
+ * The amount of buffered events not yet dispatched to listeners.
72
+ */
73
+ get countOutstandingEvents(): number {
74
+ return this.outstandingEvents.length;
75
+ }
76
+
77
+ private notifyInner(dispatch: (waiter: QueueWaiter<T>) => void) {
78
+ const existing = this.waitingConsumer;
79
+ this.waitingConsumer = undefined;
80
+
81
+ const dispatchAndNotifyListeners = (waiter: QueueWaiter<T>) => {
82
+ dispatch(waiter);
83
+ this.options.eventDelivered?.();
84
+ };
85
+
86
+ if (existing) {
87
+ dispatchAndNotifyListeners(existing);
88
+ } else {
89
+ this.outstandingEvents.push(dispatchAndNotifyListeners);
90
+ }
91
+ }
92
+
93
+ notify(value: T) {
94
+ this.notifyInner((l) => l.resolve(value));
95
+ }
96
+
97
+ notifyError(error: unknown) {
98
+ this.notifyInner((l) => l.reject(error));
99
+ }
100
+
101
+ waitForEvent(signal: AbortSignal): Promise<T | undefined> {
102
+ return new Promise((resolve, reject) => {
103
+ if (this.waitingConsumer != null) {
104
+ throw new Error('Illegal call to waitForEvent, already has a waiter.');
105
+ }
106
+
107
+ const complete = () => {
108
+ signal?.removeEventListener('abort', onAbort);
109
+ };
110
+
111
+ const onAbort = () => {
112
+ complete();
113
+ this.waitingConsumer = undefined;
114
+ resolve(undefined);
115
+ };
116
+
117
+ const waiter: QueueWaiter<T> = {
118
+ resolve: (value) => {
119
+ complete();
120
+ resolve(value);
121
+ },
122
+ reject: (error) => {
123
+ complete();
124
+ reject(error);
125
+ }
126
+ };
127
+
128
+ if (signal.aborted) {
129
+ resolve(undefined);
130
+ } else if (this.countOutstandingEvents > 0) {
131
+ const [event] = this.outstandingEvents.splice(0, 1);
132
+ event(waiter);
133
+ } else {
134
+ this.waitingConsumer = waiter;
135
+ signal.addEventListener('abort', onAbort);
136
+ }
137
+ });
138
+ }
139
+
140
+ /**
141
+ * Creates an async iterable backed by event queues.
142
+ *
143
+ * @param run A function invoked for every new listener. It receives a queue backing the async iterator.
144
+ * @param abort An additional abort signal. The `run` callback will also be aborted when `AsyncIterator.return` is
145
+ * called.
146
+ * @returns An object conforming to the async iterable protocol.
147
+ */
148
+ static queueBasedAsyncIterable<T>(
149
+ run: (queue: EventQueue<T>, abort: AbortSignal) => void,
150
+ abort?: AbortSignal
151
+ ): AsyncIterable<T> {
152
+ return {
153
+ [symbolAsyncIterator]: () => {
154
+ const queue = new EventQueue<T>();
155
+ const controller = new AbortController();
156
+
157
+ function dispose() {
158
+ controller.abort();
159
+ abort?.removeEventListener('abort', dispose);
160
+ }
161
+
162
+ if (abort) {
163
+ if (abort.aborted) {
164
+ controller.abort();
165
+ } else {
166
+ abort.addEventListener('abort', dispose);
167
+ }
168
+ }
169
+
170
+ run(queue, controller.signal);
171
+
172
+ return {
173
+ async next(): Promise<IteratorResult<T>> {
174
+ const event = await queue.waitForEvent(controller.signal);
175
+ return event == null ? doneResult : valueResult(event);
176
+ },
177
+ async return(): Promise<IteratorResult<T>> {
178
+ dispose();
179
+ return doneResult;
180
+ }
181
+ };
182
+ }
183
+ };
184
+ }
185
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Some JavaScript engines, in particular older versions of React Native, don't support Symbol.asyncIterator.
3
+ *
4
+ * For those, users relying on async generators typically lower them with a transpiler and [this polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6).
5
+ * This definition is compatible with that polyfill, so transpiled apps can use async iterables created by the PowerSync
6
+ * SDK.
7
+ */
8
+ export const symbolAsyncIterator: typeof Symbol.asyncIterator =
9
+ Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');