@powersync/common 1.57.1 → 2.0.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.
Files changed (219) hide show
  1. package/lib/attachments/AttachmentContext.d.ts +5 -5
  2. package/lib/attachments/AttachmentContext.js +6 -2
  3. package/lib/attachments/AttachmentContext.js.map +1 -1
  4. package/lib/attachments/AttachmentQueue.d.ts +6 -6
  5. package/lib/attachments/AttachmentQueue.js +9 -8
  6. package/lib/attachments/AttachmentQueue.js.map +1 -1
  7. package/lib/attachments/AttachmentService.d.ts +3 -3
  8. package/lib/attachments/AttachmentService.js +4 -3
  9. package/lib/attachments/AttachmentService.js.map +1 -1
  10. package/lib/attachments/Schema.d.ts +2 -2
  11. package/lib/attachments/SyncingService.d.ts +2 -2
  12. package/lib/attachments/SyncingService.js +21 -6
  13. package/lib/attachments/SyncingService.js.map +1 -1
  14. package/lib/client/{AbstractPowerSyncDatabase.d.ts → CommonPowerSyncDatabase.d.ts} +56 -232
  15. package/lib/client/CommonPowerSyncDatabase.js +2 -0
  16. package/lib/client/CommonPowerSyncDatabase.js.map +1 -0
  17. package/lib/client/SQLOpenFactory.d.ts +35 -13
  18. package/lib/client/SQLOpenFactory.js +1 -25
  19. package/lib/client/SQLOpenFactory.js.map +1 -1
  20. package/lib/client/compilableQueryWatch.d.ts +2 -2
  21. package/lib/client/compilableQueryWatch.js +1 -2
  22. package/lib/client/compilableQueryWatch.js.map +1 -1
  23. package/lib/client/connection/PowerSyncBackendConnector.d.ts +3 -3
  24. package/lib/client/runOnSchemaChange.d.ts +2 -2
  25. package/lib/client/runOnSchemaChange.js.map +1 -1
  26. package/lib/client/sync/bucket/CrudEntry.d.ts +3 -34
  27. package/lib/client/sync/bucket/CrudEntry.js +0 -99
  28. package/lib/client/sync/bucket/CrudEntry.js.map +1 -1
  29. package/lib/client/sync/options.d.ts +65 -0
  30. package/lib/client/sync/options.js +25 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/sync-streams.d.ts +1 -1
  33. package/lib/client/triggers/TriggerManager.d.ts +9 -38
  34. package/lib/client/watched/GetAllQuery.d.ts +3 -3
  35. package/lib/client/watched/GetAllQuery.js +1 -1
  36. package/lib/client/watched/GetAllQuery.js.map +1 -1
  37. package/lib/client/watched/WatchedQuery.d.ts +2 -10
  38. package/lib/client/watched/WatchedQuery.js +0 -11
  39. package/lib/client/watched/WatchedQuery.js.map +1 -1
  40. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +0 -50
  41. package/lib/client/watched/processors/DifferentialQueryProcessor.js +1 -176
  42. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +1 -1
  43. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +0 -22
  44. package/lib/client/watched/processors/OnChangeQueryProcessor.js +1 -82
  45. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +1 -1
  46. package/lib/db/DBAdapter.d.ts +72 -154
  47. package/lib/db/DBAdapter.js +70 -108
  48. package/lib/db/DBAdapter.js.map +1 -1
  49. package/lib/db/QueryResult.d.ts +104 -0
  50. package/lib/db/QueryResult.js +96 -0
  51. package/lib/db/QueryResult.js.map +1 -0
  52. package/lib/db/crud/SyncProgress.d.ts +1 -13
  53. package/lib/db/crud/SyncProgress.js +1 -62
  54. package/lib/db/crud/SyncProgress.js.map +1 -1
  55. package/lib/db/crud/SyncStatus.d.ts +32 -66
  56. package/lib/db/crud/SyncStatus.js +1 -253
  57. package/lib/db/crud/SyncStatus.js.map +1 -1
  58. package/lib/db/schema/Column.d.ts +0 -7
  59. package/lib/db/schema/Column.js +0 -7
  60. package/lib/db/schema/Column.js.map +1 -1
  61. package/lib/db/schema/Index.d.ts +2 -6
  62. package/lib/db/schema/Index.js +1 -4
  63. package/lib/db/schema/Index.js.map +1 -1
  64. package/lib/db/schema/IndexedColumn.d.ts +2 -6
  65. package/lib/db/schema/IndexedColumn.js +1 -4
  66. package/lib/db/schema/IndexedColumn.js.map +1 -1
  67. package/lib/db/schema/Schema.d.ts +4 -28
  68. package/lib/db/schema/Schema.js.map +1 -1
  69. package/lib/db/schema/Table.d.ts +50 -96
  70. package/lib/db/schema/Table.js +83 -91
  71. package/lib/db/schema/Table.js.map +1 -1
  72. package/lib/index.d.ts +5 -21
  73. package/lib/index.js +5 -22
  74. package/lib/index.js.map +1 -1
  75. package/lib/utils/BaseObserver.d.ts +1 -1
  76. package/lib/utils/BaseObserver.js +1 -1
  77. package/lib/utils/Logger.d.ts +52 -23
  78. package/lib/utils/Logger.js +35 -33
  79. package/lib/utils/Logger.js.map +1 -1
  80. package/lib/utils/MetaBaseObserver.d.ts +11 -11
  81. package/lib/utils/MetaBaseObserver.js +1 -50
  82. package/lib/utils/MetaBaseObserver.js.map +1 -1
  83. package/lib/utils/mutex.d.ts +3 -53
  84. package/lib/utils/mutex.js +1 -156
  85. package/lib/utils/mutex.js.map +1 -1
  86. package/package.json +8 -45
  87. package/src/attachments/AttachmentContext.ts +11 -10
  88. package/src/attachments/AttachmentQueue.ts +15 -14
  89. package/src/attachments/AttachmentService.ts +7 -6
  90. package/src/attachments/Schema.ts +2 -2
  91. package/src/attachments/SyncingService.ts +23 -9
  92. package/src/client/CommonPowerSyncDatabase.ts +540 -0
  93. package/src/client/SQLOpenFactory.ts +38 -22
  94. package/src/client/compilableQueryWatch.ts +3 -4
  95. package/src/client/connection/PowerSyncBackendConnector.ts +3 -3
  96. package/src/client/runOnSchemaChange.ts +2 -2
  97. package/src/client/sync/bucket/CrudEntry.ts +4 -104
  98. package/src/client/sync/options.ts +77 -0
  99. package/src/client/sync/sync-streams.ts +1 -1
  100. package/src/client/triggers/TriggerManager.ts +10 -41
  101. package/src/client/watched/GetAllQuery.ts +3 -3
  102. package/src/client/watched/WatchedQuery.ts +2 -15
  103. package/src/client/watched/processors/DifferentialQueryProcessor.ts +0 -223
  104. package/src/client/watched/processors/OnChangeQueryProcessor.ts +0 -111
  105. package/src/db/DBAdapter.ts +141 -226
  106. package/src/db/QueryResult.ts +195 -0
  107. package/src/db/crud/SyncProgress.ts +2 -42
  108. package/src/db/crud/SyncStatus.ts +45 -220
  109. package/src/db/schema/Column.ts +0 -8
  110. package/src/db/schema/Index.ts +3 -6
  111. package/src/db/schema/IndexedColumn.ts +3 -6
  112. package/src/db/schema/Schema.ts +4 -4
  113. package/src/db/schema/Table.ts +111 -186
  114. package/src/index.ts +5 -21
  115. package/src/utils/BaseObserver.ts +1 -1
  116. package/src/utils/Logger.ts +80 -34
  117. package/src/utils/MetaBaseObserver.ts +14 -60
  118. package/src/utils/mutex.ts +4 -201
  119. package/dist/bundle.cjs +0 -14390
  120. package/dist/bundle.cjs.map +0 -1
  121. package/dist/bundle.mjs +0 -14309
  122. package/dist/bundle.mjs.map +0 -1
  123. package/dist/bundle.node.cjs +0 -12021
  124. package/dist/bundle.node.cjs.map +0 -1
  125. package/dist/bundle.node.mjs +0 -11940
  126. package/dist/bundle.node.mjs.map +0 -1
  127. package/dist/index.d.cts +0 -4651
  128. package/legacy/sync_protocol.d.ts +0 -103
  129. package/lib/client/AbstractPowerSyncDatabase.js +0 -990
  130. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  131. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +0 -28
  132. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -28
  133. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  134. package/lib/client/ConnectionManager.d.ts +0 -115
  135. package/lib/client/ConnectionManager.js +0 -294
  136. package/lib/client/ConnectionManager.js.map +0 -1
  137. package/lib/client/CustomQuery.d.ts +0 -22
  138. package/lib/client/CustomQuery.js +0 -43
  139. package/lib/client/CustomQuery.js.map +0 -1
  140. package/lib/client/constants.d.ts +0 -4
  141. package/lib/client/constants.js +0 -5
  142. package/lib/client/constants.js.map +0 -1
  143. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +0 -56
  144. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -29
  145. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  146. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +0 -37
  147. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -165
  148. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  149. package/lib/client/sync/stream/AbstractRemote.d.ts +0 -180
  150. package/lib/client/sync/stream/AbstractRemote.js +0 -505
  151. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  152. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +0 -265
  153. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +0 -705
  154. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  155. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +0 -15
  156. package/lib/client/sync/stream/WebsocketClientTransport.js +0 -62
  157. package/lib/client/sync/stream/WebsocketClientTransport.js.map +0 -1
  158. package/lib/client/sync/stream/core-instruction.d.ts +0 -77
  159. package/lib/client/sync/stream/core-instruction.js +0 -30
  160. package/lib/client/sync/stream/core-instruction.js.map +0 -1
  161. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +0 -6
  162. package/lib/client/triggers/MemoryTriggerClaimManager.js +0 -21
  163. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +0 -1
  164. package/lib/client/triggers/TriggerManagerImpl.d.ts +0 -39
  165. package/lib/client/triggers/TriggerManagerImpl.js +0 -410
  166. package/lib/client/triggers/TriggerManagerImpl.js.map +0 -1
  167. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +0 -68
  168. package/lib/client/watched/processors/AbstractQueryProcessor.js +0 -151
  169. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +0 -1
  170. package/lib/db/ConnectionClosedError.d.ts +0 -12
  171. package/lib/db/ConnectionClosedError.js +0 -23
  172. package/lib/db/ConnectionClosedError.js.map +0 -1
  173. package/lib/db/schema/TableV2.d.ts +0 -11
  174. package/lib/db/schema/TableV2.js +0 -11
  175. package/lib/db/schema/TableV2.js.map +0 -1
  176. package/lib/utils/AbortOperation.d.ts +0 -11
  177. package/lib/utils/AbortOperation.js +0 -21
  178. package/lib/utils/AbortOperation.js.map +0 -1
  179. package/lib/utils/ControlledExecutor.d.ts +0 -31
  180. package/lib/utils/ControlledExecutor.js +0 -54
  181. package/lib/utils/ControlledExecutor.js.map +0 -1
  182. package/lib/utils/async.d.ts +0 -46
  183. package/lib/utils/async.js +0 -147
  184. package/lib/utils/async.js.map +0 -1
  185. package/lib/utils/compatibility.d.ts +0 -8
  186. package/lib/utils/compatibility.js +0 -9
  187. package/lib/utils/compatibility.js.map +0 -1
  188. package/lib/utils/parseQuery.d.ts +0 -12
  189. package/lib/utils/parseQuery.js +0 -20
  190. package/lib/utils/parseQuery.js.map +0 -1
  191. package/lib/utils/queue.d.ts +0 -16
  192. package/lib/utils/queue.js +0 -42
  193. package/lib/utils/queue.js.map +0 -1
  194. package/lib/utils/stream_transform.d.ts +0 -41
  195. package/lib/utils/stream_transform.js +0 -211
  196. package/lib/utils/stream_transform.js.map +0 -1
  197. package/src/client/AbstractPowerSyncDatabase.ts +0 -1408
  198. package/src/client/AbstractPowerSyncOpenFactory.ts +0 -45
  199. package/src/client/ConnectionManager.ts +0 -405
  200. package/src/client/CustomQuery.ts +0 -56
  201. package/src/client/constants.ts +0 -4
  202. package/src/client/sync/bucket/BucketStorageAdapter.ts +0 -65
  203. package/src/client/sync/bucket/SqliteBucketStorage.ts +0 -202
  204. package/src/client/sync/stream/AbstractRemote.ts +0 -644
  205. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +0 -970
  206. package/src/client/sync/stream/WebsocketClientTransport.ts +0 -82
  207. package/src/client/sync/stream/core-instruction.ts +0 -109
  208. package/src/client/triggers/MemoryTriggerClaimManager.ts +0 -25
  209. package/src/client/triggers/TriggerManagerImpl.ts +0 -501
  210. package/src/client/watched/processors/AbstractQueryProcessor.ts +0 -226
  211. package/src/db/ConnectionClosedError.ts +0 -25
  212. package/src/db/schema/TableV2.ts +0 -11
  213. package/src/utils/AbortOperation.ts +0 -19
  214. package/src/utils/ControlledExecutor.ts +0 -78
  215. package/src/utils/async.ts +0 -185
  216. package/src/utils/compatibility.ts +0 -9
  217. package/src/utils/parseQuery.ts +0 -31
  218. package/src/utils/queue.ts +0 -48
  219. package/src/utils/stream_transform.ts +0 -260
