@powersync/shared-internals 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/websockets.mjs.map +1 -1
  2. package/dist/websockets.node.mjs.map +1 -1
  3. package/legacy/sync_protocol.d.ts +1 -103
  4. package/lib/client/BasePowerSyncDatabase.js +2 -4
  5. package/lib/client/BasePowerSyncDatabase.js.map +1 -1
  6. package/lib/client/watched/AbstractQueryProcessor.d.ts +5 -0
  7. package/lib/client/watched/AbstractQueryProcessor.js +18 -0
  8. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -1
  9. package/lib/standalone/api.d.ts +63 -0
  10. package/lib/standalone/api.js +17 -0
  11. package/lib/standalone/api.js.map +1 -0
  12. package/lib/standalone/client.d.ts +43 -0
  13. package/lib/standalone/client.js +172 -0
  14. package/lib/standalone/client.js.map +1 -0
  15. package/lib/standalone/client_state.d.ts +30 -0
  16. package/lib/standalone/client_state.js +224 -0
  17. package/lib/standalone/client_state.js.map +1 -0
  18. package/lib/standalone/oplog.d.ts +87 -0
  19. package/lib/standalone/oplog.js +225 -0
  20. package/lib/standalone/oplog.js.map +1 -0
  21. package/lib/standalone/requests.d.ts +22 -0
  22. package/lib/standalone/requests.js +2 -0
  23. package/lib/standalone/requests.js.map +1 -0
  24. package/lib/standalone/sync_protocol.d.ts +91 -0
  25. package/lib/standalone/sync_protocol.js +10 -0
  26. package/lib/standalone/sync_protocol.js.map +1 -0
  27. package/lib/standalone.d.ts +6 -0
  28. package/lib/standalone.js +4 -0
  29. package/lib/standalone.js.map +1 -0
  30. package/lib/utils/stream_transform.js +2 -0
  31. package/lib/utils/stream_transform.js.map +1 -1
  32. package/lib/version.d.ts +1 -1
  33. package/lib/version.js +1 -1
  34. package/package.json +10 -1
  35. package/src/client/BasePowerSyncDatabase.ts +2 -7
  36. package/src/client/watched/AbstractQueryProcessor.ts +19 -0
  37. package/src/standalone/api.ts +75 -0
  38. package/src/standalone/client.ts +216 -0
  39. package/src/standalone/client_state.ts +263 -0
  40. package/src/standalone/oplog.ts +243 -0
  41. package/src/standalone/requests.ts +25 -0
  42. package/src/standalone/sync_protocol.ts +119 -0
  43. package/src/standalone.ts +6 -0
  44. package/src/utils/stream_transform.ts +2 -0
  45. package/src/version.ts +1 -1
