tsdf 18.0.1 → 18.1.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,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CxDIO_Pv.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1108,6 +1108,13 @@ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
1108
1108
  registry.delete(getStoreRegistryKey(sessionKey, storeName));
1109
1109
  if (registry.size === 0) registeredAsyncStartupStoreCleanupCallbacks.delete(adapter);
1110
1110
  }
1111
+ /**
1112
+ * Managed adapters keyed by themselves. Helpers used by the `local-sync`
1113
+ * persistence paths look adapters up here instead of using `instanceof`, so
1114
+ * bundlers can drop the `ManagedAsyncStorageAdapter` class from apps that never
1115
+ * create an async adapter.
1116
+ */
1117
+ const managedAsyncStorageAdapters = /* @__PURE__ */ new WeakMap();
1111
1118
  var ManagedAsyncStorageAdapter = class {
1112
1119
  kind = "async";
1113
1120
  #driver;
@@ -1125,6 +1132,7 @@ var ManagedAsyncStorageAdapter = class {
1125
1132
  constructor(driver) {
1126
1133
  this.#driver = driver;
1127
1134
  registerAsyncStorageReadCacheParticipant(this);
1135
+ managedAsyncStorageAdapters.set(this, this);
1128
1136
  }
1129
1137
  get debugLogger() {
1130
1138
  return this.#debugLogger;
@@ -2224,7 +2232,8 @@ const PER_KEY_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE = 25;
2224
2232
  const INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE = 250;
2225
2233
  /** Number of keys idle-deadline maintenance removes per commit. */
2226
2234
  function getAsyncStorageMaintenanceRemoveBatchSize(adapter) {
2227
- return adapter instanceof ManagedAsyncStorageAdapter ? adapter.getMaintenanceRemoveBatchSize() : INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE;
2235
+ const managedAdapter = adapter && managedAsyncStorageAdapters.get(adapter);
2236
+ return managedAdapter ? managedAdapter.getMaintenanceRemoveBatchSize() : INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE;
2228
2237
  }
2229
2238
  /**
2230
2239
  * Removes entries only while they still have the metadata the caller read,
@@ -2233,7 +2242,8 @@ function getAsyncStorageMaintenanceRemoveBatchSize(adapter) {
2233
2242
  * other adapters only get a best-effort metadata re-read before removing.
2234
2243
  */
2235
2244
  async function removeAsyncStorageNamespaceEntriesIfUnchanged(adapter, scope, entries) {
2236
- if (adapter instanceof ManagedAsyncStorageAdapter) return adapter.commitToNamespaceNow(scope, { conditionalRemoves: entries });
2245
+ const managedAdapter = managedAsyncStorageAdapters.get(adapter);
2246
+ if (managedAdapter) return managedAdapter.commitToNamespaceNow(scope, { conditionalRemoves: entries });
2237
2247
  const namespace = adapter.openNamespace(scope);
2238
2248
  const currentEntries = new Map((await namespace.listMetadata()).map((entry) => [entry.key, entry]));
2239
2249
  const removes = [];
@@ -1,3 +1,3 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-JsSCNBTr.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-BameJ4st.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CZThibFg.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-BEJA8z8c.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-BameJ4st.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-BEJA8z8c.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { $ as parseAsyncStorageRecordKey, A as serializeJsonForStorage, J as getNamespaceId, K as compareMetadata, Q as normalizeStaticPolicy, X as getPersistedNamespaceId, Y as getPayloadRecordKey, Z as matchesConditionalRemove, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, tt as serializeProtectedRef, y as emitTSDFDebugLog } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { $ as parseAsyncStorageRecordKey, A as serializeJsonForStorage, J as getNamespaceId, K as compareMetadata, Q as normalizeStaticPolicy, X as getPersistedNamespaceId, Y as getPayloadRecordKey, Z as matchesConditionalRemove, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, tt as serializeProtectedRef, y as emitTSDFDebugLog } from "./asyncStorageAdapter-CxDIO_Pv.js";
2
2
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
3
3
  import { isObject } from "@ls-stack/utils/typeGuards";
4
4
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
package/dist/main.d.ts CHANGED
@@ -44,7 +44,7 @@ type StoreManagerStoreDefaults = {
44
44
  /** Default minimum interval between low-priority fetches for attached stores. */readonly lowPriorityThrottleMs: number; /** Default coalescing window used by attached stores when they do not override it. */
45
45
  readonly baseCoalescingWindowMs: number; /** Extra browser-tab coalescing delay applied only while a tab is in the background. */
46
46
  readonly backgroundCoalescingDelayMs: number; /** Default adaptive throttle for real-time updates in attached stores. */
47
- readonly dynamicRealtimeThrottleMs: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. */
47
+ readonly dynamicRealtimeThrottleMs: DynamicRealtimeThrottleMs; /** Shared window-close blocker held by every mutation in attached stores from start until it settles. */
48
48
  readonly blockWindowClose: BlockWindowCloseHandler | null; /** Default focus revalidation policy for attached stores. */
49
49
  readonly revalidateOnWindowFocus: boolean | (() => boolean) | undefined;
50
50
  };
@@ -106,7 +106,7 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
106
106
  lowPriorityThrottleMs?: number; /** Default coalescing window for attached stores. Defaults to 16ms. */
107
107
  baseCoalescingWindowMs?: number; /** Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to 3000ms. */
108
108
  backgroundCoalescingDelayMs?: number; /** Default adaptive throttle for real-time updates in attached stores. Store-level values override it. */
109
- dynamicRealtimeThrottleMs?: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. Pass `null` to disable. */
109
+ dynamicRealtimeThrottleMs?: DynamicRealtimeThrottleMs; /** Shared window-close blocker held by every mutation in attached stores from start until it settles. Pass `null` to disable. */
110
110
  blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
111
111
  onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
112
112
  onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-URS9eulL.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-JsSCNBTr.js";
1
+ import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-CxDIO_Pv.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-CZThibFg.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { deepEqual } from "@ls-stack/utils/deepEqual";
@@ -2789,7 +2789,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2789
2789
  }
2790
2790
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2791
2791
  async function clearAllSessionStorage(sessionKey) {
2792
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Bxrrj_Mt.js");
2792
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Dno2qiLy.js");
2793
2793
  await Promise.all([
2794
2794
  clearSessionStorage(sessionKey, "local-sync"),
2795
2795
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -5289,38 +5289,41 @@ var SessionOfflineCoordinator = class {
5289
5289
  }
5290
5290
  #scheduleRecoveryProbe(target) {
5291
5291
  this.#scheduledRecoveryMode = target.mode;
5292
- this.#recoveryTimer = setTimeout(async () => {
5292
+ this.#recoveryTimer = setTimeout(() => {
5293
5293
  this.#recoveryTimer = null;
5294
5294
  this.#scheduledRecoveryMode = null;
5295
- const nextTarget = this.#getDesiredRecoveryTarget();
5296
- if (nextTarget === null || nextTarget.mode !== target.mode) return;
5297
- let recovered = false;
5298
- try {
5299
- recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5300
- } catch {
5301
- recovered = false;
5302
- }
5303
- const recoveryCheckAt = Date.now();
5304
- if (recovered) {
5305
- this.#recoveryAttempt = 0;
5306
- if (target.mode === "network") {
5307
- this.setNetworkActive(false, {
5308
- classified: false,
5309
- recoveryCheckAt
5310
- });
5311
- return;
5312
- }
5313
- this.setOutageActive(false, { recoveryCheckAt });
5295
+ this.#runRecoveryProbe(target);
5296
+ }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5297
+ }
5298
+ async #runRecoveryProbe(target) {
5299
+ const nextTarget = this.#getDesiredRecoveryTarget();
5300
+ if (nextTarget === null || nextTarget.mode !== target.mode) return;
5301
+ let recovered = false;
5302
+ try {
5303
+ recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5304
+ } catch {
5305
+ recovered = false;
5306
+ }
5307
+ const recoveryCheckAt = Date.now();
5308
+ if (recovered) {
5309
+ this.#recoveryAttempt = 0;
5310
+ if (target.mode === "network") {
5311
+ this.setNetworkActive(false, {
5312
+ classified: false,
5313
+ recoveryCheckAt
5314
+ });
5314
5315
  return;
5315
5316
  }
5316
- this.#updateStatus((current) => ({
5317
- ...current,
5318
- lastRecoveryCheckAt: recoveryCheckAt
5319
- }));
5320
- this.#recoveryAttempt += 1;
5321
- const nextProbeTarget = this.#getDesiredRecoveryTarget();
5322
- if (nextProbeTarget !== null && nextProbeTarget.mode === target.mode) this.#scheduleRecoveryProbe(nextProbeTarget);
5323
- }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5317
+ this.setOutageActive(false, { recoveryCheckAt });
5318
+ return;
5319
+ }
5320
+ this.#updateStatus((current) => ({
5321
+ ...current,
5322
+ lastRecoveryCheckAt: recoveryCheckAt
5323
+ }));
5324
+ this.#recoveryAttempt += 1;
5325
+ const nextProbeTarget = this.#getDesiredRecoveryTarget();
5326
+ if (nextProbeTarget !== null && nextProbeTarget.mode === target.mode) this.#scheduleRecoveryProbe(nextProbeTarget);
5324
5327
  }
