@powersync/shared-internals 0.0.0-tmp.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 (153) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/bundle.cjs +11787 -0
  4. package/dist/bundle.cjs.map +1 -0
  5. package/dist/bundle.mjs +11757 -0
  6. package/dist/bundle.mjs.map +1 -0
  7. package/dist/bundle.node.cjs +9418 -0
  8. package/dist/bundle.node.cjs.map +1 -0
  9. package/dist/bundle.node.mjs +9388 -0
  10. package/dist/bundle.node.mjs.map +1 -0
  11. package/dist/index.d.cts +1159 -0
  12. package/dist/websockets.mjs +7558 -0
  13. package/dist/websockets.mjs.map +1 -0
  14. package/dist/websockets.node.mjs +5189 -0
  15. package/dist/websockets.node.mjs.map +1 -0
  16. package/legacy/sync_protocol.d.ts +103 -0
  17. package/lib/client/BasePowerSyncDatabase.d.ts +147 -0
  18. package/lib/client/BasePowerSyncDatabase.js +622 -0
  19. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  20. package/lib/client/ConnectionManager.d.ts +116 -0
  21. package/lib/client/ConnectionManager.js +306 -0
  22. package/lib/client/ConnectionManager.js.map +1 -0
  23. package/lib/client/CustomQuery.d.ts +21 -0
  24. package/lib/client/CustomQuery.js +43 -0
  25. package/lib/client/CustomQuery.js.map +1 -0
  26. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +42 -0
  27. package/lib/client/sync/bucket/BucketStorageAdapter.js +23 -0
  28. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  29. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  30. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  31. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  32. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +33 -0
  33. package/lib/client/sync/bucket/SqliteBucketStorage.js +166 -0
  34. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  35. package/lib/client/sync/options.d.ts +9 -0
  36. package/lib/client/sync/options.js +16 -0
  37. package/lib/client/sync/options.js.map +1 -0
  38. package/lib/client/sync/stream/AbstractRemote.d.ts +125 -0
  39. package/lib/client/sync/stream/AbstractRemote.js +265 -0
  40. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  41. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +138 -0
  42. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +611 -0
  43. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  44. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  45. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  46. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  47. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  48. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  49. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  50. package/lib/client/sync/stream/core-instruction.d.ts +75 -0
  51. package/lib/client/sync/stream/core-instruction.js +4 -0
  52. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  53. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  54. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  55. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  56. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  57. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  58. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  59. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  60. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  61. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  63. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  64. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  66. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  67. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  68. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  69. package/lib/client/watched/WatchedQuery.js +12 -0
  70. package/lib/client/watched/WatchedQuery.js.map +1 -0
  71. package/lib/constants.d.ts +5 -0
  72. package/lib/constants.js +6 -0
  73. package/lib/constants.js.map +1 -0
  74. package/lib/db/ConnectionClosedError.d.ts +12 -0
  75. package/lib/db/ConnectionClosedError.js +23 -0
  76. package/lib/db/ConnectionClosedError.js.map +1 -0
  77. package/lib/db/crud/SyncProgress.d.ts +10 -0
  78. package/lib/db/crud/SyncProgress.js +33 -0
  79. package/lib/db/crud/SyncProgress.js.map +1 -0
  80. package/lib/db/crud/SyncStatus.d.ts +48 -0
  81. package/lib/db/crud/SyncStatus.js +178 -0
  82. package/lib/db/crud/SyncStatus.js.map +1 -0
  83. package/lib/db/openDatabase.d.ts +7 -0
  84. package/lib/db/openDatabase.js +22 -0
  85. package/lib/db/openDatabase.js.map +1 -0
  86. package/lib/index.d.ts +22 -0
  87. package/lib/index.js +22 -0
  88. package/lib/index.js.map +1 -0
  89. package/lib/utils/AbortOperation.d.ts +11 -0
  90. package/lib/utils/AbortOperation.js +21 -0
  91. package/lib/utils/AbortOperation.js.map +1 -0
  92. package/lib/utils/ControlledExecutor.d.ts +31 -0
  93. package/lib/utils/ControlledExecutor.js +54 -0
  94. package/lib/utils/ControlledExecutor.js.map +1 -0
  95. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  96. package/lib/utils/MetaBaseObserver.js +51 -0
  97. package/lib/utils/MetaBaseObserver.js.map +1 -0
  98. package/lib/utils/async.d.ts +46 -0
  99. package/lib/utils/async.js +147 -0
  100. package/lib/utils/async.js.map +1 -0
  101. package/lib/utils/compatibility.d.ts +8 -0
  102. package/lib/utils/compatibility.js +9 -0
  103. package/lib/utils/compatibility.js.map +1 -0
  104. package/lib/utils/mutex.d.ts +42 -0
  105. package/lib/utils/mutex.js +150 -0
  106. package/lib/utils/mutex.js.map +1 -0
  107. package/lib/utils/parseQuery.d.ts +12 -0
  108. package/lib/utils/parseQuery.js +20 -0
  109. package/lib/utils/parseQuery.js.map +1 -0
  110. package/lib/utils/queue.d.ts +16 -0
  111. package/lib/utils/queue.js +42 -0
  112. package/lib/utils/queue.js.map +1 -0
  113. package/lib/utils/stream_transform.d.ts +41 -0
  114. package/lib/utils/stream_transform.js +211 -0
  115. package/lib/utils/stream_transform.js.map +1 -0
  116. package/lib/version.d.ts +1 -0
  117. package/lib/version.js +4 -0
  118. package/lib/version.js.map +1 -0
  119. package/package.json +65 -0
  120. package/src/client/BasePowerSyncDatabase.ts +853 -0
  121. package/src/client/ConnectionManager.ts +419 -0
  122. package/src/client/CustomQuery.ts +60 -0
  123. package/src/client/sync/bucket/BucketStorageAdapter.ts +51 -0
  124. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  125. package/src/client/sync/bucket/SqliteBucketStorage.ts +213 -0
  126. package/src/client/sync/options.ts +24 -0
  127. package/src/client/sync/stream/AbstractRemote.ts +369 -0
  128. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +795 -0
  129. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  130. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  131. package/src/client/sync/stream/core-instruction.ts +78 -0
  132. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  133. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  134. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  135. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  136. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  137. package/src/client/watched/WatchedQuery.ts +14 -0
  138. package/src/constants.ts +6 -0
  139. package/src/db/ConnectionClosedError.ts +25 -0
  140. package/src/db/crud/SyncProgress.ts +39 -0
  141. package/src/db/crud/SyncStatus.ts +234 -0
  142. package/src/db/openDatabase.ts +23 -0
  143. package/src/index.ts +24 -0
  144. package/src/utils/AbortOperation.ts +19 -0
  145. package/src/utils/ControlledExecutor.ts +78 -0
  146. package/src/utils/MetaBaseObserver.ts +65 -0
  147. package/src/utils/async.ts +185 -0
  148. package/src/utils/compatibility.ts +9 -0
  149. package/src/utils/mutex.ts +186 -0
  150. package/src/utils/parseQuery.ts +31 -0
  151. package/src/utils/queue.ts +48 -0
  152. package/src/utils/stream_transform.ts +260 -0
  153. package/src/version.ts +3 -0
