@powersync/common 0.0.0-dev-20260128170746 → 0.0.0-dev-20260202160933

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 (216) hide show
  1. package/package.json +1 -1
  2. package/src/index.ts +1 -0
  3. package/src/utils/mutex.ts +1 -1
  4. package/dist/bundle.cjs +0 -14456
  5. package/dist/bundle.cjs.map +0 -1
  6. package/dist/bundle.mjs +0 -14366
  7. package/dist/bundle.mjs.map +0 -1
  8. package/dist/bundle.node.cjs +0 -11934
  9. package/dist/bundle.node.cjs.map +0 -1
  10. package/dist/bundle.node.mjs +0 -11844
  11. package/dist/bundle.node.mjs.map +0 -1
  12. package/dist/index.d.cts +0 -4265
  13. package/lib/attachments/AttachmentContext.d.ts +0 -86
  14. package/lib/attachments/AttachmentContext.js +0 -229
  15. package/lib/attachments/AttachmentContext.js.map +0 -1
  16. package/lib/attachments/AttachmentErrorHandler.d.ts +0 -31
  17. package/lib/attachments/AttachmentErrorHandler.js +0 -2
  18. package/lib/attachments/AttachmentErrorHandler.js.map +0 -1
  19. package/lib/attachments/AttachmentQueue.d.ts +0 -149
  20. package/lib/attachments/AttachmentQueue.js +0 -362
  21. package/lib/attachments/AttachmentQueue.js.map +0 -1
  22. package/lib/attachments/AttachmentService.d.ts +0 -29
  23. package/lib/attachments/AttachmentService.js +0 -56
  24. package/lib/attachments/AttachmentService.js.map +0 -1
  25. package/lib/attachments/LocalStorageAdapter.d.ts +0 -62
  26. package/lib/attachments/LocalStorageAdapter.js +0 -6
  27. package/lib/attachments/LocalStorageAdapter.js.map +0 -1
  28. package/lib/attachments/RemoteStorageAdapter.d.ts +0 -27
  29. package/lib/attachments/RemoteStorageAdapter.js +0 -2
  30. package/lib/attachments/RemoteStorageAdapter.js.map +0 -1
  31. package/lib/attachments/Schema.d.ts +0 -50
  32. package/lib/attachments/Schema.js +0 -62
  33. package/lib/attachments/Schema.js.map +0 -1
  34. package/lib/attachments/SyncingService.d.ts +0 -62
  35. package/lib/attachments/SyncingService.js +0 -168
  36. package/lib/attachments/SyncingService.js.map +0 -1
  37. package/lib/attachments/WatchedAttachmentItem.d.ts +0 -17
  38. package/lib/attachments/WatchedAttachmentItem.js +0 -2
  39. package/lib/attachments/WatchedAttachmentItem.js.map +0 -1
  40. package/lib/client/AbstractPowerSyncDatabase.d.ts +0 -615
  41. package/lib/client/AbstractPowerSyncDatabase.js +0 -983
  42. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  43. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +0 -22
  44. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -25
  45. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  46. package/lib/client/ConnectionManager.d.ts +0 -112
  47. package/lib/client/ConnectionManager.js +0 -294
  48. package/lib/client/ConnectionManager.js.map +0 -1
  49. package/lib/client/CustomQuery.d.ts +0 -22
  50. package/lib/client/CustomQuery.js +0 -43
  51. package/lib/client/CustomQuery.js.map +0 -1
  52. package/lib/client/Query.d.ts +0 -97
  53. package/lib/client/Query.js +0 -2
  54. package/lib/client/Query.js.map +0 -1
  55. package/lib/client/SQLOpenFactory.d.ts +0 -42
  56. package/lib/client/SQLOpenFactory.js +0 -20
  57. package/lib/client/SQLOpenFactory.js.map +0 -1
  58. package/lib/client/compilableQueryWatch.d.ts +0 -7
  59. package/lib/client/compilableQueryWatch.js +0 -38
  60. package/lib/client/compilableQueryWatch.js.map +0 -1
  61. package/lib/client/connection/PowerSyncBackendConnector.d.ts +0 -23
  62. package/lib/client/connection/PowerSyncBackendConnector.js +0 -2
  63. package/lib/client/connection/PowerSyncBackendConnector.js.map +0 -1
  64. package/lib/client/connection/PowerSyncCredentials.d.ts +0 -5
  65. package/lib/client/connection/PowerSyncCredentials.js +0 -2
  66. package/lib/client/connection/PowerSyncCredentials.js.map +0 -1
  67. package/lib/client/constants.d.ts +0 -1
  68. package/lib/client/constants.js +0 -2
  69. package/lib/client/constants.js.map +0 -1
  70. package/lib/client/runOnSchemaChange.d.ts +0 -2
  71. package/lib/client/runOnSchemaChange.js +0 -24
  72. package/lib/client/runOnSchemaChange.js.map +0 -1
  73. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +0 -102
  74. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -19
  75. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  76. package/lib/client/sync/bucket/CrudBatch.d.ts +0 -31
  77. package/lib/client/sync/bucket/CrudBatch.js +0 -26
  78. package/lib/client/sync/bucket/CrudBatch.js.map +0 -1
  79. package/lib/client/sync/bucket/CrudEntry.d.ts +0 -95
  80. package/lib/client/sync/bucket/CrudEntry.js +0 -110
  81. package/lib/client/sync/bucket/CrudEntry.js.map +0 -1
  82. package/lib/client/sync/bucket/CrudTransaction.d.ts +0 -29
  83. package/lib/client/sync/bucket/CrudTransaction.js +0 -25
  84. package/lib/client/sync/bucket/CrudTransaction.js.map +0 -1
  85. package/lib/client/sync/bucket/OpType.d.ts +0 -16
  86. package/lib/client/sync/bucket/OpType.js +0 -23
  87. package/lib/client/sync/bucket/OpType.js.map +0 -1
  88. package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
  89. package/lib/client/sync/bucket/OplogEntry.js +0 -36
  90. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  91. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +0 -61
  92. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -324
  93. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  94. package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
  95. package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
  96. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  97. package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
  98. package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
  99. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  100. package/lib/client/sync/stream/AbstractRemote.d.ts +0 -140
  101. package/lib/client/sync/stream/AbstractRemote.js +0 -506
  102. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  103. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +0 -240
  104. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +0 -990
  105. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  106. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +0 -15
  107. package/lib/client/sync/stream/WebsocketClientTransport.js +0 -61
  108. package/lib/client/sync/stream/WebsocketClientTransport.js.map +0 -1
  109. package/lib/client/sync/stream/core-instruction.d.ts +0 -72
  110. package/lib/client/sync/stream/core-instruction.js +0 -27
  111. package/lib/client/sync/stream/core-instruction.js.map +0 -1
  112. package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
  113. package/lib/client/sync/stream/streaming-sync-types.js +0 -26
  114. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  115. package/lib/client/sync/sync-streams.d.ts +0 -98
  116. package/lib/client/sync/sync-streams.js +0 -2
  117. package/lib/client/sync/sync-streams.js.map +0 -1
  118. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +0 -6
  119. package/lib/client/triggers/MemoryTriggerClaimManager.js +0 -21
  120. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +0 -1
  121. package/lib/client/triggers/TriggerManager.d.ts +0 -459
  122. package/lib/client/triggers/TriggerManager.js +0 -11
  123. package/lib/client/triggers/TriggerManager.js.map +0 -1
  124. package/lib/client/triggers/TriggerManagerImpl.d.ts +0 -39
  125. package/lib/client/triggers/TriggerManagerImpl.js +0 -393
  126. package/lib/client/triggers/TriggerManagerImpl.js.map +0 -1
  127. package/lib/client/triggers/sanitizeSQL.d.ts +0 -34
  128. package/lib/client/triggers/sanitizeSQL.js +0 -69
  129. package/lib/client/triggers/sanitizeSQL.js.map +0 -1
  130. package/lib/client/watched/GetAllQuery.d.ts +0 -32
  131. package/lib/client/watched/GetAllQuery.js +0 -25
  132. package/lib/client/watched/GetAllQuery.js.map +0 -1
  133. package/lib/client/watched/WatchedQuery.d.ts +0 -100
  134. package/lib/client/watched/WatchedQuery.js +0 -14
  135. package/lib/client/watched/WatchedQuery.js.map +0 -1
  136. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +0 -68
  137. package/lib/client/watched/processors/AbstractQueryProcessor.js +0 -151
  138. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +0 -1
  139. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +0 -121
  140. package/lib/client/watched/processors/DifferentialQueryProcessor.js +0 -173
  141. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +0 -1
  142. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +0 -33
  143. package/lib/client/watched/processors/OnChangeQueryProcessor.js +0 -83
  144. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +0 -1
  145. package/lib/client/watched/processors/comparators.d.ts +0 -30
  146. package/lib/client/watched/processors/comparators.js +0 -35
  147. package/lib/client/watched/processors/comparators.js.map +0 -1
  148. package/lib/db/ConnectionClosedError.d.ts +0 -10
  149. package/lib/db/ConnectionClosedError.js +0 -21
  150. package/lib/db/ConnectionClosedError.js.map +0 -1
  151. package/lib/db/DBAdapter.d.ts +0 -115
  152. package/lib/db/DBAdapter.js +0 -20
  153. package/lib/db/DBAdapter.js.map +0 -1
  154. package/lib/db/crud/SyncProgress.d.ts +0 -68
  155. package/lib/db/crud/SyncProgress.js +0 -61
  156. package/lib/db/crud/SyncProgress.js.map +0 -1
  157. package/lib/db/crud/SyncStatus.d.ts +0 -195
  158. package/lib/db/crud/SyncStatus.js +0 -250
  159. package/lib/db/crud/SyncStatus.js.map +0 -1
  160. package/lib/db/crud/UploadQueueStatus.d.ts +0 -20
  161. package/lib/db/crud/UploadQueueStatus.js +0 -25
  162. package/lib/db/crud/UploadQueueStatus.js.map +0 -1
  163. package/lib/db/schema/Column.d.ts +0 -30
  164. package/lib/db/schema/Column.js +0 -43
  165. package/lib/db/schema/Column.js.map +0 -1
  166. package/lib/db/schema/Index.d.ts +0 -22
  167. package/lib/db/schema/Index.js +0 -30
  168. package/lib/db/schema/Index.js.map +0 -1
  169. package/lib/db/schema/IndexedColumn.d.ts +0 -19
  170. package/lib/db/schema/IndexedColumn.js +0 -30
  171. package/lib/db/schema/IndexedColumn.js.map +0 -1
  172. package/lib/db/schema/RawTable.d.ts +0 -61
  173. package/lib/db/schema/RawTable.js +0 -33
  174. package/lib/db/schema/RawTable.js.map +0 -1
  175. package/lib/db/schema/Schema.d.ts +0 -54
  176. package/lib/db/schema/Schema.js +0 -61
  177. package/lib/db/schema/Schema.js.map +0 -1
  178. package/lib/db/schema/Table.d.ts +0 -157
  179. package/lib/db/schema/Table.js +0 -208
  180. package/lib/db/schema/Table.js.map +0 -1
  181. package/lib/db/schema/TableV2.d.ts +0 -9
  182. package/lib/db/schema/TableV2.js +0 -9
  183. package/lib/db/schema/TableV2.js.map +0 -1
  184. package/lib/index.d.ts +0 -61
  185. package/lib/index.js +0 -62
  186. package/lib/index.js.map +0 -1
  187. package/lib/types/types.d.ts +0 -8
  188. package/lib/types/types.js +0 -2
  189. package/lib/types/types.js.map +0 -1
  190. package/lib/utils/AbortOperation.d.ts +0 -9
  191. package/lib/utils/AbortOperation.js +0 -19
  192. package/lib/utils/AbortOperation.js.map +0 -1
  193. package/lib/utils/BaseObserver.d.ts +0 -18
  194. package/lib/utils/BaseObserver.js +0 -27
  195. package/lib/utils/BaseObserver.js.map +0 -1
  196. package/lib/utils/ControlledExecutor.d.ts +0 -25
  197. package/lib/utils/ControlledExecutor.js +0 -51
  198. package/lib/utils/ControlledExecutor.js.map +0 -1
  199. package/lib/utils/DataStream.d.ts +0 -62
  200. package/lib/utils/DataStream.js +0 -169
  201. package/lib/utils/DataStream.js.map +0 -1
  202. package/lib/utils/Logger.d.ts +0 -31
  203. package/lib/utils/Logger.js +0 -37
  204. package/lib/utils/Logger.js.map +0 -1
  205. package/lib/utils/MetaBaseObserver.d.ts +0 -29
  206. package/lib/utils/MetaBaseObserver.js +0 -51
  207. package/lib/utils/MetaBaseObserver.js.map +0 -1
  208. package/lib/utils/async.d.ts +0 -23
  209. package/lib/utils/async.js +0 -55
  210. package/lib/utils/async.js.map +0 -1
  211. package/lib/utils/mutex.d.ts +0 -7
  212. package/lib/utils/mutex.js +0 -29
  213. package/lib/utils/mutex.js.map +0 -1
  214. package/lib/utils/parseQuery.d.ts +0 -6
  215. package/lib/utils/parseQuery.js +0 -17
  216. package/lib/utils/parseQuery.js.map +0 -1