@@ -0,0 +1,91 @@
1
+ export type SyncDataBucketJSON = {
2
+ bucket: string;
3
+ has_more?: boolean;
4
+ after?: string;
5
+ next_after?: string;
6
+ data: OplogEntryJSON[];
7
+ };
8
+ export interface OplogEntryJSON {
9
+ checksum: number;
10
+ data?: string;
11
+ object_id?: string;
12
+ object_type?: string;
13
+ op_id: string;
14
+ op: OpTypeJSON;
15
+ subkey?: string;
16
+ }
17
+ export type OpTypeJSON = 'CLEAR' | 'MOVE' | 'PUT' | 'REMOVE';
18
+ /**
19
+ * 64-bit unsigned integer stored as a string in base-10.
20
+ *
21
+ * Not sortable as a string.
22
+ */
23
+ export type OpId = string;
24
+ export interface BucketChecksum {
25
+ bucket: string;
26
+ priority?: number;
27
+ /**
28
+ * 32-bit unsigned hash.
29
+ */
30
+ checksum: number;
31
+ /**
32
+ * Count of operations - informational only.
33
+ */
34
+ count?: number;
35
+ /**
36
+ * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
37
+ * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
38
+ * present.
39
+ */
40
+ subscriptions?: any;
41
+ }
42
+ export interface Checkpoint {
43
+ last_op_id: OpId;
44
+ buckets: BucketChecksum[];
45
+ write_checkpoint?: string;
46
+ streams?: StreamDescription[];
47
+ }
48
+ export interface StreamDescription {
49
+ name: string;
50
+ is_default: boolean;
51
+ errors: StreamSubscriptionError[];
52
+ }
53
+ export interface StreamSubscriptionError {
54
+ /**
55
+ * The index of the subscription in the request's `streams.subscriptions` array, or `default` for errors on a stream
56
+ * included by default.
57
+ */
58
+ subscription: number | 'default';
59
+ message: string;
60
+ }
61
+ export interface StreamingSyncCheckpoint {
62
+ checkpoint: Checkpoint;
63
+ }
64
+ export interface StreamingSyncCheckpointDiff {
65
+ checkpoint_diff: {
66
+ last_op_id: OpId;
67
+ updated_buckets: BucketChecksum[];
68
+ removed_buckets: string[];
69
+ write_checkpoint?: string;
70
+ };
71
+ }
72
+ export interface StreamingSyncDataJSON {
73
+ data: SyncDataBucketJSON;
74
+ }
75
+ export interface StreamingSyncCheckpointComplete {
76
+ checkpoint_complete: {
77
+ last_op_id: OpId;
78
+ };
79
+ }
80
+ export interface StreamingSyncCheckpointPartiallyComplete {
81
+ partial_checkpoint_complete: {
82
+ priority: number;
83
+ last_op_id: OpId;
84
+ };
85
+ }
86
+ export interface StreamingSyncKeepalive {
87
+ /** If specified, token expires in this many seconds. */
88
+ token_expires_in: number;
89
+ }
90
+ export type BucketLine = StreamingSyncCheckpoint | StreamingSyncCheckpointDiff | StreamingSyncDataJSON | StreamingSyncCheckpointComplete | StreamingSyncCheckpointPartiallyComplete;
91
+ export type StreamingSyncLine = BucketLine | StreamingSyncKeepalive;
@@ -0,0 +1,10 @@
1
+ // TypeScript definitions for sync lines sent by the PowerSync service. These aren't used in the implementation of
2
+ // PowerSync SDKs, but we keep them around for:
3
+ //
4
+ // 1. Tests mocking the PowerSync service.
5
+ // 2. The diagnostic app tracking schema updates and bucket sizes by decoding protocol messages.
6
+ // 3. A small standalone client not used in the main SDK.
7
+ //
8
+ // Use 2 should be replaced with the builtin diagnostic collection of the core extension eventually.
9
+ export {};
10
+ //# sourceMappingURL=sync_protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync_protocol.js","sourceRoot":"","sources":["../../src/standalone/sync_protocol.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,+CAA+C;AAC/C,EAAE;AACF,2CAA2C;AAC3C,iGAAiG;AACjG,0DAA0D;AAC1D,EAAE;AACF,oGAAoG"}
@@ -0,0 +1,6 @@
1
+ export type * from './standalone/api.js';
2
+ export type { StreamDescription, StreamSubscriptionError } from './standalone/sync_protocol.js';
3
+ export type { RequestedStreamSubscription, StreamSubscriptionRequest } from './standalone/requests.js';
4
+ export { LocalWriteState } from './standalone/client_state.js';
5
+ export { RestartSyncError, UnexpectedResponseError } from './standalone/api.js';
6
+ export * from './standalone/client.js';
@@ -0,0 +1,4 @@
1
+ export { LocalWriteState } from './standalone/client_state.js';
2
+ export { RestartSyncError, UnexpectedResponseError } from './standalone/api.js';
3
+ export * from './standalone/client.js';
4
+ //# sourceMappingURL=standalone.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standalone.js","sourceRoot":"","sources":["../src/standalone.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,cAAc,wBAAwB,CAAC"}
@@ -130,6 +130,8 @@ export function extractJsonLines(source, decoder) {
130
130
  }
131
131
  const { done, value } = await source.next();
