@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
@@ -21,44 +21,12 @@ export enum UpdateType {
21
21
  DELETE = 'DELETE'
22
22
  }
23
23
 
24
- /**
25
- * @internal
26
- */
27
- export type CrudEntryJSON = {
28
- id: string;
29
- data: string;
30
- tx_id?: number;
31
- };
32
-
33
- type CrudEntryDataJSON = {
34
- data: Record<string, any>;
35
- old?: Record<string, any>;
36
- op: UpdateType;
37
- type: string;
38
- id: string;
39
- metadata?: string;
40
- };
41
-
42
- /**
43
- * The output JSON seems to be a third type of JSON, not the same as the input JSON.
44
- */
45
- type CrudEntryOutputJSON = {
46
- op_id: number;
47
- op: UpdateType;
48
- type: string;
49
- id: string;
50
- tx_id?: number;
51
- data?: Record<string, any>;
52
- old?: Record<string, any>;
53
- metadata?: string;
54
- };
55
-
56
24
  /**
57
25
  * A single client-side change.
58
26
  *
59
27
  * @public
60
28
  */
61
- export class CrudEntry {
29
+ export interface CrudEntry {
62
30
  /**
63
31
  * Auto-incrementing client-side id.
64
32
  */
@@ -99,83 +67,15 @@ export class CrudEntry {
99
67
  */
100
68
  metadata?: string;
101
69
 
102
- static fromRow(dbRow: CrudEntryJSON) {
103
- const data: CrudEntryDataJSON = JSON.parse(dbRow.data);
104
- return new CrudEntry(
105
- parseInt(dbRow.id),
106
- data.op,
107
- data.type,
108
- data.id,
109
- dbRow.tx_id,
110
- data.data,
111
- data.old,
112
- data.metadata
113
- );
114
- }
115
-
116
- constructor(
117
- clientId: number,
118
- op: UpdateType,
119
- table: string,
120
- id: string,
121
- transactionId?: number,
122
- opData?: Record<string, any>,
123
- previousValues?: Record<string, any>,
124
- metadata?: string
125
- ) {
126
- this.clientId = clientId;
127
- this.id = id;
128
- this.op = op;
129
- this.opData = opData;
130
- this.table = table;
131
- this.transactionId = transactionId;
132
- this.previousValues = previousValues;
133
- this.metadata = metadata;
134
- }
135
-
136
70
  /**
137
71
  * Converts the change to JSON format.
138
72
  */
139
- toJSON(): CrudEntryOutputJSON {
140
- return {
141
- op_id: this.clientId,
142
- op: this.op,
143
- type: this.table,
144
- id: this.id,
145
- tx_id: this.transactionId,
146
- data: this.opData,
147
- old: this.previousValues,
148
- metadata: this.metadata
149
- };
150
- }
151
-
152
- equals(entry: CrudEntry) {
153
- return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());
154
- }
73
+ toJSON(): unknown;
155
74
 
156
- /**
157
- * The hash code for this object.
158
- * @deprecated This should not be necessary in the JS SDK.
159
- * Use the @see CrudEntry#equals method instead.
160
- * TODO remove in the next major release.
161
- */
162
- hashCode() {
163
- return JSON.stringify(this.toComparisonArray());
164
- }
75
+ equals(entry: CrudEntry): boolean;
165
76
 
166
77
  /**
167
78
  * Generates an array for use in deep comparison operations
168
79
  */
169
- toComparisonArray() {
170
- return [
171
- this.transactionId,
172
- this.clientId,
173
- this.op,
174
- this.table,
175
- this.id,
176
- this.opData,
177
- this.previousValues,
178
- this.metadata
179
- ];
180
- }
80
+ toComparisonArray(): unknown[];
181
81
  }
@@ -0,0 +1,77 @@
1
+ import { StreamingSyncRequestParameterType } from './stream/JsonValue.js';
2
+
3
+ /**
4
+ * Options that affect how the PowerSync SDK connects to the PowerSync Service.
5
+ *
6
+ * @public
7
+ */
8
+ export interface SyncOptions {
9
+ // Note: When adding new fields to this interface, consider that these objects need to be serializable.
10
+
11
+ /**
12
+ * A set of metadata to be included in service logs.
13
+ */
14
+ appMetadata?: Record<string, string>;
15
+
16
+ /**
17
+ * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
18
+ */
19
+ params?: Record<string, StreamingSyncRequestParameterType>;
20
+
21
+ /**
22
+ * The connection method to use when streaming updates from
23
+ * the PowerSync backend instance.
24
+ *
25
+ * The default value is SDK-specific. {@link SyncStreamConnectionMethod.HTTP} is the preferred implementation and used
26
+ * by default, except for React Native apps without Expo. Those don't support streaming HTTP responses, which is why
27
+ * {@link SyncStreamConnectionMethod.WEB_SOCKET} is used as a workaround.
28
+ */
29
+ connectionMethod?: SyncStreamConnectionMethod;
30
+
31
+ fetchStrategy?: FetchStrategy;
32
+
33
+ /**
34
+ * Whether to include streams that have `auto_subscribe: true` in their definition.
35
+ *
36
+ * This defaults to `true`.
37
+ */
38
+ includeDefaultStreams?: boolean;
39
+
40
+ /**
41
+ * Delay for retrying sync streaming operations
42
+ * from the PowerSync backend after an error occurs.
43
+ */
44
+ retryDelayMs?: number;
45
+
46
+ /**
47
+ * Backend Connector CRUD operations are throttled
48
+ * to occur at most every `crudUploadThrottleMs`
49
+ * milliseconds.
50
+ */
51
+ crudUploadThrottleMs?: number;
52
+ }
53
+
54
+ /**
55
+ * @public
56
+ */
57
+ export enum SyncStreamConnectionMethod {
58
+ HTTP = 'http',
59
+ WEB_SOCKET = 'web-socket'
60
+ }
61
+
62
+ /**
63
+ * @public
64
+ */
65
+ export enum FetchStrategy {
66
+ /**
67
+ * Queues multiple sync events before processing, reducing round-trips.
68
+ * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.
69
+ */
70
+ Buffered = 'buffered',
71
+
72
+ /**
73
+ * Processes each sync event immediately before requesting the next.
74
+ * This reduces processing overhead and improves real-time responsiveness.
75
+ */
76
+ Sequential = 'sequential'
77
+ }
@@ -81,7 +81,7 @@ export interface SyncStreamSubscribeOptions {
81
81
  /**
82
82
  * A handle to a {@link SyncStreamDescription} that allows subscribing to the stream.
83
83
  *
84
- * To obtain an instance of {@link SyncStream}, call {@link AbstractPowerSyncDatabase.syncStream}.
84
+ * To obtain an instance of {@link SyncStream}, call {@link CommonPowerSyncDatabase.syncStream}.
85
85
  *
86
86
  * @public
87
87
  */
@@ -163,9 +163,10 @@ export interface TriggerCreationHooks {
163
163
 
164
164
  /**
165
165
  * Common interface for options used in creating a diff trigger.
166
+ *
167
+ * @alpha @experimental
166
168
  */
167
-
168
- interface BaseCreateDiffTriggerOptions {
169
+ export interface BaseCreateDiffTriggerOptions {
169
170
  /**
170
171
  * PowerSync source table/view to trigger and track changes from.
171
172
  * This should be present in the PowerSync database's schema.
@@ -188,16 +189,18 @@ interface BaseCreateDiffTriggerOptions {
188
189
  * The row id is available in the `id` column.
189
190
  *
190
191
  * NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL.
191
- * Any user input strings here should be sanitized externally. The {@link when} string template function performs
192
- * some basic sanitization, extra external sanitization is recommended.
192
+ * Any user input strings here should be sanitized externally. The {@link BaseCreateDiffTriggerOptions.when} string
193
+ * template function performs some basic sanitization, extra external sanitization is recommended.
193
194
  *
194
195
  * @example
196
+ * ```JavaScript
195
197
  * {
196
198
  * 'INSERT': sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}`,
197
199
  * 'INSERT': `TRUE`,
198
200
  * 'UPDATE': sanitizeSQL`NEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active'`,
199
201
  * 'DELETE': sanitizeSQL`json_extract(OLD.data, '$.list_id') = 'abcd'`
200
202
  * }
203
+ * ```
201
204
  */
202
205
  when: Partial<Record<DiffTriggerOperation, string>>;
203
206
 
@@ -264,7 +267,9 @@ export interface WithDiffOptions {
264
267
  * @experimental @alpha
265
268
  * Context for the `onChange` handler provided to {@link TriggerManager#trackTableDiff}.
266
269
  */
267
- export interface TriggerDiffHandlerContext extends LockContext {
270
+ export interface TriggerDiffHandlerContext {
271
+ context: LockContext;
272
+
268
273
  /**
269
274
  * The name of the temporary destination table created by the trigger.
270
275
  */
@@ -363,7 +368,6 @@ export interface TrackDiffOptions extends BaseCreateDiffTriggerOptions {
363
368
 
364
369
  /**
365
370
  * The minimum interval, in milliseconds, between {@link TrackDiffOptions.onChange} invocations.
366
- * @default {@link DEFAULT_WATCH_THROTTLE_MS}
367
371
  */
368
372
  throttleMs?: number;
369
373
  }
@@ -472,38 +476,3 @@ export interface TriggerManager {
472
476
  */
473
477
  trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback>;
474
478
  }
475
-
476
- /**
477
- * @experimental
478
- * @internal
479
- * Manages claims on persisted SQLite triggers and destination tables to enable proper cleanup
480
- * when they are no longer actively in use.
481
- *
482
- * When using persisted triggers (especially for OPFS multi-tab scenarios), we need a reliable way to determine which resources are still actively in use across different connections/tabs so stale resources can be safely cleaned up without interfering with active triggers.
483
- *
484
- * A cleanup process runs
485
- * on database creation (and every 2 minutes) that:
486
- * 1. Queries for existing managed persisted resources
487
- * 2. Checks with the claim manager if any consumer is actively using those resources
488
- * 3. Deletes unused resources
489
- */
490
-
491
- export interface TriggerClaimManager {
492
- /**
493
- * Obtains or marks a claim on a certain identifier.
494
- * @returns a callback to release the claim.
495
- */
496
- obtainClaim: (identifier: string) => Promise<() => Promise<void>>;
497
- /**
498
- * Checks if a claim is present for an identifier.
499
- */
500
- checkClaim: (identifier: string) => Promise<boolean>;
501
- }
502
-
503
- /**
504
- * @experimental
505
- * @internal
506
- */
507
- export interface TriggerManagerConfig {
508
- claimManager: TriggerClaimManager;
509
- }
@@ -1,5 +1,5 @@
1
1
  import { CompiledQuery } from '../../types/types.js';
2
- import { AbstractPowerSyncDatabase } from '../AbstractPowerSyncDatabase.js';
2
+ import { CommonPowerSyncDatabase } from '../CommonPowerSyncDatabase.js';
3
3
  import { WatchCompatibleQuery } from './WatchedQuery.js';
4
4
 
5
5
  /**
@@ -24,7 +24,7 @@ export type GetAllQueryOptions<RowType = unknown> = {
24
24
  };
25
25
 
26
26
  /**
27
- * Performs a {@link AbstractPowerSyncDatabase.getAll} operation for a watched query.
27
+ * Performs a {@link DBGetUtils.getAll} operation for a watched query.
28
28
  *
29
29
  * @public
30
30
  */
@@ -38,7 +38,7 @@ export class GetAllQuery<RowType = unknown> implements WatchCompatibleQuery<RowT
38
38
  };
39
39
  }
40
40
 
41
- async execute(options: { db: AbstractPowerSyncDatabase }): Promise<RowType[]> {
41
+ async execute(options: { db: CommonPowerSyncDatabase }): Promise<RowType[]> {
42
42
  const { db } = options;
43
43
  const { sql, parameters = [] } = this.compile();
44
44
  const rawResult = await db.getAll<Record<string, unknown>>(sql, [...parameters]);
@@ -1,7 +1,7 @@
1
1
  import { CompiledQuery } from '../../types/types.js';
2
2
  import { BaseListener } from '../../utils/BaseObserver.js';
3
3
  import { MetaBaseObserverInterface } from '../../utils/MetaBaseObserver.js';
4
- import { AbstractPowerSyncDatabase } from '../AbstractPowerSyncDatabase.js';
4
+ import { CommonPowerSyncDatabase } from '../CommonPowerSyncDatabase.js';
5
5
 
6
6
  /**
7
7
  * State for {@link WatchedQuery} instances.
@@ -41,7 +41,7 @@ export interface WatchedQueryState<Data> {
41
41
  export interface WatchExecuteOptions {
42
42
  sql: string;
43
43
  parameters: any[];
44
- db: AbstractPowerSyncDatabase;
44
+ db: CommonPowerSyncDatabase;
45
45
  }
46
46
 
47
47
  /**
@@ -96,19 +96,6 @@ export interface WatchedQueryListener<Data> extends BaseListener {
96
96
  [WatchedQueryListenerEvent.CLOSED]?: () => void | Promise<void>;
97
97
  }
98
98
 
99
- /**
100
- * @internal
101
- */
102
- export const DEFAULT_WATCH_THROTTLE_MS = 30;
103
-
104
- /**
105
- * @internal
106
- */
107
- export const DEFAULT_WATCH_QUERY_OPTIONS: WatchedQueryOptions = {
108
- throttleMs: DEFAULT_WATCH_THROTTLE_MS,
109
- reportFetching: true
110
- };
111
-
112
99
  /**
113
100
  * @public
114
101
  */
@@ -1,10 +1,4 @@
1
1
  import { WatchCompatibleQuery, WatchedQuery, WatchedQueryListener, WatchedQueryOptions } from '../WatchedQuery.js';
2
- import {
3
- AbstractQueryProcessor,
4
- AbstractQueryProcessorOptions,
5
- LinkQueryOptions,
6
- MutableWatchedQueryState
7
- } from './AbstractQueryProcessor.js';
8
2
 
9
3
  /**
10
4
  * Represents an updated row in a differential watched query.
@@ -76,7 +70,6 @@ export interface DifferentialWatchedQueryOptions<RowType> extends WatchedQueryOp
76
70
  * Row comparator used to identify and compare rows in the result set.
77
71
  * If not provided, the default comparator will be used which keys items by their `id` property if available,
78
72
  * otherwise it uses JSON stringification of the entire item for keying and comparison.
79
- * @defaultValue {@link DEFAULT_ROW_COMPARATOR}
80
73
  */
81
74
  rowComparator?: DifferentialWatchedQueryComparator<RowType>;
82
75
  }
@@ -110,219 +103,3 @@ export type DifferentialWatchedQuery<RowType> = WatchedQuery<
110
103
  DifferentialWatchedQuerySettings<RowType>,
111
104
  DifferentialWatchedQueryListener<RowType>
112
105
  >;
113
-
114
- /**
115
- * @internal
116
- */
117
- export interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<
118
- RowType[],
119
- DifferentialWatchedQuerySettings<RowType>
120
- > {
121
- rowComparator?: DifferentialWatchedQueryComparator<RowType>;
122
- }
123
-
124
- type DataHashMap<RowType> = Map<string, { hash: string; item: RowType }>;
125
-
126
- /**
127
- * An empty differential result set.
128
- * This is used as the initial state for differential incrementally watched queries.
129
- *
130
- * @internal
131
- */
132
- export const EMPTY_DIFFERENTIAL = {
133
- added: [],
134
- all: [],
135
- removed: [],
136
- updated: [],
137
- unchanged: []
138
- };
139
-
140
- /**
141
- * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
142
- * It keys items by their `id` property if available, alternatively it uses JSON stringification
143
- * of the entire item for the key and comparison.
144
- *
145
- * @internal
146
- */
147
- export const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any> = {
148
- keyBy: (item) => {
149
- if (item && typeof item == 'object' && typeof item['id'] == 'string') {
150
- return item['id'];
151
- }
152
- return JSON.stringify(item);
153
- },
154
- compareBy: (item) => JSON.stringify(item)
155
- };
156
-
157
- /**
158
- * Uses the PowerSync onChange event to trigger watched queries.
159
- * Results are emitted on every change of the relevant tables.
160
- * @internal
161
- */
162
- export class DifferentialQueryProcessor<RowType>
163
- extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>>
164
- implements DifferentialWatchedQuery<RowType>
165
- {
166
- protected comparator: DifferentialWatchedQueryComparator<RowType>;
167
-
168
- constructor(protected options: DifferentialQueryProcessorOptions<RowType>) {
169
- super(options);
170
- this.comparator = options.rowComparator ?? DEFAULT_ROW_COMPARATOR;
171
- }
172
-
173
- /*
174
- * @returns If the sets are equal
175
- */
176
- protected differentiate(
177
- current: RowType[],
178
- previousMap: DataHashMap<RowType>
179
- ): { diff: WatchedQueryDifferential<RowType>; map: DataHashMap<RowType>; hasChanged: boolean } {
180
- const { keyBy, compareBy } = this.comparator;
181
-
182
- let hasChanged = false;
183
- const currentMap = new Map<string, { hash: string; item: RowType }>();
184
- const removedTracker = new Set(previousMap.keys());
185
-
186
- // Allow mutating to populate the data temporarily.
187
- const diff = {
188
- all: [] as RowType[],
189
- added: [] as RowType[],
190
- removed: [] as RowType[],
191
- updated: [] as WatchedQueryRowDifferential<RowType>[],
192
- unchanged: [] as RowType[]
193
- };
194
-
195
- /**
196
- * Looping over the current result set array is important to preserve
197
- * the ordering of the result set.
198
- * We can replace items in the current array with previous object references if they are equal.
199
- */
200
- for (const item of current) {
201
- const key = keyBy(item);
202
- const hash = compareBy(item);
203
- currentMap.set(key, { hash, item });
204
-
205
- const previousItem = previousMap.get(key);
206
- if (!previousItem) {
207
- // New item
208
- hasChanged = true;
209
- diff.added.push(item);
210
- diff.all.push(item);
211
- } else {
212
- // Existing item
213
- if (hash == previousItem.hash) {
214
- diff.unchanged.push(previousItem.item);
215
- // Use the previous object reference
216
- diff.all.push(previousItem.item);
217
- // update the map to preserve the reference
218
- currentMap.set(key, previousItem);
219
- } else {
220
- hasChanged = true;
221
- diff.updated.push({ current: item, previous: previousItem.item });
222
- // Use the new reference
223
- diff.all.push(item);
224
- }
225
- }
226
- // The item is present, we don't consider it removed
227
- removedTracker.delete(key);
228
- }
229
-
230
- diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key)!.item);
231
- hasChanged = hasChanged || diff.removed.length > 0;
232
-
233
- return {
234
- diff,
235
- hasChanged,
236
- map: currentMap
237
- };
238
- }
239
-
240
- protected async linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void> {
241
- const { db, watchOptions } = this.options;
242
- const { abortSignal } = options;
243
-
244
- const compiledQuery = watchOptions.query.compile();
245
- const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters as any[], {
246
- tables: options.settings.triggerOnTables
247
- });
248
-
249
- let currentMap: DataHashMap<RowType> = new Map();
250
-
251
- // populate the currentMap from the placeholder data
252
- this.state.data.forEach((item) => {
253
- currentMap.set(this.comparator.keyBy(item), {
254
- hash: this.comparator.compareBy(item),
255
- item
256
- });
257
- });
258
-
259
- db.onChangeWithCallback(
260
- {
261
- onChange: async () => {
262
- if (this.closed || abortSignal.aborted) {
263
- return;
264
- }
265
- // This fires for each change of the relevant tables
266
- try {
267
- if (this.reportFetching && !this.state.isFetching) {
268
- await this.updateState({ isFetching: true });
269
- }
270
-
271
- const partialStateUpdate: Partial<MutableWatchedQueryState<RowType[]>> = {};
272
-
273
- // Always run the query if an underlying table has changed
274
- const result = await watchOptions.query.execute({
275
- sql: compiledQuery.sql,
276
- // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
277
- // This allows simpler compatibility with PowerSync queries
278
- parameters: [...compiledQuery.parameters],
279
- db: this.options.db
280
- });
281
-
282
- if (abortSignal.aborted) {
283
- return;
284
- }
285
-
286
- if (this.reportFetching) {
287
- partialStateUpdate.isFetching = false;
288
- }
289
-
290
- if (this.state.isLoading) {
291
- partialStateUpdate.isLoading = false;
292
- }
293
-
294
- const { diff, hasChanged, map } = this.differentiate(result, currentMap);
295
- // Update for future comparisons
296
- currentMap = map;
297
-
298
- if (hasChanged) {
299
- await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));
300
- Object.assign(partialStateUpdate, {
301
- data: diff.all
302
- });
303
- }
304
-
305
- if (this.state.error) {
306
- partialStateUpdate.error = null;
307
- }
308
-
309
- if (Object.keys(partialStateUpdate).length > 0) {
310
- await this.updateState(partialStateUpdate);
311
- }
312
- } catch (error: any) {
313
- await this.updateState({ error });
314
- }
315
- },
316
- onError: async (error) => {
317
- await this.updateState({ error });
318
- }
319
- },
320
- {
321
- signal: abortSignal,
322
- tables,
323
- throttleMs: watchOptions.throttleMs,
324
- triggerImmediate: true // used to emit the initial state
325
- }
326
- );
327
- }
328
- }