package/dist/index.d.cts DELETED
@@ -1,4265 +0,0 @@
1
- import { Mutex } from 'async-mutex';
2
- import Logger, { ILogger, ILogLevel } from 'js-logger';
3
- export { GlobalLogger, ILogHandler, ILogLevel, ILogger, ILoggerOpts } from 'js-logger';
4
- import { BSON } from 'bson';
5
- import { fetch } from 'cross-fetch';
6
-
7
- interface Disposable {
8
- dispose: () => Promise<void> | void;
9
- }
10
- type BaseListener = Record<string, ((...event: any) => any) | undefined>;
11
- interface BaseObserverInterface<T extends BaseListener> {
12
- registerListener(listener: Partial<T>): () => void;
13
- }
14
- declare class BaseObserver<T extends BaseListener = BaseListener> implements BaseObserverInterface<T> {
15
- protected listeners: Set<Partial<T>>;
16
- constructor();
17
- dispose(): void;
18
- /**
19
- * Register a listener for updates to the PowerSync client.
20
- */
21
- registerListener(listener: Partial<T>): () => void;
22
- iterateListeners(cb: (listener: Partial<T>) => any): void;
23
- iterateAsyncListeners(cb: (listener: Partial<T>) => Promise<any>): Promise<void>;
24
- }
25
-
26
- /**
27
- * Set of generic interfaces to allow PowerSync compatibility with
28
- * different SQLite DB implementations.
29
- */
30
-
31
- /**
32
- * TODO most of these types could be exported to a common `types` package
33
- * which is used by the DB adapter libraries as well.
34
- */
35
- /**
36
- * Object returned by SQL Query executions.
37
- */
38
- type QueryResult = {
39
- /** Represents the auto-generated row id if applicable. */
40
- insertId?: number;
41
- /** Number of affected rows if result of a update query. */
42
- rowsAffected: number;
43
- /** if status is undefined or 0 this object will contain the query results */
44
- rows?: {
45
- /** Raw array with all dataset */
46
- _array: any[];
47
- /** The length of the dataset */
48
- length: number;
49
- /** A convenience function to acess the index based the row object
50
- * @param idx the row index
51
- * @returns the row structure identified by column names
52
- */
53
- item: (idx: number) => any;
54
- };
55
- };
56
- interface DBGetUtils {
57
- /** Execute a read-only query and return results. */
58
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
59
- /** Execute a read-only query and return the first result, or null if the ResultSet is empty. */
60
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
61
- /** Execute a read-only query and return the first result, error if the ResultSet is empty. */
62
- get<T>(sql: string, parameters?: any[]): Promise<T>;
63
- }
64
- interface LockContext extends DBGetUtils {
65
- /** Execute a single write statement. */
66
- execute: (query: string, params?: any[] | undefined) => Promise<QueryResult>;
67
- /**
68
- * Execute a single write statement and return raw results.
69
- * Unlike `execute`, which returns an object with structured key-value pairs,
70
- * `executeRaw` returns a nested array of raw values, where each row is
71
- * represented as an array of column values without field names.
72
- *
73
- * Example result:
74
- *
75
- * ```[ [ '1', 'list 1', '33', 'Post content', '1' ] ]```
76
- *
77
- * Where as `execute`'s `rows._array` would have been:
78
- *
79
- * ```[ { id: '33', name: 'list 1', content: 'Post content', list_id: '1' } ]```
80
- */
81
- executeRaw: (query: string, params?: any[] | undefined) => Promise<any[][]>;
82
- }
83
- interface Transaction extends LockContext {
84
- /** Commit multiple changes to the local DB using the Transaction context. */
85
- commit: () => Promise<QueryResult>;
86
- /** Roll back multiple attempted changes using the Transaction context. */
87
- rollback: () => Promise<QueryResult>;
88
- }
89
- /**
90
- * Update table operation numbers from SQLite
91
- */
92
- declare enum RowUpdateType {
93
- SQLITE_INSERT = 18,
94
- SQLITE_DELETE = 9,
95
- SQLITE_UPDATE = 23
96
- }
97
- interface TableUpdateOperation {
98
- opType: RowUpdateType;
99
- rowId: number;
100
- }
101
- /**
102
- * Notification of an update to one or more tables, for the purpose of realtime change notifications.
103
- */
104
- interface UpdateNotification extends TableUpdateOperation {
105
- table: string;
106
- }
107
- interface BatchedUpdateNotification {
108
- rawUpdates: UpdateNotification[];
109
- tables: string[];
110
- groupedUpdates: Record<string, TableUpdateOperation[]>;
111
- }
112
- interface DBAdapterListener extends BaseListener {
113
- /**
114
- * Listener for table updates.
115
- * Allows for single table updates in order to maintain API compatibility
116
- * without the need for a major version bump
117
- * The DB adapter can also batch update notifications if supported.
118
- */
119
- tablesUpdated: (updateNotification: BatchedUpdateNotification | UpdateNotification) => void;
120
- }
121
- interface DBLockOptions {
122
- timeoutMs?: number;
123
- }
124
- interface DBAdapter extends BaseObserverInterface<DBAdapterListener>, DBGetUtils {
125
- close: () => void | Promise<void>;
126
- execute: (query: string, params?: any[]) => Promise<QueryResult>;
127
- executeRaw: (query: string, params?: any[]) => Promise<any[][]>;
128
- executeBatch: (query: string, params?: any[][]) => Promise<QueryResult>;
129
- name: string;
130
- readLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
131
- readTransaction: <T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions) => Promise<T>;
132
- writeLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
133
- writeTransaction: <T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions) => Promise<T>;
134
- /**
135
- * This method refreshes the schema information across all connections. This is for advanced use cases, and should generally not be needed.
136
- */
137
- refreshSchema: () => Promise<void>;
138
- }
139
- declare function isBatchedUpdateNotification(update: BatchedUpdateNotification | UpdateNotification): update is BatchedUpdateNotification;
140
- declare function extractTableUpdates(update: BatchedUpdateNotification | UpdateNotification): string[];
141
-
142
- /**
143
- * 64-bit unsigned integer stored as a string in base-10.
144
- *
145
- * Not sortable as a string.
146
- */
147
- type OpId = string;
148
- /**
149
- * Type of local change.
150
- */
151
- declare enum UpdateType {
152
- /** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */
153
- PUT = "PUT",
154
- /** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */
155
- PATCH = "PATCH",
156
- /** Delete existing row. Contains the id. Generated by DELETE statements. */
157
- DELETE = "DELETE"
158
- }
159
- type CrudEntryJSON = {
160
- id: string;
161
- data: string;
162
- tx_id?: number;
163
- };
164
- /**
165
- * The output JSON seems to be a third type of JSON, not the same as the input JSON.
166
- */
167
- type CrudEntryOutputJSON = {
168
- op_id: number;
169
- op: UpdateType;
170
- type: string;
171
- id: string;
172
- tx_id?: number;
173
- data?: Record<string, any>;
174
- old?: Record<string, any>;
175
- metadata?: string;
176
- };
177
- /**
178
- * A single client-side change.
179
- */
180
- declare class CrudEntry {
181
- /**
182
- * Auto-incrementing client-side id.
183
- */
184
- clientId: number;
185
- /**
186
- * ID of the changed row.
187
- */
188
- id: string;
189
- /**
190
- * Type of change.
191
- */
192
- op: UpdateType;
193
- /**
194
- * Data associated with the change.
195
- */
196
- opData?: Record<string, any>;
197
- /**
198
- * For tables where the `trackPreviousValues` option has been enabled, this tracks previous values for
199
- * `UPDATE` and `DELETE` statements.
200
- */
201
- previousValues?: Record<string, any>;
202
- /**
203
- * Table that contained the change.
204
- */
205
- table: string;
206
- /**
207
- * Auto-incrementing transaction id. This is the same for all operations within the same transaction.
208
- */
209
- transactionId?: number;
210
- /**
211
- * Client-side metadata attached with this write.
212
- *
213
- * This field is only available when the `trackMetadata` option was set to `true` when creating a table
214
- * and the insert or update statement set the `_metadata` column.
215
- */
216
- metadata?: string;
217
- static fromRow(dbRow: CrudEntryJSON): CrudEntry;
218
- constructor(clientId: number, op: UpdateType, table: string, id: string, transactionId?: number, opData?: Record<string, any>, previousValues?: Record<string, any>, metadata?: string);
219
- /**
220
- * Converts the change to JSON format.
221
- */
222
- toJSON(): CrudEntryOutputJSON;
223
- equals(entry: CrudEntry): boolean;
224
- /**
225
- * The hash code for this object.
226
- * @deprecated This should not be necessary in the JS SDK.
227
- * Use the @see CrudEntry#equals method instead.
228
- * TODO remove in the next major release.
229
- */
230
- hashCode(): string;
231
- /**
232
- * Generates an array for use in deep comparison operations
233
- */
234
- toComparisonArray(): (string | number | Record<string, any> | undefined)[];
235
- }
236
-
237
- /**
238
- * A batch of client-side changes.
239
- */
240
- declare class CrudBatch {
241
- /**
242
- * List of client-side changes.
243
- */
244
- crud: CrudEntry[];
245
- /**
246
- * true if there are more changes in the local queue.
247
- */
248
- haveMore: boolean;
249
- /**
250
- * Call to remove the changes from the local queue, once successfully uploaded.
251
- */
252
- complete: (writeCheckpoint?: string) => Promise<void>;
253
- constructor(
254
- /**
255
- * List of client-side changes.
256
- */
257
- crud: CrudEntry[],
258
- /**
259
- * true if there are more changes in the local queue.
260
- */
261
- haveMore: boolean,
262
- /**
263
- * Call to remove the changes from the local queue, once successfully uploaded.
264
- */
265
- complete: (writeCheckpoint?: string) => Promise<void>);
266
- }
267
-
268
- declare enum OpTypeEnum {
269
- CLEAR = 1,
270
- MOVE = 2,
271
- PUT = 3,
272
- REMOVE = 4
273
- }
274
- type OpTypeJSON = string;
275
- /**
276
- * Used internally for sync buckets.
277
- */
278
- declare class OpType {
279
- value: OpTypeEnum;
280
- static fromJSON(jsonValue: OpTypeJSON): OpType;
281
- constructor(value: OpTypeEnum);
282
- toJSON(): string;
283
- }
284
-
285
- interface OplogEntryJSON {
286
- checksum: number;
287
- data?: string;
288
- object_id?: string;
289
- object_type?: string;
290
- op_id: string;
291
- op: OpTypeJSON;
292
- subkey?: string;
293
- }
294
- declare class OplogEntry {
295
- op_id: OpId;
296
- op: OpType;
297
- checksum: number;
298
- subkey?: string | undefined;
299
- object_type?: string | undefined;
300
- object_id?: string | undefined;
301
- data?: string | undefined;
302
- static fromRow(row: OplogEntryJSON): OplogEntry;
303
- constructor(op_id: OpId, op: OpType, checksum: number, subkey?: string | undefined, object_type?: string | undefined, object_id?: string | undefined, data?: string | undefined);
304
- toJSON(fixedKeyEncoding?: boolean): OplogEntryJSON;
305
- }
306
-
307
- type SyncDataBucketJSON = {
308
- bucket: string;
309
- has_more?: boolean;
310
- after?: string;
311
- next_after?: string;
312
- data: OplogEntryJSON[];
313
- };
314
- declare class SyncDataBucket {
315
- bucket: string;
316
- data: OplogEntry[];
317
- /**
318
- * True if the response does not contain all the data for this bucket, and another request must be made.
319
- */
320
- has_more: boolean;
321
- /**
322
- * The `after` specified in the request.
323
- */
324
- after?: OpId | undefined;
325
- /**
326
- * Use this for the next request.
327
- */
328
- next_after?: OpId | undefined;
329
- static fromRow(row: SyncDataBucketJSON): SyncDataBucket;
330
- constructor(bucket: string, data: OplogEntry[],
331
- /**
332
- * True if the response does not contain all the data for this bucket, and another request must be made.
333
- */
334
- has_more: boolean,
335
- /**
336
- * The `after` specified in the request.
337
- */
338
- after?: OpId | undefined,
339
- /**
340
- * Use this for the next request.
341
- */
342
- next_after?: OpId | undefined);
343
- toJSON(fixedKeyEncoding?: boolean): SyncDataBucketJSON;
344
- }
345
-
346
- declare class SyncDataBatch {
347
- buckets: SyncDataBucket[];
348
- static fromJSON(json: any): SyncDataBatch;
349
- constructor(buckets: SyncDataBucket[]);
350
- }
351
-
352
- interface BucketDescription {
353
- name: string;
354
- priority: number;
355
- }
356
- interface Checkpoint {
357
- last_op_id: OpId;
358
- buckets: BucketChecksum[];
359
- write_checkpoint?: string;
360
- streams?: any[];
361
- }
362
- interface BucketState {
363
- bucket: string;
364
- op_id: string;
365
- }
366
- interface ChecksumCache {
367
- checksums: Map<string, {
368
- checksum: BucketChecksum;
369
- last_op_id: OpId;
370
- }>;
371
- lastOpId: OpId;
372
- }
373
- interface SyncLocalDatabaseResult {
374
- ready: boolean;
375
- checkpointValid: boolean;
376
- checkpointFailures?: string[];
377
- }
378
- type SavedProgress = {
379
- atLast: number;
380
- sinceLast: number;
381
- };
382
- type BucketOperationProgress = Record<string, SavedProgress>;
383
- interface BucketChecksum {
384
- bucket: string;
385
- priority?: number;
386
- /**
387
- * 32-bit unsigned hash.
388
- */
389
- checksum: number;
390
- /**
391
- * Count of operations - informational only.
392
- */
393
- count?: number;
394
- /**
395
- * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
396
- * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
397
- * present.
398
- */
399
- subscriptions?: any;
400
- }
401
- declare enum PSInternalTable {
402
- DATA = "ps_data",
403
- CRUD = "ps_crud",
404
- BUCKETS = "ps_buckets",
405
- OPLOG = "ps_oplog",
406
- UNTYPED = "ps_untyped"
407
- }
408
- declare enum PowerSyncControlCommand {
409
- PROCESS_TEXT_LINE = "line_text",
410
- PROCESS_BSON_LINE = "line_binary",
411
- STOP = "stop",
412
- START = "start",
413
- NOTIFY_TOKEN_REFRESHED = "refreshed_token",
414
- NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload",
415
- UPDATE_SUBSCRIPTIONS = "update_subscriptions"
416
- }
417
- interface BucketStorageListener extends BaseListener {
418
- crudUpdate: () => void;
419
- }
420
- interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListener>, Disposable {
421
- init(): Promise<void>;
422
- saveSyncData(batch: SyncDataBatch, fixedKeyFormat?: boolean): Promise<void>;
423
- removeBuckets(buckets: string[]): Promise<void>;
424
- setTargetCheckpoint(checkpoint: Checkpoint): Promise<void>;
425
- startSession(): void;
426
- getBucketStates(): Promise<BucketState[]>;
427
- getBucketOperationProgress(): Promise<BucketOperationProgress>;
428
- hasMigratedSubkeys(): Promise<boolean>;
429
- migrateToFixedSubkeys(): Promise<void>;
430
- syncLocalDatabase(checkpoint: Checkpoint, priority?: number): Promise<{
431
- checkpointValid: boolean;
432
- ready: boolean;
433
- failures?: any[];
434
- }>;
435
- nextCrudItem(): Promise<CrudEntry | undefined>;
436
- hasCrud(): Promise<boolean>;
437
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
438
- hasCompletedSync(): Promise<boolean>;
439
- updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
440
- getMaxOpId(): string;
441
- /**
442
- * Get an unique client id.
443
- */
444
- getClientId(): Promise<string>;
445
- /**
446
- * Invokes the `powersync_control` function for the sync client.
447
- */
448
- control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
449
- }
450
-
451
- type DataStreamOptions<ParsedData, SourceData> = {
452
- mapLine?: (line: SourceData) => ParsedData;
453
- /**
454
- * Close the stream if any consumer throws an error
455
- */
456
- closeOnError?: boolean;
457
- pressure?: {
458
- highWaterMark?: number;
459
- lowWaterMark?: number;
460
- };
461
- logger?: ILogger;
462
- };
463
- type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
464
- interface DataStreamListener<Data extends any = any> extends BaseListener {
465
- data: (data: Data) => Promise<void>;
466
- closed: () => void;
467
- error: (error: Error) => void;
468
- highWater: () => Promise<void>;
469
- lowWater: () => Promise<void>;
470
- }
471
- declare const DEFAULT_PRESSURE_LIMITS: {
472
- highWater: number;
473
- lowWater: number;
474
- };
475
- /**
476
- * A very basic implementation of a data stream with backpressure support which does not use
477
- * native JS streams or async iterators.
478
- * This is handy for environments such as React Native which need polyfills for the above.
479
- */
480
- declare class DataStream<ParsedData, SourceData = any> extends BaseObserver<DataStreamListener<ParsedData>> {
481
- protected options?: DataStreamOptions<ParsedData, SourceData> | undefined;
482
- dataQueue: SourceData[];
483
- protected isClosed: boolean;
484
- protected processingPromise: Promise<void> | null;
485
- protected notifyDataAdded: (() => void) | null;
486
- protected logger: ILogger;
487
- protected mapLine: (line: SourceData) => ParsedData;
488
- constructor(options?: DataStreamOptions<ParsedData, SourceData> | undefined);
489
- get highWatermark(): number;
490
- get lowWatermark(): number;
491
- get closed(): boolean;
492
- close(): Promise<void>;
493
- /**
494
- * Enqueues data for the consumers to read
495
- */
496
- enqueueData(data: SourceData): void;
497
- /**
498
- * Reads data once from the data stream
499
- * @returns a Data payload or Null if the stream closed.
500
- */
501
- read(): Promise<ParsedData | null>;
502
- /**
503
- * Executes a callback for each data item in the stream
504
- */
505
- forEach(callback: DataStreamCallback<ParsedData>): () => void;
506
- protected processQueue(): Promise<void> | undefined;
507
- protected hasDataReader(): boolean;
508
- protected _processQueue(): Promise<void>;
509
- protected iterateAsyncErrored(cb: (l: Partial<DataStreamListener<ParsedData>>) => Promise<void>): Promise<void>;
510
- }
511
-
512
- interface PowerSyncCredentials {
513
- endpoint: string;
514
- token: string;
515
- expiresAt?: Date;
516
- }
517
-
518
- /**
519
- * For sync2.json
520
- */
521
- interface ContinueCheckpointRequest {
522
- /**
523
- * Existing bucket states. Only these buckets are synchronized.
524
- */
525
- buckets: BucketRequest[];
526
- checkpoint_token: string;
527
- limit?: number;
528
- }
529
- interface SyncNewCheckpointRequest {
530
- /**
531
- * Existing bucket states. Used if include_data is specified.
532
- */
533
- buckets?: BucketRequest[];
534
- request_checkpoint: {
535
- /**
536
- * Whether or not to include an initial data request.
537
- */
538
- include_data: boolean;
539
- /**
540
- * Whether or not to compute a checksum.
541
- */
542
- include_checksum: boolean;
543
- };
544
- limit?: number;
545
- }
546
- type SyncRequest = ContinueCheckpointRequest | SyncNewCheckpointRequest;
547
- interface SyncResponse {
548
- /**
549
- * Data for the buckets returned. May not have an an entry for each bucket in the request.
550
- */
551
- data?: SyncDataBucketJSON[];
552
- /**
553
- * True if the response limit has been reached, and another request must be made.
554
- */
555
- has_more: boolean;
556
- checkpoint_token?: string;
557
- checkpoint?: Checkpoint;
558
- }
559
- type JSONValue = string | number | boolean | null | undefined | JSONObject | JSONArray;
560
- interface JSONObject {
561
- [key: string]: JSONValue;
562
- }
563
- type JSONArray = JSONValue[];
564
- type StreamingSyncRequestParameterType = JSONValue;
565
- interface StreamingSyncRequest {
566
- /**
567
- * Existing bucket states.
568
- */
569
- buckets?: BucketRequest[];
570
- /**
571
- * If specified, limit the response to only include these buckets.
572
- */
573
- only?: string[];
574
- /**
575
- * Whether or not to compute a checksum for each checkpoint
576
- */
577
- include_checksum: boolean;
578
- /**
579
- * Changes the response to stringified data in each OplogEntry
580
- */
581
- raw_data: boolean;
582
- /**
583
- * Client parameters to be passed to the sync rules.
584
- */
585
- parameters?: Record<string, StreamingSyncRequestParameterType>;
586
- /**
587
- * Application metadata to be included in service logs.
588
- */
589
- app_metadata?: Record<string, string>;
590
- client_id?: string;
591
- }
592
- interface StreamingSyncCheckpoint {
593
- checkpoint: Checkpoint;
594
- }
595
- interface StreamingSyncCheckpointDiff {
596
- checkpoint_diff: {
597
- last_op_id: OpId;
598
- updated_buckets: BucketChecksum[];
599
- removed_buckets: string[];
600
- write_checkpoint?: string;
601
- };
602
- }
603
- interface StreamingSyncDataJSON {
604
- data: SyncDataBucketJSON;
605
- }
606
- interface StreamingSyncCheckpointComplete {
607
- checkpoint_complete: {
608
- last_op_id: OpId;
609
- };
610
- }
611
- interface StreamingSyncCheckpointPartiallyComplete {
612
- partial_checkpoint_complete: {
613
- priority: number;
614
- last_op_id: OpId;
615
- };
616
- }
617
- interface StreamingSyncKeepalive {
618
- /** If specified, token expires in this many seconds. */
619
- token_expires_in: number;
620
- }
621
- type StreamingSyncLine = StreamingSyncDataJSON | StreamingSyncCheckpoint | StreamingSyncCheckpointDiff | StreamingSyncCheckpointComplete | StreamingSyncCheckpointPartiallyComplete | StreamingSyncKeepalive;
622
- type CrudUploadNotification = {
623
- crud_upload_completed: null;
624
- };
625
- type StreamingSyncLineOrCrudUploadComplete = StreamingSyncLine | CrudUploadNotification;
626
- interface BucketRequest {
627
- name: string;
628
- /**
629
- * Base-10 number. Sync all data from this bucket with op_id > after.
630
- */
631
- after: OpId;
632
- }
633
- declare function isStreamingSyncData(line: StreamingSyncLine): line is StreamingSyncDataJSON;
634
- declare function isStreamingKeepalive(line: StreamingSyncLine): line is StreamingSyncKeepalive;
635
- declare function isStreamingSyncCheckpoint(line: StreamingSyncLine): line is StreamingSyncCheckpoint;
636
- declare function isStreamingSyncCheckpointComplete(line: StreamingSyncLine): line is StreamingSyncCheckpointComplete;
637
- declare function isStreamingSyncCheckpointPartiallyComplete(line: StreamingSyncLine): line is StreamingSyncCheckpointPartiallyComplete;
638
- declare function isStreamingSyncCheckpointDiff(line: StreamingSyncLine): line is StreamingSyncCheckpointDiff;
639
- declare function isContinueCheckpointRequest(request: SyncRequest): request is ContinueCheckpointRequest;
640
- declare function isSyncNewCheckpointRequest(request: SyncRequest): request is SyncNewCheckpointRequest;
641
- /**
642
- * For crud.json
643
- */
644
- interface CrudRequest {
645
- data: CrudEntry[];
646
- }
647
- interface CrudResponse {
648
- /**
649
- * A sync response with a checkpoint >= this checkpoint would contain all the changes in this request.
650
- *
651
- * Any earlier checkpoint may or may not contain these changes.
652
- *
653
- * May be empty when the request contains no ops.
654
- */
655
- checkpoint?: OpId;
656
- }
657
-
658
- type BSONImplementation = typeof BSON;
659
- type RemoteConnector = {
660
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
661
- invalidateCredentials?: () => void;
662
- };
663
- declare const DEFAULT_REMOTE_LOGGER: Logger.ILogger;
664
- type SyncStreamOptions = {
665
- path: string;
666
- data: StreamingSyncRequest;
667
- headers?: Record<string, string>;
668
- abortSignal?: AbortSignal;
669
- fetchOptions?: Request;
670
- };
671
- declare enum FetchStrategy {
672
- /**
673
- * Queues multiple sync events before processing, reducing round-trips.
674
- * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.
675
- */
676
- Buffered = "buffered",
677
- /**
678
- * Processes each sync event immediately before requesting the next.
679
- * This reduces processing overhead and improves real-time responsiveness.
680
- */
681
- Sequential = "sequential"
682
- }
683
- type SocketSyncStreamOptions = SyncStreamOptions & {
684
- fetchStrategy: FetchStrategy;
685
- };
686
- type FetchImplementation = typeof fetch;
687
- /**
688
- * Class wrapper for providing a fetch implementation.
689
- * The class wrapper is used to distinguish the fetchImplementation
690
- * option in [AbstractRemoteOptions] from the general fetch method
691
- * which is typeof "function"
692
- */
693
- declare class FetchImplementationProvider {
694
- getFetch(): FetchImplementation;
695
- }
696
- type AbstractRemoteOptions = {
697
- /**
698
- * Transforms the PowerSync base URL which might contain
699
- * `http(s)://` to the corresponding WebSocket variant
700
- * e.g. `ws(s)://`
701
- */
702
- socketUrlTransformer: (url: string) => string;
703
- /**
704
- * Optionally provide the fetch implementation to use.
705
- * Note that this usually needs to be bound to the global scope.
706
- * Binding should be done before passing here.
707
- */
708
- fetchImplementation: FetchImplementation | FetchImplementationProvider;
709
- /**
710
- * Optional options to pass directly to all `fetch` calls.
711
- *
712
- * This can include fields such as `dispatcher` (e.g. for proxy support),
713
- * `cache`, or any other fetch-compatible options.
714
- */
715
- fetchOptions?: {};
716
- };
717
- declare const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;
718
- declare abstract class AbstractRemote {
719
- protected connector: RemoteConnector;
720
- protected logger: ILogger;
721
- protected credentials: PowerSyncCredentials | null;
722
- protected options: AbstractRemoteOptions;
723
- constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
724
- /**
725
- * @returns a fetch implementation (function)
726
- * which can be called to perform fetch requests
727
- */
728
- get fetch(): FetchImplementation;
729
- /**
730
- * Get credentials currently cached, or fetch new credentials if none are
731
- * available.
732
- *
733
- * These credentials may have expired already.
734
- */
735
- getCredentials(): Promise<PowerSyncCredentials | null>;
736
- /**
737
- * Fetch a new set of credentials and cache it.
738
- *
739
- * Until this call succeeds, `getCredentials` will still return the
740
- * old credentials.
741
- *
742
- * This may be called before the current credentials have expired.
743
- */
744
- prefetchCredentials(): Promise<PowerSyncCredentials | null>;
745
- /**
746
- * Get credentials for PowerSync.
747
- *
748
- * This should always fetch a fresh set of credentials - don't use cached
749
- * values.
750
- */
751
- fetchCredentials(): Promise<PowerSyncCredentials | null>;
752
- /***
753
- * Immediately invalidate credentials.
754
- *
755
- * This may be called when the current credentials have expired.
756
- */
757
- invalidateCredentials(): void;
758
- getUserAgent(): string;
759
- protected buildRequest(path: string): Promise<{
760
- url: string;
761
- headers: {
762
- 'content-type': string;
763
- Authorization: string;
764
- 'x-user-agent': string;
765
- };
766
- }>;
767
- post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
768
- get(path: string, headers?: Record<string, string>): Promise<any>;
769
- /**
770
- * Provides a BSON implementation. The import nature of this varies depending on the platform
771
- */
772
- abstract getBSON(): Promise<BSONImplementation>;
773
- /**
774
- * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
775
- * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
776
- */
777
- protected createTextDecoder(): TextDecoder;
778
- protected createSocket(url: string): WebSocket;
779
- /**
780
- * Returns a data stream of sync line data.
781
- *
782
- * @param map Maps received payload frames to the typed event value.
783
- * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
784
- * (required for compatibility with older sync services).
785
- */
786
- socketStreamRaw<T>(options: SocketSyncStreamOptions, map: (buffer: Uint8Array) => T, bson?: typeof BSON): Promise<DataStream<T>>;
787
- /**
788
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
789
- */
790
- postStreamRaw<T>(options: SyncStreamOptions, mapLine: (line: string) => T): Promise<DataStream<T>>;
791
- }
792
-
793
- declare enum LockType {
794
- CRUD = "crud",
795
- SYNC = "sync"
796
- }
797
- declare enum SyncStreamConnectionMethod {
798
- HTTP = "http",
799
- WEB_SOCKET = "web-socket"
800
- }
801
- declare enum SyncClientImplementation {
802
- /**
803
- * Decodes and handles sync lines received from the sync service in JavaScript.
804
- *
805
- * This is the default option.
806
- *
807
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
808
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
809
- * version of the PowerSync SDK.
810
- */
811
- JAVASCRIPT = "js",
812
- /**
813
- * This implementation offloads the sync line decoding and handling into the PowerSync
814
- * core extension.
815
- *
816
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
817
- * recommended client implementation for all apps.
818
- *
819
- * ## Compatibility warning
820
- *
821
- * The Rust sync client stores sync data in a format that is slightly different than the one used
822
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
823
- * databases, the PowerSync SDK will migrate the format automatically.
824
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
825
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
826
- * back to {@link JAVASCRIPT} later.
827
- *
828
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
829
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
830
- * can lead to sync issues.
831
- */
832
- RUST = "rust"
833
- }
834
- /**
835
- * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
836
- */
837
- declare const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
838
- /**
839
- * Abstract Lock to be implemented by various JS environments
840
- */
841
- interface LockOptions<T> {
842
- callback: () => Promise<T>;
843
- type: LockType;
844
- signal?: AbortSignal;
845
- }
846
- interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
847
- adapter: BucketStorageAdapter;
848
- subscriptions: SubscribedStream[];
849
- uploadCrud: () => Promise<void>;
850
- /**
851
- * An identifier for which PowerSync DB this sync implementation is
852
- * linked to. Most commonly DB name, but not restricted to DB name.
853
- */
854
- identifier?: string;
855
- logger?: ILogger;
856
- remote: AbstractRemote;
857
- }
858
- interface StreamingSyncImplementationListener extends BaseListener {
859
- /**
860
- * Triggered whenever a status update has been attempted to be made or
861
- * refreshed.
862
- */
863
- statusUpdated?: ((statusUpdate: SyncStatusOptions) => void) | undefined;
864
- /**
865
- * Triggers whenever the status' members have changed in value
866
- */
867
- statusChanged?: ((status: SyncStatus) => void) | undefined;
868
- }
869
- /**
870
- * Configurable options to be used when connecting to the PowerSync
871
- * backend instance.
872
- */
873
- type PowerSyncConnectionOptions = Omit<InternalConnectionOptions, 'serializedSchema'>;
874
- interface InternalConnectionOptions extends BaseConnectionOptions, AdditionalConnectionOptions {
875
- }
876
- /** @internal */
877
- interface BaseConnectionOptions {
878
- /**
879
- * A set of metadata to be included in service logs.
880
- */
881
- appMetadata?: Record<string, string>;
882
- /**
883
- * Whether to use a JavaScript implementation to handle received sync lines from the sync
884
- * service, or whether this work should be offloaded to the PowerSync core extension.
885
- *
886
- * This defaults to the JavaScript implementation ({@link SyncClientImplementation.JAVASCRIPT})
887
- * since the ({@link SyncClientImplementation.RUST}) implementation is experimental at the moment.
888
- */
889
- clientImplementation?: SyncClientImplementation;
890
- /**
891
- * The connection method to use when streaming updates from
892
- * the PowerSync backend instance.
893
- * Defaults to a HTTP streaming connection.
894
- */
895
- connectionMethod?: SyncStreamConnectionMethod;
896
- /**
897
- * The fetch strategy to use when streaming updates from the PowerSync backend instance.
898
- */
899
- fetchStrategy?: FetchStrategy;
900
- /**
901
- * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
902
- */
903
- params?: Record<string, StreamingSyncRequestParameterType>;
904
- /**
905
- * Whether to include streams that have `auto_subscribe: true` in their definition.
906
- *
907
- * This defaults to `true`.
908
- */
909
- includeDefaultStreams?: boolean;
910
- /**
911
- * The serialized schema - mainly used to forward information about raw tables to the sync client.
912
- */
913
- serializedSchema?: any;
914
- }
915
- /** @internal */
916
- interface AdditionalConnectionOptions {
917
- /**
918
- * Delay for retrying sync streaming operations
919
- * from the PowerSync backend after an error occurs.
920
- */
921
- retryDelayMs?: number;
922
- /**
923
- * Backend Connector CRUD operations are throttled
924
- * to occur at most every `crudUploadThrottleMs`
925
- * milliseconds.
926
- */
927
- crudUploadThrottleMs?: number;
928
- }
929
- /** @internal */
930
- interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
931
- subscriptions: SubscribedStream[];
932
- }
933
- interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
934
- /**
935
- * Connects to the sync service
936
- */
937
- connect(options?: InternalConnectionOptions): Promise<void>;
938
- /**
939
- * Disconnects from the sync services.
940
- * @throws if not connected or if abort is not controlled internally
941
- */
942
- disconnect(): Promise<void>;
943
- getWriteCheckpoint: () => Promise<string>;
944
- hasCompletedSync: () => Promise<boolean>;
945
- isConnected: boolean;
946
- lastSyncedAt?: Date;
947
- syncStatus: SyncStatus;
948
- triggerCrudUpload: () => void;
949
- waitForReady(): Promise<void>;
950
- waitForStatus(status: SyncStatusOptions): Promise<void>;
951
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
952
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
953
- }
954
- declare const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
955
- declare const DEFAULT_RETRY_DELAY_MS = 5000;
956
- declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
957
- retryDelayMs: number;
958
- crudUploadThrottleMs: number;
959
- };
960
- type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
961
- declare const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;
962
- type SubscribedStream = {
963
- name: string;
964
- params: Record<string, any> | null;
965
- };
966
- declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
967
- protected _lastSyncedAt: Date | null;
968
- protected options: AbstractStreamingSyncImplementationOptions;
969
- protected abortController: AbortController | null;
970
- protected uploadAbortController: AbortController | null;
971
- protected crudUpdateListener?: () => void;
972
- protected streamingSyncPromise?: Promise<void>;
973
- protected logger: ILogger;
974
- private activeStreams;
975
- private isUploadingCrud;
976
- private notifyCompletedUploads?;
977
- private handleActiveStreamsChange?;
978
- syncStatus: SyncStatus;
979
- triggerCrudUpload: () => void;
980
- constructor(options: AbstractStreamingSyncImplementationOptions);
981
- waitForReady(): Promise<void>;
982
- waitForStatus(status: SyncStatusOptions): Promise<void>;
983
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
984
- get lastSyncedAt(): Date | undefined;
985
- get isConnected(): boolean;
986
- dispose(): Promise<void>;
987
- abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
988
- hasCompletedSync(): Promise<boolean>;
989
- getWriteCheckpoint(): Promise<string>;
990
- protected _uploadAllCrud(): Promise<void>;
991
- connect(options?: PowerSyncConnectionOptions): Promise<void>;
992
- disconnect(): Promise<void>;
993
- /**
994
- * @deprecated use [connect instead]
995
- */
996
- streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
997
- private collectLocalBucketState;
998
- /**
999
- * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
1000
- * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
1001
- * While this is not a problem as long as it's done consistently, it causes issues when a database
1002
- * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
1003
- * is enabled.
1004
- *
1005
- * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
1006
- * migration is only triggered when necessary (for now). The function returns whether the new format
1007
- * should be used, so that the JS SDK is able to write to updated databases.
1008
- *
1009
- * @param requireFixedKeyFormat Whether we require the new format or also support the old one.
1010
- * The Rust client requires the new subkey format.
1011
- * @returns Whether the database is now using the new, fixed subkey format.
1012
- */
1013
- private requireKeyFormat;
1014
- protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<RustIterationResult | null>;
1015
- private legacyStreamingSyncIteration;
1016
- private rustSyncIteration;
1017
- private updateSyncStatusForStartingCheckpoint;
1018
- private applyCheckpoint;
1019
- protected updateSyncStatus(options: SyncStatusOptions): void;
1020
- private delayRetry;
1021
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
1022
- }
1023
- interface RustIterationResult {
1024
- immediateRestart: boolean;
1025
- }
1026
-
1027
- interface CoreStreamSubscription {
1028
- progress: {
1029
- total: number;
1030
- downloaded: number;
1031
- };
1032
- name: string;
1033
- parameters: any;
1034
- priority: number | null;
1035
- active: boolean;
1036
- is_default: boolean;
1037
- has_explicit_subscription: boolean;
1038
- expires_at: number | null;
1039
- last_synced_at: number | null;
1040
- }
1041
- interface BucketProgress {
1042
- priority: number;
1043
- at_last: number;
1044
- since_last: number;
1045
- target_count: number;
1046
- }
1047
-
1048
- /**
1049
- * A description of a sync stream, consisting of its {@link name} and the {@link parameters} used when subscribing.
1050
- */
1051
- interface SyncStreamDescription {
1052
- /**
1053
- * The name of the stream as it appears in the stream definition for the PowerSync service.
1054
- */
1055
- name: string;
1056
- /**
1057
- * The parameters used to subscribe to the stream, if any.
1058
- *
1059
- * The same stream can be subscribed to multiple times with different parameters.
1060
- */
1061
- parameters: Record<string, any> | null;
1062
- }
1063
- /**
1064
- * Information about a subscribed sync stream.
1065
- *
1066
- * This includes the {@link SyncStreamDescription}, along with information about the current sync status.
1067
- */
1068
- interface SyncSubscriptionDescription extends SyncStreamDescription {
1069
- active: boolean;
1070
- /**
1071
- * Whether this stream subscription is included by default, regardless of whether the stream has explicitly been
1072
- * subscribed to or not.
1073
- *
1074
- * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1075
- * happens when a default stream was subscribed explicitly.
1076
- */
1077
- isDefault: boolean;
1078
- /**
1079
- * Whether this stream has been subscribed to explicitly.
1080
- *
1081
- * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1082
- * happens when a default stream was subscribed explicitly.
1083
- */
1084
- hasExplicitSubscription: boolean;
1085
- /**
1086
- * For sync streams that have a time-to-live, the current time at which the stream would expire if not subscribed to
1087
- * again.
1088
- */
1089
- expiresAt: Date | null;
1090
- /**
1091
- * Whether this stream subscription has been synced at least once.
1092
- */
1093
- hasSynced: boolean;
1094
- /**
1095
- * If {@link hasSynced} is true, the last time data from this stream has been synced.
1096
- */
1097
- lastSyncedAt: Date | null;
1098
- }
1099
- interface SyncStreamSubscribeOptions {
1100
- /**
1101
- * A "time to live" for this stream subscription, in seconds.
1102
- *
1103
- * The TTL control when a stream gets evicted after not having an active {@link SyncStreamSubscription} object
1104
- * attached to it.
1105
- */
1106
- ttl?: number;
1107
- /**
1108
- * A priority to assign to this subscription. This overrides the default priority that may have been set on streams.
1109
- *
1110
- * For details on priorities, see [priotized sync](https://docs.powersync.com/usage/use-case-examples/prioritized-sync).
1111
- */
1112
- priority?: 0 | 1 | 2 | 3;
1113
- }
1114
- /**
1115
- * A handle to a {@link SyncStreamDescription} that allows subscribing to the stream.
1116
- *
1117
- * To obtain an instance of {@link SyncStream}, call {@link AbstractPowerSyncDatabase.syncStream}.
1118
- */
1119
- interface SyncStream extends SyncStreamDescription {
1120
- /**
1121
- * Adds a subscription to this stream, requesting it to be included when connecting to the sync service.
1122
- *
1123
- * You should keep a reference to the returned {@link SyncStreamSubscription} object along as you need data for that
1124
- * stream. As soon as {@link SyncStreamSubscription.unsubscribe} is called for all subscriptions on this stream
1125
- * (including subscriptions created on other tabs), the {@link SyncStreamSubscribeOptions.ttl} starts ticking and will
1126
- * eventually evict the stream (unless {@link subscribe} is called again).
1127
- */
1128
- subscribe(options?: SyncStreamSubscribeOptions): Promise<SyncStreamSubscription>;
1129
- /**
1130
- * Clears all subscriptions attached to this stream and resets the TTL for the stream.
1131
- *
1132
- * This is a potentially dangerous operations, as it interferes with other stream subscriptions.
1133
- */
1134
- unsubscribeAll(): Promise<void>;
1135
- }
1136
- interface SyncStreamSubscription extends SyncStreamDescription {
1137
- /**
1138
- * A promise that resolves once data from in this sync stream has been synced and applied.
1139
- */
1140
- waitForFirstSync(abort?: AbortSignal): Promise<void>;
1141
- /**
1142
- * Removes this stream subscription.
1143
- */
1144
- unsubscribe(): void;
1145
- }
1146
-
1147
- /** @internal */
1148
- type InternalProgressInformation = Record<string, BucketProgress>;
1149
- /**
1150
- * Information about a progressing download made by the PowerSync SDK.
1151
- *
1152
- * To obtain these values, use {@link SyncProgress}, available through
1153
- * {@link SyncStatus#downloadProgress}.
1154
- */
1155
- interface ProgressWithOperations {
1156
- /**
1157
- * The total amount of operations to download for the current sync iteration
1158
- * to complete.
1159
- */
1160
- totalOperations: number;
1161
- /**
1162
- * The amount of operations that have already been downloaded.
1163
- */
1164
- downloadedOperations: number;
1165
- /**
1166
- * Relative progress, as {@link downloadedOperations} of {@link totalOperations}.
1167
- *
1168
- * This will be a number between `0.0` and `1.0` (inclusive).
1169
- *
1170
- * When this number reaches `1.0`, all changes have been received from the sync service.
1171
- * Actually applying these changes happens before the `downloadProgress` field is cleared from
1172
- * {@link SyncStatus}, so progress can stay at `1.0` for a short while before completing.
1173
- */
1174
- downloadedFraction: number;
1175
- }
1176
- /**
1177
- * Provides realtime progress on how PowerSync is downloading rows.
1178
- *
1179
- * The progress until the next complete sync is available through the fields on {@link ProgressWithOperations},
1180
- * which this class implements.
1181
- * Additionally, the {@link SyncProgress.untilPriority} method can be used to otbain progress towards
1182
- * a specific priority (instead of the progress for the entire download).
1183
- *
1184
- * The reported progress always reflects the status towards the end of a sync iteration (after
1185
- * which a consistent snapshot of all buckets is available locally).
1186
- *
1187
- * In rare cases (in particular, when a [compacting](https://docs.powersync.com/usage/lifecycle-maintenance/compacting-buckets)
1188
- * operation takes place between syncs), it's possible for the returned numbers to be slightly
1189
- * inaccurate. For this reason, {@link SyncProgress} should be seen as an approximation of progress.
1190
- * The information returned is good enough to build progress bars, but not exact enough to track
1191
- * individual download counts.
1192
- *
1193
- * Also note that data is downloaded in bulk, which means that individual counters are unlikely
1194
- * to be updated one-by-one.
1195
- */
1196
- declare class SyncProgress implements ProgressWithOperations {
1197
- protected internal: InternalProgressInformation;
1198
- totalOperations: number;
1199
- downloadedOperations: number;
1200
- downloadedFraction: number;
1201
- constructor(internal: InternalProgressInformation);
1202
- /**
1203
- * Returns download progress towards all data up until the specified priority being received.
1204
- *
1205
- * The returned {@link ProgressWithOperations} tracks the target amount of operations that need
1206
- * to be downloaded in total and how many of them have already been received.
1207
- */
1208
- untilPriority(priority: number): ProgressWithOperations;
1209
- }
1210
-
1211
- type SyncDataFlowStatus = Partial<{
1212
- downloading: boolean;
1213
- uploading: boolean;
1214
- /**
1215
- * Error during downloading (including connecting).
1216
- *
1217
- * Cleared on the next successful data download.
1218
- */
1219
- downloadError?: Error;
1220
- /**
1221
- * Error during uploading.
1222
- * Cleared on the next successful upload.
1223
- */
1224
- uploadError?: Error;
1225
- /**
1226
- * Internal information about how far we are downloading operations in buckets.
1227
- *
1228
- * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1229
- */
1230
- downloadProgress: InternalProgressInformation | null;
1231
- internalStreamSubscriptions: CoreStreamSubscription[] | null;
1232
- }>;
1233
- interface SyncPriorityStatus {
1234
- priority: number;
1235
- lastSyncedAt?: Date;
1236
- hasSynced?: boolean;
1237
- }
1238
- type SyncStatusOptions = {
1239
- connected?: boolean;
1240
- connecting?: boolean;
1241
- dataFlow?: SyncDataFlowStatus;
1242
- lastSyncedAt?: Date;
1243
- hasSynced?: boolean;
1244
- priorityStatusEntries?: SyncPriorityStatus[];
1245
- clientImplementation?: SyncClientImplementation;
1246
- };
1247
- declare class SyncStatus {
1248
- protected options: SyncStatusOptions;
1249
- constructor(options: SyncStatusOptions);
1250
- /**
1251
- * Returns the used sync client implementation (either the one implemented in JavaScript or the newer Rust-based
1252
- * implementation).
1253
- *
1254
- * This information is only available after a connection has been requested.
1255
- */
1256
- get clientImplementation(): SyncClientImplementation | undefined;
1257
- /**
1258
- * Indicates if the client is currently connected to the PowerSync service.
1259
- *
1260
- * @returns {boolean} True if connected, false otherwise. Defaults to false if not specified.
1261
- */
1262
- get connected(): boolean;
1263
- /**
1264
- * Indicates if the client is in the process of establishing a connection to the PowerSync service.
1265
- *
1266
- * @returns {boolean} True if connecting, false otherwise. Defaults to false if not specified.
1267
- */
1268
- get connecting(): boolean;
1269
- /**
1270
- * Time that a last sync has fully completed, if any.
1271
- * This timestamp is reset to null after a restart of the PowerSync service.
1272
- *
1273
- * @returns {Date | undefined} The timestamp of the last successful sync, or undefined if no sync has completed.
1274
- */
1275
- get lastSyncedAt(): Date | undefined;
1276
- /**
1277
- * Indicates whether there has been at least one full sync completed since initialization.
1278
- *
1279
- * @returns {boolean | undefined} True if at least one sync has completed, false if no sync has completed,
1280
- * or undefined when the state is still being loaded from the database.
1281
- */
1282
- get hasSynced(): boolean | undefined;
1283
- /**
1284
- * Provides the current data flow status regarding uploads and downloads.
1285
- *
1286
- * @returns {SyncDataFlowStatus} An object containing:
1287
- * - downloading: True if actively downloading changes (only when connected is also true)
1288
- * - uploading: True if actively uploading changes
1289
- * Defaults to {downloading: false, uploading: false} if not specified.
1290
- */
1291
- get dataFlowStatus(): Partial<{
1292
- downloading: boolean;
1293
- uploading: boolean;
1294
- /**
1295
- * Error during downloading (including connecting).
1296
- *
1297
- * Cleared on the next successful data download.
1298
- */
1299
- downloadError?: Error;
1300
- /**
1301
- * Error during uploading.
1302
- * Cleared on the next successful upload.
1303
- */
1304
- uploadError?: Error;
1305
- /**
1306
- * Internal information about how far we are downloading operations in buckets.
1307
- *
1308
- * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1309
- */
1310
- downloadProgress: InternalProgressInformation | null;
1311
- internalStreamSubscriptions: CoreStreamSubscription[] | null;
1312
- }>;
1313
- /**
1314
- * All sync streams currently being tracked in teh database.
1315
- *
1316
- * This returns null when the database is currently being opened and we don't have reliable information about all
1317
- * included streams yet.
1318
- *
1319
- * @experimental Sync streams are currently in alpha.
1320
- */
1321
- get syncStreams(): SyncStreamStatus[] | undefined;
1322
- /**
1323
- * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
1324
- *
1325
- * @experimental Sync streams are currently in alpha.
1326
- */
1327
- forStream(stream: SyncStreamDescription): SyncStreamStatus | undefined;
1328
- /**
1329
- * Provides sync status information for all bucket priorities, sorted by priority (highest first).
1330
- *
1331
- * @returns {SyncPriorityStatus[]} An array of status entries for different sync priority levels,
1332
- * sorted with highest priorities (lower numbers) first.
1333
- */
1334
- get priorityStatusEntries(): SyncPriorityStatus[];
1335
- /**
1336
- * A realtime progress report on how many operations have been downloaded and
1337
- * how many are necessary in total to complete the next sync iteration.
1338
- *
1339
- * This field is only set when {@link SyncDataFlowStatus#downloading} is also true.
1340
- */
1341
- get downloadProgress(): SyncProgress | null;
1342
- /**
1343
- * Reports the sync status (a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields)
1344
- * for a specific bucket priority level.
1345
- *
1346
- * When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority
1347
- * buckets first. When a consistent view over all buckets for all priorities up until the given priority is
1348
- * reached, PowerSync makes data from those buckets available before lower-priority buckets have finished
1349
- * syncing.
1350
- *
1351
- * This method returns the status for the requested priority or the next higher priority level that has
1352
- * status information available. This is because when PowerSync makes data for a given priority available,
1353
- * all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.
1354
- *
1355
- * For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method
1356
- * with a priority of 1 may return information for priority level 3.
1357
- *
1358
- * @param {number} priority The bucket priority for which the status should be reported
1359
- * @returns {SyncPriorityStatus} Status information for the requested priority level or the next higher level with available status
1360
- */
1361
- statusForPriority(priority: number): SyncPriorityStatus;
1362
- /**
1363
- * Compares this SyncStatus instance with another to determine if they are equal.
1364
- * Equality is determined by comparing the serialized JSON representation of both instances.
1365
- *
1366
- * @param {SyncStatus} status The SyncStatus instance to compare against
1367
- * @returns {boolean} True if the instances are considered equal, false otherwise
1368
- */
1369
- isEqual(status: SyncStatus): boolean;
1370
- /**
1371
- * Creates a human-readable string representation of the current sync status.
1372
- * Includes information about connection state, sync completion, and data flow.
1373
- *
1374
- * @returns {string} A string representation of the sync status
1375
- */
1376
- getMessage(): string;
1377
- /**
1378
- * Serializes the SyncStatus instance to a plain object.
1379
- *
1380
- * @returns {SyncStatusOptions} A plain object representation of the sync status
1381
- */
1382
- toJSON(): SyncStatusOptions;
1383
- /**
1384
- * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
1385
- * This explicitly serializes errors in the SyncStatus.
1386
- */
1387
- protected serializeError(error?: Error): {
1388
- name: string;
1389
- message: string;
1390
- stack: string | undefined;
1391
- } | undefined;
1392
- private static comparePriorities;
1393
- }
1394
- /**
1395
- * Information about a sync stream subscription.
1396
- */
1397
- interface SyncStreamStatus {
1398
- progress: ProgressWithOperations | null;
1399
- subscription: SyncSubscriptionDescription;
1400
- priority: number | null;
1401
- }
1402
-
1403
- declare class UploadQueueStats {
1404
- /**
1405
- * Number of records in the upload queue.
1406
- */
1407
- count: number;
1408
- /**
1409
- * Size of the upload queue in bytes.
1410
- */
1411
- size: number | null;
1412
- constructor(
1413
- /**
1414
- * Number of records in the upload queue.
1415
- */
1416
- count: number,
1417
- /**
1418
- * Size of the upload queue in bytes.
1419
- */
1420
- size?: number | null);
1421
- toString(): string;
1422
- }
1423
-
1424
- declare enum ColumnType {
1425
- TEXT = "TEXT",
1426
- INTEGER = "INTEGER",
1427
- REAL = "REAL"
1428
- }
1429
- interface ColumnOptions {
1430
- name: string;
1431
- type?: ColumnType;
1432
- }
1433
- type BaseColumnType<T extends number | string | null> = {
1434
- type: ColumnType;
1435
- };
1436
- type ColumnsType = Record<string, BaseColumnType<any>>;
1437
- type ExtractColumnValueType<T extends BaseColumnType<any>> = T extends BaseColumnType<infer R> ? R : unknown;
1438
- declare const MAX_AMOUNT_OF_COLUMNS = 1999;
1439
- declare const column: {
1440
- text: BaseColumnType<string | null>;
1441
- integer: BaseColumnType<number | null>;
1442
- real: BaseColumnType<number | null>;
1443
- };
1444
- declare class Column {
1445
- protected options: ColumnOptions;
1446
- constructor(options: ColumnOptions);
1447
- get name(): string;
1448
- get type(): ColumnType | undefined;
1449
- toJSON(): {
1450
- name: string;
1451
- type: ColumnType | undefined;
1452
- };
1453
- }
1454
-
1455
- /**
1456
- * A pending variant of a {@link RawTable} that doesn't have a name (because it would be inferred when creating the
1457
- * schema).
1458
- */
1459
- type RawTableType = {
1460
- /**
1461
- * The statement to run when PowerSync detects that a row needs to be inserted or updated.
1462
- */
1463
- put: PendingStatement;
1464
- /**
1465
- * The statement to run when PowerSync detects that a row needs to be deleted.
1466
- */
1467
- delete: PendingStatement;
1468
- };
1469
- /**
1470
- * A parameter to use as part of {@link PendingStatement}.
1471
- *
1472
- * For delete statements, only the `"Id"` value is supported - the sync client will replace it with the id of the row to
1473
- * be synced.
1474
- *
1475
- * For insert and replace operations, the values of columns in the table are available as parameters through
1476
- * `{Column: 'name'}`.
1477
- */
1478
- type PendingStatementParameter = 'Id' | {
1479
- Column: string;
1480
- };
1481
- /**
1482
- * A statement that the PowerSync client should use to insert or delete data into a table managed by the user.
1483
- */
1484
- type PendingStatement = {
1485
- sql: string;
1486
- params: PendingStatementParameter[];
1487
- };
1488
- /**
1489
- * Instructs PowerSync to sync data into a "raw" table.
1490
- *
1491
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
1492
- * using client-side table and column constraints.
1493
- *
1494
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
1495
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
1496
- * using raw tables.
1497
- *
1498
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
1499
- *
1500
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
1501
- * stability guarantees.
1502
- */
1503
- declare class RawTable implements RawTableType {
1504
- /**
1505
- * The name of the table.
1506
- *
1507
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
1508
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
1509
- * appears in the source / backend database) are to be handled specially.
1510
- */
1511
- name: string;
1512
- put: PendingStatement;
1513
- delete: PendingStatement;
1514
- constructor(name: string, type: RawTableType);
1515
- }
1516
-
1517
- interface IndexColumnOptions {
1518
- name: string;
1519
- ascending?: boolean;
1520
- }
1521
- declare const DEFAULT_INDEX_COLUMN_OPTIONS: Partial<IndexColumnOptions>;
1522
- declare class IndexedColumn {
1523
- protected options: IndexColumnOptions;
1524
- static createAscending(column: string): IndexedColumn;
1525
- constructor(options: IndexColumnOptions);
1526
- get name(): string;
1527
- get ascending(): boolean | undefined;
1528
- toJSON(table: Table): {
1529
- name: string;
1530
- ascending: boolean | undefined;
1531
- type: ColumnType;
1532
- };
1533
- }
1534
-
1535
- interface IndexOptions {
1536
- name: string;
1537
- columns?: IndexedColumn[];
1538
- }
1539
- declare const DEFAULT_INDEX_OPTIONS: Partial<IndexOptions>;
1540
- declare class Index {
1541
- protected options: IndexOptions;
1542
- static createAscending(options: IndexOptions, columnNames: string[]): Index;
1543
- constructor(options: IndexOptions);
1544
- get name(): string;
1545
- get columns(): IndexedColumn[];
1546
- toJSON(table: Table): {
1547
- name: string;
1548
- columns: {
1549
- name: string;
1550
- ascending: boolean | undefined;
1551
- type: ColumnType;
1552
- }[];
1553
- };
1554
- }
1555
-
1556
- /**
1557
- Generate a new table from the columns and indexes
1558
- @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.
1559
- This will be removed in the next major release.
1560
- */
1561
- declare class TableV2<Columns extends ColumnsType = ColumnsType> extends Table<Columns> {
1562
- }
1563
-
1564
- interface SharedTableOptions {
1565
- localOnly?: boolean;
1566
- insertOnly?: boolean;
1567
- viewName?: string;
1568
- trackPrevious?: boolean | TrackPreviousOptions;
1569
- trackMetadata?: boolean;
1570
- ignoreEmptyUpdates?: boolean;
1571
- }
1572
- /** Whether to include previous column values when PowerSync tracks local changes.
1573
- *
1574
- * Including old values may be helpful for some backend connector implementations, which is
1575
- * why it can be enabled on per-table or per-columm basis.
1576
- */
1577
- interface TrackPreviousOptions {
1578
- /** When defined, a list of column names for which old values should be tracked. */
1579
- columns?: string[];
1580
- /** When enabled, only include values that have actually been changed by an update. */
1581
- onlyWhenChanged?: boolean;
1582
- }
1583
- interface TableOptions extends SharedTableOptions {
1584
- /**
1585
- * The synced table name, matching sync rules
1586
- */
1587
- name: string;
1588
- columns: Column[];
1589
- indexes?: Index[];
1590
- }
1591
- type RowType<T extends TableV2<any>> = {
1592
- [K in keyof T['columnMap']]: ExtractColumnValueType<T['columnMap'][K]>;
1593
- } & {
1594
- id: string;
1595
- };
1596
- type IndexShorthand = Record<string, string[]>;
1597
- interface TableV2Options extends SharedTableOptions {
1598
- indexes?: IndexShorthand;
1599
- }
1600
- declare const DEFAULT_TABLE_OPTIONS: {
1601
- indexes: never[];
1602
- insertOnly: boolean;
1603
- localOnly: boolean;
1604
- trackPrevious: boolean;
1605
- trackMetadata: boolean;
1606
- ignoreEmptyUpdates: boolean;
1607
- };
1608
- declare const InvalidSQLCharacters: RegExp;
1609
- declare class Table<Columns extends ColumnsType = ColumnsType> {
1610
- protected options: TableOptions;
1611
- protected _mappedColumns: Columns;
1612
- static createLocalOnly(options: TableOptions): Table<ColumnsType>;
1613
- static createInsertOnly(options: TableOptions): Table<ColumnsType>;
1614
- /**
1615
- * Create a table.
1616
- * @deprecated This was only only included for TableV2 and is no longer necessary.
1617
- * Prefer to use new Table() directly.
1618
- *
1619
- * TODO remove in the next major release.
1620
- */
1621
- static createTable(name: string, table: Table): Table<ColumnsType>;
1622
- /**
1623
- * Creates a new Table instance.
1624
- *
1625
- * This constructor supports two different versions:
1626
- * 1. New constructor: Using a Columns object and an optional TableV2Options object
1627
- * 2. Deprecated constructor: Using a TableOptions object (will be removed in the next major release)
1628
- *
1629
- * @constructor
1630
- * @param {Columns | TableOptions} optionsOrColumns - Either a Columns object (for V2 syntax) or a TableOptions object (for V1 syntax)
1631
- * @param {TableV2Options} [v2Options] - Optional configuration options for V2 syntax
1632
- *
1633
- * @example
1634
- * ```javascript
1635
- * // New Constructor
1636
- * const table = new Table(
1637
- * {
1638
- * name: column.text,
1639
- * age: column.integer
1640
- * },
1641
- * { indexes: { nameIndex: ['name'] } }
1642
- * );
1643
- *```
1644
- *
1645
- *
1646
- * @example
1647
- * ```javascript
1648
- * // Deprecated Constructor
1649
- * const table = new Table({
1650
- * name: 'users',
1651
- * columns: [
1652
- * new Column({ name: 'name', type: ColumnType.TEXT }),
1653
- * new Column({ name: 'age', type: ColumnType.INTEGER })
1654
- * ]
1655
- * });
1656
- *```
1657
- */
1658
- constructor(columns: Columns, options?: TableV2Options);
1659
- /**
1660
- * @deprecated This constructor will be removed in the next major release.
1661
- * Use the new constructor shown below instead as this does not show types.
1662
- * @example
1663
- * <caption>Use this instead</caption>
1664
- * ```javascript
1665
- * const table = new Table(
1666
- * {
1667
- * name: column.text,
1668
- * age: column.integer
1669
- * },
1670
- * { indexes: { nameIndex: ['name'] } }
1671
- * );
1672
- *```
1673
- */
1674
- constructor(options: TableOptions);
1675
- copyWithName(name: string): Table;
1676
- private isTableV1;
1677
- private initTableV1;
1678
- private initTableV2;
1679
- private applyDefaultOptions;
1680
- get name(): string;
1681
- get viewNameOverride(): string | undefined;
1682
- get viewName(): string;
1683
- get columns(): Column[];
1684
- get columnMap(): Columns;
1685
- get indexes(): Index[];
1686
- get localOnly(): boolean;
1687
- get insertOnly(): boolean;
1688
- get trackPrevious(): boolean | TrackPreviousOptions;
1689
- get trackMetadata(): boolean;
1690
- get ignoreEmptyUpdates(): boolean;
1691
- get internalName(): string;
1692
- get validName(): boolean;
1693
- validate(): void;
1694
- toJSON(): {
1695
- name: string;
1696
- view_name: string;
1697
- local_only: boolean;
1698
- insert_only: boolean;
1699
- include_old: any;
1700
- include_old_only_when_changed: boolean;
1701
- include_metadata: boolean;
1702
- ignore_empty_update: boolean;
1703
- columns: {
1704
- name: string;
1705
- type: ColumnType | undefined;
1706
- }[];
1707
- indexes: {
1708
- name: string;
1709
- columns: {
1710
- name: string;
1711
- ascending: boolean | undefined;
1712
- type: ColumnType;
1713
- }[];
1714
- }[];
1715
- };
1716
- }
1717
-
1718
- type SchemaType = Record<string, Table<any>>;
1719
- type SchemaTableType<S extends SchemaType> = {
1720
- [K in keyof S]: RowType<S[K]>;
1721
- };
1722
- /**
1723
- * A schema is a collection of tables. It is used to define the structure of a database.
1724
- */
1725
- declare class Schema<S extends SchemaType = SchemaType> {
1726
- readonly types: SchemaTableType<S>;
1727
- readonly props: S;
1728
- readonly tables: Table[];
1729
- readonly rawTables: RawTable[];
1730
- constructor(tables: Table[] | S);
1731
- /**
1732
- * Adds raw tables to this schema. Raw tables are identified by their name, but entirely managed by the application
1733
- * developer instead of automatically by PowerSync.
1734
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
1735
- * using client-side table and column constraints.
1736
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
1737
- *
1738
- * @param tables An object of (table name, raw table definition) entries.
1739
- * @experimental Note that the raw tables API is still experimental and may change in the future.
1740
- */
1741
- withRawTables(tables: Record<string, RawTableType>): void;
1742
- validate(): void;
1743
- toJSON(): {
1744
- tables: {
1745
- name: string;
1746
- view_name: string;
1747
- local_only: boolean;
1748
- insert_only: boolean;
1749
- include_old: any;
1750
- include_old_only_when_changed: boolean;
1751
- include_metadata: boolean;
1752
- ignore_empty_update: boolean;
1753
- columns: {
1754
- name: string;
1755
- type: ColumnType | undefined;
1756
- }[];
1757
- indexes: {
1758
- name: string;
1759
- columns: {
1760
- name: string;
1761
- ascending: boolean | undefined;
1762
- type: ColumnType;
1763
- }[];
1764
- }[];
1765
- }[];
1766
- raw_tables: RawTable[];
1767
- };
1768
- }
1769
-
1770
- interface PowerSyncBackendConnector {
1771
- /** Allows the PowerSync client to retrieve an authentication token from your backend
1772
- * which is used to authenticate against the PowerSync service.
1773
- *
1774
- * This should always fetch a fresh set of credentials - don't use cached
1775
- * values.
1776
- *
1777
- * Return null if the user is not signed in. Throw an error if credentials
1778
- * cannot be fetched due to a network error or other temporary error.
1779
- *
1780
- * This token is kept for the duration of a sync connection.
1781
- */
1782
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
1783
- /** Upload local changes to the app backend.
1784
- *
1785
- * Use {@link AbstractPowerSyncDatabase.getCrudBatch} to get a batch of changes to upload.
1786
- *
1787
- * Any thrown errors will result in a retry after the configured wait period (default: 5 seconds).
1788
- */
1789
- uploadData: (database: AbstractPowerSyncDatabase) => Promise<void>;
1790
- }
1791
-
1792
- /**
1793
- * @internal
1794
- */
1795
- interface ConnectionManagerSyncImplementationResult {
1796
- sync: StreamingSyncImplementation;
1797
- /**
1798
- * Additional cleanup function which is called after the sync stream implementation
1799
- * is disposed.
1800
- */
1801
- onDispose: () => Promise<void> | void;
1802
- }
1803
- /**
1804
- * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
1805
- *
1806
- * @internal
1807
- */
1808
- interface CreateSyncImplementationOptions extends AdditionalConnectionOptions {
1809
- subscriptions: SubscribedStream[];
1810
- }
1811
- interface InternalSubscriptionAdapter {
1812
- firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
1813
- resolveOfflineSyncStatus(): Promise<void>;
1814
- rustSubscriptionsCommand(payload: any): Promise<void>;
1815
- }
1816
- /**
1817
- * @internal
1818
- */
1819
- interface ConnectionManagerOptions {
1820
- createSyncImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions): Promise<ConnectionManagerSyncImplementationResult>;
1821
- logger: ILogger;
1822
- }
1823
- type StoredConnectionOptions = {
1824
- connector: PowerSyncBackendConnector;
1825
- options: InternalConnectionOptions;
1826
- };
1827
- /**
1828
- * @internal
1829
- */
1830
- interface ConnectionManagerListener extends BaseListener {
1831
- syncStreamCreated: (sync: StreamingSyncImplementation) => void;
1832
- }
1833
- /**
1834
- * @internal
1835
- */
1836
- declare class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
1837
- protected options: ConnectionManagerOptions;
1838
- /**
1839
- * Tracks active connection attempts
1840
- */
1841
- protected connectingPromise: Promise<void> | null;
1842
- /**
1843
- * Tracks actively instantiating a streaming sync implementation.
1844
- */
1845
- protected syncStreamInitPromise: Promise<void> | null;
1846
- /**
1847
- * Active disconnect operation. Calling disconnect multiple times
1848
- * will resolve to the same operation.
1849
- */
1850
- protected disconnectingPromise: Promise<void> | null;
1851
- /**
1852
- * Tracks the last parameters supplied to `connect` calls.
1853
- * Calling `connect` multiple times in succession will result in:
1854
- * - 1 pending connection operation which will be aborted.
1855
- * - updating the last set of parameters while waiting for the pending
1856
- * attempt to be aborted
1857
- * - internally connecting with the last set of parameters
1858
- */
1859
- protected pendingConnectionOptions: StoredConnectionOptions | null;
1860
- syncStreamImplementation: StreamingSyncImplementation | null;
1861
- /**
1862
- * Additional cleanup function which is called after the sync stream implementation
1863
- * is disposed.
1864
- */
1865
- protected syncDisposer: (() => Promise<void> | void) | null;
1866
- /**
1867
- * Subscriptions managed in this connection manager.
1868
- *
1869
- * On the web, these local subscriptions are merged across tabs by a shared worker.
1870
- */
1871
- private locallyActiveSubscriptions;
1872
- constructor(options: ConnectionManagerOptions);
1873
- get connector(): PowerSyncBackendConnector | null;
1874
- get connectionOptions(): InternalConnectionOptions | null;
1875
- get logger(): ILogger;
1876
- close(): Promise<void>;
1877
- connect(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<void>;
1878
- protected connectInternal(): Promise<void>;
1879
- /**
1880
- * Close the sync connection.
1881
- *
1882
- * Use {@link connect} to connect again.
1883
- */
1884
- disconnect(): Promise<void>;
1885
- protected disconnectInternal(): Promise<void>;
1886
- protected performDisconnect(): Promise<void>;
1887
- stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream;
1888
- /**
1889
- * @internal exposed for testing
1890
- */
1891
- get activeStreams(): {
1892
- name: string;
1893
- params: Record<string, any> | null;
1894
- }[];
1895
- private subscriptionsMayHaveChanged;
1896
- }
1897
-
1898
- /**
1899
- * A basic comparator for incrementally watched queries. This performs a single comparison which
1900
- * determines if the result set has changed. The {@link WatchedQuery} will only emit the new result
1901
- * if a change has been detected.
1902
- */
1903
- interface WatchedQueryComparator<Data> {
1904
- checkEquality: (current: Data, previous: Data) => boolean;
1905
- }
1906
- /**
1907
- * Options for {@link ArrayComparator}
1908
- */
1909
- type ArrayComparatorOptions<ItemType> = {
1910
- /**
1911
- * Returns a string to uniquely identify an item in the array.
1912
- */
1913
- compareBy: (item: ItemType) => string;
1914
- };
1915
- /**
1916
- * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
1917
- * result has changes without necessarily processing all items in the result.
1918
- */
1919
- declare class ArrayComparator<ItemType> implements WatchedQueryComparator<ItemType[]> {
1920
- protected options: ArrayComparatorOptions<ItemType>;
1921
- constructor(options: ArrayComparatorOptions<ItemType>);
1922
- checkEquality(current: ItemType[], previous: ItemType[]): boolean;
1923
- }
1924
- /**
1925
- * Watched query comparator that always reports changed result sets.
1926
- */
1927
- declare const FalsyComparator: WatchedQueryComparator<unknown>;
1928
-
1929
- interface CompilableQuery<T> {
1930
- execute(): Promise<T[]>;
1931
- compile(): CompiledQuery;
1932
- }
1933
- interface CompiledQuery {
1934
- readonly sql: string;
1935
- readonly parameters: ReadonlyArray<unknown>;
1936
- }
1937
-
1938
- /**
1939
- * Represents the counts of listeners for each event type in a BaseListener.
1940
- */
1941
- type ListenerCounts<Listener extends BaseListener> = Partial<Record<keyof Listener, number>> & {
1942
- total: number;
1943
- };
1944
- /**
1945
- * Meta listener which reports the counts of listeners for each event type.
1946
- */
1947
- interface MetaListener<ParentListener extends BaseListener> extends BaseListener {
1948
- listenersChanged?: (counts: ListenerCounts<ParentListener>) => void;
1949
- }
1950
- interface ListenerMetaManager<Listener extends BaseListener> extends BaseObserverInterface<MetaListener<Listener>> {
1951
- counts: ListenerCounts<Listener>;
1952
- }
1953
- interface MetaBaseObserverInterface<Listener extends BaseListener> extends BaseObserverInterface<Listener> {
1954
- listenerMeta: ListenerMetaManager<Listener>;
1955
- }
1956
- /**
1957
- * A BaseObserver that tracks the counts of listeners for each event type.
1958
- */
1959
- declare class MetaBaseObserver<Listener extends BaseListener> extends BaseObserver<Listener> implements MetaBaseObserverInterface<Listener> {
1960
- protected get listenerCounts(): ListenerCounts<Listener>;
1961
- get listenerMeta(): ListenerMetaManager<Listener>;
1962
- protected metaListener: BaseObserver<MetaListener<Listener>>;
1963
- constructor();
1964
- registerListener(listener: Partial<Listener>): () => void;
1965
- }
1966
-
1967
- /**
1968
- * State for {@link WatchedQuery} instances.
1969
- */
1970
- interface WatchedQueryState<Data> {
1971
- /**
1972
- * Indicates the initial loading state (hard loading).
1973
- * Loading becomes false once the first set of results from the watched query is available or an error occurs.
1974
- */
1975
- readonly isLoading: boolean;
1976
- /**
1977
- * Indicates whether the query is currently fetching data, is true during the initial load
1978
- * and any time when the query is re-evaluating (useful for large queries).
1979
- */
1980
- readonly isFetching: boolean;
1981
- /**
1982
- * The last error that occurred while executing the query.
1983
- */
1984
- readonly error: Error | null;
1985
- /**
1986
- * The last time the query was updated.
1987
- */
1988
- readonly lastUpdated: Date | null;
1989
- /**
1990
- * The last data returned by the query.
1991
- */
1992
- readonly data: Data;
1993
- }
1994
- /**
1995
- * Options provided to the `execute` method of a {@link WatchCompatibleQuery}.
1996
- */
1997
- interface WatchExecuteOptions {
1998
- sql: string;
1999
- parameters: any[];
2000
- db: AbstractPowerSyncDatabase;
2001
- }
2002
- /**
2003
- * Similar to {@link CompatibleQuery}, except the `execute` method
2004
- * does not enforce an Array result type.
2005
- */
2006
- interface WatchCompatibleQuery<ResultType> {
2007
- execute(options: WatchExecuteOptions): Promise<ResultType>;
2008
- compile(): CompiledQuery;
2009
- }
2010
- interface WatchedQueryOptions {
2011
- /** The minimum interval between queries. */
2012
- throttleMs?: number;
2013
- /**
2014
- * If true (default) the watched query will update its state to report
2015
- * on the fetching state of the query.
2016
- * Setting to false reduces the number of state changes if the fetch status
2017
- * is not relevant to the consumer.
2018
- */
2019
- reportFetching?: boolean;
2020
- /**
2021
- * By default, watched queries requery the database on any change to any dependent table of the query.
2022
- * Supplying an override here can be used to limit the tables which trigger querying the database.
2023
- */
2024
- triggerOnTables?: string[];
2025
- }
2026
- declare enum WatchedQueryListenerEvent {
2027
- ON_DATA = "onData",
2028
- ON_ERROR = "onError",
2029
- ON_STATE_CHANGE = "onStateChange",
2030
- SETTINGS_WILL_UPDATE = "settingsWillUpdate",
2031
- CLOSED = "closed"
2032
- }
2033
- interface WatchedQueryListener<Data> extends BaseListener {
2034
- [WatchedQueryListenerEvent.ON_DATA]?: (data: Data) => void | Promise<void>;
2035
- [WatchedQueryListenerEvent.ON_ERROR]?: (error: Error) => void | Promise<void>;
2036
- [WatchedQueryListenerEvent.ON_STATE_CHANGE]?: (state: WatchedQueryState<Data>) => void | Promise<void>;
2037
- [WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?: () => void;
2038
- [WatchedQueryListenerEvent.CLOSED]?: () => void | Promise<void>;
2039
- }
2040
- declare const DEFAULT_WATCH_THROTTLE_MS = 30;
2041
- declare const DEFAULT_WATCH_QUERY_OPTIONS: WatchedQueryOptions;
2042
- interface WatchedQuery<Data = unknown, Settings extends WatchedQueryOptions = WatchedQueryOptions, Listener extends WatchedQueryListener<Data> = WatchedQueryListener<Data>> extends MetaBaseObserverInterface<Listener> {
2043
- /**
2044
- * Current state of the watched query.
2045
- */
2046
- readonly state: WatchedQueryState<Data>;
2047
- readonly closed: boolean;
2048
- /**
2049
- * Subscribe to watched query events.
2050
- * @returns A function to unsubscribe from the events.
2051
- */
2052
- registerListener(listener: Listener): () => void;
2053
- /**
2054
- * Updates the underlying query options.
2055
- * This will trigger a re-evaluation of the query and update the state.
2056
- */
2057
- updateSettings(options: Settings): Promise<void>;
2058
- /**
2059
- * Close the watched query and end all subscriptions.
2060
- */
2061
- close(): Promise<void>;
2062
- }
2063
-
2064
- /**
2065
- * @internal
2066
- */
2067
- interface AbstractQueryProcessorOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
2068
- db: AbstractPowerSyncDatabase;
2069
- watchOptions: Settings;
2070
- placeholderData: Data;
2071
- }
2072
- /**
2073
- * @internal
2074
- */
2075
- interface LinkQueryOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
2076
- abortSignal: AbortSignal;
2077
- settings: Settings;
2078
- }
2079
- type MutableDeep<T> = T extends ReadonlyArray<infer U> ? U[] : T;
2080
- /**
2081
- * @internal Mutable version of {@link WatchedQueryState}.
2082
- * This is used internally to allow updates to the state.
2083
- */
2084
- type MutableWatchedQueryState<Data> = {
2085
- -readonly [P in keyof WatchedQueryState<Data>]: MutableDeep<WatchedQueryState<Data>[P]>;
2086
- };
2087
- type WatchedQueryProcessorListener<Data> = WatchedQueryListener<Data>;
2088
- /**
2089
- * Performs underlying watching and yields a stream of results.
2090
- * @internal
2091
- */
2092
- declare abstract class AbstractQueryProcessor<Data = unknown[], Settings extends WatchedQueryOptions = WatchedQueryOptions> extends MetaBaseObserver<WatchedQueryProcessorListener<Data>> implements WatchedQuery<Data, Settings> {
2093
- protected options: AbstractQueryProcessorOptions<Data, Settings>;
2094
- readonly state: WatchedQueryState<Data>;
2095
- protected abortController: AbortController;
2096
- protected initialized: Promise<void>;
2097
- protected _closed: boolean;
2098
- protected disposeListeners: (() => void) | null;
2099
- get closed(): boolean;
2100
- constructor(options: AbstractQueryProcessorOptions<Data, Settings>);
2101
- protected constructInitialState(): WatchedQueryState<Data>;
2102
- protected get reportFetching(): boolean;
2103
- protected updateSettingsInternal(settings: Settings, signal: AbortSignal): Promise<void>;
2104
- /**
2105
- * Updates the underlying query.
2106
- */
2107
- updateSettings(settings: Settings): Promise<void>;
2108
- /**
2109
- * This method is used to link a query to the subscribers of this listener class.
2110
- * This method should perform actual query watching and report results via {@link updateState} method.
2111
- */
2112
- protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
2113
- protected updateState(update: Partial<MutableWatchedQueryState<Data>>): Promise<void>;
2114
- /**
2115
- * Configures base DB listeners and links the query to listeners.
2116
- */
2117
- protected init(signal: AbortSignal): Promise<void>;
2118
- close(): Promise<void>;
2119
- /**
2120
- * Runs a callback and reports errors to the error listeners.
2121
- */
2122
- protected runWithReporting<T>(callback: () => Promise<T>): Promise<void>;
2123
- /**
2124
- * Iterate listeners and reports errors to onError handlers.
2125
- */
2126
- protected iterateAsyncListenersWithError(callback: (listener: Partial<WatchedQueryProcessorListener<Data>>) => Promise<void> | void): Promise<void>;
2127
- }
2128
-
2129
- /**
2130
- * Represents an updated row in a differential watched query.
2131
- * It contains both the current and previous state of the row.
2132
- */
2133
- interface WatchedQueryRowDifferential<RowType> {
2134
- readonly current: RowType;
2135
- readonly previous: RowType;
2136
- }
2137
- /**
2138
- * Represents the result of a watched query that has been diffed.
2139
- * {@link DifferentialWatchedQueryState#diff} is of the {@link WatchedQueryDifferential} form.
2140
- */
2141
- interface WatchedQueryDifferential<RowType> {
2142
- readonly added: ReadonlyArray<Readonly<RowType>>;
2143
- /**
2144
- * The entire current result set.
2145
- * Array item object references are preserved between updates if the item is unchanged.
2146
- *
2147
- * e.g. In the query
2148
- * ```sql
2149
- * SELECT name, make FROM assets ORDER BY make ASC;
2150
- * ```
2151
- *
2152
- * If a previous result set contains an item (A) `{name: 'pc', make: 'Cool PC'}` and
2153
- * an update has been made which adds another item (B) to the result set (the item A is unchanged) - then
2154
- * the updated result set will be contain the same object reference, to item A, as the previous result set.
2155
- * This is regardless of the item A's position in the updated result set.
2156
- */
2157
- readonly all: ReadonlyArray<Readonly<RowType>>;
2158
- readonly removed: ReadonlyArray<Readonly<RowType>>;
2159
- readonly updated: ReadonlyArray<WatchedQueryRowDifferential<Readonly<RowType>>>;
2160
- readonly unchanged: ReadonlyArray<Readonly<RowType>>;
2161
- }
2162
- /**
2163
- * Row comparator for differentially watched queries which keys and compares items in the result set.
2164
- */
2165
- interface DifferentialWatchedQueryComparator<RowType> {
2166
- /**
2167
- * Generates a unique key for the item.
2168
- */
2169
- keyBy: (item: RowType) => string;
2170
- /**
2171
- * Generates a token for comparing items with matching keys.
2172
- */
2173
- compareBy: (item: RowType) => string;
2174
- }
2175
- /**
2176
- * Options for building a differential watched query with the {@link Query} builder.
2177
- */
2178
- interface DifferentialWatchedQueryOptions<RowType> extends WatchedQueryOptions {
2179
- /**
2180
- * Initial result data which is presented while the initial loading is executing.
2181
- */
2182
- placeholderData?: RowType[];
2183
- /**
2184
- * Row comparator used to identify and compare rows in the result set.
2185
- * If not provided, the default comparator will be used which keys items by their `id` property if available,
2186
- * otherwise it uses JSON stringification of the entire item for keying and comparison.
2187
- * @defaultValue {@link DEFAULT_ROW_COMPARATOR}
2188
- */
2189
- rowComparator?: DifferentialWatchedQueryComparator<RowType>;
2190
- }
2191
- /**
2192
- * Settings for differential incremental watched queries using.
2193
- */
2194
- interface DifferentialWatchedQuerySettings<RowType> extends DifferentialWatchedQueryOptions<RowType> {
2195
- /**
2196
- * The query here must return an array of items that can be differentiated.
2197
- */
2198
- query: WatchCompatibleQuery<RowType[]>;
2199
- }
2200
- interface DifferentialWatchedQueryListener<RowType> extends WatchedQueryListener<ReadonlyArray<Readonly<RowType>>> {
2201
- onDiff?: (diff: WatchedQueryDifferential<RowType>) => void | Promise<void>;
2202
- }
2203
- type DifferentialWatchedQuery<RowType> = WatchedQuery<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>, DifferentialWatchedQueryListener<RowType>>;
2204
- /**
2205
- * @internal
2206
- */
2207
- interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<RowType[], DifferentialWatchedQuerySettings<RowType>> {
2208
- rowComparator?: DifferentialWatchedQueryComparator<RowType>;
2209
- }
2210
- type DataHashMap<RowType> = Map<string, {
2211
- hash: string;
2212
- item: RowType;
2213
- }>;
2214
- /**
2215
- * An empty differential result set.
2216
- * This is used as the initial state for differential incrementally watched queries.
2217
- */
2218
- declare const EMPTY_DIFFERENTIAL: {
2219
- added: never[];
2220
- all: never[];
2221
- removed: never[];
2222
- updated: never[];
2223
- unchanged: never[];
2224
- };
2225
- /**
2226
- * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
2227
- * It keys items by their `id` property if available, alternatively it uses JSON stringification
2228
- * of the entire item for the key and comparison.
2229
- */
2230
- declare const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any>;
2231
- /**
2232
- * Uses the PowerSync onChange event to trigger watched queries.
2233
- * Results are emitted on every change of the relevant tables.
2234
- * @internal
2235
- */
2236
- declare class DifferentialQueryProcessor<RowType> extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>> implements DifferentialWatchedQuery<RowType> {
2237
- protected options: DifferentialQueryProcessorOptions<RowType>;
2238
- protected comparator: DifferentialWatchedQueryComparator<RowType>;
2239
- constructor(options: DifferentialQueryProcessorOptions<RowType>);
2240
- protected differentiate(current: RowType[], previousMap: DataHashMap<RowType>): {
2241
- diff: WatchedQueryDifferential<RowType>;
2242
- map: DataHashMap<RowType>;
2243
- hasChanged: boolean;
2244
- };
2245
- protected linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void>;
2246
- }
2247
-
2248
- /**
2249
- * Settings for {@link WatchedQuery} instances created via {@link Query#watch}.
2250
- */
2251
- interface WatchedQuerySettings<DataType> extends WatchedQueryOptions {
2252
- query: WatchCompatibleQuery<DataType>;
2253
- }
2254
- /**
2255
- * {@link WatchedQuery} returned from {@link Query#watch}.
2256
- */
2257
- type StandardWatchedQuery<DataType> = WatchedQuery<DataType, WatchedQuerySettings<DataType>>;
2258
- /**
2259
- * @internal
2260
- */
2261
- interface OnChangeQueryProcessorOptions<Data> extends AbstractQueryProcessorOptions<Data, WatchedQuerySettings<Data>> {
2262
- comparator?: WatchedQueryComparator<Data>;
2263
- }
2264
- /**
2265
- * Uses the PowerSync onChange event to trigger watched queries.
2266
- * Results are emitted on every change of the relevant tables.
2267
- * @internal
2268
- */
2269
- declare class OnChangeQueryProcessor<Data> extends AbstractQueryProcessor<Data, WatchedQuerySettings<Data>> {
2270
- protected options: OnChangeQueryProcessorOptions<Data>;
2271
- constructor(options: OnChangeQueryProcessorOptions<Data>);
2272
- /**
2273
- * @returns If the sets are equal
2274
- */
2275
- protected checkEquality(current: Data, previous: Data): boolean;
2276
- protected linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
2277
- }
2278
-
2279
- /**
2280
- * Query parameters for {@link ArrayQueryDefinition#parameters}
2281
- */
2282
- type QueryParam = string | number | boolean | null | undefined | bigint | Uint8Array;
2283
- /**
2284
- * Options for building a query with {@link AbstractPowerSyncDatabase#query}.
2285
- * This query will be executed with {@link AbstractPowerSyncDatabase#getAll}.
2286
- */
2287
- interface ArrayQueryDefinition<RowType = unknown> {
2288
- sql: string;
2289
- parameters?: ReadonlyArray<Readonly<QueryParam>>;
2290
- /**
2291
- * Maps the raw SQLite row to a custom typed object.
2292
- * @example
2293
- * ```javascript
2294
- * mapper: (row) => ({
2295
- * ...row,
2296
- * created_at: new Date(row.created_at as string),
2297
- * })
2298
- * ```
2299
- */
2300
- mapper?: (row: Record<string, unknown>) => RowType;
2301
- }
2302
- /**
2303
- * Options for {@link Query#watch}.
2304
- */
2305
- interface StandardWatchedQueryOptions<RowType> extends WatchedQueryOptions {
2306
- /**
2307
- * The underlying watched query implementation (re)evaluates the query on any SQLite table change.
2308
- *
2309
- * Providing this optional comparator can be used to filter duplicate result set emissions when the result set is unchanged.
2310
- * The comparator compares the previous and current result set.
2311
- *
2312
- * For an efficient comparator see {@link ArrayComparator}.
2313
- *
2314
- * @example
2315
- * ```javascript
2316
- * comparator: new ArrayComparator({
2317
- * compareBy: (item) => JSON.stringify(item)
2318
- * })
2319
- * ```
2320
- */
2321
- comparator?: WatchedQueryComparator<RowType[]>;
2322
- /**
2323
- * The initial data state reported while the query is loading for the first time.
2324
- * @default []
2325
- */
2326
- placeholderData?: RowType[];
2327
- }
2328
- interface Query<RowType> {
2329
- /**
2330
- * Creates a {@link WatchedQuery} which watches and emits results of the linked query.
2331
- *
2332
- * By default the returned watched query will emit changes whenever a change to the underlying SQLite tables is made.
2333
- * These changes might not be relevant to the query, but the query will emit a new result set.
2334
- *
2335
- * A {@link StandardWatchedQueryOptions#comparator} can be provided to limit the data emissions. The watched query will still
2336
- * query the underlying DB on underlying table changes, but the result will only be emitted if the comparator detects a change in the results.
2337
- *
2338
- * The comparator in this method is optimized and returns early as soon as it detects a change. Each data emission will correlate to a change in the result set,
2339
- * but note that the result set will not maintain internal object references to the previous result set. If internal object references are needed,
2340
- * consider using {@link Query#differentialWatch} instead.
2341
- */
2342
- watch(options?: StandardWatchedQueryOptions<RowType>): StandardWatchedQuery<ReadonlyArray<Readonly<RowType>>>;
2343
- /**
2344
- * Creates a {@link WatchedQuery} which watches and emits results of the linked query.
2345
- *
2346
- * This query method watches for changes in the underlying SQLite tables and runs the query on each table change.
2347
- * The difference between the current and previous result set is computed.
2348
- * The watched query will not emit changes if the result set is identical to the previous result set.
2349
- *
2350
- * If the result set is different, the watched query will emit the new result set and emit a detailed diff of the changes via the `onData` and `onDiff` listeners.
2351
- *
2352
- * The deep differentiation allows maintaining result set object references between result emissions.
2353
- * The {@link DifferentialWatchedQuery#state} `data` array will contain the previous row references for unchanged rows.
2354
- *
2355
- * @example
2356
- * ```javascript
2357
- * const watchedLists = powerSync.query({sql: 'SELECT * FROM lists'})
2358
- * .differentialWatch();
2359
- *
2360
- * const disposeListener = watchedLists.registerListener({
2361
- * onData: (lists) => {
2362
- * console.log('The latest result set for the query is', lists);
2363
- * },
2364
- * onDiff: (diff) => {
2365
- * console.log('The lists result set has changed since the last emission', diff.added, diff.removed, diff.updated, diff.all)
2366
- * }
2367
- * })
2368
- * ```
2369
- */
2370
- differentialWatch(options?: DifferentialWatchedQueryOptions<RowType>): DifferentialWatchedQuery<RowType>;
2371
- }
2372
-
2373
- interface SQLOpenOptions {
2374
- /**
2375
- * Filename for the database.
2376
- */
2377
- dbFilename: string;
2378
- /**
2379
- * Directory where the database file is located.
2380
- *
2381
- * When set, the directory must exist when the database is opened, it will
2382
- * not be created automatically.
2383
- */
2384
- dbLocation?: string;
2385
- /**
2386
- * Enable debugMode to log queries to the performance timeline.
2387
- *
2388
- * Defaults to false.
2389
- *
2390
- * To enable in development builds, use:
2391
- *
2392
- * debugMode: process.env.NODE_ENV !== 'production'
2393
- */
2394
- debugMode?: boolean;
2395
- }
2396
- interface SQLOpenFactory {
2397
- /**
2398
- * Opens a connection adapter to a SQLite DB
2399
- */
2400
- openDB(): DBAdapter;
2401
- }
2402
- /**
2403
- * Tests if the input is a {@link SQLOpenOptions}
2404
- */
2405
- declare const isSQLOpenOptions: (test: any) => test is SQLOpenOptions;
2406
- /**
2407
- * Tests if input is a {@link SQLOpenFactory}
2408
- */
2409
- declare const isSQLOpenFactory: (test: any) => test is SQLOpenFactory;
2410
- /**
2411
- * Tests if input is a {@link DBAdapter}
2412
- */
2413
- declare const isDBAdapter: (test: any) => test is DBAdapter;
2414
-
2415
- declare class CrudTransaction extends CrudBatch {
2416
- /**
2417
- * List of client-side changes.
2418
- */
2419
- crud: CrudEntry[];
2420
- /**
2421
- * Call to remove the changes from the local queue, once successfully uploaded.
2422
- */
2423
- complete: (checkpoint?: string) => Promise<void>;
2424
- /**
2425
- * If null, this contains a list of changes recorded without an explicit transaction associated.
2426
- */
2427
- transactionId?: number | undefined;
2428
- constructor(
2429
- /**
2430
- * List of client-side changes.
2431
- */
2432
- crud: CrudEntry[],
2433
- /**
2434
- * Call to remove the changes from the local queue, once successfully uploaded.
2435
- */
2436
- complete: (checkpoint?: string) => Promise<void>,
2437
- /**
2438
- * If null, this contains a list of changes recorded without an explicit transaction associated.
2439
- */
2440
- transactionId?: number | undefined);
2441
- }
2442
-
2443
- /**
2444
- * SQLite operations to track changes for with {@link TriggerManager}
2445
- * @experimental
2446
- */
2447
- declare enum DiffTriggerOperation {
2448
- INSERT = "INSERT",
2449
- UPDATE = "UPDATE",
2450
- DELETE = "DELETE"
2451
- }
2452
- /**
2453
- * @experimental
2454
- * Diffs created by {@link TriggerManager#createDiffTrigger} are stored in a temporary table.
2455
- * This is the base record structure for all diff records.
2456
- *
2457
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by default SQLite database queries.
2458
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2459
- */
2460
- interface BaseTriggerDiffRecord<TOperationId extends string | number = number> {
2461
- /**
2462
- * The modified row's `id` column value.
2463
- */
2464
- id: string;
2465
- /**
2466
- * The operation performed which created this record.
2467
- */
2468
- operation: DiffTriggerOperation;
2469
- /**
2470
- * Auto-incrementing primary key for the operation.
2471
- * Defaults to number as returned by database queries (wa-sqlite returns lower 32 bits).
2472
- * Can be string for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2473
- */
2474
- operation_id: TOperationId;
2475
- /**
2476
- * Time the change operation was recorded.
2477
- * This is in ISO 8601 format, e.g. `2023-10-01T12:00:00.000Z`.
2478
- */
2479
- timestamp: string;
2480
- }
2481
- /**
2482
- * @experimental
2483
- * Represents a diff record for a SQLite UPDATE operation.
2484
- * This record contains the new value and optionally the previous value.
2485
- * Values are stored as JSON strings.
2486
- */
2487
- interface TriggerDiffUpdateRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2488
- operation: DiffTriggerOperation.UPDATE;
2489
- /**
2490
- * The updated state of the row in JSON string format.
2491
- */
2492
- value: string;
2493
- /**
2494
- * The previous value of the row in JSON string format.
2495
- */
2496
- previous_value: string;
2497
- }
2498
- /**
2499
- * @experimental
2500
- * Represents a diff record for a SQLite INSERT operation.
2501
- * This record contains the new value represented as a JSON string.
2502
- */
2503
- interface TriggerDiffInsertRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2504
- operation: DiffTriggerOperation.INSERT;
2505
- /**
2506
- * The value of the row, at the time of INSERT, in JSON string format.
2507
- */
2508
- value: string;
2509
- }
2510
- /**
2511
- * @experimental
2512
- * Represents a diff record for a SQLite DELETE operation.
2513
- * This record contains the new value represented as a JSON string.
2514
- */
2515
- interface TriggerDiffDeleteRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2516
- operation: DiffTriggerOperation.DELETE;
2517
- /**
2518
- * The value of the row, before the DELETE operation, in JSON string format.
2519
- */
2520
- value: string;
2521
- }
2522
- /**
2523
- * @experimental
2524
- * Diffs created by {@link TriggerManager#createDiffTrigger} are stored in a temporary table.
2525
- * This is the record structure for all diff records.
2526
- *
2527
- * Querying the DIFF table directly with {@link TriggerDiffHandlerContext#withDiff} will return records
2528
- * with the structure of this type.
2529
- *
2530
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by database queries.
2531
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2532
- *
2533
- * @example
2534
- * ```typescript
2535
- * // Default: operation_id is number
2536
- * const diffs = await context.withDiff<TriggerDiffRecord>('SELECT * FROM DIFF');
2537
- *
2538
- * // With string operation_id for full precision
2539
- * const diffsWithString = await context.withDiff<TriggerDiffRecord<string>>(
2540
- * 'SELECT * FROM DIFF',
2541
- * undefined,
2542
- * { castOperationIdAsText: true }
2543
- * );
2544
- * ```
2545
- */
2546
- type TriggerDiffRecord<TOperationId extends string | number = number> = TriggerDiffUpdateRecord<TOperationId> | TriggerDiffInsertRecord<TOperationId> | TriggerDiffDeleteRecord<TOperationId>;
2547
- /**
2548
- * @experimental
2549
- * Querying the DIFF table directly with {@link TriggerDiffHandlerContext#withExtractedDiff} will return records
2550
- * with the tracked columns extracted from the JSON value.
2551
- * This type represents the structure of such records.
2552
- *
2553
- * @template T - The type for the extracted columns from the tracked JSON value.
2554
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by database queries.
2555
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2556
- *
2557
- * @example
2558
- * ```typescript
2559
- * // Default: operation_id is number
2560
- * const diffs = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}>>('SELECT * FROM DIFF');
2561
- *
2562
- * // With string operation_id for full precision
2563
- * const diffsWithString = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}, string>>(
2564
- * 'SELECT * FROM DIFF',
2565
- * undefined,
2566
- * { castOperationIdAsText: true }
2567
- * );
2568
- * ```
2569
- */
2570
- type ExtractedTriggerDiffRecord<T, TOperationId extends string | number = number> = T & {
2571
- [K in keyof Omit<BaseTriggerDiffRecord<TOperationId>, 'id'> as `__${string & K}`]: TriggerDiffRecord<TOperationId>[K];
2572
- } & {
2573
- __previous_value?: string;
2574
- };
2575
- /**
2576
- * @experimental
2577
- * Hooks used in the creation of a table diff trigger.
2578
- */
2579
- interface TriggerCreationHooks {
2580
- /**
2581
- * Executed inside a write lock before the trigger is created.
2582
- */
2583
- beforeCreate?: (context: LockContext) => Promise<void>;
2584
- }
2585
- /**
2586
- * Common interface for options used in creating a diff trigger.
2587
- */
2588
- interface BaseCreateDiffTriggerOptions {
2589
- /**
2590
- * PowerSync source table/view to trigger and track changes from.
2591
- * This should be present in the PowerSync database's schema.
2592
- */
2593
- source: string;
2594
- /**
2595
- * Columns to track and report changes for.
2596
- * Defaults to all columns in the source table.
2597
- * Use an empty array to track only the ID and operation.
2598
- */
2599
- columns?: string[];
2600
- /**
2601
- * Condition to filter when the triggers should fire.
2602
- * This corresponds to a SQLite [WHEN](https://sqlite.org/lang_createtrigger.html) clause in the trigger body.
2603
- * This is useful for only triggering on specific conditions.
2604
- * For example, you can use it to only trigger on certain values in the NEW row.
2605
- * Note that for PowerSync the row data is stored in a JSON column named `data`.
2606
- * The row id is available in the `id` column.
2607
- *
2608
- * NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL.
2609
- * Any user input strings here should be sanitized externally. The {@link when} string template function performs
2610
- * some basic sanitization, extra external sanitization is recommended.
2611
- *
2612
- * @example
2613
- * {
2614
- * 'INSERT': sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}`,
2615
- * 'INSERT': `TRUE`,
2616
- * 'UPDATE': sanitizeSQL`NEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active'`,
2617
- * 'DELETE': sanitizeSQL`json_extract(OLD.data, '$.list_id') = 'abcd'`
2618
- * }
2619
- */
2620
- when: Partial<Record<DiffTriggerOperation, string>>;
2621
- /**
2622
- * Hooks which allow execution during the trigger creation process.
2623
- */
2624
- hooks?: TriggerCreationHooks;
2625
- /**
2626
- * Use storage-backed (non-TEMP) tables and triggers that persist across sessions.
2627
- * These resources are still automatically disposed when no longer claimed.
2628
- */
2629
- useStorage?: boolean;
2630
- }
2631
- /**
2632
- * @experimental
2633
- * Options for {@link TriggerManager#createDiffTrigger}.
2634
- */
2635
- interface CreateDiffTriggerOptions extends BaseCreateDiffTriggerOptions {
2636
- /**
2637
- * Destination table to send changes to.
2638
- * This table is created internally as a SQLite temporary table.
2639
- * This table will be dropped once the trigger is removed.
2640
- */
2641
- destination: string;
2642
- }
2643
- /**
2644
- * @experimental
2645
- * Callback to drop a trigger after it has been created.
2646
- */
2647
- type TriggerRemoveCallback = () => Promise<void>;
2648
- /**
2649
- * @experimental
2650
- * Options for {@link TriggerDiffHandlerContext#withDiff}.
2651
- */
2652
- interface WithDiffOptions {
2653
- /**
2654
- * If true, casts `operation_id` as TEXT in the internal CTE to preserve full 64-bit precision.
2655
- * Use this when you need to ensure `operation_id` is treated as a string to avoid precision loss
2656
- * for values exceeding JavaScript's Number.MAX_SAFE_INTEGER.
2657
- *
2658
- * When enabled, use {@link TriggerDiffRecord}<string> to type the result correctly.
2659
- */
2660
- castOperationIdAsText?: boolean;
2661
- }
2662
- /**
2663
- * @experimental
2664
- * Context for the `onChange` handler provided to {@link TriggerManager#trackTableDiff}.
2665
- */
2666
- interface TriggerDiffHandlerContext extends LockContext {
2667
- /**
2668
- * The name of the temporary destination table created by the trigger.
2669
- */
2670
- destinationTable: string;
2671
- /**
2672
- * Allows querying the database with access to the table containing DIFF records.
2673
- * The diff table is accessible via the `DIFF` accessor.
2674
- *
2675
- * The `DIFF` table is of the form described in {@link TriggerManager#createDiffTrigger}
2676
- * ```sql
2677
- * CREATE TEMP DIFF (
2678
- * operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
2679
- * id TEXT,
2680
- * operation TEXT,
2681
- * timestamp TEXT,
2682
- * value TEXT,
2683
- * previous_value TEXT
2684
- * );
2685
- * ```
2686
- *
2687
- * Note that the `value` and `previous_value` columns store the row state in JSON string format.
2688
- * To access the row state in an extracted form see {@link TriggerDiffHandlerContext#withExtractedDiff}.
2689
- *
2690
- * @example
2691
- * ```sql
2692
- * --- This fetches the current state of `todo` rows which have a diff operation present.
2693
- * --- The state of the row at the time of the operation is accessible in the DIFF records.
2694
- * SELECT
2695
- * todos.*
2696
- * FROM
2697
- * DIFF
2698
- * JOIN todos ON DIFF.id = todos.id
2699
- * WHERE json_extract(DIFF.value, '$.status') = 'active'
2700
- * ```
2701
- *
2702
- * @example
2703
- * ```typescript
2704
- * // With operation_id cast as TEXT for full precision
2705
- * const diffs = await context.withDiff<TriggerDiffRecord<string>>(
2706
- * 'SELECT * FROM DIFF',
2707
- * undefined,
2708
- * { castOperationIdAsText: true }
2709
- * );
2710
- * // diffs[0].operation_id is now typed as string
2711
- * ```
2712
- */
2713
- withDiff: <T = any>(query: string, params?: ReadonlyArray<Readonly<any>>, options?: WithDiffOptions) => Promise<T[]>;
2714
- /**
2715
- * Allows querying the database with access to the table containing diff records.
2716
- * The diff table is accessible via the `DIFF` accessor.
2717
- *
2718
- * This is similar to {@link withDiff} but extracts the row columns from the tracked JSON value. The diff operation
2719
- * data is aliased as `__` columns to avoid column conflicts.
2720
- *
2721
- * For {@link DiffTriggerOperation#DELETE} operations the previous_value columns are extracted for convenience.
2722
- *
2723
- *
2724
- * ```sql
2725
- * CREATE TEMP TABLE DIFF (
2726
- * id TEXT,
2727
- * replicated_column_1 COLUMN_TYPE,
2728
- * replicated_column_2 COLUMN_TYPE,
2729
- * __operation TEXT,
2730
- * __timestamp TEXT,
2731
- * __previous_value TEXT
2732
- * );
2733
- * ```
2734
- *
2735
- * @example
2736
- * ```sql
2737
- * SELECT
2738
- * todos.*
2739
- * FROM
2740
- * DIFF
2741
- * JOIN todos ON DIFF.id = todos.id
2742
- * --- The todo column names are extracted from json and are available as DIFF.name
2743
- * WHERE DIFF.name = 'example'
2744
- * ```
2745
- */
2746
- withExtractedDiff: <T = any>(query: string, params?: ReadonlyArray<Readonly<any>>) => Promise<T[]>;
2747
- }
2748
- /**
2749
- * @experimental
2750
- * Options for tracking changes to a table with {@link TriggerManager#trackTableDiff}.
2751
- */
2752
- interface TrackDiffOptions extends BaseCreateDiffTriggerOptions {
2753
- /**
2754
- * Handler for processing diff operations.
2755
- * Automatically invoked once diff items are present.
2756
- * Diff items are automatically cleared after the handler is invoked.
2757
- */
2758
- onChange: (context: TriggerDiffHandlerContext) => Promise<void>;
2759
- /**
2760
- * The minimum interval, in milliseconds, between {@link onChange} invocations.
2761
- * @default {@link DEFAULT_WATCH_THROTTLE_MS}
2762
- */
2763
- throttleMs?: number;
2764
- }
2765
- /**
2766
- * @experimental
2767
- */
2768
- interface TriggerManager {
2769
- /**
2770
- * @experimental
2771
- * Creates a temporary trigger which tracks changes to a source table
2772
- * and writes changes to a destination table.
2773
- * The temporary destination table is created internally and will be dropped when the trigger is removed.
2774
- * The temporary destination table is created with the structure:
2775
- *
2776
- * ```sql
2777
- * CREATE TEMP TABLE ${destination} (
2778
- * operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
2779
- * id TEXT,
2780
- * operation TEXT,
2781
- * timestamp TEXT,
2782
- * value TEXT,
2783
- * previous_value TEXT
2784
- * );
2785
- * ```
2786
- * The `value` column contains the JSON representation of the row's value at the change.
2787
- *
2788
- * For {@link DiffTriggerOperation#UPDATE} operations the `previous_value` column contains the previous value of the changed row
2789
- * in a JSON format.
2790
- *
2791
- * NB: The triggers created by this method might be invalidated by {@link AbstractPowerSyncDatabase#updateSchema} calls.
2792
- * These triggers should manually be dropped and recreated when updating the schema.
2793
- *
2794
- * @returns A callback to remove the trigger and drop the destination table.
2795
- *
2796
- * @example
2797
- * ```javascript
2798
- * const dispose = await database.triggers.createDiffTrigger({
2799
- * source: 'lists',
2800
- * destination: 'ps_temp_lists_diff',
2801
- * columns: ['name'],
2802
- * when: {
2803
- * [DiffTriggerOperation.INSERT]: 'TRUE',
2804
- * [DiffTriggerOperation.UPDATE]: 'TRUE',
2805
- * [DiffTriggerOperation.DELETE]: 'TRUE'
2806
- * }
2807
- * });
2808
- * ```
2809
- */
2810
- createDiffTrigger(options: CreateDiffTriggerOptions): Promise<TriggerRemoveCallback>;
2811
- /**
2812
- * @experimental
2813
- * Tracks changes for a table. Triggering a provided handler on changes.
2814
- * Uses {@link createDiffTrigger} internally to create a temporary destination table.
2815
- *
2816
- * @returns A callback to cleanup the trigger and stop tracking changes.
2817
- *
2818
- * NB: The triggers created by this method might be invalidated by {@link AbstractPowerSyncDatabase#updateSchema} calls.
2819
- * These triggers should manually be dropped and recreated when updating the schema.
2820
- *
2821
- * @example
2822
- * ```javascript
2823
- * const dispose = database.triggers.trackTableDiff({
2824
- * source: 'todos',
2825
- * columns: ['list_id'],
2826
- * when: {
2827
- * [DiffTriggerOperation.INSERT]: sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(someIdVariable)}`
2828
- * },
2829
- * onChange: async (context) => {
2830
- * // Fetches the todo records that were inserted during this diff
2831
- * const newTodos = await context.withDiff<Database['todos']>(`
2832
- * SELECT
2833
- * todos.*
2834
- * FROM
2835
- * DIFF
2836
- * JOIN todos ON DIFF.id = todos.id
2837
- * `);
2838
- *
2839
- * // Process newly created todos
2840
- * },
2841
- * hooks: {
2842
- * beforeCreate: async (lockContext) => {
2843
- * // This hook is executed inside the write lock before the trigger is created.
2844
- * // It can be used to synchronize the current state of the table with processor logic.
2845
- * // Any changes after this callback are guaranteed to trigger the `onChange` handler.
2846
- *
2847
- * // Read the current state of the todos table
2848
- * const currentTodos = await lockContext.getAll<Database['todos']>(
2849
- * `
2850
- * SELECT
2851
- * *
2852
- * FROM
2853
- * todos
2854
- * WHERE
2855
- * list_id = ?
2856
- * `,
2857
- * ['123']
2858
- * );
2859
- *
2860
- * // Process existing todos
2861
- * }
2862
- * }
2863
- * });
2864
- * ```
2865
- */
2866
- trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback>;
2867
- }
2868
- /**
2869
- * @experimental
2870
- * @internal
2871
- * Manages claims on persisted SQLite triggers and destination tables to enable proper cleanup
2872
- * when they are no longer actively in use.
2873
- *
2874
- * 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.
2875
- *
2876
- * A cleanup process runs
2877
- * on database creation (and every 2 minutes) that:
2878
- * 1. Queries for existing managed persisted resources
2879
- * 2. Checks with the claim manager if any consumer is actively using those resources
2880
- * 3. Deletes unused resources
2881
- */
2882
- interface TriggerClaimManager {
2883
- /**
2884
- * Obtains or marks a claim on a certain identifier.
2885
- * @returns a callback to release the claim.
2886
- */
2887
- obtainClaim: (identifier: string) => Promise<() => Promise<void>>;
2888
- /**
2889
- * Checks if a claim is present for an identifier.
2890
- */
2891
- checkClaim: (identifier: string) => Promise<boolean>;
2892
- }
2893
- /**
2894
- * @experimental
2895
- * @internal
2896
- */
2897
- interface TriggerManagerConfig {
2898
- claimManager: TriggerClaimManager;
2899
- }
2900
-
2901
- type TriggerManagerImplOptions = TriggerManagerConfig & {
2902
- db: AbstractPowerSyncDatabase;
2903
- schema: Schema;
2904
- };
2905
- type TriggerManagerImplConfiguration = {
2906
- useStorageByDefault: boolean;
2907
- };
2908
- /**
2909
- * @internal
2910
- * @experimental
2911
- */
2912
- declare class TriggerManagerImpl implements TriggerManager {
2913
- protected options: TriggerManagerImplOptions;
2914
- protected schema: Schema;
2915
- protected defaultConfig: TriggerManagerImplConfiguration;
2916
- protected cleanupTimeout: ReturnType<typeof setTimeout> | null;
2917
- protected isDisposed: boolean;
2918
- constructor(options: TriggerManagerImplOptions);
2919
- protected get db(): AbstractPowerSyncDatabase;
2920
- protected getUUID(): Promise<string>;
2921
- protected removeTriggers(tx: LockContext, triggerIds: string[]): Promise<void>;
2922
- dispose(): void;
2923
- /**
2924
- * Updates default config settings for platform specific use-cases.
2925
- */
2926
- updateDefaults(config: TriggerManagerImplConfiguration): void;
2927
- protected generateTriggerName(operation: DiffTriggerOperation, destinationTable: string, triggerId: string): string;
2928
- /**
2929
- * Cleanup any SQLite triggers or tables that are no longer in use.
2930
- */
2931
- cleanupResources(): Promise<void>;
2932
- createDiffTrigger(options: CreateDiffTriggerOptions): Promise<() => Promise<void>>;
2933
- trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback>;
2934
- }
2935
-
2936
- interface DisconnectAndClearOptions {
2937
- /** When set to false, data in local-only tables is preserved. */
2938
- clearLocal?: boolean;
2939
- }
2940
- interface BasePowerSyncDatabaseOptions extends AdditionalConnectionOptions {
2941
- /** Schema used for the local database. */
2942
- schema: Schema;
2943
- /**
2944
- * @deprecated Use {@link retryDelayMs} instead as this will be removed in future releases.
2945
- */
2946
- retryDelay?: number;
2947
- logger?: ILogger;
2948
- }
2949
- interface PowerSyncDatabaseOptions extends BasePowerSyncDatabaseOptions {
2950
- /**
2951
- * Source for a SQLite database connection.
2952
- * This can be either:
2953
- * - A {@link DBAdapter} if providing an instantiated SQLite connection
2954
- * - A {@link SQLOpenFactory} which will be used to open a SQLite connection
2955
- * - {@link SQLOpenOptions} for opening a SQLite connection with a default {@link SQLOpenFactory}
2956
- */
2957
- database: DBAdapter | SQLOpenFactory | SQLOpenOptions;
2958
- }
2959
- interface PowerSyncDatabaseOptionsWithDBAdapter extends BasePowerSyncDatabaseOptions {
2960
- database: DBAdapter;
2961
- }
2962
- interface PowerSyncDatabaseOptionsWithOpenFactory extends BasePowerSyncDatabaseOptions {
2963
- database: SQLOpenFactory;
2964
- }
2965
- interface PowerSyncDatabaseOptionsWithSettings extends BasePowerSyncDatabaseOptions {
2966
- database: SQLOpenOptions;
2967
- }
2968
- interface SQLOnChangeOptions {
2969
- signal?: AbortSignal;
2970
- tables?: string[];
2971
- /** The minimum interval between queries. */
2972
- throttleMs?: number;
2973
- /**
2974
- * @deprecated All tables specified in {@link tables} will be watched, including PowerSync tables with prefixes.
2975
- *
2976
- * Allows for watching any SQL table
2977
- * by not removing PowerSync table name prefixes
2978
- */
2979
- rawTableNames?: boolean;
2980
- /**
2981
- * Emits an empty result set immediately
2982
- */
2983
- triggerImmediate?: boolean;
2984
- }
2985
- interface SQLWatchOptions extends SQLOnChangeOptions {
2986
- /**
2987
- * Optional comparator which will be used to compare the results of the query.
2988
- * The watched query will only yield results if the comparator returns false.
2989
- */
2990
- comparator?: WatchedQueryComparator<QueryResult>;
2991
- }
2992
- interface WatchOnChangeEvent {
2993
- changedTables: string[];
2994
- }
2995
- interface WatchHandler {
2996
- onResult: (results: QueryResult) => void;
2997
- onError?: (error: Error) => void;
2998
- }
2999
- interface WatchOnChangeHandler {
3000
- onChange: (event: WatchOnChangeEvent) => Promise<void> | void;
3001
- onError?: (error: Error) => void;
3002
- }
3003
- interface PowerSyncDBListener extends StreamingSyncImplementationListener {
3004
- initialized: () => void;
3005
- schemaChanged: (schema: Schema) => void;
3006
- closing: () => Promise<void> | void;
3007
- closed: () => Promise<void> | void;
3008
- }
3009
- interface PowerSyncCloseOptions {
3010
- /**
3011
- * Disconnect the sync stream client if connected.
3012
- * This is usually true, but can be false for Web when using
3013
- * multiple tabs and a shared sync provider.
3014
- */
3015
- disconnect?: boolean;
3016
- }
3017
- declare const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions;
3018
- declare const DEFAULT_POWERSYNC_DB_OPTIONS: {
3019
- retryDelayMs: number;
3020
- crudUploadThrottleMs: number;
3021
- };
3022
- declare const DEFAULT_CRUD_BATCH_LIMIT = 100;
3023
- /**
3024
- * Requesting nested or recursive locks can block the application in some circumstances.
3025
- * This default lock timeout will act as a failsafe to throw an error if a lock cannot
3026
- * be obtained.
3027
- */
3028
- declare const DEFAULT_LOCK_TIMEOUT_MS = 120000;
3029
- /**
3030
- * Tests if the input is a {@link PowerSyncDatabaseOptionsWithSettings}
3031
- * @internal
3032
- */
3033
- declare const isPowerSyncDatabaseOptionsWithSettings: (test: any) => test is PowerSyncDatabaseOptionsWithSettings;
3034
- declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDBListener> {
3035
- protected options: PowerSyncDatabaseOptions;
3036
- /**
3037
- * Returns true if the connection is closed.
3038
- */
3039
- closed: boolean;
3040
- ready: boolean;
3041
- /**
3042
- * Current connection status.
3043
- */
3044
- currentStatus: SyncStatus;
3045
- sdkVersion: string;
3046
- protected bucketStorageAdapter: BucketStorageAdapter;
3047
- protected _isReadyPromise: Promise<void>;
3048
- protected connectionManager: ConnectionManager;
3049
- private subscriptions;
3050
- get syncStreamImplementation(): StreamingSyncImplementation | null;
3051
- /**
3052
- * The connector used to connect to the PowerSync service.
3053
- *
3054
- * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
3055
- */
3056
- get connector(): PowerSyncBackendConnector | null;
3057
- /**
3058
- * The resolved connection options used to connect to the PowerSync service.
3059
- *
3060
- * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
3061
- */
3062
- get connectionOptions(): InternalConnectionOptions | null;
3063
- protected _schema: Schema;
3064
- private _database;
3065
- protected runExclusiveMutex: Mutex;
3066
- /**
3067
- * @experimental
3068
- * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
3069
- */
3070
- readonly triggers: TriggerManager;
3071
- protected triggersImpl: TriggerManagerImpl;
3072
- logger: ILogger;
3073
- constructor(options: PowerSyncDatabaseOptionsWithDBAdapter);
3074
- constructor(options: PowerSyncDatabaseOptionsWithOpenFactory);
3075
- constructor(options: PowerSyncDatabaseOptionsWithSettings);
3076
- constructor(options: PowerSyncDatabaseOptions);
3077
- /**
3078
- * Schema used for the local database.
3079
- */
3080
- get schema(): Schema<{
3081
- [x: string]: Table<any>;
3082
- }>;
3083
- /**
3084
- * The underlying database.
3085
- *
3086
- * For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.
3087
- */
3088
- get database(): DBAdapter;
3089
- /**
3090
- * Whether a connection to the PowerSync service is currently open.
3091
- */
3092
- get connected(): boolean;
3093
- get connecting(): boolean;
3094
- /**
3095
- * Opens the DBAdapter given open options using a default open factory
3096
- */
3097
- protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
3098
- /**
3099
- * Generates a base configuration for {@link TriggerManagerImpl}.
3100
- * Implementations should override this if necessary.
3101
- */
3102
- protected generateTriggerManagerConfig(): TriggerManagerConfig;
3103
- protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
3104
- protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
3105
- /**
3106
- * @returns A promise which will resolve once initialization is completed.
3107
- */
3108
- waitForReady(): Promise<void>;
3109
- /**
3110
- * Wait for the first sync operation to complete.
3111
- *
3112
- * @param request Either an abort signal (after which the promise will complete regardless of
3113
- * whether a full sync was completed) or an object providing an abort signal and a priority target.
3114
- * When a priority target is set, the promise may complete when all buckets with the given (or higher)
3115
- * priorities have been synchronized. This can be earlier than a complete sync.
3116
- * @returns A promise which will resolve once the first full sync has completed.
3117
- */
3118
- waitForFirstSync(request?: AbortSignal | {
3119
- signal?: AbortSignal;
3120
- priority?: number;
3121
- }): Promise<void>;
3122
- /**
3123
- * Waits for the first sync status for which the `status` callback returns a truthy value.
3124
- */
3125
- waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
3126
- /**
3127
- * Allows for extended implementations to execute custom initialization
3128
- * logic as part of the total init process
3129
- */
3130
- abstract _initialize(): Promise<void>;
3131
- /**
3132
- * Entry point for executing initialization logic.
3133
- * This is to be automatically executed in the constructor.
3134
- */
3135
- protected initialize(): Promise<void>;
3136
- protected loadVersion(): Promise<void>;
3137
- protected resolveOfflineSyncStatus(): Promise<void>;
3138
- /**
3139
- * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
3140
- *
3141
- * Cannot be used while connected - this should only be called before {@link AbstractPowerSyncDatabase.connect}.
3142
- */
3143
- updateSchema(schema: Schema): Promise<void>;
3144
- /**
3145
- * Wait for initialization to complete.
3146
- * While initializing is automatic, this helps to catch and report initialization errors.
3147
- */
3148
- init(): Promise<void>;
3149
- protected resolvedConnectionOptions(options: CreateSyncImplementationOptions): CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions;
3150
- /**
3151
- * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.
3152
- * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.
3153
- */
3154
- dispose(): void;
3155
- /**
3156
- * Locking mechanism for exclusively running critical portions of connect/disconnect operations.
3157
- * Locking here is mostly only important on web for multiple tab scenarios.
3158
- */
3159
- protected runExclusive<T>(callback: () => Promise<T>): Promise<T>;
3160
- /**
3161
- * Connects to stream of events from the PowerSync instance.
3162
- */
3163
- connect(connector: PowerSyncBackendConnector, options?: PowerSyncConnectionOptions): Promise<void>;
3164
- /**
3165
- * Close the sync connection.
3166
- *
3167
- * Use {@link connect} to connect again.
3168
- */
3169
- disconnect(): Promise<void>;
3170
- /**
3171
- * Disconnect and clear the database.
3172
- * Use this when logging out.
3173
- * The database can still be queried after this is called, but the tables
3174
- * would be empty.
3175
- *
3176
- * To preserve data in local-only tables, set clearLocal to false.
3177
- */
3178
- disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
3179
- /**
3180
- * Create a sync stream to query its status or to subscribe to it.
3181
- *
3182
- * @param name The name of the stream to subscribe to.
3183
- * @param params Optional parameters for the stream subscription.
3184
- * @returns A {@link SyncStream} instance that can be subscribed to.
3185
- * @experimental Sync streams are currently in alpha.
3186
- */
3187
- syncStream(name: string, params?: Record<string, any>): SyncStream;
3188
- /**
3189
- * Close the database, releasing resources.
3190
- *
3191
- * Also disconnects any active connection.
3192
- *
3193
- * Once close is called, this connection cannot be used again - a new one
3194
- * must be constructed.
3195
- */
3196
- close(options?: PowerSyncCloseOptions): Promise<void>;
3197
- /**
3198
- * Get upload queue size estimate and count.
3199
- */
3200
- getUploadQueueStats(includeSize?: boolean): Promise<UploadQueueStats>;
3201
- /**
3202
- * Get a batch of CRUD data to upload.
3203
- *
3204
- * Returns null if there is no data to upload.
3205
- *
3206
- * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
3207
- *
3208
- * Once the data have been successfully uploaded, call {@link CrudBatch.complete} before
3209
- * requesting the next batch.
3210
- *
3211
- * Use {@link limit} to specify the maximum number of updates to return in a single
3212
- * batch.
3213
- *
3214
- * This method does include transaction ids in the result, but does not group
3215
- * data by transaction. One batch may contain data from multiple transactions,
3216
- * and a single transaction may be split over multiple batches.
3217
- *
3218
- * @param limit Maximum number of CRUD entries to include in the batch
3219
- * @returns A batch of CRUD operations to upload, or null if there are none
3220
- */
3221
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
3222
- /**
3223
- * Get the next recorded transaction to upload.
3224
- *
3225
- * Returns null if there is no data to upload.
3226
- *
3227
- * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
3228
- *
3229
- * Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before
3230
- * requesting the next transaction.
3231
- *
3232
- * Unlike {@link getCrudBatch}, this only returns data from a single transaction at a time.
3233
- * All data for the transaction is loaded into memory.
3234
- *
3235
- * @returns A transaction of CRUD operations to upload, or null if there are none
3236
- */
3237
- getNextCrudTransaction(): Promise<CrudTransaction | null>;
3238
- /**
3239
- * Returns an async iterator of completed transactions with local writes against the database.
3240
- *
3241
- * This is typically used from the {@link PowerSyncBackendConnector.uploadData} callback. Each entry emitted by the
3242
- * returned iterator is a full transaction containing all local writes made while that transaction was active.
3243
- *
3244
- * Unlike {@link getNextCrudTransaction}, which always returns the oldest transaction that hasn't been
3245
- * {@link CrudTransaction.complete}d yet, this iterator can be used to receive multiple transactions. Calling
3246
- * {@link CrudTransaction.complete} will mark that and all prior transactions emitted by the iterator as completed.
3247
- *
3248
- * This can be used to upload multiple transactions in a single batch, e.g with:
3249
- *
3250
- * ```JavaScript
3251
- * let lastTransaction = null;
3252
- * let batch = [];
3253
- *
3254
- * for await (const transaction of database.getCrudTransactions()) {
3255
- * batch.push(...transaction.crud);
3256
- * lastTransaction = transaction;
3257
- *
3258
- * if (batch.length > 10) {
3259
- * break;
3260
- * }
3261
- * }
3262
- * ```
3263
- *
3264
- * If there is no local data to upload, the async iterator complete without emitting any items.
3265
- *
3266
- * Note that iterating over async iterables requires a [polyfill](https://github.com/powersync-ja/powersync-js/tree/main/packages/react-native#babel-plugins-watched-queries)
3267
- * for React Native.
3268
- */
3269
- getCrudTransactions(): AsyncIterable<CrudTransaction, null>;
3270
- /**
3271
- * Get an unique client id for this database.
3272
- *
3273
- * The id is not reset when the database is cleared, only when the database is deleted.
3274
- *
3275
- * @returns A unique identifier for the database instance
3276
- */
3277
- getClientId(): Promise<string>;
3278
- private handleCrudCheckpoint;
3279
- /**
3280
- * Execute a SQL write (INSERT/UPDATE/DELETE) query
3281
- * and optionally return results.
3282
- *
3283
- * @param sql The SQL query to execute
3284
- * @param parameters Optional array of parameters to bind to the query
3285
- * @returns The query result as an object with structured key-value pairs
3286
- */
3287
- execute(sql: string, parameters?: any[]): Promise<QueryResult>;
3288
- /**
3289
- * Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.
3290
- * This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.
3291
- *
3292
- * @param sql The SQL query to execute
3293
- * @param parameters Optional array of parameters to bind to the query
3294
- * @returns The raw query result from the underlying database as a nested array of raw values, where each row is
3295
- * represented as an array of column values without field names.
3296
- */
3297
- executeRaw(sql: string, parameters?: any[]): Promise<any[][]>;
3298
- /**
3299
- * Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set
3300
- * and optionally return results.
3301
- * This is faster than executing separately with each parameter set.
3302
- *
3303
- * @param sql The SQL query to execute
3304
- * @param parameters Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution
3305
- * @returns The query result
3306
- */
3307
- executeBatch(sql: string, parameters?: any[][]): Promise<QueryResult>;
3308
- /**
3309
- * Execute a read-only query and return results.
3310
- *
3311
- * @param sql The SQL query to execute
3312
- * @param parameters Optional array of parameters to bind to the query
3313
- * @returns An array of results
3314
- */
3315
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
3316
- /**
3317
- * Execute a read-only query and return the first result, or null if the ResultSet is empty.
3318
- *
3319
- * @param sql The SQL query to execute
3320
- * @param parameters Optional array of parameters to bind to the query
3321
- * @returns The first result if found, or null if no results are returned
3322
- */
3323
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
3324
- /**
3325
- * Execute a read-only query and return the first result, error if the ResultSet is empty.
3326
- *
3327
- * @param sql The SQL query to execute
3328
- * @param parameters Optional array of parameters to bind to the query
3329
- * @returns The first result matching the query
3330
- * @throws Error if no rows are returned
3331
- */
3332
- get<T>(sql: string, parameters?: any[]): Promise<T>;
3333
- /**
3334
- * Takes a read lock, without starting a transaction.
3335
- * In most cases, {@link readTransaction} should be used instead.
3336
- */
3337
- readLock<T>(callback: (db: DBAdapter) => Promise<T>): Promise<T>;
3338
- /**
3339
- * Takes a global lock, without starting a transaction.
3340
- * In most cases, {@link writeTransaction} should be used instead.
3341
- */
3342
- writeLock<T>(callback: (db: DBAdapter) => Promise<T>): Promise<T>;
3343
- /**
3344
- * Open a read-only transaction.
3345
- * Read transactions can run concurrently to a write transaction.
3346
- * Changes from any write transaction are not visible to read transactions started before it.
3347
- *
3348
- * @param callback Function to execute within the transaction
3349
- * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
3350
- * @returns The result of the callback
3351
- * @throws Error if the lock cannot be obtained within the timeout period
3352
- */
3353
- readTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
3354
- /**
3355
- * Open a read-write transaction.
3356
- * This takes a global lock - only one write transaction can execute against the database at a time.
3357
- * Statements within the transaction must be done on the provided {@link Transaction} interface.
3358
- *
3359
- * @param callback Function to execute within the transaction
3360
- * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
3361
- * @returns The result of the callback
3362
- * @throws Error if the lock cannot be obtained within the timeout period
3363
- */
3364
- writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
3365
- /**
3366
- * This version of `watch` uses {@link AsyncGenerator}, for documentation see {@link watchWithAsyncGenerator}.
3367
- * Can be overloaded to use a callback handler instead, for documentation see {@link watchWithCallback}.
3368
- *
3369
- * @example
3370
- * ```javascript
3371
- * async *attachmentIds() {
3372
- * for await (const result of this.powersync.watch(
3373
- * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3374
- * []
3375
- * )) {
3376
- * yield result.rows?._array.map((r) => r.id) ?? [];
3377
- * }
3378
- * }
3379
- * ```
3380
- */
3381
- watch(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
3382
- /**
3383
- * See {@link watchWithCallback}.
3384
- *
3385
- * @example
3386
- * ```javascript
3387
- * onAttachmentIdsChange(onResult) {
3388
- * this.powersync.watch(
3389
- * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3390
- * [],
3391
- * {
3392
- * onResult: (result) => onResult(result.rows?._array.map((r) => r.id) ?? [])
3393
- * }
3394
- * );
3395
- * }
3396
- * ```
3397
- */
3398
- watch(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
3399
- /**
3400
- * Allows defining a query which can be used to build a {@link WatchedQuery}.
3401
- * The defined query will be executed with {@link AbstractPowerSyncDatabase#getAll}.
3402
- * An optional mapper function can be provided to transform the results.
3403
- *
3404
- * @example
3405
- * ```javascript
3406
- * const watchedTodos = powersync.query({
3407
- * sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3408
- * parameters: [],
3409
- * mapper: (row) => ({
3410
- * ...row,
3411
- * created_at: new Date(row.created_at as string)
3412
- * })
3413
- * })
3414
- * .watch()
3415
- * // OR use .differentialWatch() for fine-grained watches.
3416
- * ```
3417
- */
3418
- query<RowType>(query: ArrayQueryDefinition<RowType>): Query<RowType>;
3419
- /**
3420
- * Allows building a {@link WatchedQuery} using an existing {@link WatchCompatibleQuery}.
3421
- * The watched query will use the provided {@link WatchCompatibleQuery.execute} method to query results.
3422
- *
3423
- * @example
3424
- * ```javascript
3425
- *
3426
- * // Potentially a query from an ORM like Drizzle
3427
- * const query = db.select().from(lists);
3428
- *
3429
- * const watchedTodos = powersync.customQuery(query)
3430
- * .watch()
3431
- * // OR use .differentialWatch() for fine-grained watches.
3432
- * ```
3433
- */
3434
- customQuery<RowType>(query: WatchCompatibleQuery<RowType[]>): Query<RowType>;
3435
- /**
3436
- * Execute a read query every time the source tables are modified.
3437
- * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.
3438
- * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
3439
- *
3440
- * Note that the `onChange` callback member of the handler is required.
3441
- *
3442
- * @param sql The SQL query to execute
3443
- * @param parameters Optional array of parameters to bind to the query
3444
- * @param handler Callbacks for handling results and errors
3445
- * @param options Options for configuring watch behavior
3446
- */
3447
- watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
3448
- /**
3449
- * Execute a read query every time the source tables are modified.
3450
- * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.
3451
- * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
3452
- *
3453
- * @param sql The SQL query to execute
3454
- * @param parameters Optional array of parameters to bind to the query
3455
- * @param options Options for configuring watch behavior
3456
- * @returns An AsyncIterable that yields QueryResults whenever the data changes
3457
- */
3458
- watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
3459
- /**
3460
- * Resolves the list of tables that are used in a SQL query.
3461
- * If tables are specified in the options, those are used directly.
3462
- * Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.
3463
- *
3464
- * @param sql The SQL query to analyze
3465
- * @param parameters Optional parameters for the SQL query
3466
- * @param options Optional watch options that may contain explicit table list
3467
- * @returns Array of table names that the query depends on
3468
- */
3469
- resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]>;
3470
- /**
3471
- * This version of `onChange` uses {@link AsyncGenerator}, for documentation see {@link onChangeWithAsyncGenerator}.
3472
- * Can be overloaded to use a callback handler instead, for documentation see {@link onChangeWithCallback}.
3473
- *
3474
- * @example
3475
- * ```javascript
3476
- * async monitorChanges() {
3477
- * for await (const event of this.powersync.onChange({tables: ['todos']})) {
3478
- * console.log('Detected change event:', event);
3479
- * }
3480
- * }
3481
- * ```
3482
- */
3483
- onChange(options?: SQLOnChangeOptions): AsyncIterable<WatchOnChangeEvent>;
3484
- /**
3485
- * See {@link onChangeWithCallback}.
3486
- *
3487
- * @example
3488
- * ```javascript
3489
- * monitorChanges() {
3490
- * this.powersync.onChange({
3491
- * onChange: (event) => {
3492
- * console.log('Change detected:', event);
3493
- * }
3494
- * }, { tables: ['todos'] });
3495
- * }
3496
- * ```
3497
- */
3498
- onChange(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
3499
- /**
3500
- * Invoke the provided callback on any changes to any of the specified tables.
3501
- *
3502
- * This is preferred over {@link watchWithCallback} when multiple queries need to be performed
3503
- * together when data is changed.
3504
- *
3505
- * Note that the `onChange` callback member of the handler is required.
3506
- *
3507
- * @param handler Callbacks for handling change events and errors
3508
- * @param options Options for configuring watch behavior
3509
- * @returns A dispose function to stop watching for changes
3510
- */
3511
- onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
3512
- /**
3513
- * Create a Stream of changes to any of the specified tables.
3514
- *
3515
- * This is preferred over {@link watchWithAsyncGenerator} when multiple queries need to be performed
3516
- * together when data is changed.
3517
- *
3518
- * Note: do not declare this as `async *onChange` as it will not work in React Native.
3519
- *
3520
- * @param options Options for configuring watch behavior
3521
- * @returns An AsyncIterable that yields change events whenever the specified tables change
3522
- */
3523
- onChangeWithAsyncGenerator(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent>;
3524
- private handleTableChanges;
3525
- private processTableUpdates;
3526
- /**
3527
- * @ignore
3528
- */
3529
- private executeReadOnly;
3530
- }
3531
-
3532
- declare const LogLevel: {
3533
- TRACE: Logger.ILogLevel;
3534
- DEBUG: Logger.ILogLevel;
3535
- INFO: Logger.ILogLevel;
3536
- TIME: Logger.ILogLevel;
3537
- WARN: Logger.ILogLevel;
3538
- ERROR: Logger.ILogLevel;
3539
- OFF: Logger.ILogLevel;
3540
- };
3541
- interface CreateLoggerOptions {
3542
- logLevel?: ILogLevel;
3543
- }
3544
- /**
3545
- * Retrieves the base (default) logger instance.
3546
- *
3547
- * This base logger controls the default logging configuration and is shared
3548
- * across all loggers created with `createLogger`. Adjusting settings on this
3549
- * base logger affects all loggers derived from it unless explicitly overridden.
3550
- *
3551
- */
3552
- declare function createBaseLogger(): typeof Logger;
3553
- /**
3554
- * Creates and configures a new named logger based on the base logger.
3555
- *
3556
- * Named loggers allow specific modules or areas of your application to have
3557
- * their own logging levels and behaviors. These loggers inherit configuration
3558
- * from the base logger by default but can override settings independently.
3559
- */
3560
- declare function createLogger(name: string, options?: CreateLoggerOptions): ILogger;
3561
-
3562
- declare const ATTACHMENT_TABLE = "attachments";
3563
- /**
3564
- * AttachmentRecord represents an attachment in the local database.
3565
- *
3566
- * @experimental
3567
- */
3568
- interface AttachmentRecord {
3569
- id: string;
3570
- filename: string;
3571
- localUri?: string;
3572
- size?: number;
3573
- mediaType?: string;
3574
- timestamp?: number;
3575
- metaData?: string;
3576
- hasSynced?: boolean;
3577
- state: AttachmentState;
3578
- }
3579
- /**
3580
- * Maps a database row to an AttachmentRecord.
3581
- *
3582
- * @param row - The database row object
3583
- * @returns The corresponding AttachmentRecord
3584
- *
3585
- * @experimental
3586
- */
3587
- declare function attachmentFromSql(row: any): AttachmentRecord;
3588
- /**
3589
- * AttachmentState represents the current synchronization state of an attachment.
3590
- *
3591
- * @experimental
3592
- */
3593
- declare enum AttachmentState {
3594
- QUEUED_UPLOAD = 0,// Attachment to be uploaded
3595
- QUEUED_DOWNLOAD = 1,// Attachment to be downloaded
3596
- QUEUED_DELETE = 2,// Attachment to be deleted
3597
- SYNCED = 3,// Attachment has been synced
3598
- ARCHIVED = 4
3599
- }
3600
- interface AttachmentTableOptions extends Omit<TableV2Options, 'name' | 'columns'> {
3601
- }
3602
- /**
3603
- * AttachmentTable defines the schema for the attachment queue table.
3604
- *
3605
- * @internal
3606
- */
3607
- declare class AttachmentTable extends Table {
3608
- constructor(options?: AttachmentTableOptions);
3609
- }
3610
-
3611
- /**
3612
- * AttachmentContext provides database operations for managing attachment records.
3613
- *
3614
- * Provides methods to query, insert, update, and delete attachment records with
3615
- * proper transaction management through PowerSync.
3616
- *
3617
- * @internal
3618
- */
3619
- declare class AttachmentContext {
3620
- /** PowerSync database instance for executing queries */
3621
- db: AbstractPowerSyncDatabase;
3622
- /** Name of the database table storing attachment records */
3623
- tableName: string;
3624
- /** Logger instance for diagnostic information */
3625
- logger: ILogger;
3626
- /** Maximum number of archived attachments to keep before cleanup */
3627
- archivedCacheLimit: number;
3628
- /**
3629
- * Creates a new AttachmentContext instance.
3630
- *
3631
- * @param db - PowerSync database instance
3632
- * @param tableName - Name of the table storing attachment records. Default: 'attachments'
3633
- * @param logger - Logger instance for diagnostic output
3634
- */
3635
- constructor(db: AbstractPowerSyncDatabase, tableName: string | undefined, logger: ILogger, archivedCacheLimit: number);
3636
- /**
3637
- * Retrieves all active attachments that require synchronization.
3638
- * Active attachments include those queued for upload, download, or delete.
3639
- * Results are ordered by timestamp in ascending order.
3640
- *
3641
- * @returns Promise resolving to an array of active attachment records
3642
- */
3643
- getActiveAttachments(): Promise<AttachmentRecord[]>;
3644
- /**
3645
- * Retrieves all archived attachments.
3646
- *
3647
- * Archived attachments are no longer referenced but haven't been permanently deleted.
3648
- * These are candidates for cleanup operations to free up storage space.
3649
- *
3650
- * @returns Promise resolving to an array of archived attachment records
3651
- */
3652
- getArchivedAttachments(): Promise<AttachmentRecord[]>;
3653
- /**
3654
- * Retrieves all attachment records regardless of state.
3655
- * Results are ordered by timestamp in ascending order.
3656
- *
3657
- * @returns Promise resolving to an array of all attachment records
3658
- */
3659
- getAttachments(): Promise<AttachmentRecord[]>;
3660
- /**
3661
- * Inserts or updates an attachment record within an existing transaction.
3662
- *
3663
- * Performs an upsert operation (INSERT OR REPLACE). Must be called within
3664
- * an active database transaction context.
3665
- *
3666
- * @param attachment - The attachment record to upsert
3667
- * @param context - Active database transaction context
3668
- */
3669
- upsertAttachment(attachment: AttachmentRecord, context: Transaction): Promise<void>;
3670
- getAttachment(id: string): Promise<AttachmentRecord | undefined>;
3671
- /**
3672
- * Permanently deletes an attachment record from the database.
3673
- *
3674
- * This operation removes the attachment record but does not delete
3675
- * the associated local or remote files. File deletion should be handled
3676
- * separately through the appropriate storage adapters.
3677
- *
3678
- * @param attachmentId - Unique identifier of the attachment to delete
3679
- */
3680
- deleteAttachment(attachmentId: string): Promise<void>;
3681
- clearQueue(): Promise<void>;
3682
- deleteArchivedAttachments(callback?: (attachments: AttachmentRecord[]) => Promise<void>): Promise<boolean>;
3683
- /**
3684
- * Saves multiple attachment records in a single transaction.
3685
- *
3686
- * All updates are saved in a single batch after processing.
3687
- * If the attachments array is empty, no database operations are performed.
3688
- *
3689
- * @param attachments - Array of attachment records to save
3690
- */
3691
- saveAttachments(attachments: AttachmentRecord[]): Promise<void>;
3692
- }
3693
-
3694
- /**
3695
- * SyncErrorHandler provides custom error handling for attachment sync operations.
3696
- * Implementations determine whether failed operations should be retried or archived.
3697
- *
3698
- * @experimental
3699
- * @alpha This is currently experimental and may change without a major version bump.
3700
- */
3701
- interface AttachmentErrorHandler {
3702
- /**
3703
- * Handles a download error for a specific attachment.
3704
- * @param attachment The attachment that failed to download
3705
- * @param error The error encountered during the download
3706
- * @returns `true` to retry the operation, `false` to archive the attachment
3707
- */
3708
- onDownloadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3709
- /**
3710
- * Handles an upload error for a specific attachment.
3711
- * @param attachment The attachment that failed to upload
3712
- * @param error The error encountered during the upload
3713
- * @returns `true` to retry the operation, `false` to archive the attachment
3714
- */
3715
- onUploadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3716
- /**
3717
- * Handles a delete error for a specific attachment.
3718
- * @param attachment The attachment that failed to delete
3719
- * @param error The error encountered during the delete
3720
- * @returns `true` to retry the operation, `false` to archive the attachment
3721
- */
3722
- onDeleteError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3723
- }
3724
-
3725
- type AttachmentData = ArrayBuffer | string;
3726
- declare enum EncodingType {
3727
- UTF8 = "utf8",
3728
- Base64 = "base64"
3729
- }
3730
- /**
3731
- * LocalStorageAdapter defines the interface for local file storage operations.
3732
- * Implementations handle file I/O, directory management, and storage initialization.
3733
- *
3734
- * @experimental
3735
- * @alpha This is currently experimental and may change without a major version bump.
3736
- */
3737
- interface LocalStorageAdapter {
3738
- /**
3739
- * Saves data to a local file.
3740
- * @param filePath Path where the file will be stored
3741
- * @param data Data to store (ArrayBuffer, Blob, or string)
3742
- * @returns Number of bytes written
3743
- */
3744
- saveFile(filePath: string, data: AttachmentData): Promise<number>;
3745
- /**
3746
- * Retrieves file data as an ArrayBuffer.
3747
- * @param filePath Path where the file is stored
3748
- * @returns ArrayBuffer containing the file data
3749
- */
3750
- readFile(filePath: string): Promise<ArrayBuffer>;
3751
- /**
3752
- * Deletes the file at the given path.
3753
- * @param filePath Path where the file is stored
3754
- */
3755
- deleteFile(filePath: string): Promise<void>;
3756
- /**
3757
- * Checks if a file exists at the given path.
3758
- * @param filePath Path where the file is stored
3759
- * @returns True if the file exists, false otherwise
3760
- */
3761
- fileExists(filePath: string): Promise<boolean>;
3762
- /**
3763
- * Creates a directory at the specified path.
3764
- * @param path The full path to the directory
3765
- */
3766
- makeDir(path: string): Promise<void>;
3767
- /**
3768
- * Removes a directory at the specified path.
3769
- * @param path The full path to the directory
3770
- */
3771
- rmDir(path: string): Promise<void>;
3772
- /**
3773
- * Initializes the storage adapter (e.g., creating necessary directories).
3774
- */
3775
- initialize(): Promise<void>;
3776
- /**
3777
- * Clears all files in the storage.
3778
- */
3779
- clear(): Promise<void>;
3780
- /**
3781
- * Returns the file path for the provided filename in the storage directory.
3782
- * @param filename The filename to get the path for
3783
- * @returns The full file path
3784
- */
3785
- getLocalUri(filename: string): string;
3786
- }
3787
-
3788
- /**
3789
- * RemoteStorageAdapter defines the interface for remote storage operations.
3790
- * Implementations handle uploading, downloading, and deleting files from remote storage.
3791
- *
3792
- * @experimental
3793
- * @alpha This is currently experimental and may change without a major version bump.
3794
- */
3795
- interface RemoteStorageAdapter {
3796
- /**
3797
- * Uploads a file to remote storage.
3798
- * @param fileData The binary content of the file to upload
3799
- * @param attachment The associated attachment metadata
3800
- */
3801
- uploadFile(fileData: ArrayBuffer, attachment: AttachmentRecord): Promise<void>;
3802
- /**
3803
- * Downloads a file from remote storage.
3804
- * @param attachment The attachment describing the file to download
3805
- * @returns The binary data of the downloaded file
3806
- */
3807
- downloadFile(attachment: AttachmentRecord): Promise<ArrayBuffer>;
3808
- /**
3809
- * Deletes a file from remote storage.
3810
- * @param attachment The attachment describing the file to delete
3811
- */
3812
- deleteFile(attachment: AttachmentRecord): Promise<void>;
3813
- }
3814
-
3815
- /**
3816
- * WatchedAttachmentItem represents an attachment reference in your application's data model.
3817
- * Use either filename OR fileExtension (not both).
3818
- *
3819
- * @experimental
3820
- */
3821
- type WatchedAttachmentItem = {
3822
- id: string;
3823
- filename: string;
3824
- fileExtension?: never;
3825
- metaData?: string;
3826
- } | {
3827
- id: string;
3828
- fileExtension: string;
3829
- filename?: never;
3830
- metaData?: string;
3831
- };
3832
-
3833
- /**
3834
- * AttachmentQueue manages the lifecycle and synchronization of attachments
3835
- * between local and remote storage.
3836
- * Provides automatic synchronization, upload/download queuing, attachment monitoring,
3837
- * verification and repair of local files, and cleanup of archived attachments.
3838
- *
3839
- * @experimental
3840
- * @alpha This is currently experimental and may change without a major version bump.
3841
- */
3842
- declare class AttachmentQueue {
3843
- /** Timer for periodic synchronization operations */
3844
- private periodicSyncTimer?;
3845
- /** Service for synchronizing attachments between local and remote storage */
3846
- private readonly syncingService;
3847
- /** Adapter for local file storage operations */
3848
- readonly localStorage: LocalStorageAdapter;
3849
- /** Adapter for remote file storage operations */
3850
- readonly remoteStorage: RemoteStorageAdapter;
3851
- /**
3852
- * Callback function to watch for changes in attachment references in your data model.
3853
- *
3854
- * This should be implemented by the user of AttachmentQueue to monitor changes in your application's
3855
- * data that reference attachments. When attachments are added, removed, or modified,
3856
- * this callback should trigger the onUpdate function with the current set of attachments.
3857
- */
3858
- private readonly watchAttachments;
3859
- /** Name of the database table storing attachment records */
3860
- readonly tableName: string;
3861
- /** Logger instance for diagnostic information */
3862
- readonly logger: ILogger;
3863
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3864
- readonly syncIntervalMs: number;
3865
- /** Duration in milliseconds to throttle sync operations */
3866
- readonly syncThrottleDuration: number;
3867
- /** Whether to automatically download remote attachments. Default: true */
3868
- readonly downloadAttachments: boolean;
3869
- /** Maximum number of archived attachments to keep before cleanup. Default: 100 */
3870
- readonly archivedCacheLimit: number;
3871
- /** Service for managing attachment-related database operations */
3872
- private readonly attachmentService;
3873
- /** PowerSync database instance */
3874
- private readonly db;
3875
- /** Cleanup function for status change listener */
3876
- private statusListenerDispose?;
3877
- private watchActiveAttachments;
3878
- private watchAttachmentsAbortController;
3879
- /**
3880
- * Creates a new AttachmentQueue instance.
3881
- *
3882
- * @param options - Configuration options
3883
- * @param options.db - PowerSync database instance
3884
- * @param options.remoteStorage - Remote storage adapter for upload/download operations
3885
- * @param options.localStorage - Local storage adapter for file persistence
3886
- * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
3887
- * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
3888
- * @param options.logger - Logger instance. Defaults to db.logger
3889
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
3890
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
3891
- * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
3892
- * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
3893
- */
3894
- constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName, syncIntervalMs, syncThrottleDuration, downloadAttachments, archivedCacheLimit, errorHandler }: {
3895
- db: AbstractPowerSyncDatabase;
3896
- remoteStorage: RemoteStorageAdapter;
3897
- localStorage: LocalStorageAdapter;
3898
- watchAttachments: (onUpdate: (attachment: WatchedAttachmentItem[]) => Promise<void>, signal: AbortSignal) => void;
3899
- tableName?: string;
3900
- logger?: ILogger;
3901
- syncIntervalMs?: number;
3902
- syncThrottleDuration?: number;
3903
- downloadAttachments?: boolean;
3904
- archivedCacheLimit?: number;
3905
- errorHandler?: AttachmentErrorHandler;
3906
- });
3907
- /**
3908
- * Generates a new attachment ID using a SQLite UUID function.
3909
- *
3910
- * @returns Promise resolving to the new attachment ID
3911
- */
3912
- generateAttachmentId(): Promise<string>;
3913
- /**
3914
- * Starts the attachment synchronization process.
3915
- *
3916
- * This method:
3917
- * - Stops any existing sync operations
3918
- * - Sets up periodic synchronization based on syncIntervalMs
3919
- * - Registers listeners for active attachment changes
3920
- * - Processes watched attachments to queue uploads/downloads
3921
- * - Handles state transitions for archived and new attachments
3922
- */
3923
- startSync(): Promise<void>;
3924
- /**
3925
- * Synchronizes all active attachments between local and remote storage.
3926
- *
3927
- * This is called automatically at regular intervals when sync is started,
3928
- * but can also be called manually to trigger an immediate sync.
3929
- */
3930
- syncStorage(): Promise<void>;
3931
- /**
3932
- * Stops the attachment synchronization process.
3933
- *
3934
- * Clears the periodic sync timer and closes all active attachment watchers.
3935
- */
3936
- stopSync(): Promise<void>;
3937
- /**
3938
- * Saves a file to local storage and queues it for upload to remote storage.
3939
- *
3940
- * @param options - File save options
3941
- * @param options.data - The file data as ArrayBuffer, Blob, or base64 string
3942
- * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')
3943
- * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')
3944
- * @param options.metaData - Optional metadata to associate with the attachment
3945
- * @param options.id - Optional custom ID. If not provided, a UUID will be generated
3946
- * @param options.updateHook - Optional callback to execute additional database operations
3947
- * within the same transaction as the attachment creation
3948
- * @returns Promise resolving to the created attachment record
3949
- */
3950
- saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }: {
3951
- data: AttachmentData;
3952
- fileExtension: string;
3953
- mediaType?: string;
3954
- metaData?: string;
3955
- id?: string;
3956
- updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
3957
- }): Promise<AttachmentRecord>;
3958
- deleteFile({ id, updateHook }: {
3959
- id: string;
3960
- updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
3961
- }): Promise<void>;
3962
- expireCache(): Promise<void>;
3963
- clearQueue(): Promise<void>;
3964
- /**
3965
- * Verifies the integrity of all attachment records and repairs inconsistencies.
3966
- *
3967
- * This method checks each attachment record against the local filesystem and:
3968
- * - Updates localUri if the file exists at a different path
3969
- * - Archives attachments with missing local files that haven't been uploaded
3970
- * - Requeues synced attachments for download if their local files are missing
3971
- */
3972
- verifyAttachments(): Promise<void>;
3973
- }
3974
-
3975
- /**
3976
- * Service for querying and watching attachment records in the database.
3977
- *
3978
- * @internal
3979
- */
3980
- declare class AttachmentService {
3981
- private db;
3982
- private logger;
3983
- private tableName;
3984
- private mutex;
3985
- private context;
3986
- constructor(db: AbstractPowerSyncDatabase, logger: ILogger, tableName?: string, archivedCacheLimit?: number);
3987
- /**
3988
- * Creates a differential watch query for active attachments requiring synchronization.
3989
- * @returns Watch query that emits changes for queued uploads, downloads, and deletes
3990
- */
3991
- watchActiveAttachments({ throttleMs }?: {
3992
- throttleMs?: number;
3993
- }): DifferentialWatchedQuery<AttachmentRecord>;
3994
- /**
3995
- * Executes a callback with exclusive access to the attachment context.
3996
- */
3997
- withContext<T>(callback: (context: AttachmentContext) => Promise<T>): Promise<T>;
3998
- }
3999
-
4000
- /**
4001
- * Orchestrates attachment synchronization between local and remote storage.
4002
- * Handles uploads, downloads, deletions, and state transitions.
4003
- *
4004
- * @internal
4005
- */
4006
- declare class SyncingService {
4007
- private attachmentService;
4008
- private localStorage;
4009
- private remoteStorage;
4010
- private logger;
4011
- private errorHandler?;
4012
- constructor(attachmentService: AttachmentService, localStorage: LocalStorageAdapter, remoteStorage: RemoteStorageAdapter, logger: ILogger, errorHandler?: AttachmentErrorHandler);
4013
- /**
4014
- * Processes attachments based on their state (upload, download, or delete).
4015
- * All updates are saved in a single batch after processing.
4016
- *
4017
- * @param attachments - Array of attachment records to process
4018
- * @param context - Attachment context for database operations
4019
- * @returns Promise that resolves when all attachments have been processed and saved
4020
- */
4021
- processAttachments(attachments: AttachmentRecord[], context: AttachmentContext): Promise<void>;
4022
- /**
4023
- * Uploads an attachment from local storage to remote storage.
4024
- * On success, marks as SYNCED. On failure, defers to error handler or archives.
4025
- *
4026
- * @param attachment - The attachment record to upload
4027
- * @returns Updated attachment record with new state
4028
- * @throws Error if the attachment has no localUri
4029
- */
4030
- uploadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4031
- /**
4032
- * Downloads an attachment from remote storage to local storage.
4033
- * Retrieves the file, converts to base64, and saves locally.
4034
- * On success, marks as SYNCED. On failure, defers to error handler or archives.
4035
- *
4036
- * @param attachment - The attachment record to download
4037
- * @returns Updated attachment record with local URI and new state
4038
- */
4039
- downloadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4040
- /**
4041
- * Deletes an attachment from both remote and local storage.
4042
- * Removes the remote file, local file (if exists), and the attachment record.
4043
- * On failure, defers to error handler or archives.
4044
- *
4045
- * @param attachment - The attachment record to delete
4046
- * @returns Updated attachment record
4047
- */
4048
- deleteAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4049
- /**
4050
- * Performs cleanup of archived attachments by removing their local files and records.
4051
- * Errors during local file deletion are logged but do not prevent record deletion.
4052
- */
4053
- deleteArchivedAttachments(context: AttachmentContext): Promise<boolean>;
4054
- }
4055
-
4056
- interface PowerSyncOpenFactoryOptions extends Partial<PowerSyncDatabaseOptions>, SQLOpenOptions {
4057
- /** Schema used for the local database. */
4058
- schema: Schema;
4059
- }
4060
- declare abstract class AbstractPowerSyncDatabaseOpenFactory {
4061
- protected options: PowerSyncOpenFactoryOptions;
4062
- constructor(options: PowerSyncOpenFactoryOptions);
4063
- /**
4064
- * Schema used for the local database.
4065
- */
4066
- get schema(): Schema<{
4067
- [x: string]: Table<any>;
4068
- }>;
4069
- protected abstract openDB(): DBAdapter;
4070
- generateOptions(): PowerSyncDatabaseOptions;
4071
- abstract generateInstance(options: PowerSyncDatabaseOptions): AbstractPowerSyncDatabase;
4072
- getInstance(): AbstractPowerSyncDatabase;
4073
- }
4074
-
4075
- interface CompilableQueryWatchHandler<T> {
4076
- onResult: (results: T[]) => void;
4077
- onError?: (error: Error) => void;
4078
- }
4079
- declare function compilableQueryWatch<T>(db: AbstractPowerSyncDatabase, query: CompilableQuery<T>, handler: CompilableQueryWatchHandler<T>, options?: SQLWatchOptions): void;
4080
-
4081
- declare const MAX_OP_ID = "9223372036854775807";
4082
-
4083
- declare function runOnSchemaChange(callback: (signal: AbortSignal) => void, db: AbstractPowerSyncDatabase, options?: SQLWatchOptions): void;
4084
-
4085
- declare class SqliteBucketStorage extends BaseObserver<BucketStorageListener> implements BucketStorageAdapter {
4086
- private db;
4087
- private logger;
4088
- tableNames: Set<string>;
4089
- private _hasCompletedSync;
4090
- private updateListener;
4091
- private _clientId?;
4092
- constructor(db: DBAdapter, logger?: ILogger);
4093
- init(): Promise<void>;
4094
- dispose(): Promise<void>;
4095
- _getClientId(): Promise<string>;
4096
- getClientId(): Promise<string>;
4097
- getMaxOpId(): string;
4098
- /**
4099
- * Reset any caches.
4100
- */
4101
- startSession(): void;
4102
- getBucketStates(): Promise<BucketState[]>;
4103
- getBucketOperationProgress(): Promise<BucketOperationProgress>;
4104
- saveSyncData(batch: SyncDataBatch, fixedKeyFormat?: boolean): Promise<void>;
4105
- removeBuckets(buckets: string[]): Promise<void>;
4106
- /**
4107
- * Mark a bucket for deletion.
4108
- */
4109
- private deleteBucket;
4110
- hasCompletedSync(): Promise<boolean>;
4111
- syncLocalDatabase(checkpoint: Checkpoint, priority?: number): Promise<SyncLocalDatabaseResult>;
4112
- /**
4113
- * Atomically update the local state to the current checkpoint.
4114
- *
4115
- * This includes creating new tables, dropping old tables, and copying data over from the oplog.
4116
- */
4117
- private updateObjectsFromBuckets;
4118
- validateChecksums(checkpoint: Checkpoint, priority: number | undefined): Promise<SyncLocalDatabaseResult>;
4119
- updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
4120
- nextCrudItem(): Promise<CrudEntry | undefined>;
4121
- hasCrud(): Promise<boolean>;
4122
- /**
4123
- * Get a batch of objects to send to the server.
4124
- * When the objects are successfully sent to the server, call .complete()
4125
- */
4126
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
4127
- writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, options?: {
4128
- timeoutMs: number;
4129
- }): Promise<T>;
4130
- /**
4131
- * Set a target checkpoint.
4132
- */
4133
- setTargetCheckpoint(checkpoint: Checkpoint): Promise<void>;
4134
- control(op: PowerSyncControlCommand, payload: string | Uint8Array | ArrayBuffer | null): Promise<string>;
4135
- hasMigratedSubkeys(): Promise<boolean>;
4136
- migrateToFixedSubkeys(): Promise<void>;
4137
- static _subkeyMigrationKey: string;
4138
- }
4139
-
4140
- /**
4141
- * Thrown when an underlying database connection is closed.
4142
- * This is particularly relevant when worker connections are marked as closed while
4143
- * operations are still in progress.
4144
- */
4145
- declare class ConnectionClosedError extends Error {
4146
- static NAME: string;
4147
- static MATCHES(input: any): boolean;
4148
- constructor(message: string);
4149
- }
4150
-
4151
- /**
4152
- * @internal
4153
- * @experimental
4154
- */
4155
- declare const MEMORY_TRIGGER_CLAIM_MANAGER: TriggerClaimManager;
4156
-
4157
- /**
4158
- * Helper function for sanitizing UUID input strings.
4159
- * Typically used with {@link sanitizeSQL}.
4160
- */
4161
- declare function sanitizeUUID(uuid: string): string;
4162
- /**
4163
- * SQL string template function for {@link TrackDiffOptions#when} and {@link CreateDiffTriggerOptions#when}.
4164
- *
4165
- * This function performs basic string interpolation for SQLite WHEN clauses.
4166
- *
4167
- * **String placeholders:**
4168
- * - All string values passed as placeholders are automatically wrapped in single quotes (`'`).
4169
- * - Do not manually wrap placeholders in single quotes in your template string; the function will handle quoting and escaping for you.
4170
- * - Any single quotes within the string value are escaped by doubling them (`''`), as required by SQL syntax.
4171
- *
4172
- * **Other types:**
4173
- * - `null` and `undefined` are converted to SQL `NULL`.
4174
- * - Objects are stringified using `JSON.stringify()` and wrapped in single quotes, with any single quotes inside the stringified value escaped.
4175
- * - Numbers and other primitive types are inserted directly.
4176
- *
4177
- * **Usage example:**
4178
- * ```typescript
4179
- * const myID = "O'Reilly";
4180
- * const clause = sanitizeSQL`New.id = ${myID}`;
4181
- * // Result: "New.id = 'O''Reilly'"
4182
- * ```
4183
- *
4184
- * Avoid manually quoting placeholders:
4185
- * ```typescript
4186
- * // Incorrect:
4187
- * sanitizeSQL`New.id = '${myID}'` // Produces double quotes: New.id = ''O''Reilly''
4188
- * ```
4189
- */
4190
- declare function sanitizeSQL(strings: TemplateStringsArray, ...values: any[]): string;
4191
-
4192
- /**
4193
- * Options for {@link GetAllQuery}.
4194
- */
4195
- type GetAllQueryOptions<RowType = unknown> = {
4196
- sql: string;
4197
- parameters?: ReadonlyArray<unknown>;
4198
- /**
4199
- * Optional mapper function to convert raw rows into the desired RowType.
4200
- * @example
4201
- * ```javascript
4202
- * (rawRow) => ({
4203
- * id: rawRow.id,
4204
- * created_at: new Date(rawRow.created_at),
4205
- * })
4206
- * ```
4207
- */
4208
- mapper?: (rawRow: Record<string, unknown>) => RowType;
4209
- };
4210
- /**
4211
- * Performs a {@link AbstractPowerSyncDatabase.getAll} operation for a watched query.
4212
- */
4213
- declare class GetAllQuery<RowType = unknown> implements WatchCompatibleQuery<RowType[]> {
4214
- protected options: GetAllQueryOptions<RowType>;
4215
- constructor(options: GetAllQueryOptions<RowType>);
4216
- compile(): CompiledQuery;
4217
- execute(options: {
4218
- db: AbstractPowerSyncDatabase;
4219
- }): Promise<RowType[]>;
4220
- }
4221
-
4222
- /**
4223
- * Calls to Abortcontroller.abort(reason: any) will result in the
4224
- * `reason` being thrown. This is not necessarily an error,
4225
- * but extends error for better logging purposes.
4226
- */
4227
- declare class AbortOperation extends Error {
4228
- protected reason: string;
4229
- constructor(reason: string);
4230
- }
4231
-
4232
- interface ControlledExecutorOptions {
4233
- /**
4234
- * If throttling is enabled, it ensures only one task runs at a time,
4235
- * 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.
4236
- * Enabled by default.
4237
- */
4238
- throttleEnabled?: boolean;
4239
- }
4240
- declare class ControlledExecutor<T> {
4241
- private task;
4242
- /**
4243
- * Represents the currently running task, which could be a Promise or undefined if no task is running.
4244
- */
4245
- private runningTask;
4246
- private pendingTaskParam;
4247
- /**
4248
- * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.
4249
- */
4250
- private isThrottling;
4251
- private closed;
4252
- constructor(task: (param: T) => Promise<void> | void, options?: ControlledExecutorOptions);
4253
- schedule(param: T): void;
4254
- dispose(): void;
4255
- private execute;
4256
- }
4257
-
4258
- interface ParsedQuery {
4259
- sqlStatement: string;
4260
- parameters: any[];
4261
- }
4262
- declare const parseQuery: <T>(query: string | CompilableQuery<T>, parameters: any[]) => ParsedQuery;
4263
-
4264
- export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RawTable, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
4265
- export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, AttachmentData, AttachmentErrorHandler, AttachmentRecord, AttachmentTableOptions, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LocalStorageAdapter, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PendingStatement, PendingStatementParameter, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RawTableType, RemoteConnector, RemoteStorageAdapter, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SubscribedStream, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerClaimManager, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerManagerConfig, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedAttachmentItem, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState, WithDiffOptions };