@powersync/common 1.52.0 → 1.53.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 (76) hide show
  1. package/dist/bundle.cjs +161 -766
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +162 -755
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +161 -766
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +162 -755
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +39 -370
  10. package/legacy/sync_protocol.d.ts +103 -0
  11. package/lib/client/ConnectionManager.js +1 -1
  12. package/lib/client/ConnectionManager.js.map +1 -1
  13. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +6 -64
  14. package/lib/client/sync/bucket/BucketStorageAdapter.js +4 -0
  15. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -1
  16. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -28
  17. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -162
  18. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -1
  19. package/lib/client/sync/stream/AbstractRemote.d.ts +2 -12
  20. package/lib/client/sync/stream/AbstractRemote.js +3 -13
  21. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  22. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +12 -35
  23. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +145 -424
  24. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  25. package/lib/client/sync/stream/JsonValue.d.ts +7 -0
  26. package/lib/client/sync/stream/JsonValue.js +2 -0
  27. package/lib/client/sync/stream/JsonValue.js.map +1 -0
  28. package/lib/client/sync/stream/core-instruction.d.ts +14 -9
  29. package/lib/client/sync/stream/core-instruction.js +3 -0
  30. package/lib/client/sync/stream/core-instruction.js.map +1 -1
  31. package/lib/db/DBAdapter.d.ts +9 -0
  32. package/lib/db/DBAdapter.js +8 -1
  33. package/lib/db/DBAdapter.js.map +1 -1
  34. package/lib/db/crud/SyncStatus.d.ts +3 -4
  35. package/lib/db/crud/SyncStatus.js +0 -4
  36. package/lib/db/crud/SyncStatus.js.map +1 -1
  37. package/lib/db/schema/RawTable.d.ts +0 -5
  38. package/lib/db/schema/Schema.d.ts +0 -2
  39. package/lib/db/schema/Schema.js +0 -2
  40. package/lib/db/schema/Schema.js.map +1 -1
  41. package/lib/index.d.ts +1 -5
  42. package/lib/index.js +1 -5
  43. package/lib/index.js.map +1 -1
  44. package/package.json +9 -6
  45. package/src/client/ConnectionManager.ts +1 -1
  46. package/src/client/sync/bucket/BucketStorageAdapter.ts +6 -71
  47. package/src/client/sync/bucket/SqliteBucketStorage.ts +1 -197
  48. package/src/client/sync/stream/AbstractRemote.ts +5 -27
  49. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +168 -496
  50. package/src/client/sync/stream/JsonValue.ts +8 -0
  51. package/src/client/sync/stream/core-instruction.ts +15 -5
  52. package/src/db/DBAdapter.ts +20 -2
  53. package/src/db/crud/SyncStatus.ts +4 -5
  54. package/src/db/schema/RawTable.ts +0 -5
  55. package/src/db/schema/Schema.ts +0 -2
  56. package/src/index.ts +1 -5
  57. package/lib/client/sync/bucket/OpType.d.ts +0 -16
  58. package/lib/client/sync/bucket/OpType.js +0 -23
  59. package/lib/client/sync/bucket/OpType.js.map +0 -1
  60. package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
  61. package/lib/client/sync/bucket/OplogEntry.js +0 -36
  62. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  63. package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
  64. package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
  65. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  66. package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
  67. package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
  68. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  69. package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
  70. package/lib/client/sync/stream/streaming-sync-types.js +0 -26
  71. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  72. package/src/client/sync/bucket/OpType.ts +0 -23
  73. package/src/client/sync/bucket/OplogEntry.ts +0 -50
  74. package/src/client/sync/bucket/SyncDataBatch.ts +0 -11
  75. package/src/client/sync/bucket/SyncDataBucket.ts +0 -49
  76. package/src/client/sync/stream/streaming-sync-types.ts +0 -210