132
132
  if (done) {
133
+ // Flush bytes the decoder may still be buffering, e.g. if the stream ended in the middle of a character.
134
+ buffer += decoder.decode();
133
135
  const remaining = buffer.trim();
134
136
  if (remaining.length != 0) {
135
137
  isFinalEvent = true;
@@ -1 +1 @@
1
- {"version":3,"file":"stream_transform.js","sourceRoot":"","sources":["../../src/utils/stream_transform.ts"],"names":[],"mappings":"AAYA,MAAM,CAAC,MAAM,UAAU,GAA8B,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;AAEtF,MAAM,UAAU,WAAW,CAAI,KAAQ;IACrC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAChC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,GAAG,CAAS,MAA+B,EAAE,GAAuB;IAClF,OAAO;QACL,IAAI,EAAE,KAAK,IAAI,EAAE;YACf,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC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AAU,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;wBAC5D,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
package/lib/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const POWERSYNC_JS_VERSION = "1.5.0";
1
+ export declare const POWERSYNC_JS_VERSION = "1.6.0";
package/lib/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.
2
2
  // The update happens in the changesets PR, before the package is built.
3
- export const POWERSYNC_JS_VERSION = '1.5.0';
3
+ export const POWERSYNC_JS_VERSION = '1.6.0';
4
4
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/shared-internals",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -12,6 +12,10 @@
12
12
  "types": "./lib/index.d.ts",
13
13
  "default": "./lib/index.js"
14
14
  },
15
+ "./standalone": {
16
+ "types": "./lib/standalone.d.ts",
17
+ "default": "./lib/standalone.js"
18
+ },
15
19
  "./websockets": {
16
20
  "types": "./lib/client/sync/stream/WebSocketSupport.d.ts",
17
21
  "node": "./dist/websockets.node.mjs",
@@ -40,6 +44,11 @@
40
44
  "peerDependencies": {
41
45
  "@powersync/common": "^2.5.0"
42
46
  },
47
+ "peerDependenciesMeta": {
48
+ "@powersync/common": {
49
+ "optional": true
50
+ }
51
+ },
43
52
  "devDependencies": {
44
53
  "@rollup/plugin-commonjs": "^29.0.0",
45
54
  "@rollup/plugin-inject": "^5.0.5",
@@ -716,10 +716,7 @@ SELECT * FROM crud_entries;
716
716
  }
717
717
 
718
718
  watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void {
719
- const {
720
- onResult,
721
- onError = (e: Error) => this.logger.log({ level: LogLevels.error, message: 'Error in watch', error: e })
722
- } = handler ?? {};
719
+ const { onResult, onError } = handler ?? {};
723
720
  if (!onResult) {
724
721
  throw new Error('onResult is required');
725
722
  }
@@ -754,9 +751,7 @@ SELECT * FROM crud_entries;
754
751
  }
755
752
  onResult(data);
756
753
  },
757
- onError: (error) => {
758
- onError(error);
759
- }
754
+ onError
760
755
  });
761
756
 
