@electric-sql/client 0.5.0 → 0.5.1

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.
@@ -1,9 +1,14 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
3
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
6
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __typeError = (msg) => {
10
+ throw TypeError(msg);
11
+ };
7
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
13
  var __spreadValues = (a, b) => {
9
14
  for (var prop in b || (b = {}))
@@ -16,6 +21,7 @@ var __spreadValues = (a, b) => {
16
21
  }
17
22
  return a;
18
23
  };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
19
25
  var __objRest = (source, exclude) => {
20
26
  var target = {};
21
27
  for (var prop in source)
@@ -41,6 +47,11 @@ var __copyProps = (to, from, except, desc) => {
41
47
  return to;
42
48
  };
43
49
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
51
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
52
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
53
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
54
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
44
55
  var __async = (__this, __arguments, generator) => {
45
56
  return new Promise((resolve, reject) => {
46
57
  var fulfilled = (value) => {
@@ -193,36 +204,54 @@ function isChangeMessage(message) {
193
204
  function isControlMessage(message) {
194
205
  return !isChangeMessage(message);
195
206
  }
207
+ function isUpToDateMessage(message) {
208
+ return isControlMessage(message) && message.headers.control === `up-to-date`;
209
+ }
196
210
 
197
- // src/client.ts
198
- var BackoffDefaults = {
199
- initialDelay: 100,
200
- maxDelay: 1e4,
201
- multiplier: 1.3
211
+ // src/queue.ts
212
+ function isThenable(value) {
213
+ return !!value && typeof value === `object` && `then` in value && typeof value.then === `function`;
214
+ }
215
+ var _processingChain;
216
+ var AsyncProcessingQueue = class {
217
+ constructor() {
218
+ __privateAdd(this, _processingChain);
219
+ }
220
+ process(callback) {
221
+ __privateSet(this, _processingChain, isThenable(__privateGet(this, _processingChain)) ? __privateGet(this, _processingChain).then(callback) : callback());
222
+ return __privateGet(this, _processingChain);
223
+ }
224
+ waitForProcessing() {
225
+ return __async(this, null, function* () {
226
+ let currentChain;
227
+ do {
228
+ currentChain = __privateGet(this, _processingChain);
229
+ yield currentChain;
230
+ } while (__privateGet(this, _processingChain) !== currentChain);
231
+ });
232
+ }
202
233
  };
234
+ _processingChain = new WeakMap();
235
+ var _queue, _callback;
203
236
  var MessageProcessor = class {
204
237
  constructor(callback) {
205
- this.messageQueue = [];
206
- this.isProcessing = false;
207
- this.callback = callback;
238
+ __privateAdd(this, _queue, new AsyncProcessingQueue());
239
+ __privateAdd(this, _callback);
240
+ __privateSet(this, _callback, callback);
208
241
  }
209
242
  process(messages) {
210
- this.messageQueue.push(messages);
211
- if (!this.isProcessing) {
212
- this.processQueue();
213
- }
243
+ __privateGet(this, _queue).process(() => __privateGet(this, _callback).call(this, messages));
214
244
  }
215
- processQueue() {
245
+ waitForProcessing() {
216
246
  return __async(this, null, function* () {
217
- this.isProcessing = true;
218
- while (this.messageQueue.length > 0) {
219
- const messages = this.messageQueue.shift();
220
- yield this.callback(messages);
221
- }
222
- this.isProcessing = false;
247
+ yield __privateGet(this, _queue).waitForProcessing();
223
248
  });
224
249
  }
225
250
  };
251
+ _queue = new WeakMap();
252
+ _callback = new WeakMap();
253
+
254
+ // src/error.ts
226
255
  var FetchError = class _FetchError extends Error {
227
256
  constructor(status, text, json, headers, url, message) {
228
257
  super(
@@ -251,324 +280,414 @@ var FetchError = class _FetchError extends Error {
251
280
  });
252
281
  }
253
282
  };
283
+ var FetchBackoffAbortError = class extends Error {
284
+ constructor() {
285
+ super(`Fetch with backoff aborted`);
286
+ }
287
+ };
288
+
289
+ // src/fetch.ts
290
+ var BackoffDefaults = {
291
+ initialDelay: 100,
292
+ maxDelay: 1e4,
293
+ multiplier: 1.3
294
+ };
295
+ function createFetchWithBackoff(fetchClient, backoffOptions = BackoffDefaults) {
296
+ const {
297
+ initialDelay,
298
+ maxDelay,
299
+ multiplier,
300
+ debug = false,
301
+ onFailedAttempt
302
+ } = backoffOptions;
303
+ return (...args) => __async(this, null, function* () {
304
+ var _a;
305
+ const url = args[0];
306
+ const options = args[1];
307
+ let delay = initialDelay;
308
+ let attempt = 0;
309
+ while (true) {
310
+ try {
311
+ const result = yield fetchClient(...args);
312
+ if (result.ok) return result;
313
+ else throw yield FetchError.fromResponse(result, url.toString());
314
+ } catch (e) {
315
+ onFailedAttempt == null ? void 0 : onFailedAttempt();
316
+ if ((_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.aborted) {
317
+ throw new FetchBackoffAbortError();
318
+ } else if (e instanceof FetchError && e.status >= 400 && e.status < 500) {
319
+ throw e;
320
+ } else {
321
+ yield new Promise((resolve) => setTimeout(resolve, delay));
322
+ delay = Math.min(delay * multiplier, maxDelay);
323
+ if (debug) {
324
+ attempt++;
325
+ console.log(`Retry attempt #${attempt} after ${delay}ms`);
326
+ }
327
+ }
328
+ }
329
+ }
330
+ });
331
+ }
332
+
333
+ // src/constants.ts
334
+ var SHAPE_ID_HEADER = `x-electric-shape-id`;
335
+ var CHUNK_LAST_OFFSET_HEADER = `x-electric-chunk-last-offset`;
336
+ var SHAPE_SCHEMA_HEADER = `x-electric-schema`;
337
+ var SHAPE_ID_QUERY_PARAM = `shape_id`;
338
+ var OFFSET_QUERY_PARAM = `offset`;
339
+ var WHERE_QUERY_PARAM = `where`;
340
+ var LIVE_QUERY_PARAM = `live`;
341
+
342
+ // src/client.ts
343
+ var _fetchClient, _messageParser, _subscribers, _upToDateSubscribers, _lastOffset, _lastSyncedAt, _isUpToDate, _connected, _shapeId, _schema, _ShapeStream_instances, publish_fn, sendErrorToSubscribers_fn, notifyUpToDateSubscribers_fn, sendErrorToUpToDateSubscribers_fn, reset_fn;
254
344
  var ShapeStream = class {
255
345
  constructor(options) {
256
- this.subscribers = /* @__PURE__ */ new Map();
257
- this.upToDateSubscribers = /* @__PURE__ */ new Map();
346
+ __privateAdd(this, _ShapeStream_instances);
347
+ __privateAdd(this, _fetchClient);
348
+ __privateAdd(this, _messageParser);
349
+ __privateAdd(this, _subscribers, /* @__PURE__ */ new Map());
350
+ __privateAdd(this, _upToDateSubscribers, /* @__PURE__ */ new Map());
351
+ __privateAdd(this, _lastOffset);
352
+ __privateAdd(this, _lastSyncedAt);
258
353
  // unix time
259
- this.isUpToDate = false;
260
- this.connected = false;
354
+ __privateAdd(this, _isUpToDate, false);
355
+ __privateAdd(this, _connected, false);
356
+ __privateAdd(this, _shapeId);
357
+ __privateAdd(this, _schema);
261
358
  var _a, _b, _c;
262
- this.validateOptions(options);
359
+ validateOptions(options);
263
360
  this.options = __spreadValues({ subscribe: true }, options);
264
- this.lastOffset = (_a = this.options.offset) != null ? _a : `-1`;
265
- this.shapeId = this.options.shapeId;
266
- this.messageParser = new MessageParser(options.parser);
267
- this.backoffOptions = (_b = options.backoffOptions) != null ? _b : BackoffDefaults;
268
- this.fetchClient = (_c = options.fetchClient) != null ? _c : (...args) => fetch(...args);
361
+ __privateSet(this, _lastOffset, (_a = this.options.offset) != null ? _a : `-1`);
362
+ __privateSet(this, _shapeId, this.options.shapeId);
363
+ __privateSet(this, _messageParser, new MessageParser(options.parser));
364
+ __privateSet(this, _fetchClient, createFetchWithBackoff(
365
+ (_b = options.fetchClient) != null ? _b : (...args) => fetch(...args),
366
+ __spreadProps(__spreadValues({}, (_c = options.backoffOptions) != null ? _c : BackoffDefaults), {
367
+ onFailedAttempt: () => {
368
+ var _a2, _b2;
369
+ __privateSet(this, _connected, false);
370
+ (_b2 = (_a2 = options.backoffOptions) == null ? void 0 : _a2.onFailedAttempt) == null ? void 0 : _b2.call(_a2);
371
+ }
372
+ })
373
+ ));
269
374
  this.start();
270
375
  }
376
+ get shapeId() {
377
+ return __privateGet(this, _shapeId);
378
+ }
379
+ get isUpToDate() {
380
+ return __privateGet(this, _isUpToDate);
381
+ }
271
382
  start() {
272
383
  return __async(this, null, function* () {
273
384
  var _a;
274
- this.isUpToDate = false;
385
+ __privateSet(this, _isUpToDate, false);
275
386
  const { url, where, signal } = this.options;
276
387
  try {
277
- while (!(signal == null ? void 0 : signal.aborted) && !this.isUpToDate || this.options.subscribe) {
388
+ while (!(signal == null ? void 0 : signal.aborted) && !__privateGet(this, _isUpToDate) || this.options.subscribe) {
278
389
  const fetchUrl = new URL(url);
279
- if (where) fetchUrl.searchParams.set(`where`, where);
280
- fetchUrl.searchParams.set(`offset`, this.lastOffset);
281
- if (this.isUpToDate) {
282
- fetchUrl.searchParams.set(`live`, `true`);
390
+ if (where) fetchUrl.searchParams.set(WHERE_QUERY_PARAM, where);
391
+ fetchUrl.searchParams.set(OFFSET_QUERY_PARAM, __privateGet(this, _lastOffset));
392
+ if (__privateGet(this, _isUpToDate)) {
393
+ fetchUrl.searchParams.set(LIVE_QUERY_PARAM, `true`);
283
394
  }
284
- if (this.shapeId) {
285
- fetchUrl.searchParams.set(`shape_id`, this.shapeId);
395
+ if (__privateGet(this, _shapeId)) {
396
+ fetchUrl.searchParams.set(SHAPE_ID_QUERY_PARAM, __privateGet(this, _shapeId));
286
397
  }
287
398
  let response;
288
399
  try {
289
- const maybeResponse = yield this.fetchWithBackoff(fetchUrl);
290
- if (maybeResponse) response = maybeResponse;
291
- else break;
400
+ response = yield __privateGet(this, _fetchClient).call(this, fetchUrl.toString(), { signal });
401
+ __privateSet(this, _connected, true);
292
402
  } catch (e) {
403
+ if (e instanceof FetchBackoffAbortError) break;
293
404
  if (!(e instanceof FetchError)) throw e;
294
405
  if (e.status == 400) {
295
- this.reset();
296
- this.publish(e.json);
406
+ __privateMethod(this, _ShapeStream_instances, reset_fn).call(this);
407
+ __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, e.json);
297
408
  continue;
298
409
  } else if (e.status == 409) {
299
- const newShapeId = e.headers[`x-electric-shape-id`];
300
- this.reset(newShapeId);
301
- this.publish(e.json);
410
+ const newShapeId = e.headers[SHAPE_ID_HEADER];
411
+ __privateMethod(this, _ShapeStream_instances, reset_fn).call(this, newShapeId);
412
+ __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, e.json);
302
413
  continue;
303
414
  } else if (e.status >= 400 && e.status < 500) {
304
- this.sendErrorToUpToDateSubscribers(e);
305
- this.sendErrorToSubscribers(e);
415
+ __privateMethod(this, _ShapeStream_instances, sendErrorToUpToDateSubscribers_fn).call(this, e);
416
+ __privateMethod(this, _ShapeStream_instances, sendErrorToSubscribers_fn).call(this, e);
306
417
  throw e;
307
418
  }
308
419
  }
309
420
  const { headers, status } = response;
310
- const shapeId = headers.get(`X-Electric-Shape-Id`);
421
+ const shapeId = headers.get(SHAPE_ID_HEADER);
311
422
  if (shapeId) {
312
- this.shapeId = shapeId;
423
+ __privateSet(this, _shapeId, shapeId);
313
424
  }
314
- const lastOffset = headers.get(`X-Electric-Chunk-Last-Offset`);
425
+ const lastOffset = headers.get(CHUNK_LAST_OFFSET_HEADER);
315
426
  if (lastOffset) {
316
- this.lastOffset = lastOffset;
427
+ __privateSet(this, _lastOffset, lastOffset);
317
428
  }
318
429
  const getSchema = () => {
319
- const schemaHeader = headers.get(`X-Electric-Schema`);
430
+ const schemaHeader = headers.get(SHAPE_SCHEMA_HEADER);
320
431
  return schemaHeader ? JSON.parse(schemaHeader) : {};
321
432
  };
322
- this.schema = (_a = this.schema) != null ? _a : getSchema();
433
+ __privateSet(this, _schema, (_a = __privateGet(this, _schema)) != null ? _a : getSchema());
323
434
  const messages = status === 204 ? `[]` : yield response.text();
324
435
  if (status === 204) {
325
- this.lastSyncedAt = Date.now();
436
+ __privateSet(this, _lastSyncedAt, Date.now());
326
437
  }
327
- const batch = this.messageParser.parse(messages, this.schema);
438
+ const batch = __privateGet(this, _messageParser).parse(messages, __privateGet(this, _schema));
328
439
  if (batch.length > 0) {
329
440
  const lastMessage = batch[batch.length - 1];
330
- if (isControlMessage(lastMessage) && lastMessage.headers.control === `up-to-date`) {
331
- this.lastSyncedAt = Date.now();
332
- if (!this.isUpToDate) {
333
- this.isUpToDate = true;
334
- this.notifyUpToDateSubscribers();
441
+ if (isUpToDateMessage(lastMessage)) {
442
+ __privateSet(this, _lastSyncedAt, Date.now());
443
+ if (!__privateGet(this, _isUpToDate)) {
444
+ __privateSet(this, _isUpToDate, true);
445
+ __privateMethod(this, _ShapeStream_instances, notifyUpToDateSubscribers_fn).call(this);
335
446
  }
336
447
  }
337
- this.publish(batch);
448
+ __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, batch);
338
449
  }
339
450
  }
340
451
  } finally {
341
- this.connected = false;
452
+ __privateSet(this, _connected, false);
342
453
  }
343
454
  });
344
455
  }
345
456
  subscribe(callback, onError) {
346
457
  const subscriptionId = Math.random();
347
458
  const subscriber = new MessageProcessor(callback);
348
- this.subscribers.set(subscriptionId, [subscriber, onError]);
459
+ __privateGet(this, _subscribers).set(subscriptionId, [subscriber, onError]);
349
460
  return () => {
350
- this.subscribers.delete(subscriptionId);
461
+ __privateGet(this, _subscribers).delete(subscriptionId);
351
462
  };
352
463
  }
353
464
  unsubscribeAll() {
354
- this.subscribers.clear();
355
- }
356
- publish(messages) {
357
- this.subscribers.forEach(([subscriber, _]) => {
358
- subscriber.process(messages);
359
- });
360
- }
361
- sendErrorToSubscribers(error) {
362
- this.subscribers.forEach(([_, errorFn]) => {
363
- errorFn == null ? void 0 : errorFn(error);
364
- });
465
+ __privateGet(this, _subscribers).clear();
365
466
  }
366
467
  subscribeOnceToUpToDate(callback, error) {
367
468
  const subscriptionId = Math.random();
368
- this.upToDateSubscribers.set(subscriptionId, [callback, error]);
469
+ __privateGet(this, _upToDateSubscribers).set(subscriptionId, [callback, error]);
369
470
  return () => {
370
- this.upToDateSubscribers.delete(subscriptionId);
471
+ __privateGet(this, _upToDateSubscribers).delete(subscriptionId);
371
472
  };
372
473
  }
373
474
  unsubscribeAllUpToDateSubscribers() {
374
- this.upToDateSubscribers.clear();
475
+ __privateGet(this, _upToDateSubscribers).clear();
476
+ }
477
+ /** Unix time at which we last synced. Undefined when `isLoading` is true. */
478
+ lastSyncedAt() {
479
+ return __privateGet(this, _lastSyncedAt);
375
480
  }
376
481
  /** Time elapsed since last sync (in ms). Infinity if we did not yet sync. */
377
482
  lastSynced() {
378
- if (this.lastSyncedAt === void 0) return Infinity;
379
- return Date.now() - this.lastSyncedAt;
483
+ if (__privateGet(this, _lastSyncedAt) === void 0) return Infinity;
484
+ return Date.now() - __privateGet(this, _lastSyncedAt);
380
485
  }
486
+ /** Indicates if we are connected to the Electric sync service. */
381
487
  isConnected() {
382
- return this.connected;
488
+ return __privateGet(this, _connected);
383
489
  }
384
490
  /** True during initial fetch. False afterwise. */
385
491
  isLoading() {
386
492
  return !this.isUpToDate;
387
493
  }
388
- notifyUpToDateSubscribers() {
389
- this.upToDateSubscribers.forEach(([callback]) => {
390
- callback();
391
- });
494
+ };
495
+ _fetchClient = new WeakMap();
496
+ _messageParser = new WeakMap();
497
+ _subscribers = new WeakMap();
498
+ _upToDateSubscribers = new WeakMap();
499
+ _lastOffset = new WeakMap();
500
+ _lastSyncedAt = new WeakMap();
501
+ _isUpToDate = new WeakMap();
502
+ _connected = new WeakMap();
503
+ _shapeId = new WeakMap();
504
+ _schema = new WeakMap();
505
+ _ShapeStream_instances = new WeakSet();
506
+ publish_fn = function(messages) {
507
+ __privateGet(this, _subscribers).forEach(([subscriber, _]) => {
508
+ subscriber.process(messages);
509
+ });
510
+ };
511
+ sendErrorToSubscribers_fn = function(error) {
512
+ __privateGet(this, _subscribers).forEach(([_, errorFn]) => {
513
+ errorFn == null ? void 0 : errorFn(error);
514
+ });
515
+ };
516
+ notifyUpToDateSubscribers_fn = function() {
517
+ __privateGet(this, _upToDateSubscribers).forEach(([callback]) => {
518
+ callback();
519
+ });
520
+ };
521
+ sendErrorToUpToDateSubscribers_fn = function(error) {
522
+ __privateGet(this, _upToDateSubscribers).forEach(
523
+ ([_, errorCallback]) => errorCallback(error)
524
+ );
525
+ };
526
+ /**
527
+ * Resets the state of the stream, optionally with a provided
528
+ * shape ID
529
+ */
530
+ reset_fn = function(shapeId) {
531
+ __privateSet(this, _lastOffset, `-1`);
532
+ __privateSet(this, _shapeId, shapeId);
533
+ __privateSet(this, _isUpToDate, false);
534
+ __privateSet(this, _connected, false);
535
+ __privateSet(this, _schema, void 0);
536
+ };
537
+ function validateOptions(options) {
538
+ if (!options.url) {
539
+ throw new Error(`Invalid shape option. It must provide the url`);
392
540
  }
393
- sendErrorToUpToDateSubscribers(error) {
394
- this.upToDateSubscribers.forEach(
395
- ([_, errorCallback]) => errorCallback(error)
541
+ if (options.signal && !(options.signal instanceof AbortSignal)) {
542
+ throw new Error(
543
+ `Invalid signal option. It must be an instance of AbortSignal.`
396
544
  );
397
545
  }
398
- /**
399
- * Resets the state of the stream, optionally with a provided
400
- * shape ID
401
- */
402
- reset(shapeId) {
403
- this.lastOffset = `-1`;
404
- this.shapeId = shapeId;
405
- this.isUpToDate = false;
406
- this.connected = false;
407
- this.schema = void 0;
408
- }
409
- validateOptions(options) {
410
- if (!options.url) {
411
- throw new Error(`Invalid shape option. It must provide the url`);
412
- }
413
- if (options.signal && !(options.signal instanceof AbortSignal)) {
414
- throw new Error(
415
- `Invalid signal option. It must be an instance of AbortSignal.`
416
- );
417
- }
418
- if (options.offset !== void 0 && options.offset !== `-1` && !options.shapeId) {
419
- throw new Error(
420
- `shapeId is required if this isn't an initial fetch (i.e. offset > -1)`
421
- );
422
- }
423
- }
424
- fetchWithBackoff(url) {
425
- return __async(this, null, function* () {
426
- const { initialDelay, maxDelay, multiplier } = this.backoffOptions;
427
- const signal = this.options.signal;
428
- let delay = initialDelay;
429
- let attempt = 0;
430
- while (true) {
431
- try {
432
- const result = yield this.fetchClient(url.toString(), { signal });
433
- if (result.ok) {
434
- if (this.options.subscribe) {
435
- this.connected = true;
436
- }
437
- return result;
438
- } else throw yield FetchError.fromResponse(result, url.toString());
439
- } catch (e) {
440
- this.connected = false;
441
- if (signal == null ? void 0 : signal.aborted) {
442
- return void 0;
443
- } else if (e instanceof FetchError && e.status >= 400 && e.status < 500) {
444
- throw e;
445
- } else {
446
- yield new Promise((resolve) => setTimeout(resolve, delay));
447
- delay = Math.min(delay * multiplier, maxDelay);
448
- attempt++;
449
- console.log(`Retry attempt #${attempt} after ${delay}ms`);
450
- }
451
- }
452
- }
453
- });
546
+ if (options.offset !== void 0 && options.offset !== `-1` && !options.shapeId) {
547
+ throw new Error(
548
+ `shapeId is required if this isn't an initial fetch (i.e. offset > -1)`
549
+ );
454
550
  }
455
- };
551
+ return;
552
+ }
553
+
554
+ // src/shape.ts
555
+ var _stream, _data, _subscribers2, _hasNotifiedSubscribersUpToDate, _error, _Shape_instances, process_fn, handleError_fn, notify_fn;
456
556
  var Shape = class {
457
557
  constructor(stream) {
458
- this.data = /* @__PURE__ */ new Map();
459
- this.subscribers = /* @__PURE__ */ new Map();
460
- this.error = false;
461
- this.hasNotifiedSubscribersUpToDate = false;
462
- this.stream = stream;
463
- this.stream.subscribe(this.process.bind(this), this.handleError.bind(this));
464
- const unsubscribe = this.stream.subscribeOnceToUpToDate(
558
+ __privateAdd(this, _Shape_instances);
559
+ __privateAdd(this, _stream);
560
+ __privateAdd(this, _data, /* @__PURE__ */ new Map());
561
+ __privateAdd(this, _subscribers2, /* @__PURE__ */ new Map());
562
+ __privateAdd(this, _hasNotifiedSubscribersUpToDate, false);
563
+ __privateAdd(this, _error, false);
564
+ __privateSet(this, _stream, stream);
565
+ __privateGet(this, _stream).subscribe(
566
+ __privateMethod(this, _Shape_instances, process_fn).bind(this),
567
+ __privateMethod(this, _Shape_instances, handleError_fn).bind(this)
568
+ );
569
+ const unsubscribe = __privateGet(this, _stream).subscribeOnceToUpToDate(
465
570
  () => {
466
571
  unsubscribe();
467
572
  },
468
573
  (e) => {
469
- this.handleError(e);
574
+ __privateMethod(this, _Shape_instances, handleError_fn).call(this, e);
470
575
  throw e;
471
576
  }
472
577
  );
473
578
  }
474
- lastSynced() {
475
- return this.stream.lastSynced();
476
- }
477
- isConnected() {
478
- return this.stream.isConnected();
479
- }
480
- /** True during initial fetch. False afterwise. */
481
- isLoading() {
482
- return this.stream.isLoading();
579
+ get isUpToDate() {
580
+ return __privateGet(this, _stream).isUpToDate;
483
581
  }
484
582
  get value() {
485
- return new Promise((resolve) => {
486
- if (this.stream.isUpToDate) {
583
+ return new Promise((resolve, reject) => {
584
+ if (__privateGet(this, _stream).isUpToDate) {
487
585
  resolve(this.valueSync);
488
586
  } else {
489
- const unsubscribe = this.stream.subscribeOnceToUpToDate(
490
- () => {
491
- unsubscribe();
492
- resolve(this.valueSync);
493
- },
494
- (e) => {
495
- throw e;
496
- }
497
- );
587
+ const unsubscribe = this.subscribe((shapeData) => {
588
+ unsubscribe();
589
+ if (__privateGet(this, _error)) reject(__privateGet(this, _error));
590
+ resolve(shapeData);
591
+ });
498
592
  }
499
593
  });
500
594
  }
501
595
  get valueSync() {
502
- return this.data;
596
+ return __privateGet(this, _data);
597
+ }
598
+ get error() {
599
+ return __privateGet(this, _error);
600
+ }
601
+ /** Unix time at which we last synced. Undefined when `isLoading` is true. */
602
+ lastSyncedAt() {
603
+ return __privateGet(this, _stream).lastSyncedAt();
604
+ }
605
+ /** Time elapsed since last sync (in ms). Infinity if we did not yet sync. */
606
+ lastSynced() {
607
+ return __privateGet(this, _stream).lastSynced();
608
+ }
609
+ /** True during initial fetch. False afterwise. */
610
+ isLoading() {
611
+ return __privateGet(this, _stream).isLoading();
612
+ }
613
+ /** Indicates if we are connected to the Electric sync service. */
614
+ isConnected() {
615
+ return __privateGet(this, _stream).isConnected();
503
616
  }
504
617
  subscribe(callback) {
505
618
  const subscriptionId = Math.random();
506
- this.subscribers.set(subscriptionId, callback);
619
+ __privateGet(this, _subscribers2).set(subscriptionId, callback);
507
620
  return () => {
508
- this.subscribers.delete(subscriptionId);
621
+ __privateGet(this, _subscribers2).delete(subscriptionId);
509
622
  };
510
623
  }
511
624
  unsubscribeAll() {
512
- this.subscribers.clear();
625
+ __privateGet(this, _subscribers2).clear();
513
626
  }
514
627
  get numSubscribers() {
515
- return this.subscribers.size;
628
+ return __privateGet(this, _subscribers2).size;
516
629
  }
517
- process(messages) {
518
- let dataMayHaveChanged = false;
519
- let isUpToDate = false;
520
- let newlyUpToDate = false;
521
- messages.forEach((message) => {
522
- if (isChangeMessage(message)) {
523
- dataMayHaveChanged = [`insert`, `update`, `delete`].includes(
524
- message.headers.operation
525
- );
526
- switch (message.headers.operation) {
527
- case `insert`:
528
- this.data.set(message.key, message.value);
529
- break;
530
- case `update`:
531
- this.data.set(message.key, __spreadValues(__spreadValues({}, this.data.get(message.key)), message.value));
532
- break;
533
- case `delete`:
534
- this.data.delete(message.key);
535
- break;
536
- }
537
- }
538
- if (isControlMessage(message)) {
539
- switch (message.headers.control) {
540
- case `up-to-date`:
541
- isUpToDate = true;
542
- if (!this.hasNotifiedSubscribersUpToDate) {
543
- newlyUpToDate = true;
544
- }
545
- break;
546
- case `must-refetch`:
547
- this.data.clear();
548
- this.error = false;
549
- isUpToDate = false;
550
- newlyUpToDate = false;
551
- break;
552
- }
630
+ };
631
+ _stream = new WeakMap();
632
+ _data = new WeakMap();
633
+ _subscribers2 = new WeakMap();
634
+ _hasNotifiedSubscribersUpToDate = new WeakMap();
635
+ _error = new WeakMap();
636
+ _Shape_instances = new WeakSet();
637
+ process_fn = function(messages) {
638
+ let dataMayHaveChanged = false;
639
+ let isUpToDate = false;
640
+ let newlyUpToDate = false;
641
+ messages.forEach((message) => {
642
+ if (isChangeMessage(message)) {
643
+ dataMayHaveChanged = [`insert`, `update`, `delete`].includes(
644
+ message.headers.operation
645
+ );
646
+ switch (message.headers.operation) {
647
+ case `insert`:
648
+ __privateGet(this, _data).set(message.key, message.value);
649
+ break;
650
+ case `update`:
651
+ __privateGet(this, _data).set(message.key, __spreadValues(__spreadValues({}, __privateGet(this, _data).get(message.key)), message.value));
652
+ break;
653
+ case `delete`:
654
+ __privateGet(this, _data).delete(message.key);
655
+ break;
553
656
  }
554
- });
555
- if (newlyUpToDate || isUpToDate && dataMayHaveChanged) {
556
- this.hasNotifiedSubscribersUpToDate = true;
557
- this.notify();
558
657
  }
559
- }
560
- handleError(e) {
561
- if (e instanceof FetchError) {
562
- this.error = e;
563
- this.notify();
658
+ if (isControlMessage(message)) {
659
+ switch (message.headers.control) {
660
+ case `up-to-date`:
661
+ isUpToDate = true;
662
+ if (!__privateGet(this, _hasNotifiedSubscribersUpToDate)) {
663
+ newlyUpToDate = true;
664
+ }
665
+ break;
666
+ case `must-refetch`:
667
+ __privateGet(this, _data).clear();
668
+ __privateSet(this, _error, false);
669
+ isUpToDate = false;
670
+ newlyUpToDate = false;
671
+ break;
672
+ }
564
673
  }
674
+ });
675
+ if (newlyUpToDate || isUpToDate && dataMayHaveChanged) {
676
+ __privateSet(this, _hasNotifiedSubscribersUpToDate, true);
677
+ __privateMethod(this, _Shape_instances, notify_fn).call(this);
565
678
  }
566
- notify() {
567
- this.subscribers.forEach((callback) => {
568
- callback(this.valueSync);
569
- });
679
+ };
680
+ handleError_fn = function(e) {
681
+ if (e instanceof FetchError) {
682
+ __privateSet(this, _error, e);
683
+ __privateMethod(this, _Shape_instances, notify_fn).call(this);
570
684
  }
571
685
  };
686
+ notify_fn = function() {
687
+ __privateGet(this, _subscribers2).forEach((callback) => {
688
+ callback(this.valueSync);
689
+ });
690
+ };
572
691
  // Annotate the CommonJS export names for ESM import in node:
573
692
  0 && (module.exports = {
574
693
  BackoffDefaults,