@@ -1819,8 +1819,15 @@ class BaseTransaction {
1819
1819
  class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
1820
1820
  static async runWith(ctx, fn) {
1821
1821
  let tx = new TransactionImplementation(ctx);
1822
+ // For write transactions, use BEGIN IMMEDIATE to immediately obtain a write lock on the database (instead of doing
1823
+ // that on the first statement). If we have a genuine read-only connection, we also use BEGIN IMMEDIATE there: In
1824
+ // WAL mode, that ensures we pin the current state of the database (instead of the state at the first statement in
1825
+ // the transaction). But if we have a "fake" read-only connection implemented through `pragma query_only = true`, we
1826
+ // can't use this trick because it would attempt to lock the connection. So there, we use a regular `BEGIN`
1827
+ // statement.
1828
+ const useBeginImmediate = ctx.connectionType != 'queryOnly';
1822
1829
  try {
1823
- await ctx.execute('BEGIN IMMEDIATE');
1830
+ await ctx.execute(useBeginImmediate ? 'BEGIN IMMEDIATE' : 'BEGIN');
1824
1831
  const result = await fn(tx);
1825
1832
  await tx.commit();
1826
1833
  return result;
@@ -1979,16 +1986,12 @@ class SyncStatus {
1979
1986
  *
1980
1987
  * This returns null when the database is currently being opened and we don't have reliable information about all
1981
1988
  * included streams yet.
1982
- *
1983
- * @experimental Sync streams are currently in alpha.
1984
1989
  */
1985
1990
  get syncStreams() {
1986
1991
  return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));
1987
1992
  }
1988
1993
  /**
1989
1994
  * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
1990
- *
1991
- * @experimental Sync streams are currently in alpha.
1992
1995
  */
1993
1996
  forStream(stream) {
1994
1997
  const asJson = JSON.stringify(stream.parameters);
@@ -2571,7 +2574,7 @@ class SyncStreamSubscriptionHandle {
2571
2574
  constructor(subscription) {
2572
2575
  this.subscription = subscription;
2573
2576
  subscription.refcount++;
2574
- _finalizer?.register(this, subscription);
2577
+ _finalizer?.register(this, subscription, this);
2575
2578
  }
2576
2579
  get name() {
2577
2580
  return this.subscription.name;
@@ -3160,6 +3163,10 @@ exports.PowerSyncControlCommand = void 0;
3160
3163
  PowerSyncControlCommand["NOTIFY_TOKEN_REFRESHED"] = "refreshed_token";
3161
3164
  PowerSyncControlCommand["NOTIFY_CRUD_UPLOAD_COMPLETED"] = "completed_upload";
3162
3165
  PowerSyncControlCommand["UPDATE_SUBSCRIPTIONS"] = "update_subscriptions";
3166
+ /**
3167
+ * An `established` or `end` event for response streams.
3168
+ */
3169
+ PowerSyncControlCommand["CONNECTION_STATE"] = "connection";
3163
3170
  })(exports.PowerSyncControlCommand || (exports.PowerSyncControlCommand = {}));
3164
3171
 
3165
3172
  /**
@@ -3341,103 +3348,6 @@ class AbortOperation extends Error {
3341
3348
  }
3342
3349
  }
3343
3350
 
3344
- exports.OpTypeEnum = void 0;
3345
- (function (OpTypeEnum) {
3346
- OpTypeEnum[OpTypeEnum["CLEAR"] = 1] = "CLEAR";
3347
- OpTypeEnum[OpTypeEnum["MOVE"] = 2] = "MOVE";
3348
- OpTypeEnum[OpTypeEnum["PUT"] = 3] = "PUT";
3349
- OpTypeEnum[OpTypeEnum["REMOVE"] = 4] = "REMOVE";
3350
- })(exports.OpTypeEnum || (exports.OpTypeEnum = {}));
3351
- /**
3352
- * Used internally for sync buckets.
3353
- */
3354
- class OpType {
3355
- value;
3356
- static fromJSON(jsonValue) {
3357
- return new OpType(exports.OpTypeEnum[jsonValue]);
3358
- }
3359
- constructor(value) {
3360
- this.value = value;
3361
- }
3362
- toJSON() {
3363
- return Object.entries(exports.OpTypeEnum).find(([, value]) => value === this.value)[0];
3364
- }
3365
- }
3366
-
3367
- class OplogEntry {
3368
- op_id;
3369
- op;
3370
- checksum;
3371
- subkey;
3372
- object_type;
3373
- object_id;
3374
- data;
3375
- static fromRow(row) {
3376
- return new OplogEntry(row.op_id, OpType.fromJSON(row.op), row.checksum, row.subkey, row.object_type, row.object_id, row.data);
3377
- }
3378
- constructor(op_id, op, checksum, subkey, object_type, object_id, data) {
3379
- this.op_id = op_id;
3380
- this.op = op;
3381
- this.checksum = checksum;
3382
- this.subkey = subkey;
3383
- this.object_type = object_type;
3384
- this.object_id = object_id;
3385
- this.data = data;
3386
- }
3387
- toJSON(fixedKeyEncoding = false) {
3388
- return {
3389
- op_id: this.op_id,
3390
- op: this.op.toJSON(),
3391
- object_type: this.object_type,
3392
- object_id: this.object_id,
3393
- checksum: this.checksum,
3394
- data: this.data,
3395
- // Older versions of the JS SDK used to always JSON.stringify here. That has always been wrong,
3396
- // but we need to migrate gradually to not break existing databases.
3397
- subkey: fixedKeyEncoding ? this.subkey : JSON.stringify(this.subkey)
3398
- };
3399
- }
3400
- }
3401
-
3402
- class SyncDataBucket {
3403
- bucket;
3404
- data;
3405
- has_more;
3406
- after;
3407
- next_after;
3408
- static fromRow(row) {
3409
- return new SyncDataBucket(row.bucket, row.data.map((entry) => OplogEntry.fromRow(entry)), row.has_more ?? false, row.after, row.next_after);
3410
- }
3411
- constructor(bucket, data,
3412
- /**
3413
- * True if the response does not contain all the data for this bucket, and another request must be made.
3414
- */
3415
- has_more,
3416
- /**
3417
- * The `after` specified in the request.
3418
- */
3419
- after,
3420
- /**
3421
- * Use this for the next request.
3422
- */
3423
- next_after) {
3424
- this.bucket = bucket;
3425
- this.data = data;
3426
- this.has_more = has_more;
3427
- this.after = after;
3428
- this.next_after = next_after;
3429
- }
3430
- toJSON(fixedKeyEncoding = false) {
3431
- return {
3432
- bucket: this.bucket,
3433
- has_more: this.has_more,
3434
- after: this.after,
3435
- next_after: this.next_after,
3436
- data: this.data.map((entry) => entry.toJSON(fixedKeyEncoding))
3437
- };
3438
- }
3439
- }
3440
-
3441
3351
  var dist = {};
3442
3352
 
3443
3353
  var Codecs = {};
@@ -8222,7 +8132,7 @@ function requireDist () {
8222
8132
 
8223
8133
  var distExports = requireDist();
8224
8134
 
8225
- var version = "1.52.0";
8135
+ var version = "1.53.0";
8226
8136
  var PACKAGE = {
8227
8137
  version: version};
8228
8138
 
@@ -8392,22 +8302,6 @@ const doneResult = { done: true, value: undefined };
8392
8302
  function valueResult(value) {
8393
8303
  return { done: false, value };
8394
8304
  }
8395
- /**
8396
- * A variant of {@link Array.map} for async iterators.
8397
- */
8398
- function map(source, map) {
8399
- return {
8400
- next: async () => {
8401
- const value = await source.next();
8402
- if (value.done) {
8403
- return value;
8404
- }
8405
- else {
8406
- return { value: map(value.value) };
8407
- }
8408
- }
8409
- };
8410
- }
8411
8305
  /**
8412
8306
  * Expands a source async iterator by allowing to inject events asynchronously.
8413
8307
  *
@@ -8779,22 +8673,12 @@ class AbstractRemote {
8779
8673
  * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
8780
8674
  *
8781
8675
  * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
8782
- *
8783
- * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
8784
- * (required for compatibility with older sync services).
8785
8676
  */
8786
- async socketStreamRaw(options, bson) {
8677
+ async socketStreamRaw(options) {
8787
8678
  const { path, fetchStrategy = exports.FetchStrategy.Buffered } = options;
8788
- const mimeType = bson == null ? 'application/json' : 'application/bson';
8679
+ const mimeType = 'application/json';
8789
8680
  function toBuffer(js) {
8790
- let contents;
8791
- if (bson != null) {
8792
- contents = bson.serialize(js);
8793
- }
8794
- else {
8795
- contents = JSON.stringify(js);
8796
- }
8797
- return node_buffer.Buffer.from(contents);
8681
+ return node_buffer.Buffer.from(JSON.stringify(js));
8798
8682
  }
8799
8683
  const syncQueueRequestSize = fetchStrategy == exports.FetchStrategy.Buffered ? 10 : 1;
8800
8684
  const request = await this.buildRequest(path);
@@ -9095,31 +8979,8 @@ function coreStatusToJs(status) {
9095
8979
  priorityStatusEntries: status.priority_status.map(priorityToJs)
9096
8980
  };
9097
8981
  }
9098
-
9099
- function isStreamingSyncData(line) {
9100
- return line.data != null;
9101
- }
9102
- function isStreamingKeepalive(line) {
9103
- return line.token_expires_in != null;
9104
- }
9105
- function isStreamingSyncCheckpoint(line) {
9106
- return line.checkpoint != null;
9107
- }
9108
- function isStreamingSyncCheckpointComplete(line) {
9109
- return line.checkpoint_complete != null;
9110
- }
9111
- function isStreamingSyncCheckpointPartiallyComplete(line) {
9112
- return line.partial_checkpoint_complete != null;
9113
- }
9114
- function isStreamingSyncCheckpointDiff(line) {
9115
- return line.checkpoint_diff != null;
9116
- }
9117
- function isContinueCheckpointRequest(request) {
9118
- return (Array.isArray(request.buckets) &&
9119
- typeof request.checkpoint_token == 'string');
9120
- }
9121
- function isSyncNewCheckpointRequest(request) {
9122
- return typeof request.request_checkpoint == 'object';
8982
+ function isInterruptingInstruction(instruction) {
8983
+ return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;
9123
8984
  }
9124
8985
 
9125
8986
  exports.LockType = void 0;
@@ -9134,35 +8995,21 @@ exports.SyncStreamConnectionMethod = void 0;
9134
8995
  })(exports.SyncStreamConnectionMethod || (exports.SyncStreamConnectionMethod = {}));
9135
8996
  exports.SyncClientImplementation = void 0;
9136
8997
  (function (SyncClientImplementation) {
9137
- /**
9138
- * Decodes and handles sync lines received from the sync service in JavaScript.
9139
- *
9140
- * This is the default option.
9141
- *
9142
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
9143
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
9144
- * version of the PowerSync SDK.
9145
- */
9146
- SyncClientImplementation["JAVASCRIPT"] = "js";
9147
8998
  /**
9148
8999
  * This implementation offloads the sync line decoding and handling into the PowerSync
9149
9000
  * core extension.
9150
9001
  *
9151
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
9152
- * recommended client implementation for all apps.
9002
+ * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
9153
9003
  *
9154
9004
  * ## Compatibility warning
9155
9005
  *
9156
9006
  * The Rust sync client stores sync data in a format that is slightly different than the one used
9157
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
9158
- * databases, the PowerSync SDK will migrate the format automatically.
9159
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
9160
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
9161
- * back to {@link JAVASCRIPT} later.
9007
+ * by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
9008
+ * migrate the format automatically.
9162
9009
  *
9163
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
9164
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
9165
- * can lead to sync issues.
9010
+ * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
9011
+ * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
9012
+ * possible anymore. Problematic SDK versions have been released before 2025-06-09.
9166
9013
  */
9167
9014
  SyncClientImplementation["RUST"] = "rust";
9168
9015
  })(exports.SyncClientImplementation || (exports.SyncClientImplementation = {}));
@@ -9185,13 +9032,7 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
9185
9032
  serializedSchema: undefined,
9186
9033
  includeDefaultStreams: true
9187
9034
  };
9188
- // The priority we assume when we receive checkpoint lines where no priority is set.
9189
- // This is the default priority used by the sync service, but can be set to an arbitrary
9190
- // value since sync services without priorities also won't send partial sync completion
9191
- // messages.
9192
- const FALLBACK_PRIORITY = 3;
9193
9035
  class AbstractStreamingSyncImplementation extends BaseObserver {
9194
- _lastSyncedAt;
9195
9036
  options;
9196
9037
  abortController;
9197
9038
  // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
@@ -9201,6 +9042,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9201
9042
  streamingSyncPromise;
9202
9043
  logger;
9203
9044
  activeStreams;
9045
+ connectionMayHaveChanged = false;
9204
9046
  isUploadingCrud = false;
9205
9047
  notifyCompletedUploads;
9206
9048
  handleActiveStreamsChange;
@@ -9280,9 +9122,6 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9280
9122
  this.crudUpdateListener = undefined;
9281
9123
  this.uploadAbortController?.abort();
9282
9124
  }
9283
- async hasCompletedSync() {
9284
- return this.options.adapter.hasCompletedSync();
9285
- }
9286
9125
  async getWriteCheckpoint() {
9287
9126
  const clientId = await this.options.adapter.getClientId();
9288
9127
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
@@ -9364,7 +9203,7 @@ The next upload iteration will be delayed.`);
9364
9203
  });
9365
9204
  }
9366
9205
  }
9367
- this.uploadAbortController = null;
9206
+ this.uploadAbortController = undefined;
9368
9207
  }
9369
9208
  });
9370
9209
  }
@@ -9480,6 +9319,11 @@ The next upload iteration will be delayed.`);
9480
9319
  shouldDelayRetry = false;
9481
9320
  // A disconnect was requested, we should not delay since there is no explicit retry
9482
9321
  }
9322
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
9323
+ this.connectionMayHaveChanged = false;
9324
+ this.logger.info('Sync error after changed connection, retrying immediately');
9325
+ shouldDelayRetry = false;
9326
+ }
9483
9327
  else {
9484
9328
  this.logger.error(ex);
9485
9329
  }
@@ -9510,17 +9354,14 @@ The next upload iteration will be delayed.`);
9510
9354
  // Mark as disconnected if here
9511
9355
  this.updateSyncStatus({ connected: false, connecting: false });
9512
9356
  }
9513
- async collectLocalBucketState() {
9514
- const bucketEntries = await this.options.adapter.getBucketStates();
9515
- const req = bucketEntries.map((entry) => ({
9516
- name: entry.bucket,
9517
- after: entry.op_id
9518
- }));
9519
- const localDescriptions = new Map();
9520
- for (const entry of bucketEntries) {
9521
- localDescriptions.set(entry.bucket, null);
9522
- }
9523
- return [req, localDescriptions];
9357
+ markConnectionMayHaveChanged() {
9358
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
9359
+ // an active sync iteration on the connection in use.
9360
+ this.connectionMayHaveChanged = true;
9361
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
9362
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
9363
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
9364
+ this.handleActiveStreamsChange?.();
9524
9365
  }
9525
9366
  /**
9526
9367
  * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
@@ -9561,328 +9402,98 @@ The next upload iteration will be delayed.`);
9561
9402
  if (invalidMetadata.length > 0) {
9562
9403
  throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
9563
9404
  }
