@powersync/common 0.0.0-dev-20260503073249 → 0.0.0-dev-20260630141119

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