5325
5328
  #syncRecoveryProbe() {
5326
5329
  const target = this.#getDesiredRecoveryTarget();
@@ -8596,8 +8599,8 @@ async function performMutationWithLifecycle(startMutation, mutation, onError, op
8596
8599
  endMutation();
8597
8600
  return Result.err(mutationSkipped);
8598
8601
  }
8602
+ unblockWindowClose = blockWindowClose?.().unblock ?? null;
8599
8603
  if (debounce) {
8600
- unblockWindowClose = blockWindowClose?.().unblock ?? null;
8601
8604
  const debounceKey = getCompositeKey([debounce.context, debounce.payload]);
8602
8605
  const groupRollbacks = pendingDebounceRollbacks.get(debounceKey) ?? [];
8603
8606
  groupRollbacks.push(...rollbacks);
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-JsSCNBTr.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CZThibFg.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { $ as parseAsyncStorageRecordKey, J as getNamespaceId, Y as getPayloadRecordKey, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, y as emitTSDFDebugLog } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { $ as parseAsyncStorageRecordKey, J as getNamespaceId, Y as getPayloadRecordKey, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, y as emitTSDFDebugLog } from "./asyncStorageAdapter-CxDIO_Pv.js";
2
2
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
3
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
4
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -887,6 +887,6 @@ var OpfsAsyncStorageDriver = class {
887
887
  };
888
888
  //#endregion
889
889
  //#region src/persistentStorage/opfsPersistentStorage.ts
890
- const opfsPersistentStorage = /* @__PURE__ */ createAsyncStorageAdapter(new OpfsAsyncStorageDriver());
890
+ const opfsPersistentStorage = /* @__PURE__ */ createAsyncStorageAdapter(/* @__PURE__ */ new OpfsAsyncStorageDriver());
891
891
  //#endregion
892
892
  export { encodePathSegment as a, getNavigatorStorageDirectory as i, getDirectoryHandleIfExists as n, getFileHandleIfExists as r, opfsPersistentStorage as t };
package/docs/mutations.md CHANGED
@@ -83,11 +83,12 @@ The payload can be:
83
83
 
84
84
  1. **Lock**: The scheduler is locked for the affected items/queries, preventing concurrent fetches. An in-flight fetch for them is aborted so it can't commit stale data, and it is retried once the lock is released. Calls awaiting the aborted fetch (e.g. `awaitFetch`, `getItemFromStateOrFetch`) resolve with the retry's result
85
85
  2. **Optimistic update**: If provided, runs immediately. If it returns `false`, the mutation is cancelled
86
- 3. **Debounce** (optional): Waits for `ms` milliseconds. During debounce, the window close is blocked
87
- 4. **Execute mutation**: The async mutation function runs
88
- 5. **On success**: Calls `onSuccess`, optionally invalidates data
89
- 6. **On error**: Rolls back optimistic state, normalizes the error, and calls `onMutationError` with the `silentErrors` flag
90
- 7. **Unlock**: The scheduler is unlocked, pending fetches resume
86
+ 3. **Block window close**: If the manager `blockWindowClose` option is set, window close is blocked until the mutation settles (including the debounce wait)
87
+ 4. **Debounce** (optional): Waits for `ms` milliseconds
88
+ 5. **Execute mutation**: The async mutation function runs
89
+ 6. **On success**: Calls `onSuccess`, optionally invalidates data
90
+ 7. **On error**: Rolls back optimistic state, normalizes the error, and calls `onMutationError` with the `silentErrors` flag
91
+ 8. **Unlock**: The scheduler is unlocked, pending fetches resume
91
92
 
92
93
  ## Return Value
93
94
 
@@ -157,7 +158,7 @@ await store.performMutation({
157
158
  });
158
159
  ```
159
160
 
160
- During the debounce period, the window close is blocked to prevent data loss.
161
+ The window close stays blocked during the debounce period too, so a pending debounced mutation isn't lost if the tab is closed.
161
162
 
162
163
  Superseded calls never send their mutation, so their optimistic updates are handed to the call that superseded them: if that call fails, the state goes back to what it was before the first superseded call.
163
164
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "18.0.1",
3
+ "version": "18.1.1",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",