@powersync/shared-internals 0.0.0-dev-20260827080125

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,388 @@
1
+ import { type fetch } from 'cross-fetch';
2
+ import { FetchStrategy, PowerSyncCredentials, LogLevels, PowerSyncLogger } from '@powersync/common';
3
+
4
+ import { AbortOperation } from '../../../utils/AbortOperation.js';
5
+ import {
6
+ doneResult,
7
+ extractBsonObjects,
8
+ extractJsonLines,
9
+ SimpleAsyncIterator
10
+ } from '../../../utils/stream_transform.js';
11
+ import { WebSocketSupport, WebSocketSyncStreamPlatform } from './WebSocketSupport.js';
12
+ import { EventQueue } from '../../../utils/async.js';
13
+ import { POWERSYNC_JS_VERSION } from '../../../version.js';
14
+
15
+ /**
16
+ * @internal
17
+ */
18
+ export type RemoteConnector = {
19
+ fetchCredentials: () => Promise<PowerSyncCredentials | null>;
20
+ invalidateCredentials?: () => void;
21
+ };
22
+
23
+ const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
24
+
25
+ const webSocketPlatform: WebSocketSyncStreamPlatform = {
26
+ LogLevels,
27
+ EventQueue,
28
+ AbortOperation
29
+ };
30
+
31
+ /**
32
+ * @internal
33
+ */
34
+ export type SyncStreamOptions = {
35
+ path: string;
36
+ data: unknown;
37
+ abortSignal: AbortSignal;
38
+ };
39
+
40
+ /**
41
+ * @internal
42
+ */
43
+ export type FetchImplementation = typeof fetch;
44
+
45
+ export function lazyFetchImplementation(getFetch: () => FetchImplementation): FetchImplementation {
46
+ let resolved: FetchImplementation;
47
+
48
+ return (request) => {
49
+ const fetch = (resolved ??= getFetch());
50
+ return fetch(request);
51
+ };
52
+ }
53
+
54
+ export interface FetchOptions {
55
+ resource: string;
56
+ request: RequestInit;
57
+ expectStreamingResponse: boolean;
58
+ }
59
+
60
+ /**
61
+ * @internal
62
+ */
63
+ export interface SocketSyncStreamOptions {
64
+ path: string;
65
+ fetchStrategy: FetchStrategy;
66
+ abortSignal: AbortSignal;
67
+ data: unknown;
68
+ }
69
+
70
+ export interface PreparedRequest {
71
+ url: string;
72
+ headers: Record<string, string>;
73
+ userAgent: string;
74
+ path: string;
75
+ }
76
+
77
+ /**
78
+ * @internal
79
+ */
80
+ export abstract class AbstractRemote {
81
+ protected credentials: PowerSyncCredentials | null = null;
82
+
83
+ constructor(
84
+ protected connector: RemoteConnector,
85
+ readonly logger: PowerSyncLogger
86
+ ) {}
87
+
88
+ /**
89
+ * Sends a request using a suitable `fetch` implementation for the current platform.
90
+ */
91
+ protected abstract fetch(options: FetchOptions): Promise<Response>;
92
+
93
+ /**
94
+ * Get credentials currently cached, or fetch new credentials if none are
95
+ * available.
96
+ *
97
+ * These credentials may have expired already.
98
+ */
99
+ async getCredentials(): Promise<PowerSyncCredentials | null> {
100
+ if (this.credentials) {
101
+ return this.credentials;
102
+ }
103
+
104
+ return this.prefetchCredentials();
105
+ }
106
+
107
+ /**
108
+ * Fetch a new set of credentials and cache it.
109
+ *
110
+ * Until this call succeeds, `getCredentials` will still return the
111
+ * old credentials.
112
+ *
113
+ * This may be called before the current credentials have expired.
114
+ */
115
+ async prefetchCredentials() {
116
+ this.credentials = await this.fetchCredentials();
117
+
118
+ return this.credentials;
119
+ }
120
+
121
+ /**
122
+ * Get credentials for PowerSync.
123
+ *
124
+ * This should always fetch a fresh set of credentials - don't use cached
125
+ * values.
126
+ */
127
+ async fetchCredentials() {
128
+ const credentials = await this.connector.fetchCredentials();
129
+ if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
130
+ throw new Error(
131
+ `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
132
+ );
133
+ }
134
+
135
+ return credentials;
136
+ }
137
+
138
+ /***
139
+ * Immediately invalidate credentials.
140
+ *
141
+ * This may be called when the current credentials have expired.
142
+ */
143
+ invalidateCredentials() {
144
+ this.credentials = null;
145
+ this.connector.invalidateCredentials?.();
146
+ }
147
+
148
+ getUserAgent() {
149
+ return `powersync-js/${POWERSYNC_JS_VERSION}`;
150
+ }
151
+
152
+ protected async buildRequest(path: string): Promise<PreparedRequest> {
153
+ const credentials = await this.getCredentials();
154
+ if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
155
+ throw new Error('PowerSync endpoint not configured');
156
+ } else if (credentials?.token == null || credentials?.token == '') {
157
+ const error: any = new Error(`Not signed in`);
158
+ error.status = 401;
159
+ throw error;
160
+ }
161
+
162
+ const userAgent = this.getUserAgent();
163
+
164
+ return {
165
+ url: credentials.endpoint + path,
166
+ headers: {
167
+ 'content-type': 'application/json',
168
+ Authorization: `Token ${credentials.token}`,
169
+ 'x-user-agent': userAgent
170
+ },
171
+ userAgent,
172
+ path
173
+ };
174
+ }
175
+
176
+ async fetchAndDecodeJson({
177
+ path,
178
+ method = 'GET',
179
+ headers,
180
+ body,
181
+ signal
182
+ }: {
183
+ path: string;
184
+ method?: string;
185
+ headers?: Record<string, string>;
186
+ body?: string;
187
+ signal?: AbortSignal;
188
+ }): Promise<any> {
189
+ const request = await this.buildRequest(path);
190
+ const res = await this.fetch({
191
+ resource: request.url,
192
+ request: {
193
+ method,
194
+ headers: {
195
+ ...headers,
196
+ ...request.headers
197
+ },
198
+ body,
199
+ signal
200
+ },
201
+ expectStreamingResponse: false
202
+ });
203
+
204
+ if (res.status === 401) {
205
+ this.invalidateCredentials();
206
+ }
207
+
208
+ if (!res.ok) {
209
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
210
+ }
211
+
212
+ return res.json();
213
+ }
214
+
215
+ /**
216
+ * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
217
+ * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
218
+ */
219
+ createTextDecoder(): TextDecoder {
220
+ return new TextDecoder();
221
+ }
222
+
223
+ createSocket(url: string): WebSocket {
224
+ return new WebSocket(url);
225
+ }
226
+
227
+ /**
228
+ * Loads `@powersync/shared-internals/websockets`.
229
+ *
230
+ * We prefer to load that as a lazy module with a dynamic `import()` expressions on most platforms. An exception is
231
+ * React Native, where WebSocket support is preferred and we want to load this directly.
232
+ */
233
+ protected abstract loadWebSocketSupport(platform: WebSocketSyncStreamPlatform): Promise<WebSocketSupport>;
234
+
235
+ /**
236
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
237
+ *
238
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
239
+ */
240
+ async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
241
+ const support = await this.loadWebSocketSupport(webSocketPlatform);
242
+
243
+ const request = await this.buildRequest(options.path);
244
+ request.url = request.url.replace(/^https?:\/\//, function (match) {
245
+ return match === 'https://' ? 'wss://' : 'ws://';
246
+ });
247
+ const { fetchStrategy = FetchStrategy.Buffered, abortSignal, data } = options;
248
+
249
+ return await support.webSocketSyncStream({
250
+ remote: this,
251
+ buffered: fetchStrategy == FetchStrategy.Buffered,
252
+ abortSignal,
253
+ requestPayload: data,
254
+ request
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
260
+ * async iterator of byte blobs.
261
+ *
262
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
263
+ */
264
+ protected async fetchStreamRaw(
265
+ options: SyncStreamOptions
266
+ ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
267
+ const { data, path, abortSignal } = options;
268
+ const request = await this.buildRequest(path);
269
+
270
+ /**
271
+ * This abort controller will abort pending fetch requests.
272
+ * If the request has resolved, it will be used to close the readable stream.
273
+ * Which will cancel the network request.
274
+ *
275
+ * This nested controller is required since:
276
+ * Aborting the active fetch request while it is being consumed seems to throw
277
+ * an unhandled exception on the window level.
278
+ */
279
+ if (abortSignal.aborted) {
280
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
281
+ }
282
+
283
+ const controller = new AbortController();
284
+ let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
285
+ abortSignal.addEventListener('abort', () => {
286
+ const reason =
287
+ abortSignal.reason ??
288
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
289
+
290
+ if (reader == null) {
291
+ // Only abort via the abort controller if the request has not resolved yet
292
+ controller.abort(reason);
293
+ } else {
294
+ reader.cancel(reason).catch(() => {
295
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
296
+ // ignore it here.
297
+ });
298
+ }
299
+ });
300
+
301
+ let res: Response;
302
+ let responseIsBson = false;
303
+ try {
304
+ const ndJson = 'application/x-ndjson';
305
+ const bson = 'application/vnd.powersync.bson-stream';
306
+
307
+ res = await this.fetch({
308
+ resource: request.url,
309
+ request: {
310
+ method: 'POST',
311
+ headers: {
312
+ ...request.headers,
313
+ accept: `${bson};q=0.9,${ndJson};q=0.8`
314
+ },
315
+ body: JSON.stringify(data),
316
+ signal: controller.signal,
317
+ cache: 'no-store'
318
+ },
319
+ expectStreamingResponse: true
320
+ });
321
+
322
+ if (!res.ok || !res.body) {
323
+ const text = await res.text();
324
+ const error: any = new Error(`HTTP ${res.statusText}: ${text}`);
325
+ error.status = res.status;
326
+
327
+ this.logger.log({
328
+ level: LogLevels.error,
329
+ message: `Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`,
330
+ error
331
+ });
332
+
333
+ if (res.status === 401) {
334
+ this.invalidateCredentials();
335
+ }
336
+
337
+ throw error;
338
+ }
339
+
340
+ const contentType = res.headers.get('content-type');
341
+ responseIsBson = contentType == bson;
342
+ } catch (ex: any) {
343
+ if (ex.name == 'AbortError') {
344
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
345
+ }
346
+ throw ex;
347
+ }
348
+
349
+ reader = res.body.getReader();
350
+
351
+ const stream: SimpleAsyncIterator<Uint8Array> = {
352
+ next: async () => {
353
+ if (controller.signal.aborted) {
354
+ return doneResult;
355
+ }
356
+
357
+ try {
358
+ return await reader.read();
359
+ } catch (ex) {
360
+ if (controller.signal.aborted) {
361
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
362
+ // things working as intended, we can return a done event and consider the exception handled.
363
+ return doneResult;
364
+ }
365
+
366
+ throw ex;
367
+ }
368
+ }
369
+ };
370
+
371
+ return { isBson: responseIsBson, stream };
372
+ }
373
+
374
+ /**
375
+ * Posts a `/sync/stream` request.
376
+ *
377
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
378
+ * `Uint8Array`s.
379
+ */
380
+ async fetchStream(options: SyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array | string>> {
381
+ const { isBson, stream } = await this.fetchStreamRaw(options);
382
+ if (isBson) {
383
+ return extractBsonObjects(stream);
384
+ } else {
385
+ return extractJsonLines(stream, this.createTextDecoder());
386
+ }
387
+ }
388
+ }