@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
@@ -1,624 +0,0 @@
1
- import type { BSON } from 'bson';
2
- import { type fetch } from 'cross-fetch';
3
- import Logger, { ILogger } from 'js-logger';
4
- import { Requestable, RSocket, RSocketConnector } from 'rsocket-core';
5
- import PACKAGE from '../../../../package.json' with { type: 'json' };
6
- import { AbortOperation } from '../../../utils/AbortOperation.js';
7
- import { PowerSyncCredentials } from '../../connection/PowerSyncCredentials.js';
8
- import { WebsocketClientTransport } from './WebsocketClientTransport.js';
9
- import { StreamingSyncRequest } from './streaming-sync-types.js';
10
- import {
11
- doneResult,
12
- extractBsonObjects,
13
- extractJsonLines,
14
- SimpleAsyncIterator
15
- } from '../../../utils/stream_transform.js';
16
- import { EventIterator } from 'event-iterator';
17
- import type { Queue } from 'event-iterator/lib/event-iterator.js';
18
-
19
- export type BSONImplementation = typeof BSON;
20
-
21
- export type RemoteConnector = {
22
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
23
- invalidateCredentials?: () => void;
24
- };
25
-
26
- const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
27
- const POWERSYNC_JS_VERSION = PACKAGE.version;
28
-
29
- const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
30
- const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
31
-
32
- // Keep alive message is sent every period
33
- const KEEP_ALIVE_MS = 20_000;
34
-
35
- // One message of any type must be received in this period.
36
- const SOCKET_TIMEOUT_MS = 30_000;
37
-
38
- // One keepalive message must be received in this period.
39
- // If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed
40
- // significantly. Therefore this is longer than the socket timeout.
41
- const KEEP_ALIVE_LIFETIME_MS = 90_000;
42
-
43
- export const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
44
-
45
- export type SyncStreamOptions = {
46
- path: string;
47
- data: StreamingSyncRequest;
48
- headers?: Record<string, string>;
49
- abortSignal: AbortSignal;
50
- fetchOptions?: Request;
51
- };
52
-
53
- export enum FetchStrategy {
54
- /**
55
- * Queues multiple sync events before processing, reducing round-trips.
56
- * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.
57
- */
58
- Buffered = 'buffered',
59
-
60
- /**
61
- * Processes each sync event immediately before requesting the next.
62
- * This reduces processing overhead and improves real-time responsiveness.
63
- */
64
- Sequential = 'sequential'
65
- }
66
-
67
- export type SocketSyncStreamOptions = SyncStreamOptions & {
68
- fetchStrategy: FetchStrategy;
69
- };
70
-
71
- export type FetchImplementation = typeof fetch;
72
-
73
- /**
74
- * Class wrapper for providing a fetch implementation.
75
- * The class wrapper is used to distinguish the fetchImplementation
76
- * option in [AbstractRemoteOptions] from the general fetch method
77
- * which is typeof "function"
78
- */
79
- export class FetchImplementationProvider {
80
- getFetch(): FetchImplementation {
81
- throw new Error('Unspecified fetch implementation');
82
- }
83
- }
84
-
85
- export type AbstractRemoteOptions = {
86
- /**
87
- * Transforms the PowerSync base URL which might contain
88
- * `http(s)://` to the corresponding WebSocket variant
89
- * e.g. `ws(s)://`
90
- */
91
- socketUrlTransformer: (url: string) => string;
92
-
93
- /**
94
- * Optionally provide the fetch implementation to use.
95
- * Note that this usually needs to be bound to the global scope.
96
- * Binding should be done before passing here.
97
- */
98
- fetchImplementation: FetchImplementation | FetchImplementationProvider;
99
-
100
- /**
101
- * Optional options to pass directly to all `fetch` calls.
102
- *
103
- * This can include fields such as `dispatcher` (e.g. for proxy support),
104
- * `cache`, or any other fetch-compatible options.
105
- */
106
- fetchOptions?: {};
107
- };
108
-
109
- export const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions = {
110
- socketUrlTransformer: (url) =>
111
- url.replace(/^https?:\/\//, function (match) {
112
- return match === 'https://' ? 'wss://' : 'ws://';
113
- }),
114
- fetchImplementation: new FetchImplementationProvider(),
115
- fetchOptions: {}
116
- };
117
-
118
- export abstract class AbstractRemote {
119
- protected credentials: PowerSyncCredentials | null = null;
120
- protected options: AbstractRemoteOptions;
121
-
122
- constructor(
123
- protected connector: RemoteConnector,
124
- protected logger: ILogger = DEFAULT_REMOTE_LOGGER,
125
- options?: Partial<AbstractRemoteOptions>
126
- ) {
127
- this.options = {
128
- ...DEFAULT_REMOTE_OPTIONS,
129
- ...(options ?? {})
130
- };
131
- }
132
-
133
- /**
134
- * @returns a fetch implementation (function)
135
- * which can be called to perform fetch requests
136
- */
137
- get fetch(): FetchImplementation {
138
- const { fetchImplementation } = this.options;
139
- return fetchImplementation instanceof FetchImplementationProvider
140
- ? fetchImplementation.getFetch()
141
- : fetchImplementation;
142
- }
143
-
144
- /**
145
- * Get credentials currently cached, or fetch new credentials if none are
146
- * available.
147
- *
148
- * These credentials may have expired already.
149
- */
150
- async getCredentials(): Promise<PowerSyncCredentials | null> {
151
- if (this.credentials) {
152
- return this.credentials;
153
- }
154
-
155
- return this.prefetchCredentials();
156
- }
157
-
158
- /**
159
- * Fetch a new set of credentials and cache it.
160
- *
161
- * Until this call succeeds, `getCredentials` will still return the
162
- * old credentials.
163
- *
164
- * This may be called before the current credentials have expired.
165
- */
166
- async prefetchCredentials() {
167
- this.credentials = await this.fetchCredentials();
168
-
169
- return this.credentials;
170
- }
171
-
172
- /**
173
- * Get credentials for PowerSync.
174
- *
175
- * This should always fetch a fresh set of credentials - don't use cached
176
- * values.
177
- */
178
- async fetchCredentials() {
179
- const credentials = await this.connector.fetchCredentials();
180
- if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
181
- throw new Error(
182
- `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
183
- );
184
- }
185
-
186
- return credentials;
187
- }
188
-
189
- /***
190
- * Immediately invalidate credentials.
191
- *
192
- * This may be called when the current credentials have expired.
193
- */
194
- invalidateCredentials() {
195
- this.credentials = null;
196
- this.connector.invalidateCredentials?.();
197
- }
198
-
199
- getUserAgent() {
200
- return `powersync-js/${POWERSYNC_JS_VERSION}`;
201
- }
202
-
203
- protected async buildRequest(path: string) {
204
- const credentials = await this.getCredentials();
205
- if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
206
- throw new Error('PowerSync endpoint not configured');
207
- } else if (credentials?.token == null || credentials?.token == '') {
208
- const error: any = new Error(`Not signed in`);
209
- error.status = 401;
210
- throw error;
211
- }
212
-
213
- const userAgent = this.getUserAgent();
214
-
215
- return {
216
- url: credentials.endpoint + path,
217
- headers: {
218
- 'content-type': 'application/json',
219
- Authorization: `Token ${credentials.token}`,
220
- 'x-user-agent': userAgent
221
- }
222
- };
223
- }
224
-
225
- async post(path: string, data: any, headers: Record<string, string> = {}): Promise<any> {
226
- const request = await this.buildRequest(path);
227
- const res = await this.fetch(request.url, {
228
- method: 'POST',
229
- headers: {
230
- ...headers,
231
- ...request.headers
232
- },
233
- body: JSON.stringify(data)
234
- });
235
-
236
- if (res.status === 401) {
237
- this.invalidateCredentials();
238
- }
239
-
240
- if (!res.ok) {
241
- throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
242
- }
243
-
244
- return res.json();
245
- }
246
-
247
- async get(path: string, headers?: Record<string, string>): Promise<any> {
248
- const request = await this.buildRequest(path);
249
- const res = await this.fetch(request.url, {
250
- method: 'GET',
251
- headers: {
252
- ...headers,
253
- ...request.headers
254
- }
255
- });
256
-
257
- if (res.status === 401) {
258
- this.invalidateCredentials();
259
- }
260
-
261
- if (!res.ok) {
262
- throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
263
- }
264
-
265
- return res.json();
266
- }
267
-
268
- /**
269
- * Provides a BSON implementation. The import nature of this varies depending on the platform
270
- */
271
- abstract getBSON(): Promise<BSONImplementation>;
272
-
273
- /**
274
- * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
275
- * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
276
- */
277
- createTextDecoder(): TextDecoder {
278
- return new TextDecoder();
279
- }
280
-
281
- protected createSocket(url: string): WebSocket {
282
- return new WebSocket(url);
283
- }
284
-
285
- /**
286
- * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
287
- *
288
- * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
289
- *
290
- * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
291
- * (required for compatibility with older sync services).
292
- */
293
- async socketStreamRaw(
294
- options: SocketSyncStreamOptions,
295
- bson?: typeof BSON
296
- ): Promise<SimpleAsyncIterator<Uint8Array>> {
297
- const { path, fetchStrategy = FetchStrategy.Buffered } = options;
298
- const mimeType = bson == null ? 'application/json' : 'application/bson';
299
-
300
- function toBuffer(js: any): Buffer {
301
- let contents: any;
302
- if (bson != null) {
303
- contents = bson.serialize(js);
304
- } else {
305
- contents = JSON.stringify(js);
306
- }
307
-
308
- return Buffer.from(contents);
309
- }
310
-
311
- const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
312
- const request = await this.buildRequest(path);
313
- const url = this.options.socketUrlTransformer(request.url);
314
-
315
- // Add the user agent in the setup payload - we can't set custom
316
- // headers with websockets on web. The browser userAgent is however added
317
- // automatically as a header.
318
- const userAgent = this.getUserAgent();
319
-
320
- // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
321
- // to abort the connection.
322
- let pendingSocket: WebSocket | null = null;
323
- let keepAliveTimeout: any;
324
- let rsocket: RSocket | null = null;
325
- let queue: Queue<Uint8Array> | null = null;
326
- let didClose = false;
327
-
328
- const abortRequest = () => {
329
- if (didClose) {
330
- return;
331
- }
332
- didClose = true;
333
-
334
- clearTimeout(keepAliveTimeout);
335
-
336
- if (pendingSocket) {
337
- pendingSocket.close();
338
- }
339
-
340
- if (rsocket) {
341
- rsocket.close();
342
- }
343
-
344
- if (queue) {
345
- queue.stop();
346
- }
347
- };
348
-
349
- // Handle upstream abort
350
- if (options.abortSignal.aborted) {
351
- throw new AbortOperation('Connection request aborted');
352
- } else {
353
- options.abortSignal.addEventListener('abort', abortRequest);
354
- }
355
-
356
- const resetTimeout = () => {
357
- clearTimeout(keepAliveTimeout);
358
- keepAliveTimeout = setTimeout(() => {
359
- this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
360
- abortRequest();
361
- }, SOCKET_TIMEOUT_MS);
362
- };
363
- resetTimeout();
364
-
365
- const connector = new RSocketConnector({
366
- transport: new WebsocketClientTransport({
367
- url,
368
- wsCreator: (url) => {
369
- const socket = (pendingSocket = this.createSocket(url));
370
-
371
- socket.addEventListener('message', () => {
372
- resetTimeout();
373
- });
374
- return socket;
375
- }
376
- }),
377
- setup: {
378
- keepAlive: KEEP_ALIVE_MS,
379
- lifetime: KEEP_ALIVE_LIFETIME_MS,
380
- dataMimeType: mimeType,
381
- metadataMimeType: mimeType,
382
- payload: {
383
- data: null,
384
- metadata: toBuffer({
385
- token: request.headers.Authorization,
386
- user_agent: userAgent
387
- })
388
- }
389
- }
390
- });
391
-
392
- try {
393
- rsocket = await connector.connect();
394
- // The connection is established, we no longer need to monitor the initial timeout
395
- pendingSocket = null;
396
- } catch (ex) {
397
- this.logger.error(`Failed to connect WebSocket`, ex);
398
- abortRequest();
399
-
400
- throw ex;
401
- }
402
-
403
- resetTimeout();
404
-
405
- // Helps to prevent double close scenarios
406
- rsocket.onClose(() => (rsocket = null));
407
-
408
- return await new Promise((resolve, reject) => {
409
- let connectionEstablished = false;
410
- let pendingEventsCount = syncQueueRequestSize;
411
- let paused = false;
412
- let res: Requestable | null = null;
413
-
414
- function requestMore() {
415
- const delta = syncQueueRequestSize - pendingEventsCount;
416
- if (!paused && delta > 0) {
417
- res?.request(delta);
418
- pendingEventsCount = syncQueueRequestSize;
419
- }
420
- }
421
-
422
- const events = new EventIterator<Uint8Array>(
423
- (q) => {
424
- queue = q;
425
-
426
- q.on('highWater', () => (paused = true));
427
- q.on('lowWater', () => {
428
- paused = false;
429
- requestMore();
430
- });
431
- },
432
- { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER }
433
- )[Symbol.asyncIterator]();
434
-
435
- res = rsocket!.requestStream(
436
- {
437
- data: toBuffer(options.data),
438
- metadata: toBuffer({
439
- path
440
- })
441
- },
442
- syncQueueRequestSize, // The initial N amount
443
- {
444
- onError: (e) => {
445
- if (e.message.includes('PSYNC_')) {
446
- if (e.message.includes('PSYNC_S21')) {
447
- this.invalidateCredentials();
448
- }
449
- } else {
450
- // Possible that connection is with an older service, always invalidate to be safe
451
- if (e.message !== 'Closed. ') {
452
- this.invalidateCredentials();
453
- }
454
- }
455
-
456
- // Don't log closed as an error
457
- if (e.message !== 'Closed. ') {
458
- this.logger.error(e);
459
- }
460
- // RSocket will close the RSocket stream automatically
461
- // Close the downstream stream as well - this will close the RSocket connection and WebSocket
462
- abortRequest();
463
- // Handles cases where the connection failed e.g. auth error or connection error
464
- if (!connectionEstablished) {
465
- reject(e);
466
- }
467
- },
468
- onNext: (payload) => {
469
- // The connection is active
470
- if (!connectionEstablished) {
471
- connectionEstablished = true;
472
- resolve(events);
473
- }
474
- const { data } = payload;
475
-
476
- if (data) {
477
- queue!.push(data);
478
- }
479
-
480
- // Less events are now pending
481
- pendingEventsCount--;
482
-
483
- // Request another event (unless the downstream consumer is paused).
484
- requestMore();
485
- },
486
- onComplete: () => {
487
- abortRequest(); // this will also emit a done event
488
- },
489
- onExtension: () => {}
490
- }
491
- );
492
- });
493
- }
494
-
495
- /**
496
- * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
497
- * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
498
- *
499
- * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
500
- */
501
- protected get supportsStreamingBinaryResponses(): boolean {
502
- return true;
503
- }
504
-
505
- /**
506
- * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
507
- * async iterator of byte blobs.
508
- *
509
- * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
510
- */
511
- protected async fetchStreamRaw(
512
- options: SyncStreamOptions
513
- ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
514
- const { data, path, headers, abortSignal } = options;
515
- const request = await this.buildRequest(path);
516
-
517
- /**
518
- * This abort controller will abort pending fetch requests.
519
- * If the request has resolved, it will be used to close the readable stream.
520
- * Which will cancel the network request.
521
- *
522
- * This nested controller is required since:
523
- * Aborting the active fetch request while it is being consumed seems to throw
524
- * an unhandled exception on the window level.
525
- */
526
- if (abortSignal.aborted) {
527
- throw new AbortOperation('Abort request received before making fetchStreamRaw request');
528
- }
529
-
530
- const controller = new AbortController();
531
- let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
532
- abortSignal.addEventListener('abort', () => {
533
- const reason =
534
- abortSignal.reason ??
535
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
536
-
537
- if (reader == null) {
538
- // Only abort via the abort controller if the request has not resolved yet
539
- controller.abort(reason);
540
- } else {
541
- reader.cancel(reason).catch(() => {
542
- // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
543
- // ignore it here.
544
- });
545
- }
546
- });
547
-
548
- let res: Response;
549
- let responseIsBson = false;
550
- try {
551
- const ndJson = 'application/x-ndjson';
552
- const bson = 'application/vnd.powersync.bson-stream';
553
-
554
- res = await this.fetch(request.url, {
555
- method: 'POST',
556
- headers: {
557
- ...headers,
558
- ...request.headers,
559
- accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
560
- },
561
- body: JSON.stringify(data),
562
- signal: controller.signal,
563
- cache: 'no-store',
564
- ...(this.options.fetchOptions ?? {}),
565
- ...options.fetchOptions
566
- });
567
-
568
- if (!res.ok || !res.body) {
569
- const text = await res.text();
570
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
571
- const error: any = new Error(`HTTP ${res.statusText}: ${text}`);
572
- error.status = res.status;
573
- throw error;
574
- }
575
-
576
- const contentType = res.headers.get('content-type');
577
- responseIsBson = contentType == bson;
578
- } catch (ex) {
579
- if (ex.name == 'AbortError') {
580
- throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
581
- }
582
- throw ex;
583
- }
584
-
585
- reader = res.body.getReader();
586
-
587
- const stream: SimpleAsyncIterator<Uint8Array> = {
588
- next: async () => {
589
- if (controller.signal.aborted) {
590
- return doneResult;
591
- }
592
-
593
- try {
594
- return await reader.read();
595
- } catch (ex) {
596
- if (controller.signal.aborted) {
597
- // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
598
- // things working as intended, we can return a done event and consider the exception handled.
599
- return doneResult;
600
- }
601
-
602
- throw ex;
603
- }
604
- }
605
- };
606
-
607
- return { isBson: responseIsBson, stream };
608
- }
609
-
610
- /**
611
- * Posts a `/sync/stream` request.
612
- *
613
- * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
614
- * {@link Uint8Array}s.
615
- */
616
- async fetchStream(options: SyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array | string>> {
617
- const { isBson, stream } = await this.fetchStreamRaw(options);
618
- if (isBson) {
619
- return extractBsonObjects(stream);
620
- } else {
621
- return extractJsonLines(stream, this.createTextDecoder());
622
- }
623
- }
624
- }