9564
- const clientImplementation = resolvedOptions.clientImplementation;
9565
- this.updateSyncStatus({ clientImplementation });
9566
- if (clientImplementation == exports.SyncClientImplementation.JAVASCRIPT) {
9567
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
9568
- return null;
9569
- }
9570
- else {
9571
- await this.requireKeyFormat(true);
9572
- return await this.rustSyncIteration(signal, resolvedOptions);
9573
- }
9405
+ await this.requireKeyFormat(true);
9406
+ return await this.rustSyncIteration(signal, resolvedOptions);
9574
9407
  }
9575
9408
  });
9576
9409
  }
9577
- async receiveSyncLines(data) {
9578
- const { options, connection, bson } = data;
9410
+ receiveSyncLines(data) {
9411
+ const { options, connection } = data;
9579
9412
  const remote = this.options.remote;
9580
- if (connection.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9581
- return await remote.fetchStream(options);
9582
- }
9583
- else {
9584
- return await this.options.remote.socketStreamRaw({
9585
- ...options,
9586
- ...{ fetchStrategy: connection.fetchStrategy }
9587
- }, bson);
9588
- }
9589
- }
9590
- async legacyStreamingSyncIteration(signal, resolvedOptions) {
9591
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
9592
- if (rawTables != null && rawTables.length) {
9593
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
9594
- }
9595
- if (this.activeStreams.length) {
9596
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
9597
- }
9598
- this.logger.debug('Streaming sync iteration started');
9599
- this.options.adapter.startSession();
9600
- let [req, bucketMap] = await this.collectLocalBucketState();
9601
- let targetCheckpoint = null;
9602
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
9603
- let pendingValidatedCheckpoint = null;
9604
- const clientId = await this.options.adapter.getClientId();
9605
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
9606
- this.logger.debug('Requesting stream from server');
9607
- const syncOptions = {
9608
- path: '/sync/stream',
9609
- abortSignal: signal,
9610
- data: {
9611
- buckets: req,
9612
- include_checksum: true,
9613
- raw_data: true,
9614
- parameters: resolvedOptions.params,
9615
- app_metadata: resolvedOptions.appMetadata,
9616
- client_id: clientId
9617
- }
9618
- };
9619
- const bson = await this.options.remote.getBSON();
9620
- const source = await this.receiveSyncLines({
9621
- options: syncOptions,
9622
- connection: resolvedOptions,
9623
- bson
9624
- });
9625
- const stream = injectable(map(source, (line) => {
9626
- if (typeof line == 'string') {
9627
- return JSON.parse(line);
9413
+ const openInner = async () => {
9414
+ if (connection.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9415
+ return await remote.fetchStream(options);
9628
9416
  }
9629
9417
  else {
9630
- return bson.deserialize(line);
9418
+ return await this.options.remote.socketStreamRaw({
9419
+ ...options,
9420
+ ...{ fetchStrategy: connection.fetchStrategy }
9421
+ });
9631
9422
  }
9632
- }));
9633
- this.logger.debug('Stream established. Processing events');
9634
- this.notifyCompletedUploads = () => {
9635
- stream.inject({ crud_upload_completed: null });
9636
9423
  };
9637
- while (true) {
9638
- const { value: line, done } = await stream.next();
9639
- if (done) {
9640
- // The stream has closed while waiting
9641
- return;
9642
- }
9643
- if ('crud_upload_completed' in line) {
9644
- if (pendingValidatedCheckpoint != null) {
9645
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
9646
- if (applied) {
9647
- pendingValidatedCheckpoint = null;
9648
- }
9649
- else if (endIteration) {
9650
- break;
9651
- }
9424
+ let inner;
9425
+ let done = false;
9426
+ return {
9427
+ async next() {
9428
+ if (done) {
9429
+ return doneResult;
9652
9430
  }
9653
- continue;
9654
- }
9655
- // A connection is active and messages are being received
9656
- if (!this.syncStatus.connected) {
9657
- // There is a connection now
9658
- Promise.resolve().then(() => this.triggerCrudUpload());
9659
- this.updateSyncStatus({
9660
- connected: true
9661
- });
9662
- }
9663
- if (isStreamingSyncCheckpoint(line)) {
9664
- targetCheckpoint = line.checkpoint;
9665
- // New checkpoint - existing validated checkpoint is no longer valid
9666
- pendingValidatedCheckpoint = null;
9667
- const bucketsToDelete = new Set(bucketMap.keys());
9668
- const newBuckets = new Map();
9669
- for (const checksum of line.checkpoint.buckets) {
9670
- newBuckets.set(checksum.bucket, {
9671
- name: checksum.bucket,
9672
- priority: checksum.priority ?? FALLBACK_PRIORITY
9431
+ else if (inner == null) {
9432
+ inner = await openInner();
9433
+ // We're connected here, so we can tell the core extension about it.
9434
+ return valueResult({
9435
+ command: exports.PowerSyncControlCommand.CONNECTION_STATE,
9436
+ payload: 'established'
9673
9437
  });
9674
- bucketsToDelete.delete(checksum.bucket);
9675
- }
9676
- if (bucketsToDelete.size > 0) {
9677
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
9678
- }
9679
- bucketMap = newBuckets;
9680
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
9681
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
9682
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
9683
- }
9684
- else if (isStreamingSyncCheckpointComplete(line)) {
9685
- const result = await this.applyCheckpoint(targetCheckpoint);
9686
- if (result.endIteration) {
9687
- return;
9688
- }
9689
- else if (!result.applied) {
9690
- // "Could not apply checkpoint due to local data". We need to retry after
9691
- // finishing uploads.
9692
- pendingValidatedCheckpoint = targetCheckpoint;
9693
9438
  }
9694
9439
  else {
9695
- // Nothing to retry later. This would likely already be null from the last
9696
- // checksum or checksum_diff operation, but we make sure.
9697
- pendingValidatedCheckpoint = null;
9698
- }
9699
- }
9700
- else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
9701
- const priority = line.partial_checkpoint_complete.priority;
9702
- this.logger.debug('Partial checkpoint complete', priority);
9703
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
9704
- if (!result.checkpointValid) {
9705
- // This means checksums failed. Start again with a new checkpoint.
9706
- // TODO: better back-off
9707
- await new Promise((resolve) => setTimeout(resolve, 50));
9708
- return;
9709
- }
9710
- else if (!result.ready) ;
9711
- else {
9712
- // We'll keep on downloading, but can report that this priority is synced now.
9713
- this.logger.debug('partial checkpoint validation succeeded');
9714
- // All states with a higher priority can be deleted since this partial sync includes them.
9715
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
9716
- priorityStates.push({
9717
- priority,
9718
- lastSyncedAt: new Date(),
9719
- hasSynced: true
9720
- });
9721
- this.updateSyncStatus({
9722
- connected: true,
9723
- priorityStatusEntries: priorityStates
9724
- });
9725
- }
9726
- }
9727
- else if (isStreamingSyncCheckpointDiff(line)) {
9728
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
9729
- if (targetCheckpoint == null) {
9730
- throw new Error('Checkpoint diff without previous checkpoint');
9731
- }
9732
- // New checkpoint - existing validated checkpoint is no longer valid
9733
- pendingValidatedCheckpoint = null;
9734
- const diff = line.checkpoint_diff;
9735
- const newBuckets = new Map();
9736
- for (const checksum of targetCheckpoint.buckets) {
9737
- newBuckets.set(checksum.bucket, checksum);
9738
- }
9739
- for (const checksum of diff.updated_buckets) {
9740
- newBuckets.set(checksum.bucket, checksum);
9741
- }
9742
- for (const bucket of diff.removed_buckets) {
9743
- newBuckets.delete(bucket);
9744
- }
9745
- const newCheckpoint = {
9746
- last_op_id: diff.last_op_id,
9747
- buckets: [...newBuckets.values()],
9748
- write_checkpoint: diff.write_checkpoint
9749
- };
9750
- targetCheckpoint = newCheckpoint;
9751
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
9752
- bucketMap = new Map();
9753
- newBuckets.forEach((checksum, name) => bucketMap.set(name, {
9754
- name: checksum.bucket,
9755
- priority: checksum.priority ?? FALLBACK_PRIORITY
9756
- }));
9757
- const bucketsToDelete = diff.removed_buckets;
9758
- if (bucketsToDelete.length > 0) {
9759
- this.logger.debug('Remove buckets', bucketsToDelete);
9760
- }
9761
- await this.options.adapter.removeBuckets(bucketsToDelete);
9762
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
9763
- }
9764
- else if (isStreamingSyncData(line)) {
9765
- const { data } = line;
9766
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
9767
- let updatedProgress = null;
9768
- if (previousProgress) {
9769
- updatedProgress = { ...previousProgress };
9770
- const progressForBucket = updatedProgress[data.bucket];
9771
- if (progressForBucket) {
9772
- updatedProgress[data.bucket] = {
9773
- ...progressForBucket,
9774
- since_last: progressForBucket.since_last + data.data.length
9775
- };
9440
+ const event = await inner.next();
9441
+ if (event.done) {
9442
+ done = true;
9443
+ return valueResult({ command: exports.PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
9776
9444
  }
9777
- }
9778
- this.updateSyncStatus({
9779
- dataFlow: {
9780
- downloading: true,
9781
- downloadProgress: updatedProgress
9445
+ else {
9446
+ return valueResult({
9447
+ command: typeof event.value == 'string'
9448
+ ? exports.PowerSyncControlCommand.PROCESS_TEXT_LINE
9449
+ : exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9450
+ payload: event.value
9451
+ });
9782
9452
  }
9783
- });
9784
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
9785
- }
9786
- else if (isStreamingKeepalive(line)) {
9787
- const remaining_seconds = line.token_expires_in;
9788
- if (remaining_seconds == 0) {
9789
- // Connection would be closed automatically right after this
9790
- this.logger.debug('Token expiring; reconnect');
9791
- /**
9792
- * For a rare case where the backend connector does not update the token
9793
- * (uses the same one), this should have some delay.
9794
- */
9795
- await this.delayRetry();
9796
- return;
9797
- }
9798
- else if (remaining_seconds < 30) {
9799
- this.logger.debug('Token will expire soon; reconnect');
9800
- // Pre-emptively refresh the token
9801
- this.options.remote.invalidateCredentials();
9802
- return;
9803
9453
  }
9804
- this.triggerCrudUpload();
9805
- }
9806
- else {
9807
- this.logger.debug('Received unknown sync line', line);
9808
9454
  }
9809
- }
9810
- this.logger.debug('Stream input empty');
9811
- // Connection closed. Likely due to auth issue.
9812
- return;
9455
+ };
9813
9456
  }
9814
9457
  async rustSyncIteration(signal, resolvedOptions) {
9815
9458
  const syncImplementation = this;
9816
9459
  const adapter = this.options.adapter;
9817
9460
  const remote = this.options.remote;
9818
- const controller = new AbortController();
9819
- const abort = () => {
9820
- return controller.abort(signal.reason);
9821
- };
9822
- signal.addEventListener('abort', abort);
9823
- let receivingLines = null;
9824
- let hadSyncLine = false;
9825
9461
  let hideDisconnectOnRestart = false;
9462
+ let notifyTokenRefreshed;
9826
9463
  if (signal.aborted) {
9827
9464
  throw new AbortOperation('Connection request has been aborted');
9828
9465
  }
9829
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9830
- // invocation (local events include refreshed tokens and completed uploads).
9831
- // This is a single data stream so that we can handle all control calls from a single place.
9832
- let controlInvocations = null;
9833
- async function connect(instr) {
9834
- const syncOptions = {
9835
- path: '/sync/stream',
9836
- abortSignal: controller.signal,
9837
- data: instr.request
9466
+ function startCommand() {
9467
+ const options = {
9468
+ parameters: resolvedOptions.params,
9469
+ app_metadata: resolvedOptions.appMetadata,
9470
+ active_streams: syncImplementation.activeStreams,
9471
+ include_defaults: resolvedOptions.includeDefaultStreams
9838
9472
  };
9839
- controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
9840
- options: syncOptions,
9841
- connection: resolvedOptions
9842
- }), (line) => {
9843
- if (typeof line == 'string') {
9844
- return {
9845
- command: exports.PowerSyncControlCommand.PROCESS_TEXT_LINE,
9846
- payload: line
9847
- };
9848
- }
9849
- else {
9850
- return {
9851
- command: exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9852
- payload: line
9853
- };
9854
- }
9855
- }));
9856
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
9857
- // we're already connected here and can report that.
9858
- syncImplementation.updateSyncStatus({ connected: true });
9859
- try {
9860
- while (true) {
9861
- let event = await controlInvocations.next();
9862
- if (event.done) {
9863
- break;
9864
- }
9865
- const line = event.value;
9866
- await control(line.command, line.payload);
9867
- if (!hadSyncLine) {
9868
- syncImplementation.triggerCrudUpload();
9869
- hadSyncLine = true;
9870
- }
9871
- }
9872
- }
9873
- finally {
9874
- abort();
9875
- signal.removeEventListener('abort', abort);
9473
+ if (resolvedOptions.serializedSchema) {
9474
+ options.schema = resolvedOptions.serializedSchema;
9876
9475
  }
9476
+ return invokePowerSyncControl(exports.PowerSyncControlCommand.START, JSON.stringify(options));
9877
9477
  }
9878
9478
  async function stop() {
9879
- await control(exports.PowerSyncControlCommand.STOP);
9479
+ const instructions = await invokePowerSyncControl(exports.PowerSyncControlCommand.STOP);
9480
+ for (const instruction of instructions) {
9481
+ // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
9482
+ // this point.
9483
+ if (isInterruptingInstruction(instruction))
9484
+ continue;
9485
+ await handleInstruction(instruction);
9486
+ }
9880
9487
  }
9881
- async function control(op, payload) {
9488
+ async function invokePowerSyncControl(op, payload) {
9882
9489
  const rawResponse = await adapter.control(op, payload ?? null);
9883
9490
  const logger = syncImplementation.logger;
9884
9491
  logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
9885
- await handleInstructions(JSON.parse(rawResponse));
9492
+ if (op != exports.PowerSyncControlCommand.STOP) {
9493
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
9494
+ syncImplementation.connectionMayHaveChanged = false;
9495
+ }
9496
+ return JSON.parse(rawResponse);
9886
9497
  }
9887
9498
  async function handleInstruction(instruction) {
9888
9499
  if ('LogLine' in instruction) {
@@ -9901,13 +9512,6 @@ The next upload iteration will be delayed.`);
9901
9512
  else if ('UpdateSyncStatus' in instruction) {
9902
9513
  syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
9903
9514
  }
9904
- else if ('EstablishSyncStream' in instruction) {
9905
- if (receivingLines != null) {
9906
- // Already connected, this shouldn't happen during a single iteration.
9907
- throw 'Unexpected request to establish sync stream, already connected';
9908
- }
9909
- receivingLines = connect(instruction.EstablishSyncStream);
9910
- }
9911
9515
  else if ('FetchCredentials' in instruction) {
9912
9516
  if (instruction.FetchCredentials.did_expire) {
9913
9517
  remote.invalidateCredentials();
@@ -9916,16 +9520,12 @@ The next upload iteration will be delayed.`);
9916
9520
  remote.invalidateCredentials();
9917
9521
  // Restart iteration after the credentials have been refreshed.
9918
9522
  remote.fetchCredentials().then((_) => {
9919
- controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9523
+ notifyTokenRefreshed?.();
9920
9524
  }, (err) => {
9921
9525
  syncImplementation.logger.warn('Could not prefetch credentials', err);
9922
9526
  });
9923
9527
  }
9924
9528
  }
9925
- else if ('CloseSyncStream' in instruction) {
9926
- controller.abort();
9927
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9928
- }
9929
9529
  else if ('FlushFileSystem' in instruction) ;
9930
9530
  else if ('DidCompleteSync' in instruction) {
9931
9531
  syncImplementation.updateSyncStatus({
@@ -9935,101 +9535,83 @@ The next upload iteration will be delayed.`);
9935
9535
  });
9936
9536
  }
9937
9537
  }
9938
- async function handleInstructions(instructions) {
9939
- for (const instr of instructions) {
9940
- await handleInstruction(instr);
9941
- }
9942
- }
9943
9538
  try {
9944
- const options = {
9945
- parameters: resolvedOptions.params,
9946
- app_metadata: resolvedOptions.appMetadata,
9947
- active_streams: this.activeStreams,
9948
- include_defaults: resolvedOptions.includeDefaultStreams
9949
- };
9950
- if (resolvedOptions.serializedSchema) {
9951
- options.schema = resolvedOptions.serializedSchema;
9539
+ const defaultResult = { immediateRestart: false };
9540
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9541
+ // invocation (local events include refreshed tokens and completed uploads).
9542
+ // This is a single data stream so that we can handle all control calls from a single place.
9543
+ let controlInvocations = null;
9544
+ for (const startInstruction of await startCommand()) {
9545
+ if ('EstablishSyncStream' in startInstruction) {
9546
+ const syncOptions = {
9547
+ path: '/sync/stream',
9548
+ abortSignal: signal,
9549
+ data: startInstruction.EstablishSyncStream.request
9550
+ };
9551
+ controlInvocations = injectable(syncImplementation.receiveSyncLines({
9552
+ options: syncOptions,
9553
+ connection: resolvedOptions
9554
+ }));
9555
+ }
9556
+ else if ('CloseSyncStream' in startInstruction) {
9557
+ return defaultResult;
9558
+ }
9559
+ else {
9560
+ await handleInstruction(startInstruction);
9561
+ }
9952
9562
  }
9953
- await control(exports.PowerSyncControlCommand.START, JSON.stringify(options));
9563
+ if (controlInvocations == null)
9564
+ return defaultResult;
9954
9565
  this.notifyCompletedUploads = () => {
9955
- controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9566
+ controlInvocations.inject({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9956
9567
  };
9957
9568
  this.handleActiveStreamsChange = () => {
9958
- controlInvocations?.inject({
9569
+ controlInvocations.inject({
9959
9570
  command: exports.PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9960
9571
  payload: JSON.stringify(this.activeStreams)
9961
9572
  });
9962
9573
  };
9963
- await receivingLines;
9574
+ notifyTokenRefreshed = () => {
9575
+ controlInvocations.inject({
9576
+ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
9577
+ });
9578
+ };
9579
+ let hadSyncLine = false;
9580
+ loop: while (true) {
9581
+ const { done, value } = await controlInvocations.next();
9582
+ if (done)
9583
+ break;
9584
+ if (!hadSyncLine) {
9585
+ // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
9586
+ // that have been made while offline or disconnected.
9587
+ if (value.command == exports.PowerSyncControlCommand.PROCESS_TEXT_LINE ||
9588
+ value.command == exports.PowerSyncControlCommand.PROCESS_BSON_LINE) {
9589
+ hadSyncLine = true;
9590
+ this.triggerCrudUpload?.();
9591
+ }
9592
+ }
9593
+ const instructions = await invokePowerSyncControl(value.command, value.payload);
9594
+ for (const instruction of instructions) {
9595
+ if ('EstablishSyncStream' in instruction) {
9596
+ throw new Error('Received EstablishSyncStream while already connected.');
9597
+ }
9598
+ else if ('CloseSyncStream' in instruction) {
9599
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9600
+ break loop;
9601
+ }
9602
+ else {
9603
+ await handleInstruction(instruction);
9604
+ }
9605
+ }
9606
+ }
9964
9607
  }
9965
9608
  finally {
9966
9609
  this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
9610
+ notifyTokenRefreshed = undefined;
9967
9611
  await stop();
9968
9612
  }
9969
9613
  return { immediateRestart: hideDisconnectOnRestart };
9970
9614
  }
9971
- async updateSyncStatusForStartingCheckpoint(checkpoint) {
9972
- const localProgress = await this.options.adapter.getBucketOperationProgress();
9973
- const progress = {};
9974
- let invalidated = false;
9975
- for (const bucket of checkpoint.buckets) {
9976
- const savedProgress = localProgress[bucket.bucket];
9977
- const atLast = savedProgress?.atLast ?? 0;
9978
- const sinceLast = savedProgress?.sinceLast ?? 0;
9979
- progress[bucket.bucket] = {
9980
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
9981
- // will use by default.
9982
- priority: bucket.priority ?? 3,
9983
- at_last: atLast,
9984
- since_last: sinceLast,
9985
- target_count: bucket.count ?? 0
9986
- };
9987
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
9988
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
9989
- // of the bucket shrank so much that the local ops exceed the ops in the updated
9990
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
9991
- invalidated = true;
9992
- }
9993
- }
9994
- if (invalidated) {
9995
- for (const bucket in progress) {
9996
- const bucketProgress = progress[bucket];
9997
- bucketProgress.at_last = 0;
9998
- bucketProgress.since_last = 0;
9999
- }
10000
- }
10001
- this.updateSyncStatus({
10002
- dataFlow: {
10003
- downloading: true,
10004
- downloadProgress: progress
10005
- }
10006
- });
10007
- }
10008
- async applyCheckpoint(checkpoint) {
10009
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
10010
- if (!result.checkpointValid) {
10011
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
10012
- // This means checksums failed. Start again with a new checkpoint.
10013
- // TODO: better back-off
10014
- await new Promise((resolve) => setTimeout(resolve, 50));
10015
- return { applied: false, endIteration: true };
10016
- }
10017
- else if (!result.ready) {
10018
- this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
10019
- return { applied: false, endIteration: false };
10020
- }
10021
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
10022
- this.updateSyncStatus({
10023
- connected: true,
10024
- lastSyncedAt: new Date(),
10025
- dataFlow: {
10026
- downloading: false,
10027
- downloadProgress: null,
10028
- downloadError: undefined
10029
- }
10030
- });
10031
- return { applied: true, endIteration: false };
10032
- }
10033
9615
  updateSyncStatus(options) {
10034
9616
  const updatedStatus = new SyncStatus({
10035
9617
  connected: options.connected ?? this.syncStatus.connected,
@@ -11568,14 +11150,12 @@ class SqliteBucketStorage extends BaseObserver {
11568
11150
  db;
11569
11151
  logger;
11570
11152
  tableNames;
11571
- _hasCompletedSync;
11572
11153
  updateListener;
11573
11154
  _clientId;
11574
11155
  constructor(db, logger = Logger.get('SqliteBucketStorage')) {
11575
11156
  super();
11576
11157
  this.db = db;
11577
11158
  this.logger = logger;
11578
- this._hasCompletedSync = false;
11579
11159
  this.tableNames = new Set();
11580
11160
  this.updateListener = db.registerListener({
11581
11161
  tablesUpdated: (update) => {
@@ -11587,7 +11167,6 @@ class SqliteBucketStorage extends BaseObserver {
11587
11167
  });
11588
11168
  }
11589
11169
  async init() {
11590
- this._hasCompletedSync = false;
11591
11170
  const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);
11592
11171
  for (const row of existingTableRows ?? []) {
11593
11172
  this.tableNames.add(row.name);
@@ -11609,156 +11188,6 @@ class SqliteBucketStorage extends BaseObserver {
11609
11188
  getMaxOpId() {
11610
11189
  return MAX_OP_ID;
11611
11190
  }
11612
- /**
11613
- * Reset any caches.
11614
- */
11615
- startSession() { }
11616
- async getBucketStates() {
11617
- const result = await this.db.getAll("SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'");
11618
- return result;
11619
- }
11620
- async getBucketOperationProgress() {
11621
- const rows = await this.db.getAll('SELECT name, count_at_last, count_since_last FROM ps_buckets');
11622
- return Object.fromEntries(rows.map((r) => [r.name, { atLast: r.count_at_last, sinceLast: r.count_since_last }]));
11623
- }
11624
- async saveSyncData(batch, fixedKeyFormat = false) {
11625
- await this.writeTransaction(async (tx) => {
11626
- for (const b of batch.buckets) {
11627
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
11628
- 'save',
11629
- JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })
11630
- ]);
11631
- this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);
11632
- }
11633
- });
11634
- }
11635
- async removeBuckets(buckets) {
11636
- for (const bucket of buckets) {
11637
- await this.deleteBucket(bucket);
11638
- }
11639
- }
11640
- /**
11641
- * Mark a bucket for deletion.
11642
- */
11643
- async deleteBucket(bucket) {
11644
- await this.writeTransaction(async (tx) => {
11645
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);
11646
- });
11647
- this.logger.debug(`Done deleting bucket ${bucket}`);
11648
- }
11649
- async hasCompletedSync() {
11650
- if (this._hasCompletedSync) {
11651
- return true;
11652
- }
11653
- const r = await this.db.get(`SELECT powersync_last_synced_at() as synced_at`);
11654
- const completed = r.synced_at != null;
11655
- if (completed) {
11656
- this._hasCompletedSync = true;
11657
- }
11658
- return completed;
11659
- }
11660
- async syncLocalDatabase(checkpoint, priority) {
11661
- const r = await this.validateChecksums(checkpoint, priority);
11662
- if (!r.checkpointValid) {
11663
- this.logger.error('Checksums failed for', r.checkpointFailures);
11664
- for (const b of r.checkpointFailures ?? []) {
11665
- await this.deleteBucket(b);
11666
- }
11667
- return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };
11668
- }
11669
- if (priority == null) {
11670
- this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);
11671
- }
11672
- else {
11673
- this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);
11674
- }
11675
- let buckets = checkpoint.buckets;
11676
- if (priority !== undefined) {
11677
- buckets = buckets.filter((b) => hasMatchingPriority(priority, b));
11678
- }
11679
- const bucketNames = buckets.map((b) => b.bucket);
11680
- await this.writeTransaction(async (tx) => {
11681
- await tx.execute(`UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))`, [
11682
- checkpoint.last_op_id,
11683
- JSON.stringify(bucketNames)
11684
- ]);
11685
- if (priority == null && checkpoint.write_checkpoint) {
11686
- await tx.execute("UPDATE ps_buckets SET last_op = ? WHERE name = '$local'", [checkpoint.write_checkpoint]);
11687
- }
11688
- });
11689
- const valid = await this.updateObjectsFromBuckets(checkpoint, priority);
11690
- if (!valid) {
11691
- return { ready: false, checkpointValid: true };
11692
- }
11693
- return {
11694
- ready: true,
11695
- checkpointValid: true
11696
- };
11697
- }
11698
- /**
11699
- * Atomically update the local state to the current checkpoint.
11700
- *
11701
- * This includes creating new tables, dropping old tables, and copying data over from the oplog.
11702
- */
11703
- async updateObjectsFromBuckets(checkpoint, priority) {
11704
- let arg = '';
11705
- if (priority !== undefined) {
11706
- const affectedBuckets = [];
11707
- for (const desc of checkpoint.buckets) {
11708
- if (hasMatchingPriority(priority, desc)) {
11709
- affectedBuckets.push(desc.bucket);
11710
- }
11711
- }
11712
- arg = JSON.stringify({ priority, buckets: affectedBuckets });
11713
- }
11714
- return this.writeTransaction(async (tx) => {
11715
- const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
11716
- 'sync_local',
11717
- arg
11718
- ]);
11719
- if (result == 1) {
11720
- if (priority == null) {
11721
- const bucketToCount = Object.fromEntries(checkpoint.buckets.map((b) => [b.bucket, b.count]));
11722
- // The two parameters could be replaced with one, but: https://github.com/powersync-ja/better-sqlite3/pull/6
11723
- const jsonBucketCount = JSON.stringify(bucketToCount);
11724
- await tx.execute("UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL", [jsonBucketCount, jsonBucketCount]);
11725
- }
11726
- return true;
11727
- }
11728
- else {
11729
- return false;
11730
- }
11731
- });
11732
- }
11733
- async validateChecksums(checkpoint, priority) {
11734
- if (priority !== undefined) {
11735
- // Only validate the buckets within the priority we care about
11736
- const newBuckets = checkpoint.buckets.filter((cs) => hasMatchingPriority(priority, cs));
11737
- checkpoint = { ...checkpoint, buckets: newBuckets };
11738
- }
11739
- const rs = await this.db.execute('SELECT powersync_validate_checkpoint(?) as result', [
11740
- JSON.stringify({ ...checkpoint })
11741
- ]);
11742
- const resultItem = rs.rows?.item(0);
11743
- if (!resultItem) {
11744
- return {
11745
- checkpointValid: false,
11746
- ready: false,
11747
- checkpointFailures: []
11748
- };
11749
- }
11750
- const result = JSON.parse(resultItem['result']);
11751
- if (result['valid']) {
11752
- return { ready: true, checkpointValid: true };
11753
- }
11754
- else {
11755
- return {
11756
- checkpointValid: false,
11757
- ready: false,
11758
- checkpointFailures: result['failed_buckets']
11759
- };
11760
- }
11761
- }
11762
11191
  async updateLocalTarget(cb) {
11763
11192
  const rs1 = await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)", [MAX_OP_ID]);
11764
11193
  if (!rs1.length) {
@@ -11849,12 +11278,6 @@ class SqliteBucketStorage extends BaseObserver {
11849
11278
  async writeTransaction(callback, options) {
11850
11279
  return this.db.writeTransaction(callback, options);
11851
11280
  }
11852
- /**
11853
- * Set a target checkpoint.
11854
- */
11855
- async setTargetCheckpoint(checkpoint) {
11856
- // No-op for now
11857
- }
11858
11281
  async control(op, payload) {
11859
11282
  return await this.writeTransaction(async (tx) => {
11860
11283
  const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);
@@ -11878,20 +11301,6 @@ class SqliteBucketStorage extends BaseObserver {
11878
11301
  }
11879
11302
  static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
11880
11303
  }
11881
- function hasMatchingPriority(priority, bucket) {
11882
- return bucket.priority != null && bucket.priority <= priority;
11883
- }
11884
-
11885
- // TODO JSON
11886
- class SyncDataBatch {
11887
- buckets;
11888
- static fromJSON(json) {
11889
- return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
11890
- }
11891
- constructor(buckets) {
11892
- this.buckets = buckets;
11893
- }
11894
- }
11895
11304
 
11896
11305
  /**
11897
11306
  * Thrown when an underlying database connection is closed.
@@ -11951,10 +11360,8 @@ class Schema {
11951
11360
  * developer instead of automatically by PowerSync.
11952
11361
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
11953
11362
  * using client-side table and column constraints.
11954
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
11955
11363
  *
11956
11364
  * @param tables An object of (table name, raw table definition) entries.
11957
- * @experimental Note that the raw tables API is still experimental and may change in the future.
11958
11365
  */
11959
11366
  withRawTables(tables) {
11960
11367
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
@@ -12204,13 +11611,9 @@ exports.MAX_OP_ID = MAX_OP_ID;
12204
11611
  exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
12205
11612
  exports.Mutex = Mutex;
12206
11613
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
12207
- exports.OpType = OpType;
12208
- exports.OplogEntry = OplogEntry;
12209
11614
  exports.Schema = Schema;
12210
11615
  exports.Semaphore = Semaphore;
12211
11616
  exports.SqliteBucketStorage = SqliteBucketStorage;
12212
- exports.SyncDataBatch = SyncDataBatch;
12213
- exports.SyncDataBucket = SyncDataBucket;
12214
11617
  exports.SyncProgress = SyncProgress;
12215
11618
  exports.SyncStatus = SyncStatus;
12216
11619
  exports.SyncingService = SyncingService;
@@ -12225,18 +11628,10 @@ exports.createBaseLogger = createBaseLogger;
12225
11628
  exports.createLogger = createLogger;
12226
11629
  exports.extractTableUpdates = extractTableUpdates;
12227
11630
  exports.isBatchedUpdateNotification = isBatchedUpdateNotification;
12228
- exports.isContinueCheckpointRequest = isContinueCheckpointRequest;
12229
11631
  exports.isDBAdapter = isDBAdapter;
12230
11632
  exports.isPowerSyncDatabaseOptionsWithSettings = isPowerSyncDatabaseOptionsWithSettings;
12231
11633
  exports.isSQLOpenFactory = isSQLOpenFactory;
12232
11634
  exports.isSQLOpenOptions = isSQLOpenOptions;
12233
- exports.isStreamingKeepalive = isStreamingKeepalive;
12234
- exports.isStreamingSyncCheckpoint = isStreamingSyncCheckpoint;
12235
- exports.isStreamingSyncCheckpointComplete = isStreamingSyncCheckpointComplete;
12236
- exports.isStreamingSyncCheckpointDiff = isStreamingSyncCheckpointDiff;
12237
- exports.isStreamingSyncCheckpointPartiallyComplete = isStreamingSyncCheckpointPartiallyComplete;
12238
- exports.isStreamingSyncData = isStreamingSyncData;
12239
- exports.isSyncNewCheckpointRequest = isSyncNewCheckpointRequest;
12240
11635
  exports.parseQuery = parseQuery;
12241
11636
  exports.runOnSchemaChange = runOnSchemaChange;
12242
11637
  exports.sanitizeSQL = sanitizeSQL;