@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,263 @@
1
+ import { DownloadChanges, DownloadEvent, RestartSyncError } from './api.js';
2
+ import { Bucket, OplogEntry, OplogState, RowKey, RowState } from './oplog.js';
3
+ import { BucketRequest, StreamingSyncRequest, StreamSubscriptionRequest } from './requests.js';
4
+ import type { BucketChecksum, BucketLine, Checkpoint, StreamingSyncCheckpointDiff } from './sync_protocol.js';
5
+
6
+ /**
7
+ * A JavaScript sync client.
8
+ *
9
+ * This tracks the equivalent of `ps_oplog`, `ps_buckets` and `ps_updated_rows` from the core extension and can update
10
+ * its state for sync lines, emitting changed rows.
11
+ *
12
+ * Instead of storing the full oplog of each bucket, state is tracked per row (table and id): For each row, we store
13
+ * the latest operation for each bucket and subkey. Once every bucket has removed a row and that removal has been
14
+ * applied, the row's state is dropped entirely.
15
+ */
16
+ export class DownloadClientState {
17
+ readonly #oplog = new OplogState();
18
+ #bucketsByPriority: Map<number, Bucket[]> | undefined;
19
+ #checkpoint: TrackedCheckpoint | undefined;
20
+ // Whether all data for #checkpoint has been received.
21
+ #checkpointComplete = false;
22
+
23
+ #writeState: LocalWriteState;
24
+ // Rows that need to be updated on the next complete sync, e.g. because there was a local mutation for which we need
25
+ // to check whether it synced back down.
26
+ readonly #updatedRows: Map<string, RowKey>;
27
+
28
+ constructor(writeState: LocalWriteState, previous?: DownloadClientState) {
29
+ this.#writeState = writeState;
30
+
31
+ if (previous) {
32
+ this.#updatedRows = previous.#updatedRows;
33
+ // This replaces a previous client state. Mark all rows tracked by that state as updated, so that we can emit a
34
+ // delete event if they're removed.
35
+ for (const row of previous.#oplog.rows.values()) {
36
+ this.#updatedRows.set(row.key.formatted, row.key);
37
+ }
38
+ } else {
39
+ this.#updatedRows = new Map();
40
+ }
41
+ }
42
+
43
+ prepareConnectRequest(
44
+ clientId: string,
45
+ parameters: Record<string, unknown>,
46
+ streams: StreamSubscriptionRequest,
47
+ metadata?: Record<string, string>
48
+ ): StreamingSyncRequest {
49
+ const buckets = this.#oplog.buckets
50
+ .values()
51
+ .filter((f) => f.lastEntry >= 0n)
52
+ .map((bkt) => ({ name: bkt.name, after: String(bkt.lastEntry) }) satisfies BucketRequest);
53
+
54
+ return {
55
+ buckets: buckets.toArray(),
56
+ include_checksum: true,
57
+ raw_data: true,
58
+ client_id: clientId,
59
+ parameters,
60
+ streams,
61
+ app_metadata: metadata
62
+ };
63
+ }
64
+
65
+ push(line: BucketLine): DownloadEvent[] {
66
+ if ('checkpoint' in line) {
67
+ this.#checkpointComplete = false;
68
+ this.#reconcileBuckets(new TrackedCheckpoint(line.checkpoint));
69
+ const streams = line.checkpoint.streams;
70
+ if (streams != null) {
71
+ return [{ type: 'resolvedStreams', streams }];
72
+ }
73
+ } else if ('checkpoint_diff' in line) {
74
+ const existing = this.#checkpoint!;
75
+ this.#checkpointComplete = false;
76
+ existing.applyDiff(line);
77
+ this.#reconcileBuckets(existing);
78
+ } else if ('data' in line) {
79
+ const { bucket, data } = line.data;
80
+ const resolvedBucket = this.#oplog.buckets.get(bucket)!;
81
+ for (const raw of data) {
82
+ const parsed = OplogEntry.fromJson(raw);
83
+ if (parsed.id > this.#checkpoint!.last_op) {
84
+ throw new RestartSyncError('Checkpoint id out of bounds', true);
85
+ }
86
+
87
+ resolvedBucket.pushLine(this.#oplog, raw, parsed);
88
+ }
89
+ } else if ('checkpoint_complete' in line) {
90
+ this.#checkpointComplete = true;
91
+ return this.#syncLocal();
92
+ } else if ('partial_checkpoint_complete' in line) {
93
+ return this.#syncLocal(line.partial_checkpoint_complete.priority);
94
+ } else {
95
+ // Ignore unknown sync line.
96
+ }
97
+
98
+ return [];
99
+ }
100
+
101
+ /**
102
+ * Attempts to apply the last checkpoint again if all of its data has been received, e.g. because
103
+ * {@link LocalWriteState} has changed since it was received.
104
+ */
105
+ retryCheckpoint(): DownloadEvent[] {
106
+ return this.#checkpointComplete ? this.#syncLocal() : [];
107
+ }
108
+
109
+ addToUpdatedRows(key: RowKey) {
110
+ this.#updatedRows.set(key.formatted, key);
111
+ }
112
+
113
+ #reconcileBuckets(checkpoint: TrackedCheckpoint) {
114
+ this.#checkpoint = checkpoint;
115
+ const buckets = this.#oplog.buckets;
116
+
117
+ const bucketsToDelete = new Set(buckets.keys());
118
+ for (const [bucket, entry] of checkpoint.buckets.entries()) {
119
+ bucketsToDelete.delete(bucket);
120
+
121
+ const resolvedBucket = buckets.getOrInsertComputed(bucket, () => new Bucket(bucket));
122
+ resolvedBucket.priority = entry.priority ?? 3;
123
+ }
124
+
125
+ for (const remaining of bucketsToDelete) {
126
+ // All data visible because of this bucket needs to be rechecked at the next full checkpoint.
127
+ for (const key of this.#oplog.removeBucket(buckets.get(remaining)!)) {
128
+ this.addToUpdatedRows(key);
129
+ }
130
+ }
131
+
132
+ this.#bucketsByPriority = Map.groupBy(buckets.values(), (b) => b.priority);
133
+ }
134
+
135
+ #syncLocal(targetPriority?: number): DownloadEvent[] {
136
+ if (targetPriority != 0) {
137
+ const blocked = this.#checkLocalWrites();
138
+ if (blocked) {
139
+ // If all buckets in a full checkpoint have priority 0, we can still apply them as a partial checkpoint. The
140
+ // sync service doesn't send a partial_checkpoint_complete line when all buckets have the same priority, so this
141
+ // emulates that line.
142
+ const buckets = [...this.#oplog.buckets.values()];
143
+ if (targetPriority == null && buckets.length != 0 && buckets.every((b) => b.priority == 0)) {
144
+ return [{ type: 'rows', changes: this.#applyChanges(0), priority: 0 }, blocked];
145
+ }
146
+
147
+ return [blocked];
148
+ }
149
+ }
150
+
151
+ const changes = this.#applyChanges(targetPriority);
152
+ return [targetPriority == null ? { type: 'rows', changes } : { type: 'rows', changes, priority: targetPriority }];
153
+ }
154
+
155
+ /**
156
+ * Returns an event explaining why a checkpoint can't be applied due to local writes, or `undefined` if there are no
157
+ * outstanding local writes.
158
+ */
159
+ #checkLocalWrites(): DownloadEvent | undefined {
160
+ const localWrites = this.#writeState;
161
+ const target = localWrites.targetCheckpoint;
162
+ const writeCheckpoint = this.#checkpoint?.write_checkpoint;
163
+
164
+ if (localWrites.hasLocalWrites) {
165
+ // Can't apply checkpoints with mutations that haven't been uploaded yet.
166
+ return { type: 'blockedDueToLocalData' };
167
+ } else if (target != null && (writeCheckpoint == null || writeCheckpoint < target)) {
168
+ return { type: 'waitingForCheckpoint', target, received: writeCheckpoint };
169
+ }
170
+
171
+ return undefined;
172
+ }
173
+
174
+ #applyChanges(targetPriority?: number): DownloadChanges {
175
+ let affectedBuckets =
176
+ targetPriority == null
177
+ ? this.#oplog.buckets.values()
178
+ : this.#bucketsByPriority
179
+ ?.entries()
180
+ .flatMap(([priority, buckets]) => (priority > targetPriority ? [] : buckets));
181
+
182
+ const handledKeys = new Set<string>();
183
+ const handledRows: RowState[] = [];
184
+ const changes = new Map<string, Map<string, Record<string, unknown> | null>>();
185
+
186
+ const handleKey = (key: RowKey) => {
187
+ // We always search for the latest oplog entry across all buckets, so if a key was handled we don't need to handle
188
+ // it again (in case it was updated in two buckets).
189
+ if (handledKeys.has(key.formatted)) return;
190
+ handledKeys.add(key.formatted);
191
+
192
+ const row = this.#oplog.rows.get(key.formatted);
193
+ const latestEntry = row?.resolve(targetPriority);
194
+ if (row) handledRows.push(row);
195
+
196
+ const tableEntries = changes.getOrInsertComputed(key.table, () => new Map());
197
+ tableEntries.set(key.rowid, latestEntry?.data?.parsed() ?? null);
198
+ };
199
+
200
+ for (const bucket of affectedBuckets ?? []) {
201
+ const expectedChecksum = (this.#checkpoint!.buckets.get(bucket.name)?.checksum ?? 0) | 0;
202
+ if (bucket.checksum != expectedChecksum) {
203
+ throw new RestartSyncError(
204
+ `Checksum error on ${bucket.name}, expected ${expectedChecksum} but oplog is at ${bucket.checksum}`,
205
+ true
206
+ );
207
+ }
208
+
209
+ for (const row of bucket.dirtyRows) {
210
+ handleKey(row.key);
211
+ }
212
+
213
+ bucket.markApplied();
214
+ }
215
+
216
+ if (targetPriority == null) {
217
+ for (const key of this.#updatedRows.values()) {
218
+ handleKey(key);
219
+ }
220
+ this.#updatedRows.clear();
221
+ }
222
+
223
+ for (const row of handledRows) {
224
+ this.#oplog.collectGarbage(row);
225
+ }
226
+
227
+ return { updatedRows: changes };
228
+ }
229
+ }
230
+
231
+ export class LocalWriteState {
232
+ hasLocalWrites: boolean = false;
233
+ targetCheckpoint?: bigint;
234
+ }
235
+
236
+ class TrackedCheckpoint {
237
+ last_op: bigint;
238
+ write_checkpoint: bigint | null;
239
+ readonly buckets: Map<string, BucketChecksum> = new Map();
240
+
241
+ constructor(source: Checkpoint) {
242
+ this.last_op = BigInt(source.last_op_id);
243
+ this.write_checkpoint = source.write_checkpoint == null ? null : BigInt(source.write_checkpoint);
244
+ for (const bucket of source.buckets) {
245
+ this.buckets.set(bucket.bucket, bucket);
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Merges bucket changes from a diff checkpoint line into this full checkpoint.
251
+ */
252
+ applyDiff({ checkpoint_diff }: StreamingSyncCheckpointDiff) {
253
+ this.last_op = BigInt(checkpoint_diff.last_op_id);
254
+ this.write_checkpoint = checkpoint_diff.write_checkpoint == null ? null : BigInt(checkpoint_diff.write_checkpoint);
255
+
256
+ for (const update of checkpoint_diff.updated_buckets) {
257
+ this.buckets.set(update.bucket, update);
258
+ }
259
+ for (const removed of checkpoint_diff.removed_buckets) {
260
+ this.buckets.delete(removed);
261
+ }
262
+ }
263
+ }
@@ -0,0 +1,243 @@
1
+ import { RestartSyncError } from './api.js';
2
+ import type { OplogEntryJSON } from './sync_protocol.js';
3
+
4
+ export class OplogState {
5
+ readonly rows = new Map<string, RowState>();
6
+ readonly buckets = new Map<string, Bucket>();
7
+
8
+ rowState(key: RowKey) {
9
+ return this.rows.getOrInsertComputed(key.formatted, () => new RowState(key));
10
+ }
11
+
12
+ /**
13
+ * Removes a bucket and all row state associated with it.
14
+ *
15
+ * Returns keys of rows for which the bucket has contributed applied state.
16
+ */
17
+ removeBucket(bucket: Bucket): RowKey[] {
18
+ const affected: RowKey[] = [];
19
+ for (const row of bucket.rows) {
20
+ if (row.buckets.get(bucket)!.applied != null) {
21
+ affected.push(row.key);
22
+ }
23
+
24
+ row.buckets.delete(bucket);
25
+ if (row.buckets.size == 0) {
26
+ this.rows.delete(row.key.formatted);
27
+ }
28
+ }
29
+
30
+ this.buckets.delete(bucket.name);
31
+ return affected;
32
+ }
33
+
34
+ /**
35
+ * Drops the state of a row if it can no longer contribute data.
36
+ */
37
+ collectGarbage(row: RowState) {
38
+ if (!row.isRemoved) return;
39
+
40
+ for (const bucket of row.buckets.keys()) {
41
+ bucket.rows.delete(row);
42
+ }
43
+ this.rows.delete(row.key.formatted);
44
+ }
45
+ }
46
+
47
+ export class Bucket {
48
+ priority: number = 3;
49
+ checksum = 0;
50
+ lastEntry: bigint = -1n;
51
+
52
+ /**
53
+ * All rows for which this bucket has operations.
54
+ */
55
+ readonly rows = new Set<RowState>();
56
+ /**
57
+ * Rows for which this bucket has received operations that haven't been applied yet.
58
+ */
59
+ readonly dirtyRows = new Set<RowState>();
60
+
61
+ constructor(readonly name: string) {}
62
+
63
+ #addToChecksum(value: number) {
64
+ // Checksums are u32 values, they should wrap around.
65
+ this.checksum = (this.checksum + value) | 0;
66
+ }
67
+
68
+ pushLine(oplog: OplogState, raw: OplogEntryJSON, data: OplogEntry) {
69
+ if (this.lastEntry >= data.id) {
70
+ // To simplify the sync client, we only support a linear bucket history. This works for compacting buckets, but
71
+ // breaks for full defrag if that doesn't generate new bucket names. We just delete everything and restart. This
72
+ // allows not tracking checksums.
73
+ throw new RestartSyncError('already tracked entry', true);
74
+ }
75
+
76
+ const opChecksum = raw.checksum | 0;
77
+
78
+ switch (raw.op) {
79
+ case 'CLEAR': {
80
+ // All prior put operations have turned into remove operations.
81
+ for (const row of this.rows) {
82
+ const bySubkey = row.buckets.get(this)!.bySubkey;
83
+ bySubkey.clear();
84
+ bySubkey.set('', new OplogEntry(data.id, row.key, '', undefined));
85
+ this.dirtyRows.add(row);
86
+ }
87
+
88
+ // The checksum of a clear operation is the sum of all put operations we've just replaced.
89
+ this.checksum = opChecksum;
90
+ break;
91
+ }
92
+ case 'MOVE':
93
+ this.#addToChecksum(opChecksum);
94
+ break;
95
+ case 'PUT':
96
+ case 'REMOVE':
97
+ const key = data.key;
98
+ if (key == null) {
99
+ throw new RestartSyncError('Expected row key');
100
+ }
101
+
102
+ this.#addToChecksum(opChecksum);
103
+ const row = oplog.rowState(key);
104
+ row.bucketState(this).bySubkey.set(data.subkey, data);
105
+ this.rows.add(row);
106
+ this.dirtyRows.add(row);
107
+ break;
108
+ }
109
+
110
+ this.lastEntry = data.id;
111
+ }
112
+
113
+ markApplied() {
114
+ for (const row of this.dirtyRows) {
115
+ const state = row.buckets.get(this)!;
116
+ state.applied = state.resolveLatest();
117
+ }
118
+
119
+ this.dirtyRows.clear();
120
+ }
121
+ }
122
+
123
+ /**
124
+ * The state of a row (identified by table and id) across all buckets.
125
+ */
126
+ export class RowState {
127
+ readonly buckets = new Map<Bucket, BucketRowState>();
128
+
129
+ constructor(readonly key: RowKey) {}
130
+
131
+ bucketState(bucket: Bucket): BucketRowState {
132
+ return this.buckets.getOrInsertComputed(bucket, () => new BucketRowState());
133
+ }
134
+
135
+ /**
136
+ * Finds the latest oplog entry for this row across all buckets.
137
+ *
138
+ * Pending changes are only considered for buckets included in the target priority, other buckets use their applied
139
+ * state. Like the core extension, the row exists as long as any bucket has a PUT for it: A REMOVE in one bucket
140
+ * doesn't hide PUTs from other buckets.
141
+ */
142
+ resolve(targetPriority?: number): OplogEntry | undefined {
143
+ let latestPut: OplogEntry | undefined;
144
+ let latestRemove: OplogEntry | undefined;
145
+ for (const [bucket, state] of this.buckets) {
146
+ const entry = targetPriority == null || bucket.priority <= targetPriority ? state.resolveLatest() : state.applied;
147
+ if (entry == null) continue;
148
+
149
+ if (entry.data != null) {
150
+ if (latestPut == null || entry.id > latestPut.id) latestPut = entry;
151
+ } else {
152
+ if (latestRemove == null || entry.id > latestRemove.id) latestRemove = entry;
153
+ }
154
+ }
155
+
156
+ return latestPut ?? latestRemove;
157
+ }
158
+
159
+ /**
160
+ * Whether every bucket has removed this row and all of those removals have been applied.
161
+ */
162
+ get isRemoved(): boolean {
163
+ for (const [bucket, state] of this.buckets) {
164
+ if (bucket.dirtyRows.has(this) || state.applied?.data != null) {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ return true;
170
+ }
171
+ }
172
+
173
+ /**
174
+ * The state of a row within a single bucket.
175
+ */
176
+ class BucketRowState {
177
+ // Latest operation for each subkey.
178
+ readonly bySubkey = new Map<string, OplogEntry>();
179
+ // The resolved entry at the time this bucket was last applied.
180
+ applied: OplogEntry | undefined;
181
+
182
+ /**
183
+ * Resolves the current state of a row in this bucket across all subkeys.
184
+ */
185
+ resolveLatest(): OplogEntry | undefined {
186
+ let latestPut: OplogEntry | undefined;
187
+ let latestRemove: OplogEntry | undefined;
188
+
189
+ for (const entry of this.bySubkey.values()) {
190
+ if (entry.data != null) {
191
+ if (latestPut == null || entry.id > latestPut.id) latestPut = entry;
192
+ } else {
193
+ if (latestRemove == null || entry.id > latestRemove.id) latestRemove = entry;
194
+ }
195
+ }
196
+
197
+ // Within a bucket, the row exists if any subkey has a PUT (the operation is only removed once we see a REMOVE for
198
+ // every subkey).
199
+ return latestPut ?? latestRemove;
200
+ }
201
+ }
202
+
203
+ export class RowKey {
204
+ readonly formatted: string;
205
+
206
+ constructor(
207
+ readonly table: string,
208
+ readonly rowid: string
209
+ ) {
210
+ this.formatted = JSON.stringify([table, rowid]);
211
+ }
212
+ }
213
+
214
+ export class OplogEntry {
215
+ constructor(
216
+ readonly id: bigint,
217
+ readonly key: RowKey | null,
218
+ readonly subkey: string,
219
+ readonly data: OplogData | undefined
220
+ ) {}
221
+
222
+ static fromJson(source: OplogEntryJSON): OplogEntry {
223
+ const id = BigInt(source.op_id);
224
+ const data = source.data ? new OplogData(source.data) : undefined;
225
+ const key = source.object_type && source.object_id ? new RowKey(source.object_type, source.object_id) : null;
226
+
227
+ return new OplogEntry(id, key, source.subkey ?? '', data);
228
+ }
229
+ }
230
+
231
+ class OplogData {
232
+ #parsedData?: Record<string, unknown>;
233
+
234
+ constructor(readonly data: string) {}
235
+
236
+ parsed(): Record<string, unknown> {
237
+ if (this.#parsedData) {
238
+ return this.#parsedData;
239
+ }
240
+
241
+ return (this.#parsedData = JSON.parse(this.data));
242
+ }
243
+ }
@@ -0,0 +1,25 @@
1
+ export interface StreamingSyncRequest {
2
+ buckets: BucketRequest[];
3
+ include_checksum: boolean;
4
+ raw_data: true;
5
+ client_id: string;
6
+ parameters: Record<string, unknown>;
7
+ streams: StreamSubscriptionRequest;
8
+ app_metadata: Record<string, string> | undefined;
9
+ }
10
+
11
+ export interface BucketRequest {
12
+ name: string;
13
+ after: string;
14
+ }
15
+
16
+ export interface StreamSubscriptionRequest {
17
+ include_defaults: boolean;
18
+ subscriptions: RequestedStreamSubscription[];
19
+ }
20
+
21
+ export interface RequestedStreamSubscription {
22
+ stream: string;
23
+ parameters: Record<string, unknown>;
24
+ override_priority: number | null;
25
+ }
@@ -0,0 +1,119 @@
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
+
10
+ export type SyncDataBucketJSON = {
11
+ bucket: string;
12
+ has_more?: boolean;
13
+ after?: string;
14
+ next_after?: string;
15
+ data: OplogEntryJSON[];
16
+ };
17
+ export interface OplogEntryJSON {
18
+ checksum: number;
19
+ data?: string;
20
+ object_id?: string;
21
+ object_type?: string;
22
+ op_id: string;
23
+ op: OpTypeJSON;
24
+ subkey?: string;
25
+ }
26
+ export type OpTypeJSON = 'CLEAR' | 'MOVE' | 'PUT' | 'REMOVE';
27
+
28
+ /**
29
+ * 64-bit unsigned integer stored as a string in base-10.
30
+ *
31
+ * Not sortable as a string.
32
+ */
33
+ export type OpId = string;
34
+
35
+ export interface BucketChecksum {
36
+ bucket: string;
37
+ priority?: number;
38
+ /**
39
+ * 32-bit unsigned hash.
40
+ */
41
+ checksum: number;
42
+
43
+ /**
44
+ * Count of operations - informational only.
45
+ */
46
+ count?: number;
47
+ /**
48
+ * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
49
+ * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
50
+ * present.
51
+ */
52
+ subscriptions?: any;
53
+ }
54
+
55
+ export interface Checkpoint {
56
+ last_op_id: OpId;
57
+ buckets: BucketChecksum[];
58
+ write_checkpoint?: string;
59
+ streams?: StreamDescription[];
60
+ }
61
+
62
+ export interface StreamDescription {
63
+ name: string;
64
+ is_default: boolean;
65
+ errors: StreamSubscriptionError[];
66
+ }
67
+
68
+ export interface StreamSubscriptionError {
69
+ /**
70
+ * The index of the subscription in the request's `streams.subscriptions` array, or `default` for errors on a stream
71
+ * included by default.
72
+ */
73
+ subscription: number | 'default';
74
+ message: string;
75
+ }
76
+
77
+ export interface StreamingSyncCheckpoint {
78
+ checkpoint: Checkpoint;
79
+ }
80
+
81
+ export interface StreamingSyncCheckpointDiff {
82
+ checkpoint_diff: {
83
+ last_op_id: OpId;
84
+ updated_buckets: BucketChecksum[];
85
+ removed_buckets: string[];
86
+ write_checkpoint?: string;
87
+ };
88
+ }
89
+
90
+ export interface StreamingSyncDataJSON {
91
+ data: SyncDataBucketJSON;
92
+ }
93
+
94
+ export interface StreamingSyncCheckpointComplete {
95
+ checkpoint_complete: {
96
+ last_op_id: OpId;
97
+ };
98
+ }
99
+
100
+ export interface StreamingSyncCheckpointPartiallyComplete {
101
+ partial_checkpoint_complete: {
102
+ priority: number;
103
+ last_op_id: OpId;
104
+ };
105
+ }
106
+
107
+ export interface StreamingSyncKeepalive {
108
+ /** If specified, token expires in this many seconds. */
109
+ token_expires_in: number;
110
+ }
111
+
112
+ export type BucketLine =
113
+ | StreamingSyncCheckpoint
114
+ | StreamingSyncCheckpointDiff
115
+ | StreamingSyncDataJSON
116
+ | StreamingSyncCheckpointComplete
117
+ | StreamingSyncCheckpointPartiallyComplete;
118
+
119
+ export type StreamingSyncLine = BucketLine | StreamingSyncKeepalive;
@@ -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';
@@ -166,6 +166,8 @@ export function extractJsonLines(
166
166
 
167
167
  const { done, value } = await source.next();
168
168
  if (done) {
169
+ // Flush bytes the decoder may still be buffering, e.g. if the stream ended in the middle of a character.
170
+ buffer += decoder.decode();
169
171
  const remaining = buffer.trim();
170
172
  if (remaining.length != 0) {
171
173
  isFinalEvent = true;
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
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';