jotai-state-tree 1.8.0 → 1.9.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.
@@ -3900,6 +3900,689 @@ function useRouter() {
3900
3900
  return router;
3901
3901
  }
3902
3902
 
3903
+ // src/persistence.ts
3904
+ import { atom as atom4 } from "jotai";
3905
+ var workerCode = `
3906
+ self.onmessage = function(e) {
3907
+ const { key, dbName, currentSnapshot } = e.data;
3908
+
3909
+ function applyPatch(obj, patch) {
3910
+ if (patch.path === "" || patch.path === "/") {
3911
+ if (patch.op === "replace") {
3912
+ return JSON.parse(JSON.stringify(patch.value));
3913
+ }
3914
+ return obj;
3915
+ }
3916
+
3917
+ const parts = patch.path.split("/").filter(Boolean);
3918
+ let current = obj;
3919
+ for (let i = 0; i < parts.length - 1; i++) {
3920
+ const part = parts[i];
3921
+ const index = isNaN(part) ? part : Number(part);
3922
+ if (current === undefined || current === null) return obj;
3923
+ current = current[index];
3924
+ }
3925
+ if (current === undefined || current === null) return obj;
3926
+
3927
+ const lastPart = parts[parts.length - 1];
3928
+ const lastKey = isNaN(lastPart) ? lastPart : Number(lastPart);
3929
+
3930
+ if (patch.op === "replace" || patch.op === "add") {
3931
+ const val = patch.value !== undefined ? JSON.parse(JSON.stringify(patch.value)) : undefined;
3932
+ if (patch.op === "replace") {
3933
+ current[lastKey] = val;
3934
+ } else {
3935
+ if (Array.isArray(current)) {
3936
+ current.splice(lastKey, 0, val);
3937
+ } else {
3938
+ current[lastKey] = val;
3939
+ }
3940
+ }
3941
+ } else if (patch.op === "remove") {
3942
+ if (Array.isArray(current)) {
3943
+ current.splice(lastKey, 1);
3944
+ } else {
3945
+ delete current[lastKey];
3946
+ }
3947
+ }
3948
+ return obj;
3949
+ }
3950
+
3951
+ const request = indexedDB.open(dbName, 1);
3952
+ request.onerror = function() {
3953
+ self.postMessage({ error: "Failed to open IndexedDB in worker" });
3954
+ };
3955
+ request.onsuccess = function() {
3956
+ const db = request.result;
3957
+ const tx = db.transaction("sync_queue", "readwrite");
3958
+ const store = tx.objectStore("sync_queue");
3959
+ const getReq = store.getAll();
3960
+
3961
+ getReq.onerror = function() {
3962
+ db.close();
3963
+ self.postMessage({ error: "Failed to get queue from store in worker" });
3964
+ };
3965
+
3966
+ getReq.onsuccess = function() {
3967
+ const allItems = getReq.result || [];
3968
+ const queue = allItems.filter(item => item.key === key);
3969
+
3970
+ if (queue.length <= 1) {
3971
+ db.close();
3972
+ self.postMessage({ success: true, key, compacted: false });
3973
+ return;
3974
+ }
3975
+
3976
+ // Reconstruct initial snapshot by applying inverse patches in reverse order
3977
+ let initialSnapshot = JSON.parse(JSON.stringify(currentSnapshot));
3978
+ for (let i = queue.length - 1; i >= 0; i--) {
3979
+ const item = queue[i];
3980
+ for (let j = item.inversePatches.length - 1; j >= 0; j--) {
3981
+ initialSnapshot = applyPatch(initialSnapshot, item.inversePatches[j]);
3982
+ }
3983
+ }
3984
+
3985
+ // Delete old queue items
3986
+ let deleteCount = 0;
3987
+ let hasError = false;
3988
+
3989
+ function checkDone() {
3990
+ if (hasError) return;
3991
+ if (deleteCount === queue.length) {
3992
+ // Add consolidated item
3993
+ const addReq = store.add({
3994
+ key: key,
3995
+ patches: [{ op: "replace", path: "", value: currentSnapshot }],
3996
+ inversePatches: [{ op: "replace", path: "", value: initialSnapshot }],
3997
+ timestamp: Date.now()
3998
+ });
3999
+
4000
+ addReq.onerror = function() {
4001
+ db.close();
4002
+ self.postMessage({ error: "Failed to add consolidated mutation in worker" });
4003
+ };
4004
+ addReq.onsuccess = function() {
4005
+ db.close();
4006
+ self.postMessage({ success: true, key, compacted: true });
4007
+ };
4008
+ }
4009
+ }
4010
+
4011
+ for (const item of queue) {
4012
+ if (item.id !== undefined) {
4013
+ const delReq = store.delete(item.id);
4014
+ delReq.onerror = function() {
4015
+ hasError = true;
4016
+ db.close();
4017
+ self.postMessage({ error: "Failed to delete queue item in worker" });
4018
+ };
4019
+ delReq.onsuccess = function() {
4020
+ deleteCount++;
4021
+ checkDone();
4022
+ };
4023
+ }
4024
+ }
4025
+ };
4026
+ };
4027
+ };
4028
+ `;
4029
+ var IndexedDBStorage = class {
4030
+ constructor(dbName) {
4031
+ this.db = null;
4032
+ this.dbName = dbName;
4033
+ }
4034
+ async init() {
4035
+ if (this.db) return;
4036
+ return new Promise((resolve, reject) => {
4037
+ if (typeof indexedDB === "undefined") {
4038
+ reject(
4039
+ new Error(
4040
+ "[jotai-state-tree] IndexedDB is not supported in this environment."
4041
+ )
4042
+ );
4043
+ return;
4044
+ }
4045
+ const request = indexedDB.open(this.dbName, 1);
4046
+ request.onupgradeneeded = () => {
4047
+ const db = request.result;
4048
+ if (!db.objectStoreNames.contains("snapshots")) {
4049
+ db.createObjectStore("snapshots");
4050
+ }
4051
+ if (!db.objectStoreNames.contains("sync_queue")) {
4052
+ db.createObjectStore("sync_queue", {
4053
+ keyPath: "id",
4054
+ autoIncrement: true
4055
+ });
4056
+ }
4057
+ };
4058
+ request.onsuccess = () => {
4059
+ this.db = request.result;
4060
+ resolve();
4061
+ };
4062
+ request.onerror = () => {
4063
+ reject(request.error);
4064
+ };
4065
+ });
4066
+ }
4067
+ async getSnapshot(key) {
4068
+ await this.init();
4069
+ return new Promise((resolve, reject) => {
4070
+ const tx = this.db.transaction("snapshots", "readonly");
4071
+ const store = tx.objectStore("snapshots");
4072
+ const req = store.get(key);
4073
+ req.onsuccess = () => resolve(req.result);
4074
+ req.onerror = () => reject(req.error);
4075
+ });
4076
+ }
4077
+ async setSnapshot(key, value) {
4078
+ await this.init();
4079
+ return new Promise((resolve, reject) => {
4080
+ const tx = this.db.transaction("snapshots", "readwrite");
4081
+ const store = tx.objectStore("snapshots");
4082
+ const req = store.put(value, key);
4083
+ req.onsuccess = () => resolve();
4084
+ req.onerror = () => reject(req.error);
4085
+ });
4086
+ }
4087
+ async clearSnapshots() {
4088
+ await this.init();
4089
+ return new Promise((resolve, reject) => {
4090
+ const tx = this.db.transaction("snapshots", "readwrite");
4091
+ const store = tx.objectStore("snapshots");
4092
+ const req = store.clear();
4093
+ req.onsuccess = () => resolve();
4094
+ req.onerror = () => reject(req.error);
4095
+ });
4096
+ }
4097
+ async getQueue(key) {
4098
+ await this.init();
4099
+ return new Promise((resolve, reject) => {
4100
+ const tx = this.db.transaction("sync_queue", "readonly");
4101
+ const store = tx.objectStore("sync_queue");
4102
+ const req = store.getAll();
4103
+ req.onsuccess = () => {
4104
+ const results = req.result.filter(
4105
+ (item) => item.key === key
4106
+ );
4107
+ resolve(results);
4108
+ };
4109
+ req.onerror = () => reject(req.error);
4110
+ });
4111
+ }
4112
+ async addQueue(item) {
4113
+ await this.init();
4114
+ return new Promise((resolve, reject) => {
4115
+ const tx = this.db.transaction("sync_queue", "readwrite");
4116
+ const store = tx.objectStore("sync_queue");
4117
+ const req = store.add(item);
4118
+ req.onsuccess = () => resolve(req.result);
4119
+ req.onerror = () => reject(req.error);
4120
+ });
4121
+ }
4122
+ async deleteQueue(id) {
4123
+ await this.init();
4124
+ return new Promise((resolve, reject) => {
4125
+ const tx = this.db.transaction("sync_queue", "readwrite");
4126
+ const store = tx.objectStore("sync_queue");
4127
+ const req = store.delete(id);
4128
+ req.onsuccess = () => resolve();
4129
+ req.onerror = () => reject(req.error);
4130
+ });
4131
+ }
4132
+ async clearQueue(key) {
4133
+ await this.init();
4134
+ const items = await this.getQueue(key);
4135
+ if (items.length === 0) return;
4136
+ return new Promise((resolve, reject) => {
4137
+ const tx = this.db.transaction("sync_queue", "readwrite");
4138
+ const store = tx.objectStore("sync_queue");
4139
+ let completed = 0;
4140
+ let hasError = false;
4141
+ for (const item of items) {
4142
+ if (item.id !== void 0) {
4143
+ const req = store.delete(item.id);
4144
+ req.onsuccess = () => {
4145
+ completed++;
4146
+ if (completed === items.length && !hasError) {
4147
+ resolve();
4148
+ }
4149
+ };
4150
+ req.onerror = () => {
4151
+ hasError = true;
4152
+ reject(req.error);
4153
+ };
4154
+ }
4155
+ }
4156
+ });
4157
+ }
4158
+ };
4159
+ function defaultShouldRollback(error) {
4160
+ if (typeof navigator !== "undefined" && !navigator.onLine) {
4161
+ return false;
4162
+ }
4163
+ const errMsg = String(error.message || error).toLowerCase();
4164
+ if (errMsg.includes("network") || errMsg.includes("fetch") || errMsg.includes("timeout") || errMsg.includes("abort") || errMsg.includes("failed to fetch")) {
4165
+ return false;
4166
+ }
4167
+ return true;
4168
+ }
4169
+ var PersistenceManager = class {
4170
+ constructor(target, options = {}) {
4171
+ this.key = "root";
4172
+ this.patchDisposer = null;
4173
+ this.skipSyncing = false;
4174
+ this.lastFetchedTime = 0;
4175
+ this.fetchTimeout = null;
4176
+ // Optimistic & High-Performance Batching State
4177
+ this.pendingPatches = [];
4178
+ this.pendingInversePatches = [];
4179
+ this.batchScheduled = false;
4180
+ this.debounceSnapshotTimeout = null;
4181
+ this.lastSnapshotToWrite = null;
4182
+ // Window Focus and Reconnect Listeners
4183
+ this.focusListener = null;
4184
+ this.onlineListener = null;
4185
+ this.offlineListener = null;
4186
+ this.target = target;
4187
+ this.options = options;
4188
+ if (typeof indexedDB === "undefined") {
4189
+ throw new Error(
4190
+ "[jotai-state-tree] IndexedDB is not supported in this environment."
4191
+ );
4192
+ }
4193
+ if (options.key) {
4194
+ this.key = options.key;
4195
+ } else {
4196
+ const node = getStateTreeNode(target);
4197
+ const idAttribute = node.$type.identifierAttribute;
4198
+ if (idAttribute) {
4199
+ const idValue = target[idAttribute];
4200
+ if (idValue !== void 0 && idValue !== null) {
4201
+ this.key = String(idValue);
4202
+ }
4203
+ }
4204
+ }
4205
+ const dbName = options.dbName ?? "jotai-state-tree-persistence";
4206
+ this.storage = new IndexedDBStorage(dbName);
4207
+ const initialOffline = typeof navigator !== "undefined" ? !navigator.onLine : false;
4208
+ this.statusAtom = atom4({
4209
+ isLoading: true,
4210
+ isFetching: false,
4211
+ isSyncing: false,
4212
+ isOffline: initialOffline,
4213
+ pendingSyncCount: 0,
4214
+ error: null
4215
+ });
4216
+ }
4217
+ async initialize() {
4218
+ const store = getGlobalStore();
4219
+ const cachedSnapshot = await this.storage.getSnapshot(this.key);
4220
+ let queue = await this.storage.getQueue(this.key);
4221
+ if (cachedSnapshot !== void 0 && cachedSnapshot !== null) {
4222
+ this.skipSyncing = true;
4223
+ try {
4224
+ applySnapshot(this.target, cachedSnapshot);
4225
+ } finally {
4226
+ this.skipSyncing = false;
4227
+ }
4228
+ store.set(this.statusAtom, (prev) => ({
4229
+ ...prev,
4230
+ isLoading: false
4231
+ }));
4232
+ } else {
4233
+ store.set(this.statusAtom, (prev) => ({
4234
+ ...prev,
4235
+ isLoading: !!this.options.query?.queryFn
4236
+ }));
4237
+ }
4238
+ const maxQueueSize = this.options.maxQueueSize ?? 20;
4239
+ if (queue.length > maxQueueSize) {
4240
+ try {
4241
+ await this.compact();
4242
+ queue = await this.storage.getQueue(this.key);
4243
+ } catch (err) {
4244
+ console.warn("[jotai-state-tree] Initial compaction failed:", err);
4245
+ }
4246
+ }
4247
+ store.set(this.statusAtom, (prev) => ({
4248
+ ...prev,
4249
+ pendingSyncCount: queue.length
4250
+ }));
4251
+ this.patchDisposer = onPatch(this.target, (patch, reversePatch) => {
4252
+ this.handlePatch(patch, reversePatch);
4253
+ });
4254
+ if (typeof window !== "undefined") {
4255
+ this.onlineListener = () => {
4256
+ store.set(this.statusAtom, (prev) => ({ ...prev, isOffline: false }));
4257
+ this.sync();
4258
+ if (this.options.query?.refetchOnReconnect !== false) {
4259
+ this.fetch();
4260
+ }
4261
+ };
4262
+ this.offlineListener = () => {
4263
+ store.set(this.statusAtom, (prev) => ({ ...prev, isOffline: true }));
4264
+ };
4265
+ window.addEventListener("online", this.onlineListener);
4266
+ window.addEventListener("offline", this.offlineListener);
4267
+ if (this.options.query?.refetchOnWindowFocus) {
4268
+ this.focusListener = () => {
4269
+ this.fetch();
4270
+ };
4271
+ window.addEventListener("focus", this.focusListener);
4272
+ }
4273
+ }
4274
+ if (this.options.query?.queryFn) {
4275
+ this.fetchTimeout = setTimeout(() => this.fetch(), 0);
4276
+ }
4277
+ if (queue.length > 0) {
4278
+ await this.sync();
4279
+ }
4280
+ }
4281
+ async fetch(force = false) {
4282
+ const query = this.options.query;
4283
+ if (!query?.queryFn) return;
4284
+ const store = getGlobalStore();
4285
+ const status = store.get(this.statusAtom);
4286
+ if (status.isFetching) return;
4287
+ if (!force && query.staleTime !== void 0) {
4288
+ const now = Date.now();
4289
+ if (now - this.lastFetchedTime < query.staleTime) {
4290
+ return;
4291
+ }
4292
+ }
4293
+ store.set(this.statusAtom, (prev) => ({
4294
+ ...prev,
4295
+ isFetching: true
4296
+ }));
4297
+ try {
4298
+ const data = await query.queryFn();
4299
+ if (data !== void 0 && data !== null) {
4300
+ this.skipSyncing = true;
4301
+ try {
4302
+ applySnapshot(this.target, data);
4303
+ } finally {
4304
+ this.skipSyncing = false;
4305
+ }
4306
+ this.lastSnapshotToWrite = data;
4307
+ await this.storage.setSnapshot(this.key, data);
4308
+ }
4309
+ this.lastFetchedTime = Date.now();
4310
+ store.set(this.statusAtom, (prev) => ({
4311
+ ...prev,
4312
+ isFetching: false,
4313
+ isLoading: false,
4314
+ error: null
4315
+ }));
4316
+ } catch (err) {
4317
+ const error = err instanceof Error ? err : new Error(String(err));
4318
+ store.set(this.statusAtom, (prev) => ({
4319
+ ...prev,
4320
+ isFetching: false,
4321
+ isLoading: false,
4322
+ error
4323
+ }));
4324
+ throw error;
4325
+ }
4326
+ }
4327
+ handlePatch(patch, reversePatch) {
4328
+ if (this.skipSyncing) return;
4329
+ this.pendingPatches.push(patch);
4330
+ this.pendingInversePatches.push(reversePatch);
4331
+ if (!this.batchScheduled) {
4332
+ this.batchScheduled = true;
4333
+ Promise.resolve().then(() => {
4334
+ this.flushBatch();
4335
+ });
4336
+ }
4337
+ }
4338
+ async flushBatch() {
4339
+ this.batchScheduled = false;
4340
+ const patches = [...this.pendingPatches];
4341
+ const inversePatches = [...this.pendingInversePatches];
4342
+ this.pendingPatches = [];
4343
+ this.pendingInversePatches = [];
4344
+ if (patches.length === 0) return;
4345
+ const currentSnapshot = getSnapshot(this.target);
4346
+ this.lastSnapshotToWrite = currentSnapshot;
4347
+ if (this.debounceSnapshotTimeout) {
4348
+ clearTimeout(this.debounceSnapshotTimeout);
4349
+ }
4350
+ this.debounceSnapshotTimeout = setTimeout(async () => {
4351
+ if (this.lastSnapshotToWrite) {
4352
+ await this.storage.setSnapshot(this.key, this.lastSnapshotToWrite);
4353
+ }
4354
+ }, 150);
4355
+ if (this.options.mutation?.syncFn) {
4356
+ await this.storage.addQueue({
4357
+ key: this.key,
4358
+ patches,
4359
+ inversePatches,
4360
+ timestamp: Date.now()
4361
+ });
4362
+ const store = getGlobalStore();
4363
+ let queue = await this.storage.getQueue(this.key);
4364
+ const maxQueueSize = this.options.maxQueueSize ?? 20;
4365
+ if (queue.length > maxQueueSize) {
4366
+ try {
4367
+ await this.compact();
4368
+ queue = await this.storage.getQueue(this.key);
4369
+ } catch (err) {
4370
+ console.warn("[jotai-state-tree] Auto-compaction failed:", err);
4371
+ }
4372
+ }
4373
+ store.set(this.statusAtom, (prev) => ({
4374
+ ...prev,
4375
+ pendingSyncCount: queue.length
4376
+ }));
4377
+ try {
4378
+ await this.sync();
4379
+ } catch (err) {
4380
+ }
4381
+ }
4382
+ }
4383
+ /**
4384
+ * Compacts the queue by squashing multiple mutations into a single root replacement patch.
4385
+ * Runs in a background Web Worker if supported, falling back to main-thread execution.
4386
+ */
4387
+ async compact() {
4388
+ const store = getGlobalStore();
4389
+ const currentSnapshot = getSnapshot(this.target);
4390
+ const dbName = this.options.dbName ?? "jotai-state-tree-persistence";
4391
+ const isWorkerSupported = typeof Worker !== "undefined" && typeof Blob !== "undefined" && typeof URL !== "undefined";
4392
+ if (isWorkerSupported) {
4393
+ return new Promise((resolve, reject) => {
4394
+ try {
4395
+ const blob = new Blob([workerCode], {
4396
+ type: "application/javascript"
4397
+ });
4398
+ const workerUrl = URL.createObjectURL(blob);
4399
+ const worker = new Worker(workerUrl);
4400
+ worker.onmessage = async (e) => {
4401
+ worker.terminate();
4402
+ URL.revokeObjectURL(workerUrl);
4403
+ if (e.data.error) {
4404
+ reject(new Error(e.data.error));
4405
+ } else {
4406
+ const queue = await this.storage.getQueue(this.key);
4407
+ store.set(this.statusAtom, (prev) => ({
4408
+ ...prev,
4409
+ pendingSyncCount: queue.length
4410
+ }));
4411
+ resolve();
4412
+ }
4413
+ };
4414
+ worker.onerror = (err) => {
4415
+ worker.terminate();
4416
+ URL.revokeObjectURL(workerUrl);
4417
+ reject(err);
4418
+ };
4419
+ worker.postMessage({
4420
+ key: this.key,
4421
+ dbName,
4422
+ currentSnapshot
4423
+ });
4424
+ } catch (err) {
4425
+ reject(err);
4426
+ }
4427
+ });
4428
+ } else {
4429
+ const queue = await this.storage.getQueue(this.key);
4430
+ if (queue.length <= 1) return;
4431
+ this.skipSyncing = true;
4432
+ try {
4433
+ for (let i = queue.length - 1; i >= 0; i--) {
4434
+ const item = queue[i];
4435
+ for (let j = item.inversePatches.length - 1; j >= 0; j--) {
4436
+ applyPatch(this.target, item.inversePatches[j]);
4437
+ }
4438
+ }
4439
+ } finally {
4440
+ this.skipSyncing = false;
4441
+ }
4442
+ const initialSnapshot = getSnapshot(this.target);
4443
+ this.skipSyncing = true;
4444
+ try {
4445
+ applySnapshot(this.target, currentSnapshot);
4446
+ } finally {
4447
+ this.skipSyncing = false;
4448
+ }
4449
+ await this.storage.clearQueue(this.key);
4450
+ await this.storage.addQueue({
4451
+ key: this.key,
4452
+ patches: [{ op: "replace", path: "", value: currentSnapshot }],
4453
+ inversePatches: [{ op: "replace", path: "", value: initialSnapshot }],
4454
+ timestamp: Date.now()
4455
+ });
4456
+ const newQueue = await this.storage.getQueue(this.key);
4457
+ store.set(this.statusAtom, (prev) => ({
4458
+ ...prev,
4459
+ pendingSyncCount: newQueue.length
4460
+ }));
4461
+ }
4462
+ }
4463
+ async sync() {
4464
+ const mutation = this.options.mutation;
4465
+ if (!mutation?.syncFn) return;
4466
+ const store = getGlobalStore();
4467
+ const status = store.get(this.statusAtom);
4468
+ if (status.isSyncing || status.isOffline) return;
4469
+ store.set(this.statusAtom, (prev) => ({ ...prev, isSyncing: true }));
4470
+ try {
4471
+ let queue = await this.storage.getQueue(this.key);
4472
+ while (queue.length > 0) {
4473
+ if (typeof navigator !== "undefined" && !navigator.onLine) {
4474
+ store.set(this.statusAtom, (prev) => ({ ...prev, isOffline: true }));
4475
+ break;
4476
+ }
4477
+ const item = queue[0];
4478
+ try {
4479
+ const currentSnapshot = getSnapshot(this.target);
4480
+ const syncResult = await mutation.syncFn(
4481
+ currentSnapshot,
4482
+ item.patches
4483
+ );
4484
+ if (item.id !== void 0) {
4485
+ await this.storage.deleteQueue(item.id);
4486
+ }
4487
+ if (mutation.onSuccess) {
4488
+ mutation.onSuccess(syncResult);
4489
+ }
4490
+ } catch (err) {
4491
+ const error = err instanceof Error ? err : new Error(String(err));
4492
+ const shouldRollback = mutation.shouldRollback ?? defaultShouldRollback;
4493
+ if (shouldRollback(error)) {
4494
+ this.skipSyncing = true;
4495
+ try {
4496
+ for (let i = item.inversePatches.length - 1; i >= 0; i--) {
4497
+ applyPatch(this.target, item.inversePatches[i]);
4498
+ }
4499
+ const currentSnapshot = getSnapshot(this.target);
4500
+ this.lastSnapshotToWrite = currentSnapshot;
4501
+ await this.storage.setSnapshot(this.key, currentSnapshot);
4502
+ } finally {
4503
+ this.skipSyncing = false;
4504
+ }
4505
+ if (item.id !== void 0) {
4506
+ await this.storage.deleteQueue(item.id);
4507
+ }
4508
+ if (mutation.onError) {
4509
+ mutation.onError(error);
4510
+ }
4511
+ throw error;
4512
+ } else {
4513
+ store.set(this.statusAtom, (prev) => ({ ...prev, error }));
4514
+ if (mutation.onError) {
4515
+ mutation.onError(error);
4516
+ }
4517
+ break;
4518
+ }
4519
+ }
4520
+ queue = await this.storage.getQueue(this.key);
4521
+ store.set(this.statusAtom, (prev) => ({
4522
+ ...prev,
4523
+ pendingSyncCount: queue.length
4524
+ }));
4525
+ }
4526
+ const finalQueue = await this.storage.getQueue(this.key);
4527
+ store.set(this.statusAtom, (prev) => ({
4528
+ ...prev,
4529
+ isSyncing: false,
4530
+ pendingSyncCount: finalQueue.length,
4531
+ error: finalQueue.length === 0 ? null : prev.error
4532
+ }));
4533
+ } catch (err) {
4534
+ const error = err instanceof Error ? err : new Error(String(err));
4535
+ store.set(this.statusAtom, (prev) => ({
4536
+ ...prev,
4537
+ isSyncing: false,
4538
+ error
4539
+ }));
4540
+ throw error;
4541
+ }
4542
+ }
4543
+ async clear() {
4544
+ await this.storage.clearSnapshots();
4545
+ await this.storage.clearQueue(this.key);
4546
+ const store = getGlobalStore();
4547
+ store.set(this.statusAtom, (prev) => ({
4548
+ ...prev,
4549
+ pendingSyncCount: 0,
4550
+ error: null
4551
+ }));
4552
+ }
4553
+ dispose() {
4554
+ if (this.fetchTimeout) {
4555
+ clearTimeout(this.fetchTimeout);
4556
+ this.fetchTimeout = null;
4557
+ }
4558
+ if (this.debounceSnapshotTimeout) {
4559
+ clearTimeout(this.debounceSnapshotTimeout);
4560
+ this.debounceSnapshotTimeout = null;
4561
+ }
4562
+ if (this.patchDisposer) {
4563
+ this.patchDisposer();
4564
+ this.patchDisposer = null;
4565
+ }
4566
+ if (typeof window !== "undefined") {
4567
+ if (this.onlineListener) {
4568
+ window.removeEventListener("online", this.onlineListener);
4569
+ this.onlineListener = null;
4570
+ }
4571
+ if (this.offlineListener) {
4572
+ window.removeEventListener("offline", this.offlineListener);
4573
+ this.offlineListener = null;
4574
+ }
4575
+ if (this.focusListener) {
4576
+ window.removeEventListener("focus", this.focusListener);
4577
+ this.focusListener = null;
4578
+ }
4579
+ }
4580
+ }
4581
+ };
4582
+ function createPersistenceManager(target, options) {
4583
+ return new PersistenceManager(target, options);
4584
+ }
4585
+
3903
4586
  export {
3904
4587
  string,
3905
4588
  number,
@@ -4005,5 +4688,7 @@ export {
4005
4688
  RouterModel,
4006
4689
  createRouter,
4007
4690
  RouterContext,
4008
- useRouter
4691
+ useRouter,
4692
+ PersistenceManager,
4693
+ createPersistenceManager
4009
4694
  };