@@ -0,0 +1,231 @@
1
+ import {
2
+ LogLevels,
3
+ WatchedQuery,
4
+ WatchedQueryListener,
5
+ WatchedQueryListenerEvent,
6
+ WatchedQueryOptions,
7
+ WatchedQueryState
8
+ } from '@powersync/common';
9
+ import { MetaBaseObserver } from '../../utils/MetaBaseObserver.js';
10
+ import { BasePowerSyncDatabase } from '../BasePowerSyncDatabase.js';
11
+
12
+ /**
13
+ * @internal
14
+ */
15
+ export interface AbstractQueryProcessorOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
16
+ db: BasePowerSyncDatabase;
17
+ watchOptions: Settings;
18
+ placeholderData: Data;
19
+ }
20
+
21
+ /**
22
+ * @internal
23
+ */
24
+ export interface LinkQueryOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
25
+ abortSignal: AbortSignal;
26
+ settings: Settings;
27
+ }
28
+
29
+ type MutableDeep<T> =
30
+ T extends ReadonlyArray<infer U>
31
+ ? U[] // convert readonly arrays to mutable arrays
32
+ : T;
33
+
34
+ /**
35
+ * @internal Mutable version of {@link WatchedQueryState}.
36
+ * This is used internally to allow updates to the state.
37
+ */
38
+ export type MutableWatchedQueryState<Data> = {
39
+ -readonly [P in keyof WatchedQueryState<Data>]: MutableDeep<WatchedQueryState<Data>[P]>;
40
+ };
41
+
42
+ type WatchedQueryProcessorListener<Data> = WatchedQueryListener<Data>;
43
+
44
+ /**
45
+ * Performs underlying watching and yields a stream of results.
46
+ * @internal
47
+ */
48
+ export abstract class AbstractQueryProcessor<
49
+ Data = unknown[],
50
+ Settings extends WatchedQueryOptions = WatchedQueryOptions
51
+ >
52
+ extends MetaBaseObserver<WatchedQueryProcessorListener<Data>>
53
+ implements WatchedQuery<Data, Settings>
54
+ {
55
+ readonly state: WatchedQueryState<Data>;
56
+
57
+ protected abortController: AbortController;
58
+ protected initialized: Promise<void>;
59
+ protected _closed: boolean;
60
+ protected disposeListeners: (() => void) | null;
61
+
62
+ get closed() {
63
+ return this._closed;
64
+ }
65
+
66
+ constructor(protected options: AbstractQueryProcessorOptions<Data, Settings>) {
67
+ super();
68
+ this.abortController = new AbortController();
69
+ this._closed = false;
70
+ this.state = this.constructInitialState();
71
+ this.disposeListeners = null;
72
+ this.initialized = this.init(this.abortController.signal);
73
+ }
74
+
75
+ protected constructInitialState(): WatchedQueryState<Data> {
76
+ return {
77
+ isLoading: true,
78
+ isFetching: this.reportFetching, // Only set to true if we will report updates in future
79
+ error: null,
80
+ lastUpdated: null,
81
+ data: this.options.placeholderData
82
+ };
83
+ }
84
+
85
+ protected get reportFetching() {
86
+ return this.options.watchOptions.reportFetching ?? true;
87
+ }
88
+
89
+ protected async updateSettingsInternal(settings: Settings, signal: AbortSignal) {
90
+ // This may have been aborted while awaiting or if multiple calls to `updateSettings` were made
91
+ if (this._closed || signal.aborted) {
92
+ return;
93
+ }
94
+
95
+ this.options.watchOptions = settings;
96
+
97
+ this.iterateListeners((l) => l[WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?.());
98
+
99
+ if (!this.state.isFetching && this.reportFetching) {
100
+ await this.updateState({
101
+ isFetching: true
102
+ });
103
+ }
104
+
105
+ await this.runWithReporting(() =>
106
+ this.linkQuery({
107
+ abortSignal: signal,
108
+ settings
109
+ })
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Updates the underlying query.
115
+ */
116
+ async updateSettings(settings: Settings) {
117
+ // Abort the previous request
118
+ this.abortController.abort();
119
+
120
+ // Keep track of this controller's abort status
121
+ const abortController = new AbortController();
122
+ // Allow this to be aborted externally
123
+ this.abortController = abortController;
124
+
125
+ await this.initialized;
126
+ return this.updateSettingsInternal(settings, abortController.signal);
127
+ }
128
+
129
+ /**
130
+ * This method is used to link a query to the subscribers of this listener class.
131
+ * This method should perform actual query watching and report results via {@link AbstractQueryProcessor.updateState} method.
132
+ */
133
+ protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
134
+
135
+ protected async updateState(update: Partial<MutableWatchedQueryState<Data>>) {
136
+ if (this._closed) {
137
+ return;
138
+ }
139
+
140
+ if (typeof update.error !== 'undefined') {
141
+ await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error!));
142
+ // An error always stops for the current fetching state
143
+ update.isFetching = false;
144
+ update.isLoading = false;
145
+ }
146
+
147
+ Object.assign(this.state, { lastUpdated: new Date() } satisfies Partial<WatchedQueryState<Data>>, update);
148
+
149
+ if (typeof update.data !== 'undefined') {
150
+ await this.iterateAsyncListenersWithError(async (l) => l.onData?.(this.state.data));
151
+ }
152
+ await this.iterateAsyncListenersWithError(async (l) => l.onStateChange?.(this.state));
153
+ }
154
+
155
+ /**
156
+ * Configures base DB listeners and links the query to listeners.
157
+ */
158
+ protected async init(signal: AbortSignal) {
159
+ const { db } = this.options;
160
+
161
+ const disposeCloseListener = db.registerListener({
162
+ closing: async () => {
163
+ await this.close();
164
+ }
165
+ });
166
+
167
+ // Wait for the schema to be set before listening to changes
168
+ await db.waitForReady();
169
+ const disposeSchemaListener = db.registerListener({
170
+ schemaChanged: async () => {
171
+ await this.runWithReporting(async () => {
172
+ await this.updateSettings(this.options.watchOptions);
173
+ });
174
+ }
175
+ });
176
+
177
+ this.disposeListeners = () => {
178
+ disposeCloseListener();
179
+ disposeSchemaListener();
180
+ };
181
+
182
+ // Initial setup
183
+ await this.runWithReporting(async () => {
184
+ await this.updateSettingsInternal(this.options.watchOptions, signal);
185
+ });
186
+ }
187
+
188
+ async close() {
189
+ this._closed = true;
190
+ this.abortController.abort();
191
+ this.disposeListeners?.();
192
+ this.disposeListeners = null;
193
+ this.iterateListeners((l) => l.closed?.());
194
+ this.listeners.clear();
195
+ }
196
+
197
+ /**
198
+ * Runs a callback and reports errors to the error listeners.
199
+ */
200
+ protected async runWithReporting<T>(callback: () => Promise<T>): Promise<void> {
201
+ try {
202
+ await callback();
203
+ } catch (error: any) {
204
+ // This will update the error on the state and iterate error listeners
205
+ await this.updateState({ error });
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Iterate listeners and reports errors to onError handlers.
211
+ */
212
+ protected async iterateAsyncListenersWithError(
213
+ callback: (listener: Partial<WatchedQueryProcessorListener<Data>>) => Promise<void> | void
214
+ ) {
215
+ try {
216
+ await this.iterateAsyncListeners(async (l) => callback(l));
217
+ } catch (error: any) {
218
+ try {
219
+ await this.iterateAsyncListeners(async (l) => l.onError?.(error));
220
+ } catch (error) {
221
+ // Errors here are ignored
222
+ // since we are already in an error state
223
+ this.options.db.logger.log({
224
+ level: LogLevels.error,
225
+ message: 'Watched query error handler threw an Error',
226
+ error
227
+ });
228
+ }
229
+ }
230
+ }
231
+ }
@@ -0,0 +1,226 @@
1
+ import {
2
+ DifferentialWatchedQuery,
3
+ DifferentialWatchedQueryComparator,
4
+ DifferentialWatchedQuerySettings,
5
+ WatchedQueryDifferential,
6
+ WatchedQueryRowDifferential
7
+ } from '@powersync/common';
8
+ import {
9
+ AbstractQueryProcessor,
10
+ AbstractQueryProcessorOptions,
11
+ LinkQueryOptions,
12
+ MutableWatchedQueryState
13
+ } from './AbstractQueryProcessor.js';
14
+
15
+ /**
16
+ * @internal
17
+ */
18
+ export interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<
19
+ RowType[],
20
+ DifferentialWatchedQuerySettings<RowType>
21
+ > {
22
+ rowComparator?: DifferentialWatchedQueryComparator<RowType>;
23
+ }
24
+
25
+ type DataHashMap<RowType> = Map<string, { hash: string; item: RowType }>;
26
+
27
+ /**
28
+ * An empty differential result set.
29
+ * This is used as the initial state for differential incrementally watched queries.
30
+ *
31
+ * @internal
32
+ */
33
+ export const EMPTY_DIFFERENTIAL = {
34
+ added: [],
35
+ all: [],
36
+ removed: [],
37
+ updated: [],
38
+ unchanged: []
39
+ };
40
+
41
+ /**
42
+ * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
43
+ * It keys items by their `id` property if available, alternatively it uses JSON stringification
44
+ * of the entire item for the key and comparison.
45
+ *
46
+ * @internal
47
+ */
48
+ export const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any> = {
49
+ keyBy: (item) => {
50
+ if (item && typeof item == 'object' && typeof item['id'] == 'string') {
51
+ return item['id'];
52
+ }
53
+ return JSON.stringify(item);
54
+ },
55
+ compareBy: (item) => JSON.stringify(item)
56
+ };
57
+
58
+ /**
59
+ * Uses the PowerSync onChange event to trigger watched queries.
60
+ * Results are emitted on every change of the relevant tables.
61
+ * @internal
62
+ */
63
+ export class DifferentialQueryProcessor<RowType>
64
+ extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>>
65
+ implements DifferentialWatchedQuery<RowType>
66
+ {
67
+ protected comparator: DifferentialWatchedQueryComparator<RowType>;
68
+
69
+ constructor(protected options: DifferentialQueryProcessorOptions<RowType>) {
70
+ super(options);
71
+ this.comparator = options.rowComparator ?? DEFAULT_ROW_COMPARATOR;
72
+ }
73
+
74
+ /*
75
+ * @returns If the sets are equal
76
+ */
77
+ protected differentiate(
78
+ current: RowType[],
79
+ previousMap: DataHashMap<RowType>
80
+ ): { diff: WatchedQueryDifferential<RowType>; map: DataHashMap<RowType>; hasChanged: boolean } {
81
+ const { keyBy, compareBy } = this.comparator;
82
+
83
+ let hasChanged = false;
84
+ const currentMap = new Map<string, { hash: string; item: RowType }>();
85
+ const removedTracker = new Set(previousMap.keys());
86
+
87
+ // Allow mutating to populate the data temporarily.
88
+ const diff = {
89
+ all: [] as RowType[],
90
+ added: [] as RowType[],
91
+ removed: [] as RowType[],
92
+ updated: [] as WatchedQueryRowDifferential<RowType>[],
93
+ unchanged: [] as RowType[]
94
+ };
95
+
96
+ /**
97
+ * Looping over the current result set array is important to preserve
98
+ * the ordering of the result set.
99
+ * We can replace items in the current array with previous object references if they are equal.
100
+ */
101
+ for (const item of current) {
102
+ const key = keyBy(item);
103
+ const hash = compareBy(item);
104
+ currentMap.set(key, { hash, item });
105
+
106
+ const previousItem = previousMap.get(key);
107
+ if (!previousItem) {
108
+ // New item
109
+ hasChanged = true;
110
+ diff.added.push(item);
111
+ diff.all.push(item);
112
+ } else {
113
+ // Existing item
114
+ if (hash == previousItem.hash) {
115
+ diff.unchanged.push(previousItem.item);
116
+ // Use the previous object reference
117
+ diff.all.push(previousItem.item);
118
+ // update the map to preserve the reference
119
+ currentMap.set(key, previousItem);
120
+ } else {
121
+ hasChanged = true;
122
+ diff.updated.push({ current: item, previous: previousItem.item });
123
+ // Use the new reference
124
+ diff.all.push(item);
125
+ }
126
+ }
127
+ // The item is present, we don't consider it removed
128
+ removedTracker.delete(key);
129
+ }
130
+
131
+ diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key)!.item);
132
+ hasChanged = hasChanged || diff.removed.length > 0;
133
+
134
+ return {
135
+ diff,
136
+ hasChanged,
137
+ map: currentMap
138
+ };
139
+ }
140
+
141
+ protected async linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void> {
142
+ const { db, watchOptions } = this.options;
143
+ const { abortSignal } = options;
144
+
145
+ const compiledQuery = watchOptions.query.compile();
146
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters as any[], {
147
+ tables: options.settings.triggerOnTables
148
+ });
149
+
150
+ let currentMap: DataHashMap<RowType> = new Map();
151
+
152
+ // populate the currentMap from the placeholder data
153
+ this.state.data.forEach((item) => {
154
+ currentMap.set(this.comparator.keyBy(item), {
155
+ hash: this.comparator.compareBy(item),
156
+ item
157
+ });
158
+ });
159
+
160
+ db.onChangeWithCallback(
161
+ {
162
+ onChange: async () => {
163
+ if (this.closed || abortSignal.aborted) {
164
+ return;
165
+ }
166
+ // This fires for each change of the relevant tables
167
+ try {
168
+ if (this.reportFetching && !this.state.isFetching) {
169
+ await this.updateState({ isFetching: true });
170
+ }
171
+
172
+ const partialStateUpdate: Partial<MutableWatchedQueryState<RowType[]>> = {};
173
+
174
+ // Always run the query if an underlying table has changed
175
+ const result = await watchOptions.query.execute({
176
+ sql: compiledQuery.sql,
177
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
178
+ // This allows simpler compatibility with PowerSync queries
179
+ parameters: [...compiledQuery.parameters],
180
+ db: this.options.db
181
+ });
182
+
183
+ if (abortSignal.aborted) {
184
+ return;
185
+ }
186
+
187
+ if (this.reportFetching) {
188
+ partialStateUpdate.isFetching = false;
189
+ }
190
+
191
+ if (this.state.isLoading) {
192
+ partialStateUpdate.isLoading = false;
193
+ }
194
+
195
+ const { diff, hasChanged, map } = this.differentiate(result, currentMap);
196
+ // Update for future comparisons
197
+ currentMap = map;
198
+
199
+ if (hasChanged) {
200
+ await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));
201
+ Object.assign(partialStateUpdate, {
202
+ data: diff.all
203
+ });
204
+ }
205
+
206
+ if (this.state.error) {
207
+ partialStateUpdate.error = null;
208
+ }
209
+
210
+ if (Object.keys(partialStateUpdate).length > 0) {
211
+ await this.updateState(partialStateUpdate);
212
+ }
213
+ } catch (error: any) {
214
+ await this.updateState({ error });
215
+ }
216
+ }
217
+ },
218
+ {
219
+ signal: abortSignal,
220
+ tables,
221
+ throttleMs: watchOptions.throttleMs,
222
+ triggerImmediate: true // used to emit the initial state
223
+ }
224
+ );
225
+ }
226
+ }
@@ -0,0 +1,108 @@
1
+ import { WatchedQueryComparator, WatchedQuerySettings } from '@powersync/common';
2
+ import {
3
+ AbstractQueryProcessor,
4
+ AbstractQueryProcessorOptions,
5
+ LinkQueryOptions,
6
+ MutableWatchedQueryState
7
+ } from './AbstractQueryProcessor.js';
8
+
9
+ /**
10
+ * @internal
11
+ */
12
+ export interface OnChangeQueryProcessorOptions<Data> extends AbstractQueryProcessorOptions<
13
+ Data,
14
+ WatchedQuerySettings<Data>
15
+ > {
16
+ comparator?: WatchedQueryComparator<Data>;
17
+ }
18
+
19
+ /**
20
+ * Uses the PowerSync onChange event to trigger watched queries.
21
+ * Results are emitted on every change of the relevant tables.
22
+ * @internal
23
+ */
24
+ export class OnChangeQueryProcessor<Data> extends AbstractQueryProcessor<Data, WatchedQuerySettings<Data>> {
25
+ constructor(protected options: OnChangeQueryProcessorOptions<Data>) {
26
+ super(options);
27
+ }
28
+
29
+ /**
30
+ * @returns If the sets are equal
31
+ */
32
+ protected checkEquality(current: Data, previous: Data): boolean {
33
+ // Use the provided comparator if available. Assume values are unique if not available.
34
+ return this.options.comparator?.checkEquality?.(current, previous) ?? false;
35
+ }
36
+
37
+ protected async linkQuery(options: LinkQueryOptions<Data>): Promise<void> {
38
+ const { db, watchOptions } = this.options;
39
+ const { abortSignal } = options;
40
+
41
+ const compiledQuery = watchOptions.query.compile();
42
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters as any[], {
43
+ tables: options.settings.triggerOnTables
44
+ });
45
+
46
+ db.onChangeWithCallback(
47
+ {
48
+ onChange: async () => {
49
+ if (this.closed || abortSignal.aborted) {
50
+ return;
51
+ }
52
+ // This fires for each change of the relevant tables
53
+ try {
54
+ if (this.reportFetching && !this.state.isFetching) {
55
+ await this.updateState({ isFetching: true });
56
+ }
57
+
58
+ const partialStateUpdate: Partial<MutableWatchedQueryState<Data>> & { data?: Data } = {};
59
+
60
+ // Always run the query if an underlying table has changed
61
+ const result = await watchOptions.query.execute({
62
+ sql: compiledQuery.sql,
63
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
64
+ // This allows simpler compatibility with PowerSync queries
65
+ parameters: [...compiledQuery.parameters],
66
+ db: this.options.db
67
+ });
68
+
69
+ if (abortSignal.aborted) {
70
+ return;
71
+ }
72
+
73
+ if (this.reportFetching) {
74
+ partialStateUpdate.isFetching = false;
75
+ }
76
+
77
+ if (this.state.isLoading) {
78
+ partialStateUpdate.isLoading = false;
79
+ }
80
+
81
+ // Check if the result has changed
82
+ if (!this.checkEquality(result, this.state.data)) {
83
+ Object.assign(partialStateUpdate, {
84
+ data: result
85
+ });
86
+ }
87
+
88
+ if (this.state.error) {
89
+ partialStateUpdate.error = null;
90
+ }
91
+
92
+ if (Object.keys(partialStateUpdate).length > 0) {
93
+ await this.updateState(partialStateUpdate);
94
+ }
95
+ } catch (error: any) {
96
+ await this.updateState({ error });
97
+ }
98
+ }
99
+ },
100
+ {
101
+ signal: abortSignal,
102
+ tables,
103
+ throttleMs: watchOptions.throttleMs,
104
+ triggerImmediate: true // used to emit the initial state
105
+ }
106
+ );
107
+ }
108
+ }
@@ -0,0 +1,14 @@
1
+ import { WatchedQueryOptions } from '@powersync/common';
2
+
3
+ /**
4
+ * @internal
5
+ */
6
+ export const DEFAULT_WATCH_THROTTLE_MS = 30;
7
+
8
+ /**
9
+ * @internal
10
+ */
11
+ export const DEFAULT_WATCH_QUERY_OPTIONS: WatchedQueryOptions = {
12
+ throttleMs: DEFAULT_WATCH_THROTTLE_MS,
13
+ reportFetching: true
14
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @internal The priority used by the core extension to indicate that a full sync was completed.
3
+ */
4
+ export const FULL_SYNC_PRIORITY = 2147483647;
5
+
6
+ export const MAX_OP_ID = '9223372036854775807';
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,39 @@
1
+ // (bucket, progress) pairs
2
+
3
+ import { ProgressWithOperations, SyncProgress } from '@powersync/common';
4
+ import { FULL_SYNC_PRIORITY } from '../../constants.js';
5
+ import { DownloadProgress } from '../../client/sync/stream/core-instruction.js';
6
+
7
+ export class SyncProgressImpl implements SyncProgress {
8
+ totalOperations: number;
9
+ downloadedOperations: number;
10
+ downloadedFraction: number;
11
+
12
+ constructor(protected internal: DownloadProgress) {
13
+ const untilCompletion = this.untilPriority(FULL_SYNC_PRIORITY);
14
+
15
+ this.totalOperations = untilCompletion.totalOperations;
16
+ this.downloadedOperations = untilCompletion.downloadedOperations;
17
+ this.downloadedFraction = untilCompletion.downloadedFraction;
18
+ }
19
+
20
+ untilPriority(priority: number): ProgressWithOperations {
21
+ let total = 0;
22
+ let downloaded = 0;
23
+
24
+ for (const progress of Object.values(this.internal.buckets)) {
25
+ // Include higher-priority buckets, which are represented by lower numbers.
26
+ if (progress.priority <= priority) {
27
+ downloaded += progress.since_last;
28
+ total += progress.target_count - progress.at_last;
29
+ }
30
+ }
31
+
32
+ let progress = total == 0 ? 0.0 : downloaded / total;
33
+ return {
34
+ totalOperations: total,
35
+ downloadedOperations: downloaded,
36
+ downloadedFraction: progress
37
+ };
38
+ }
39
+ }