762
757
  signal?.addEventListener('abort', () => {
@@ -132,12 +132,31 @@ export abstract class AbstractQueryProcessor<
132
132
  */
133
133
  protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
134
134
 
135
+ /**
136
+ * Whether any of the registered listeners handles errors itself.
137
+ * These are the listeners which {@link AbstractQueryProcessor.updateState} reports errors to.
138
+ */
139
+ protected get hasErrorListener(): boolean {
140
+ return (this.listenerCounts[WatchedQueryListenerEvent.ON_ERROR] ?? 0) > 0;
141
+ }
142
+
135
143
  protected async updateState(update: Partial<MutableWatchedQueryState<Data>>) {
136
144
  if (this._closed) {
137
145
  return;
138
146
  }
139
147
 
140
148
  if (typeof update.error !== 'undefined') {
149
+ // `error: null` is used to clear a previous error, which should not be logged.
150
+ if (update.error && !this.hasErrorListener) {
151
+ // Errors are also reported on the query state, but that is easy to miss. Logging makes failures such as
152
+ // invalid SQL discoverable without extra wiring. Listeners which registered an `onError` handler report
153
+ // errors themselves, so logging here would only duplicate their output.
154
+ this.options.db.logger.log({
155
+ level: LogLevels.error,
156
+ message: 'Error in watched query',
157
+ error: update.error
158
+ });
159
+ }
141
160
  await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error!));
142
161
  // An error always stops for the current fetching state
143
162
  update.isFetching = false;
@@ -0,0 +1,75 @@
1
+ import { StreamSubscriptionRequest } from './requests.js';
2
+ import { StreamDescription, StreamingSyncKeepalive } from './sync_protocol.js';
3
+
4
+ export interface DownloadChanges {
5
+ updatedRows: Map<string, Map<string, Record<string, unknown> | null>>;
6
+ }
7
+
8
+ export type DownloadEvent =
9
+ // Response resolved, can mark as connected.
10
+ | { type: 'headersReceived' }
11
+ // Received an initial checkpoint describing the resolved sync streams (including errors for individual
12
+ // subscriptions).
13
+ | { type: 'resolvedStreams'; streams: StreamDescription[] }
14
+ // Local materialized rows have changed. The priority is set for partial checkpoints, and absent for complete ones.
15
+ | { type: 'rows'; changes: DownloadChanges; priority?: number }
16
+ // Could not apply server-side changes due to local data that has not yet been uploaded.
17
+ | { type: 'blockedDueToLocalData' }
18
+ // Could not apply server-side changes due to local mutations that have been uploaded, but not acknowledged yet.
19
+ | { type: 'waitingForCheckpoint'; target: bigint; received: bigint | null | undefined }
20
+ // Received a periodic keepalive notification from the service.
21
+ | { type: 'keepalive'; keepalive: StreamingSyncKeepalive };
22
+
23
+ export interface ServiceRequest {
24
+ /**
25
+ * The PowerSync Service to connect to.
26
+ */
27
+ endpoint: string;
28
+
29
+ /**
30
+ * The authentication token to use for the request.
31
+ */
32
+ token: string;
33
+
34
+ /**
35
+ * A random client id.
36
+ */
37
+ clientId: string;
38
+
39
+ /**
40
+ * An optional abort signal to abort the request.
41
+ */
42
+ signal?: AbortSignal;
43
+ }
44
+
45
+ /**
46
+ * Requests a checkpoint from the PowerSync service.
47
+ */
48
+ export interface CheckpointRequest extends ServiceRequest {
49
+ /** The local checkpoint number to reconcile with the service. */
50
+ checkpoint: bigint;
51
+ }
52
+
53
+ export interface SyncRequest extends ServiceRequest {
54
+ parameters?: Record<string, unknown>;
55
+ streams?: StreamSubscriptionRequest;
56
+ metadata?: Record<string, string>;
57
+ }
58
+
59
+ export class UnexpectedResponseError extends Error {
60
+ constructor(
61
+ readonly statusCode: number,
62
+ readonly body: string
63
+ ) {
64
+ super(`Unexpected response from PowerSync service: ${statusCode}`);
65
+ }
66
+ }
67
+
68
+ export class RestartSyncError extends Error {
69
+ constructor(
70
+ message: string,
71
+ readonly clearLocal = false
72
+ ) {
73
+ super(message);
74
+ }
75
+ }
@@ -0,0 +1,216 @@
1
+ import {
2
+ CheckpointRequest,
3
+ DownloadEvent,
4
+ RestartSyncError,
5
+ ServiceRequest,
6
+ SyncRequest,
7
+ UnexpectedResponseError
8
+ } from './api.js';
9
+ import { DownloadClientState, LocalWriteState } from './client_state.js';
10
+ import { RowKey } from './oplog.js';
11
+ import { StreamingSyncLine } from './sync_protocol.js';
12
+ import { extractJsonLines } from '../utils/stream_transform.js';
13
+ import { POWERSYNC_JS_VERSION } from '../version.js';
14
+
15
+ /**
16
+ * A small and simple PowerSync client built without SQLite.
17
+ *
18
+ * This client has no offline support, doesn't coordinate anything across tabs, doesn't automatically reconnect and
19
+ * doesn't seed checkpoint requests. It also uses recent JavaScript features, so it doesn't work with React Native.
20
+ *
21
+ * It is intended as a low-level internal building block to build non-SQLite PowerSync client plugging in to an existing
22
+ * state management framework like TanStack DB.
23
+ */
24
+ export class PowerSyncClient {
25
+ #state: DownloadClientState;
26
+ #localWrites: LocalWriteState;
27
+ #fetch: typeof fetch;
28
+ readonly #notifyUploadComplete = new Set<() => void>();
29
+
30
+ constructor({ localWrites, fetch = globalThis.fetch.bind(globalThis) }: ClientOptions) {
31
+ this.#localWrites = localWrites;
32
+ this.#state = new DownloadClientState(localWrites);
33
+ this.#fetch = fetch;
34
+ }
35
+
36
+ #resolveUri(request: ServiceRequest, path: string): URL {
37
+ const base = request.endpoint.endsWith('/') ? request.endpoint : request.endpoint + '/';
38
+ const url = URL.parse(path, base);
39
+ if (url == null) throw new Error(`Invalid service endpoint: ${request.endpoint}`);
40
+ return url;
41
+ }
42
+
43
+ #defaultHeaders(request: ServiceRequest): Record<string, string> {
44
+ return {
45
+ 'X-User-Agent': userAgent, // We can't set User-Agent on the web, the service respects this header
46
+ 'Content-Type': applicationJson,
47
+ Authorization: `Token ${request.token}`
48
+ } satisfies HeadersInit;
49
+ }
50
+
51
+ async #checkResponse(response: Response): Promise<void> {
52
+ if (response.status == 200) {
53
+ return;
54
+ }
55
+
56
+ const text = await response.text();
57
+ throw new UnexpectedResponseError(response.status, text);
58
+ }
59
+
60
+ /**
61
+ * Retries applying the last fully-received checkpoint on the active {@link streamingSync} iteration, emitting the
62
+ * resulting events from it.
63
+ *
64
+ * This should be called after updating {@link LocalWriteState}: Since checkpoint requests and the sync stream are
65
+ * independent requests, a checkpoint including the requested write checkpoint may have been received (and either
66
+ * applied or rejected) before {@link requestCheckpoint} completes.
67
+ */
68
+ retryCheckpoint() {
69
+ for (const listener of this.#notifyUploadComplete) listener();
70
+ }
71
+
72
+ markUpdated(table: string, id: string) {
73
+ this.#state.addToUpdatedRows(new RowKey(table, id));
74
+ }
75
+
76
+ /**
77
+ * Posts a checkpoint request to the PowerSync service, returning the created checkpoint id.
78
+ */
79
+ async requestCheckpoint(request: CheckpointRequest): Promise<bigint> {
80
+ const response = await this.#fetch(this.#resolveUri(request, 'sync/checkpoint-request'), {
81
+ method: 'POST',
82
+ signal: request.signal,
83
+ body: JSON.stringify({
84
+ client_id: request.clientId,
85
+ checkpoint_request_id: String(request.checkpoint)
86
+ }),
87
+ headers: this.#defaultHeaders(request)
88
+ });
89
+
90
+ await this.#checkResponse(response);
91
+ const json = await response.json();
92
+ return BigInt(json.data.checkpoint_request_id);
93
+ }
94
+
95
+ /**
96
+ * Connects to a PowerSync Service to download data, emitting client-side state changes.
97
+ */
98
+ async *streamingSync(request: SyncRequest): AsyncGenerator<DownloadEvent> {
99
+ const abort = new AbortController();
100
+ const signal = request.signal != null ? AbortSignal.any([request.signal, abort.signal]) : abort.signal;
101
+
102
+ const state = this.#state;
103
+
104
+ let lines: ReturnType<typeof extractJsonLines> | undefined;
105
+
106
+ // Whether we've received a signal to retry applying the last checkpoint, sent after uploads are completed.
107
+ let checkpointRetryRequested = false;
108
+ // Resolved when a checkpoint retry is requested, rejected when the service doesn't send a line in time.
109
+ let interrupt: PromiseWithResolvers<null> | undefined;
110
+ const requestRetry = () => {
111
+ checkpointRetryRequested = true;
112
+ interrupt?.resolve(null);
113
+ };
114
+ this.#notifyUploadComplete.add(requestRetry);
115
+
116
+ const resetOnError = (apply: () => DownloadEvent[]): DownloadEvent[] => {
117
+ try {
118
+ return apply();
119
+ } catch (e) {
120
+ if (e instanceof RestartSyncError && e.clearLocal) {
121
+ // Start from scratch
122
+ this.#state = new DownloadClientState(this.#localWrites, state);
123
+ }
124
+
125
+ throw e;
126
+ }
127
+ };
128
+
129
+ let nextLine: Promise<IteratorResult<string>> | undefined;
130
+ let idleTimeout: ReturnType<typeof setTimeout> | undefined;
131
+
132
+ try {
133
+ const response = await this.#fetch(this.#resolveUri(request, 'sync/stream'), {
134
+ method: 'POST',
135
+ signal,
136
+ body: JSON.stringify(
137
+ state.prepareConnectRequest(
138
+ request.clientId,
139
+ request.parameters ?? {},
140
+ request.streams ?? { include_defaults: true, subscriptions: [] },
141
+ request.metadata
142
+ )
143
+ ),
144
+ headers: {
145
+ ...this.#defaultHeaders(request),
146
+ Accept: 'application/x-ndjson'
147
+ }
148
+ });
149
+ await this.#checkResponse(response);
150
+
151
+ lines = extractJsonLines(response.body![Symbol.asyncIterator](), new TextDecoder());
152
+ yield { type: 'headersReceived' };
153
+
154
+ while (true) {
155
+ if (checkpointRetryRequested) {
156
+ checkpointRetryRequested = false;
157
+ yield* resetOnError(() => state.retryCheckpoint());
158
+ }
159
+
160
+ nextLine ??= lines.next();
161
+ const { promise, reject } = (interrupt = Promise.withResolvers<null>());
162
+ idleTimeout = setTimeout(() => reject(new Error('No sync line received within timeout')), SERVICE_TIMEOUT);
163
+
164
+ const event = await Promise.race([nextLine, promise]);
165
+ clearTimeout(idleTimeout);
166
+ interrupt = undefined;
167
+ if (event == null) continue; // Resolves to null when a checkpoint retry is requested
168
+
169
+ nextLine = undefined;
170
+ if (event.done) break;
171
+
172
+ const line: StreamingSyncLine = JSON.parse(event.value);
173
+ if ('token_expires_in' in line) {
174
+ yield { type: 'keepalive', keepalive: line };
175
+ } else {
176
+ yield* resetOnError(() => state.push(line));
177
+ }
178
+ }
179
+ } finally {
180
+ clearTimeout(idleTimeout);
181
+ this.#notifyUploadComplete.delete(requestRetry);
182
+ abort.abort();
183
+
184
+ // Reading from the aborted response fails, which must not replace the original error. A pending line (e.g. after
185
+ // the idle timeout) would also reject without being awaited.
186
+ nextLine?.catch(() => {});
187
+ try {
188
+ while (lines != null && !(await lines.next()).done) {
189
+ // Wait for the response to complete or throw after aborting.
190
+ }
191
+ } catch {
192
+ // Expected after aborting the request.
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ export interface ClientOptions {
199
+ /**
200
+ * State tracking local writes to prevent applying new checkpoints if needed.
201
+ */
202
+ localWrites: LocalWriteState;
203
+ /**
204
+ * A fetch implementation, mainly used for tests.
205
+ */
206
+ fetch?: typeof fetch;
207
+ }
208
+
209
+ const userAgent = `PowerSync standalone JS v${POWERSYNC_JS_VERSION}`;
210
+ const applicationJson = 'application/json';
211
+
212
+ /**
213
+ * The service sends a keepalive line roughly every 20 seconds, we manually disconnect if we don't receive something in
214
+ * time.
215
+ */
216
+ const SERVICE_TIMEOUT = 60_000;