@@ -1,226 +0,0 @@
1
- import { AbstractPowerSyncDatabase } from '../../../client/AbstractPowerSyncDatabase.js';
2
- import { MetaBaseObserver } from '../../../utils/MetaBaseObserver.js';
3
- import {
4
- WatchedQuery,
5
- WatchedQueryListener,
6
- WatchedQueryListenerEvent,
7
- WatchedQueryOptions,
8
- WatchedQueryState
9
- } from '../WatchedQuery.js';
10
-
11
- /**
12
- * @internal
13
- */
14
- export interface AbstractQueryProcessorOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
15
- db: AbstractPowerSyncDatabase;
16
- watchOptions: Settings;
17
- placeholderData: Data;
18
- }
19
-
20
- /**
21
- * @internal
22
- */
23
- export interface LinkQueryOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
24
- abortSignal: AbortSignal;
25
- settings: Settings;
26
- }
27
-
28
- type MutableDeep<T> =
29
- T extends ReadonlyArray<infer U>
30
- ? U[] // convert readonly arrays to mutable arrays
31
- : T;
32
-
33
- /**
34
- * @internal Mutable version of {@link WatchedQueryState}.
35
- * This is used internally to allow updates to the state.
36
- */
37
- export type MutableWatchedQueryState<Data> = {
38
- -readonly [P in keyof WatchedQueryState<Data>]: MutableDeep<WatchedQueryState<Data>[P]>;
39
- };
40
-
41
- type WatchedQueryProcessorListener<Data> = WatchedQueryListener<Data>;
42
-
43
- /**
44
- * Performs underlying watching and yields a stream of results.
45
- * @internal
46
- */
47
- export abstract class AbstractQueryProcessor<
48
- Data = unknown[],
49
- Settings extends WatchedQueryOptions = WatchedQueryOptions
50
- >
51
- extends MetaBaseObserver<WatchedQueryProcessorListener<Data>>
52
- implements WatchedQuery<Data, Settings>
53
- {
54
- readonly state: WatchedQueryState<Data>;
55
-
56
- protected abortController: AbortController;
57
- protected initialized: Promise<void>;
58
- protected _closed: boolean;
59
- protected disposeListeners: (() => void) | null;
60
-
61
- get closed() {
62
- return this._closed;
63
- }
64
-
65
- constructor(protected options: AbstractQueryProcessorOptions<Data, Settings>) {
66
- super();
67
- this.abortController = new AbortController();
68
- this._closed = false;
69
- this.state = this.constructInitialState();
70
- this.disposeListeners = null;
71
- this.initialized = this.init(this.abortController.signal);
72
- }
73
-
74
- protected constructInitialState(): WatchedQueryState<Data> {
75
- return {
76
- isLoading: true,
77
- isFetching: this.reportFetching, // Only set to true if we will report updates in future
78
- error: null,
79
- lastUpdated: null,
80
- data: this.options.placeholderData
81
- };
82
- }
83
-
84
- protected get reportFetching() {
85
- return this.options.watchOptions.reportFetching ?? true;
86
- }
87
-
88
- protected async updateSettingsInternal(settings: Settings, signal: AbortSignal) {
89
- // This may have been aborted while awaiting or if multiple calls to `updateSettings` were made
90
- if (this._closed || signal.aborted) {
91
- return;
92
- }
93
-
94
- this.options.watchOptions = settings;
95
-
96
- this.iterateListeners((l) => l[WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?.());
97
-
98
- if (!this.state.isFetching && this.reportFetching) {
99
- await this.updateState({
100
- isFetching: true
101
- });
102
- }
103
-
104
- await this.runWithReporting(() =>
105
- this.linkQuery({
106
- abortSignal: signal,
107
- settings
108
- })
109
- );
110
- }
111
-
112
- /**
113
- * Updates the underlying query.
114
- */
115
- async updateSettings(settings: Settings) {
116
- // Abort the previous request
117
- this.abortController.abort();
118
-
119
- // Keep track of this controller's abort status
120
- const abortController = new AbortController();
121
- // Allow this to be aborted externally
122
- this.abortController = abortController;
123
-
124
- await this.initialized;
125
- return this.updateSettingsInternal(settings, abortController.signal);
126
- }
127
-
128
- /**
129
- * This method is used to link a query to the subscribers of this listener class.
130
- * This method should perform actual query watching and report results via {@link AbstractQueryProcessor.updateState} method.
131
- */
132
- protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
133
-
134
- protected async updateState(update: Partial<MutableWatchedQueryState<Data>>) {
135
- if (this._closed) {
136
- return;
137
- }
138
-
139
- if (typeof update.error !== 'undefined') {
140
- await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error!));
141
- // An error always stops for the current fetching state
142
- update.isFetching = false;
143
- update.isLoading = false;
144
- }
145
-
146
- Object.assign(this.state, { lastUpdated: new Date() } satisfies Partial<WatchedQueryState<Data>>, update);
147
-
148
- if (typeof update.data !== 'undefined') {
149
- await this.iterateAsyncListenersWithError(async (l) => l.onData?.(this.state.data));
150
- }
151
- await this.iterateAsyncListenersWithError(async (l) => l.onStateChange?.(this.state));
152
- }
153
-
154
- /**
155
- * Configures base DB listeners and links the query to listeners.
156
- */
157
- protected async init(signal: AbortSignal) {
158
- const { db } = this.options;
159
-
160
- const disposeCloseListener = db.registerListener({
161
- closing: async () => {
162
- await this.close();
163
- }
164
- });
165
-
166
- // Wait for the schema to be set before listening to changes
167
- await db.waitForReady();
168
- const disposeSchemaListener = db.registerListener({
169
- schemaChanged: async () => {
170
- await this.runWithReporting(async () => {
171
- await this.updateSettings(this.options.watchOptions);
172
- });
173
- }
174
- });
175
-
176
- this.disposeListeners = () => {
177
- disposeCloseListener();
178
- disposeSchemaListener();
179
- };
180
-
181
- // Initial setup
182
- await this.runWithReporting(async () => {
183
- await this.updateSettingsInternal(this.options.watchOptions, signal);
184
- });
185
- }
186
-
187
- async close() {
188
- this._closed = true;
189
- this.abortController.abort();
190
- this.disposeListeners?.();
191
- this.disposeListeners = null;
192
- this.iterateListeners((l) => l.closed?.());
193
- this.listeners.clear();
194
- }
195
-
196
- /**
197
- * Runs a callback and reports errors to the error listeners.
198
- */
199
- protected async runWithReporting<T>(callback: () => Promise<T>): Promise<void> {
200
- try {
201
- await callback();
202
- } catch (error: any) {
203
- // This will update the error on the state and iterate error listeners
204
- await this.updateState({ error });
205
- }
206
- }
207
-
208
- /**
209
- * Iterate listeners and reports errors to onError handlers.
210
- */
211
- protected async iterateAsyncListenersWithError(
212
- callback: (listener: Partial<WatchedQueryProcessorListener<Data>>) => Promise<void> | void
213
- ) {
214
- try {
215
- await this.iterateAsyncListeners(async (l) => callback(l));
216
- } catch (error: any) {
217
- try {
218
- await this.iterateAsyncListeners(async (l) => l.onError?.(error));
219
- } catch (error) {
220
- // Errors here are ignored
221
- // since we are already in an error state
222
- this.options.db.logger.error('Watched query error handler threw an Error', error);
223
- }
224
- }
225
- }
226
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * Thrown when an underlying database connection is closed.
3
- * This is particularly relevant when worker connections are marked as closed while
4
- * operations are still in progress.
5
- *
6
- * @internal
7
- */
8
- export class ConnectionClosedError extends Error {
9
- static NAME = 'ConnectionClosedError';
10
-
11
- static MATCHES(input: any) {
12
- /**
13
- * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
14
- * check might fail. This also performs a failsafe check.
15
- * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
16
- */
17
- return (
18
- input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME)
19
- );
20
- }
21
- constructor(message: string) {
22
- super(message);
23
- this.name = ConnectionClosedError.NAME;
24
- }
25
- }
@@ -1,11 +0,0 @@
1
- import { ColumnsType } from './Column.js';
2
- import { Table } from './Table.js';
3
-
4
- /**
5
- Generate a new table from the columns and indexes
6
- @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.
7
- This will be removed in the next major release.
8
-
9
- @public
10
- */
11
- export class TableV2<Columns extends ColumnsType = ColumnsType> extends Table<Columns> {}
@@ -1,19 +0,0 @@
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
- }
@@ -1,78 +0,0 @@
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
- await this.runningTask;
69
- this.runningTask = undefined;
70
-
71
- if (this.pendingTaskParam) {
72
- const pendingParam = this.pendingTaskParam;
73
- this.pendingTaskParam = undefined;
74
-
75
- this.execute(pendingParam);
76
- }
77
- }
78
- }
@@ -1,185 +0,0 @@
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
- }
@@ -1,9 +0,0 @@
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');
@@ -1,31 +0,0 @@
1
- import type { CompilableQuery } from '../types/types.js';
2
-
3
- /**
4
- * @internal
5
- */
6
- export interface ParsedQuery {
7
- sqlStatement: string;
8
- parameters: any[];
9
- }
10
-
11
- /**
12
- * @internal
13
- */
14
- export const parseQuery = <T>(query: string | CompilableQuery<T>, parameters: any[]): ParsedQuery => {
15
- let sqlStatement: string;
16
-
17
- if (typeof query == 'string') {
18
- sqlStatement = query;
19
- } else {
20
- const hasAdditionalParameters = parameters.length > 0;
21
- if (hasAdditionalParameters) {
22
- throw new Error('You cannot pass parameters to a compiled query.');
23
- }
24
-
25
- const compiled = query.compile();
26
- sqlStatement = compiled.sql;
27
- parameters = compiled.parameters as any[];
28
- }
29
-
30
- return { sqlStatement, parameters: parameters };
31
- };
@@ -1,48 +0,0 @@
1
- /**
2
- * A simple fixed-capacity queue implementation.
3
- *
4
- * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around
5
- * and is `O(1)` for {@link addLast} and {@link removeFirst}.
6
- */
7
- export class Queue<T> {
8
- private table: (T | undefined)[];
9
- // Index of the first element in the table.
10
- private head: number;
11
- // Amount of items currently in the queue.
12
- private _length: number;
13
-
14
- constructor(initialItems: Iterable<T>) {
15
- this.table = [...initialItems];
16
- this.head = 0;
17
- this._length = this.table.length;
18
- }
19
-
20
- get isEmpty(): boolean {
21
- return this.length == 0;
22
- }
23
-
24
- get length(): number {
25
- return this._length;
26
- }
27
-
28
- removeFirst(): T {
29
- if (this.isEmpty) {
30
- throw new Error('Queue is empty');
31
- }
32
-
33
- const result = this.table[this.head] as T;
34
- this._length--;
35
- this.table[this.head] = undefined;
36
- this.head = (this.head + 1) % this.table.length;
37
- return result;
38
- }
39
-
40
- addLast(element: T) {
41
- if (this.length == this.table.length) {
42
- throw new Error('Queue is full');
43
- }
44
-
45
- this.table[(this.head + this._length) % this.table.length] = element;
46
- this._length++;
47
- }
48
- }