tsdf 17.0.0-alpha.13 → 17.0.0-alpha.15

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 { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-JtfdnFhk.js";
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-DgbL6kBV.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-BaojFC2B.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-B-pdNeAs.js";
2
2
  export { createAsyncStorageAdapter };
@@ -333,7 +333,10 @@ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBy
333
333
  }
334
334
  if (unprotectedBytes <= maxBytes) {
335
335
  for (const entry of entries) keptKeys.add(getKey(entry));
336
- return keptKeys;
336
+ return {
337
+ keptKeys,
338
+ unprotectedBytes
339
+ };
337
340
  }
338
341
  const sortedEntries = [...entries].sort((a, b) => {
339
342
  const aProtected = isProtected(a);
@@ -364,7 +367,10 @@ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBy
364
367
  keptUnprotectedBytes += sizeBytes;
365
368
  }
366
369
  }
367
- return keptKeys;
370
+ return {
371
+ keptKeys,
372
+ unprotectedBytes
373
+ };
368
374
  }
369
375
  //#endregion
370
376
  //#region src/persistentStorage/persistentStorageDefaults.ts
@@ -397,6 +403,57 @@ function getDefaultMaxBytesForScope(adapter, scopeKind) {
397
403
  return getDefaultMaxBytesForAdapter(adapter, getDefaultMaxBytesKindForScope(scopeKind));
398
404
  }
399
405
  //#endregion
406
+ //#region src/debug.ts
407
+ function defaultConsoleDebugLogger(entry) {
408
+ const consoleForLevel = globalThis.console[entry.level];
409
+ if (typeof consoleForLevel !== "function") return;
410
+ const details = entry.details ? {
411
+ operation: entry.operation,
412
+ ...entry.details
413
+ } : { operation: entry.operation };
414
+ consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
415
+ }
416
+ function resolveTSDFLogger(logger) {
417
+ if (logger === void 0 || logger === false) return void 0;
418
+ if (logger === true) return defaultConsoleDebugLogger;
419
+ return logger;
420
+ }
421
+ function emitTSDFDebugLog(logger, entry) {
422
+ if (!logger) return;
423
+ try {
424
+ logger(entry);
425
+ } catch (error) {
426
+ globalThis.console.error("[tsdf:debug] Debug logger failed", error);
427
+ }
428
+ }
429
+ function getTSDFDebugTimingMs() {
430
+ if (!import.meta.env.DEV) return 0;
431
+ return Date.now();
432
+ }
433
+ //#endregion
434
+ //#region src/persistentStorage/quotaDebug.ts
435
+ function logPersistentStorageQuotaCleanup(args) {
436
+ emitTSDFDebugLog(args.logger, {
437
+ area: "persistent-storage",
438
+ details: {
439
+ adapter: args.adapter,
440
+ evictedEntries: args.evictedEntries,
441
+ keptEntries: args.keptEntries,
442
+ maxBytes: args.maxBytes,
443
+ namespaceKind: args.namespaceKind,
444
+ phase: args.phase,
445
+ quota: args.quota,
446
+ status: "success",
447
+ storeName: args.storeName,
448
+ totalEntries: args.totalEntries,
449
+ unprotectedBytes: args.unprotectedBytes
450
+ },
451
+ level: "log",
452
+ message: "persistent storage quota-cleanup success",
453
+ operation: "quota-cleanup"
454
+ });
455
+ }
456
+ //#endregion
400
457
  //#region src/persistentStorage/types.ts
401
458
  function parseAsyncStorageNamespaceKind(value) {
402
459
  switch (value) {
@@ -831,6 +888,7 @@ var ManagedAsyncStorageAdapter = class {
831
888
  kind = "async";
832
889
  #driver;
833
890
  #debugLogger;
891
+ #logger;
834
892
  #cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
835
893
  #cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
836
894
  #namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
@@ -850,6 +908,13 @@ var ManagedAsyncStorageAdapter = class {
850
908
  this.#debugLogger = debugLogger;
851
909
  this.#driver.debugLogger = debugLogger;
852
910
  }
911
+ get logger() {
912
+ return this.#logger;
913
+ }
914
+ set logger(logger) {
915
+ this.#logger = logger;
916
+ this.#driver.logger = logger;
917
+ }
853
918
  async #runWithSessionWriterLock(sessionKey, callback) {
854
919
  return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
855
920
  }
@@ -1765,7 +1830,25 @@ var ManagedAsyncStorageAdapter = class {
1765
1830
  for (const payloadKey of payloadKeys) if (!indexState.entries.has(payloadKey)) payloadRecordKeysToRemove.add(getPayloadRecordKey(payloadKey));
1766
1831
  if (effectiveStaticPolicy?.maxBytes !== void 0) {
1767
1832
  const pinnedKeys = new Set(effectiveStaticPolicy.pinnedKeys ?? []);
1768
- const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1833
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1834
+ const logger = args.driver.logger;
1835
+ const evictedEntries = candidateEntries.length - keptKeys.size;
1836
+ if (logger && evictedEntries > 0) {
1837
+ const scopeKind = args.scope.kind;
1838
+ logPersistentStorageQuotaCleanup({
1839
+ adapter: "async",
1840
+ logger,
1841
+ evictedEntries,
1842
+ keptEntries: keptKeys.size,
1843
+ maxBytes: effectiveStaticPolicy.maxBytes,
1844
+ namespaceKind: scopeKind,
1845
+ phase: "startup-cleanup",
1846
+ quota: scopeKind === "listQuery.item" ? "maxItemBytes" : scopeKind === "listQuery.query" ? "maxQueryBytes" : "maxBytes",
1847
+ storeName: args.scope.storeName,
1848
+ totalEntries: candidateEntries.length,
1849
+ unprotectedBytes
1850
+ });
1851
+ }
1769
1852
  for (const { itemKey } of candidateEntries) {
1770
1853
  if (keptKeys.has(itemKey)) continue;
1771
1854
  payloadRecordKeysToRemove.add(getPayloadRecordKey(itemKey));
@@ -1836,4 +1919,4 @@ function serializeProtectedRef(ref) {
1836
1919
  return serializeProtectedRef$1(ref);
1837
1920
  }
1838
1921
  //#endregion
1839
- export { getNavigatorLockManager as A, parseAsyncStorageRecordKey as B, isModeEffectivelyActive as C, clearSessionProtectedKeysSnapshot as D, offlineResolutionRecordSchema as E, encodePersistedAsyncNamespaceKind as F, serializeProtectedRef$1 as H, getNamespaceId as I, getPayloadRecordKey as L, createCompactLocalStorageEntry as M, parseCompactLocalStorageEntry as N, getSessionProtectedKeysSnapshot as O, compareMetadata as P, getPersistedNamespaceId as R, getIsOfflineModeFromStatus as S, offlineItemEntityRefSchema as T, scheduleIdleCleanup as U, parsePersistedAsyncNamespaceKind as V, keepEntriesWithinByteBudget as _, estimateManagedAsyncStorageEntrySizeBytes as a, compactOfflineStatusSnapshotSchema as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, getSerializedStringSize as g, createTimedKeySet as h, createAsyncStorageAdapter as i, warnIfNavigatorLockUnavailable as j, setSessionProtectedKeysSnapshot as k, registerAsyncStartupStoreCleanup as l, createShouldIgnoreItemPredicate as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, getDefaultMaxBytesForScope as p, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, serializeJsonForStorage as v, isOfflineModeStatusValue as w, defaultOfflineRuntimeConfig as x, OfflineResolutionConflictParseError as y, normalizeStaticPolicy as z };
1922
+ export { offlineResolutionRecordSchema as A, getNamespaceId as B, OfflineResolutionConflictParseError as C, isModeEffectivelyActive as D, getIsOfflineModeFromStatus as E, warnIfNavigatorLockUnavailable as F, parsePersistedAsyncNamespaceKind as G, getPersistedNamespaceId as H, createCompactLocalStorageEntry as I, serializeProtectedRef$1 as K, parseCompactLocalStorageEntry as L, getSessionProtectedKeysSnapshot as M, setSessionProtectedKeysSnapshot as N, isOfflineModeStatusValue as O, getNavigatorLockManager as P, compareMetadata as R, serializeJsonForStorage as S, defaultOfflineRuntimeConfig as T, normalizeStaticPolicy as U, getPayloadRecordKey as V, parseAsyncStorageRecordKey as W, getDefaultMaxBytesForScope as _, estimateManagedAsyncStorageEntrySizeBytes as a, getSerializedStringSize as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, resolveTSDFLogger as g, getTSDFDebugTimingMs as h, createAsyncStorageAdapter as i, clearSessionProtectedKeysSnapshot as j, offlineItemEntityRefSchema as k, registerAsyncStartupStoreCleanup as l, emitTSDFDebugLog as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, logPersistentStorageQuotaCleanup as p, scheduleIdleCleanup as q, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, createShouldIgnoreItemPredicate as v, compactOfflineStatusSnapshotSchema as w, keepEntriesWithinByteBudget as x, createTimedKeySet as y, encodePersistedAsyncNamespaceKind as z };
@@ -1,4 +1,4 @@
1
- import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-CNuCgLRs.js";
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-CtltNSyd.js";
2
2
 
3
3
  //#region src/persistentStorage/asyncStorageAdapter.d.ts
4
4
  declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
@@ -1,3 +1,3 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-5jUV7H9_.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DqBAsrTX.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DobQJr0X.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-D35uqEXv.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-CNuCgLRs.js";
1
+ import { t as AsyncStorageAdapter } from "./types-CtltNSyd.js";
2
2
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
3
3
  /** Options for creating the IndexedDB persistent storage adapter. */
4
4
  type IndexedDbPersistentStorageOptions$1 = {
@@ -1,2 +1,2 @@
1
- import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-DqBAsrTX.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-D35uqEXv.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,5 +1,4 @@
1
- import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, H as serializeProtectedRef, I as getNamespaceId, L as getPayloadRecordKey, P as compareMetadata, R as getPersistedNamespaceId, V as parsePersistedAsyncNamespaceKind, a as estimateManagedAsyncStorageEntrySizeBytes, i as createAsyncStorageAdapter, v as serializeJsonForStorage, z as normalizeStaticPolicy } from "./asyncStorageAdapter-BaojFC2B.js";
2
- import { n as getTSDFDebugTimingMs, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
1
+ import { B as getNamespaceId, G as parsePersistedAsyncNamespaceKind, H as getPersistedNamespaceId, K as serializeProtectedRef, R as compareMetadata, S as serializeJsonForStorage, U as normalizeStaticPolicy, V as getPayloadRecordKey, W as parseAsyncStorageRecordKey, a as estimateManagedAsyncStorageEntrySizeBytes, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, z as encodePersistedAsyncNamespaceKind } from "./asyncStorageAdapter-B-pdNeAs.js";
3
2
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
3
  import { isObject } from "@ls-stack/utils/typeGuards";
5
4
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
package/dist/main.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFDebugOptions, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, Zt as TSDFFocusDebugOperation, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-CNuCgLRs.js";
1
+ import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFFocusDebugOperation, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, Zt as TSDFLoggerOptions, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-CtltNSyd.js";
2
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
3
3
  import { Emitter } from "evtmitter";
4
4
  import { Context } from "react";
@@ -74,7 +74,8 @@ type StoreManagerOfflineApi<TUploadRef extends ValidPayload = ValidPayload> = {
74
74
  /** Shared coordinator passed to every TSDF store instance in an app/session. */
75
75
  type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
76
76
  /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync, focus lifecycle, and persistent storage internals. */
77
- debugLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
77
+ debugLogger?: TSDFDebugLogger; /** Shared logger for low-volume production signals. */
78
+ logger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
78
79
  errorNormalizer: (exception: Error) => StoreError; /** Global fallback for persistent storage failures in attached stores. */
79
80
  onPersistentStorageError: PersistentStorageErrorHandler | undefined; /** Global fallback for mutation failures in attached stores. */
80
81
  onMutationError: StoreManagerMutationErrorHandler | undefined; /** Shared defaults used by attached stores unless a store-level override exists. */
@@ -99,12 +100,9 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
99
100
  blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
100
101
  onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
101
102
  onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
102
- revalidateOnWindowFocus?: boolean | (() => boolean);
103
- /**
104
- * Enables debug logs for browser-tab sync, focus revalidation, and persistent storage operations.
105
- * Pass `true` to use console logging, or pass a logger function.
106
- */
107
- debug?: TSDFDebugOptions; /** Optional shared offline session config for every attached store. */
103
+ revalidateOnWindowFocus?: boolean | (() => boolean); /** Enables verbose development-only logs. Pass `true` to use console logging, or pass a logger function. */
104
+ debugLogger?: TSDFLoggerOptions; /** Enables low-volume production-safe logs. Defaults to console logging; pass `false` to disable. */
105
+ logger?: TSDFLoggerOptions; /** Optional shared offline session config for every attached store. */
108
106
  offlineSession?: OfflineSessionConfig<TUploadRef>;
109
107
  };
110
108
  declare function createStoreManager<TUploadRef extends ValidPayload = ValidPayload>(options: CreateStoreManagerOptions<TUploadRef>): StoreManager<TUploadRef>;
@@ -773,7 +771,13 @@ type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload ex
773
771
  type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
774
772
  /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
775
773
  filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
776
- appendNewTo?: 'start' | 'end'; /** Whether affected queries should still refetch after the optimistic list update. */
774
+ appendNewTo?: 'start' | 'end';
775
+ /**
776
+ * Schedules a background refetch of queries this rule mutated. Leave off
777
+ * unless the optimistic update can't represent the final server state —
778
+ * e.g. server-assigned sort fields (`updatedAt`, computed scores), server-
779
+ * only membership data (permissions), or cursor pagination shifts.
780
+ */
777
781
  invalidateQueries?: boolean; /** Sort order to maintain inside affected query pages. */
778
782
  sort?: {
779
783
  /** Selects sortable values from an item. */sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[]; /** Sort direction for each `sortBy` value. */
@@ -1513,4 +1517,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
1513
1517
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
1514
1518
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
1515
1519
  //#endregion
1516
- export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFDebugOptions, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
1520
+ export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFLoggerOptions, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
package/dist/main.js CHANGED
@@ -1,6 +1,5 @@
1
- import { A as getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-BaojFC2B.js";
2
- import { n as getTSDFDebugTimingMs, r as resolveTSDFDebugLogger, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
3
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-5jUV7H9_.js";
1
+ import { A as offlineResolutionRecordSchema, C as OfflineResolutionConflictParseError, D as isModeEffectivelyActive, E as getIsOfflineModeFromStatus, F as warnIfNavigatorLockUnavailable, G as parsePersistedAsyncNamespaceKind, I as createCompactLocalStorageEntry, K as serializeProtectedRef, L as parseCompactLocalStorageEntry, M as getSessionProtectedKeysSnapshot, N as setSessionProtectedKeysSnapshot, O as isOfflineModeStatusValue, P as getNavigatorLockManager, S as serializeJsonForStorage, T as defaultOfflineRuntimeConfig, V as getPayloadRecordKey, _ as getDefaultMaxBytesForScope, a as estimateManagedAsyncStorageEntrySizeBytes, b as getSerializedStringSize, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as resolveTSDFLogger, h as getTSDFDebugTimingMs, j as clearSessionProtectedKeysSnapshot, k as offlineItemEntityRefSchema, l as registerAsyncStartupStoreCleanup, m as emitTSDFDebugLog, o as getProtectedKeysFromMetadata, p as logPersistentStorageQuotaCleanup, q as scheduleIdleCleanup, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as createShouldIgnoreItemPredicate, w as compactOfflineStatusSnapshotSchema, x as keepEntriesWithinByteBudget, y as createTimedKeySet } from "./asyncStorageAdapter-B-pdNeAs.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-DobQJr0X.js";
4
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
5
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
6
5
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
@@ -1387,7 +1386,8 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1387
1386
  if (asyncAdapter === null) return null;
1388
1387
  const sessionKey = config.getSessionKey();
1389
1388
  if (sessionKey === false) return null;
1390
- if (import.meta.env.DEV) asyncAdapter.debugLogger = config.debugLogger;
1389
+ asyncAdapter.debugLogger = config.debugLogger;
1390
+ asyncAdapter.logger = config.logger;
1391
1391
  return asyncAdapter.openNamespace({
1392
1392
  sessionKey,
1393
1393
  storeName: asyncNamespace?.storeName ?? config.storeName,
@@ -1592,7 +1592,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
1592
1592
  if (asyncAdapter === null) return null;
1593
1593
  const sessionKey = config.getSessionKey();
1594
1594
  if (sessionKey === false) return null;
1595
- if (import.meta.env.DEV) asyncAdapter.debugLogger = config.debugLogger;
1595
+ asyncAdapter.debugLogger = config.debugLogger;
1596
+ asyncAdapter.logger = config.logger;
1596
1597
  return asyncAdapter.openNamespace({
1597
1598
  sessionKey,
1598
1599
  storeName: config.storeName,
@@ -2173,7 +2174,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2173
2174
  }
2174
2175
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2175
2176
  async function clearAllSessionStorage(sessionKey) {
2176
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CjRwtUxc.js");
2177
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-0ObaLfne.js");
2177
2178
  await Promise.all([
2178
2179
  clearSessionStorage(sessionKey, "local-sync"),
2179
2180
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2300,6 +2301,26 @@ function setupCollectionPersistence(config, options = {}) {
2300
2301
  getManifestMeta: (data) => ({ p: data.payload }),
2301
2302
  valueCodec: itemStorageValueCodec
2302
2303
  });
2304
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
2305
+ function logByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
2306
+ const logger = config.logger;
2307
+ if (!logger) return;
2308
+ const evictedEntries = totalEntries - keptKeys.size;
2309
+ if (evictedEntries === 0) return;
2310
+ logPersistentStorageQuotaCleanup({
2311
+ adapter: quotaCleanupAdapter,
2312
+ logger,
2313
+ evictedEntries,
2314
+ keptEntries: keptKeys.size,
2315
+ maxBytes,
2316
+ namespaceKind: "collection.item",
2317
+ phase,
2318
+ quota: "maxBytes",
2319
+ storeName: config.storeName,
2320
+ totalEntries,
2321
+ unprotectedBytes
2322
+ });
2323
+ }
2303
2324
  function getAsyncNamespaceScope() {
2304
2325
  if (asyncStorageAdapter === null) return null;
2305
2326
  const sessionKey = config.getSessionKey();
@@ -2389,7 +2410,8 @@ function setupCollectionPersistence(config, options = {}) {
2389
2410
  protected: protectedItemKeys.has(itemKey),
2390
2411
  sizeBytes: rememberPersistedMetadataSize(itemKey, metadata.sizeBytes)
2391
2412
  }));
2392
- const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2413
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2414
+ logByteBudgetCleanup("startup-cleanup", candidateEntries.length, keptKeys, unprotectedBytes);
2393
2415
  for (const { itemKey } of candidateEntries) {
2394
2416
  if (keptKeys.has(itemKey)) continue;
2395
2417
  deleteKeys.add(getPayloadRecordKey(itemKey));
@@ -2654,7 +2676,8 @@ function setupCollectionPersistence(config, options = {}) {
2654
2676
  await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2655
2677
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2656
2678
  }
2657
- const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2679
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2680
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2658
2681
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2659
2682
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2660
2683
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2682,7 +2705,8 @@ function setupCollectionPersistence(config, options = {}) {
2682
2705
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2683
2706
  }
2684
2707
  const filteredEntries = validEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
2685
- const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2708
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2709
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2686
2710
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2687
2711
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2688
2712
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2805,7 +2829,8 @@ function setupCollectionPersistence(config, options = {}) {
2805
2829
  if (metadataByKey.has(entry.itemKey)) pendingRemoves.add(entry.itemKey);
2806
2830
  }
2807
2831
  const remainingCandidates = candidateEntries.filter(({ itemKey }) => !pendingRemoves.has(itemKey));
2808
- const keptKeys = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2832
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2833
+ logByteBudgetCleanup("flush", remainingCandidates.length, keptKeys, unprotectedBytes);
2809
2834
  if (keptKeys.size !== remainingCandidates.length) {
2810
2835
  for (const { itemKey } of remainingCandidates) {
2811
2836
  if (keptKeys.has(itemKey)) continue;
@@ -7523,7 +7548,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
7523
7548
  };
7524
7549
  }
7525
7550
  function createStoreManager(options) {
7526
- const debugLogger = import.meta.env.DEV ? resolveTSDFDebugLogger(options.debug) : void 0;
7551
+ const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
7552
+ const logger = resolveTSDFLogger(options.logger ?? true);
7527
7553
  let resolvedOfflineSession;
7528
7554
  if (options.offlineSession) {
7529
7555
  const createOfflineSessionOptions = {
@@ -7588,7 +7614,8 @@ function createStoreManager(options) {
7588
7614
  },
7589
7615
  ...offlineApi
7590
7616
  };
7591
- if (debugLogger !== void 0) storeManager.debugLogger = debugLogger;
7617
+ storeManager.debugLogger = debugLogger;
7618
+ storeManager.logger = logger;
7592
7619
  storeManagerRegistry.set(storeManager, registry);
7593
7620
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7594
7621
  return storeManager;
@@ -7681,15 +7708,15 @@ async function performMutationWithLifecycle(startMutation, mutation, onError, op
7681
7708
  //#endregion
7682
7709
  //#region src/utils/storeFocusLifecycle.ts
7683
7710
  /** @internal */
7684
- function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, debug) {
7711
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowCanRunRevalidation, onWindowFocus, onWindowCanRunRevalidation, onWindowFocusRevalidate, onTransportReconnectRevalidate, debug) {
7685
7712
  let cleanupFocusListener = null;
7686
- let cleanupReconnectFocusListener = null;
7713
+ let cleanupReconnectRevalidationListener = null;
7687
7714
  let reconnectCooldownTimeoutId = null;
7688
- let hasPendingReconnectRevalidateOnFocus = false;
7715
+ let hasPendingReconnectRevalidate = false;
7689
7716
  let lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7690
- function clearReconnectFocusListener() {
7691
- cleanupReconnectFocusListener?.();
7692
- cleanupReconnectFocusListener = null;
7717
+ function clearReconnectRevalidationListener() {
7718
+ cleanupReconnectRevalidationListener?.();
7719
+ cleanupReconnectRevalidationListener = null;
7693
7720
  }
7694
7721
  function clearReconnectCooldownTimeout() {
7695
7722
  if (reconnectCooldownTimeoutId !== null) {
@@ -7718,25 +7745,26 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7718
7745
  lastTransportReconnectRevalidateAt = Date.now();
7719
7746
  onTransportReconnectRevalidate();
7720
7747
  }
7721
- function ensureReconnectFocusListener() {
7722
- if (cleanupReconnectFocusListener) return;
7723
- cleanupReconnectFocusListener = onWindowFocus(() => {
7724
- clearReconnectFocusListener();
7725
- if (!hasPendingReconnectRevalidateOnFocus) return;
7726
- hasPendingReconnectRevalidateOnFocus = false;
7748
+ function ensureReconnectRevalidationListener() {
7749
+ if (cleanupReconnectRevalidationListener) return;
7750
+ cleanupReconnectRevalidationListener = onWindowCanRunRevalidation(() => {
7751
+ if (!getWindowCanRunRevalidation()) return;
7752
+ clearReconnectRevalidationListener();
7753
+ if (!hasPendingReconnectRevalidate) return;
7754
+ hasPendingReconnectRevalidate = false;
7727
7755
  runTransportReconnectRevalidate();
7728
7756
  });
7729
7757
  }
7730
7758
  function flushTransportReconnectRevalidate() {
7731
7759
  clearReconnectCooldownTimeout();
7732
- if (getWindowIsFocused()) {
7733
- hasPendingReconnectRevalidateOnFocus = false;
7734
- clearReconnectFocusListener();
7760
+ if (getWindowCanRunRevalidation()) {
7761
+ hasPendingReconnectRevalidate = false;
7762
+ clearReconnectRevalidationListener();
7735
7763
  runTransportReconnectRevalidate();
7736
7764
  return;
7737
7765
  }
7738
- hasPendingReconnectRevalidateOnFocus = true;
7739
- ensureReconnectFocusListener();
7766
+ hasPendingReconnectRevalidate = true;
7767
+ ensureReconnectRevalidationListener();
7740
7768
  }
7741
7769
  function scheduleTrailingTransportReconnectRevalidate() {
7742
7770
  clearReconnectCooldownTimeout();
@@ -7748,9 +7776,9 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7748
7776
  function reset() {
7749
7777
  cleanupFocusListener?.();
7750
7778
  cleanupFocusListener = null;
7751
- clearReconnectFocusListener();
7779
+ clearReconnectRevalidationListener();
7752
7780
  clearReconnectCooldownTimeout();
7753
- hasPendingReconnectRevalidateOnFocus = false;
7781
+ hasPendingReconnectRevalidate = false;
7754
7782
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7755
7783
  if (!revalidateOnWindowFocus) return;
7756
7784
  if (usesRealTimeUpdates) {
@@ -7779,9 +7807,9 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7779
7807
  function dispose() {
7780
7808
  cleanupFocusListener?.();
7781
7809
  cleanupFocusListener = null;
7782
- clearReconnectFocusListener();
7810
+ clearReconnectRevalidationListener();
7783
7811
  clearReconnectCooldownTimeout();
7784
- hasPendingReconnectRevalidateOnFocus = false;
7812
+ hasPendingReconnectRevalidate = false;
7785
7813
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7786
7814
  }
7787
7815
  function onTransportReconnect() {
@@ -7790,7 +7818,7 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7790
7818
  flushTransportReconnectRevalidate();
7791
7819
  return;
7792
7820
  }
7793
- if (hasPendingReconnectRevalidateOnFocus) return;
7821
+ if (hasPendingReconnectRevalidate) return;
7794
7822
  if (Date.now() - lastTransportReconnectRevalidateAt >= transportReconnectCooldownMs) {
7795
7823
  flushTransportReconnectRevalidate();
7796
7824
  return;
@@ -7805,6 +7833,25 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7805
7833
  };
7806
7834
  }
7807
7835
  //#endregion
7836
+ //#region src/utils/windowRevalidation.ts
7837
+ /** @internal */
7838
+ function isWindowVisible() {
7839
+ return document.visibilityState === "visible";
7840
+ }
7841
+ /** @internal */
7842
+ function onWindowVisible(handler) {
7843
+ window.addEventListener("focus", handler);
7844
+ window.addEventListener("pageshow", handler);
7845
+ window.addEventListener("visibilitychange", handler);
7846
+ document.addEventListener("visibilitychange", handler);
7847
+ return () => {
7848
+ window.removeEventListener("focus", handler);
7849
+ window.removeEventListener("pageshow", handler);
7850
+ window.removeEventListener("visibilitychange", handler);
7851
+ document.removeEventListener("visibilitychange", handler);
7852
+ };
7853
+ }
7854
+ //#endregion
7808
7855
  //#region src/collectionStore/collectionCacheLimits.ts
7809
7856
  /** @internal */
7810
7857
  function createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup) {
@@ -8501,7 +8548,8 @@ function createCollectionStore(storeOptions) {
8501
8548
  ...persistentStorageConfig.offline,
8502
8549
  session: resolvedOfflineSessionForPersistentStorage
8503
8550
  } : void 0,
8504
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8551
+ debugLogger: storeManager.debugLogger,
8552
+ logger: storeManager.logger,
8505
8553
  getSessionKey: getSessionKeyForRuntime,
8506
8554
  storeName: id
8507
8555
  }) : null;
@@ -8618,6 +8666,7 @@ function createCollectionStore(storeOptions) {
8618
8666
  return false;
8619
8667
  }
8620
8668
  const getWindowIsFocused = testOptions?.getWindowIsFocused ?? isWindowFocused;
8669
+ const getWindowCanRunRevalidation = testOptions?.getWindowCanRunRevalidation ?? isWindowVisible;
8621
8670
  function runWithoutBroadcast(callback) {
8622
8671
  remoteApplyDepth++;
8623
8672
  try {
@@ -9178,7 +9227,7 @@ function createCollectionStore(storeOptions) {
9178
9227
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
9179
9228
  return result;
9180
9229
  }
9181
- const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9230
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowCanRunRevalidation, testOptions?.onWindowFocus ?? onWindowFocus, testOptions?.onWindowCanRunRevalidation ?? onWindowVisible, () => {
9182
9231
  invalidateItem(() => true, "lowPriority");
9183
9232
  }, () => {
9184
9233
  invalidateItem(() => true, "realtimeUpdate");
@@ -9201,12 +9250,12 @@ function createCollectionStore(storeOptions) {
9201
9250
  * items need to be revalidated.
9202
9251
  *
9203
9252
  * - No-op when `usesRealTimeUpdates` is `false`.
9204
- * - If the window is focused, the first reconnect invalidates all items
9253
+ * - If the window is visible, the first reconnect invalidates all items
9205
9254
  * immediately with `realtimeUpdate` priority.
9206
9255
  * - Additional reconnects within `transportReconnectCooldownMs` are
9207
9256
  * coalesced into one trailing invalidation.
9208
- * - If the window is **not** focused, reconnect invalidation waits until the
9209
- * next window focus event.
9257
+ * - If the window is hidden, reconnect invalidation waits until the next
9258
+ * window visibility/resume event.
9210
9259
  */
9211
9260
  function onTransportReconnect() {
9212
9261
  if (isDisposed) return;
@@ -9588,7 +9637,8 @@ function createDocumentStore(storeOptions) {
9588
9637
  ...persistentStorageConfig.offline,
9589
9638
  session: resolvedOfflineSessionForPersistentStorage
9590
9639
  } : void 0,
9591
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9640
+ debugLogger: storeManager.debugLogger,
9641
+ logger: storeManager.logger,
9592
9642
  getSessionKey: getSessionKeyForRuntime,
9593
9643
  storeName: id
9594
9644
  }) : null;
@@ -9648,6 +9698,7 @@ function createDocumentStore(storeOptions) {
9648
9698
  const events = evtmitter();
9649
9699
  const storeEvents = evtmitter();
9650
9700
  const getWindowIsFocused = testOptions?.getWindowIsFocused ?? isWindowFocused;
9701
+ const getWindowCanRunRevalidation = testOptions?.getWindowCanRunRevalidation ?? isWindowVisible;
9651
9702
  function runWithoutBroadcast(callback) {
9652
9703
  remoteApplyDepth++;
9653
9704
  try {
@@ -9808,7 +9859,7 @@ function createDocumentStore(storeOptions) {
9808
9859
  usesRealTimeUpdates
9809
9860
  });
9810
9861
  if (initialStatus !== "idle" || initialData !== null || initialError !== null) scheduler.setLastFetchStartTimeForRequest(DOC_REQUEST_ID, testOptions?.initialLastFetchStartTime ?? 0);
9811
- const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9862
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowCanRunRevalidation, testOptions?.onWindowFocus ?? onWindowFocus, testOptions?.onWindowCanRunRevalidation ?? onWindowVisible, () => {
9812
9863
  invalidateData("lowPriority");
9813
9864
  }, () => {
9814
9865
  invalidateData("realtimeUpdate");
@@ -9886,12 +9937,12 @@ function createDocumentStore(storeOptions) {
9886
9937
  * needs to be revalidated.
9887
9938
  *
9888
9939
  * - No-op when `usesRealTimeUpdates` is `false`.
9889
- * - If the window is focused, the first reconnect invalidates immediately
9890
- * with `realtimeUpdate` priority.
9940
+ * - If the window is visible, the first reconnect invalidates immediately with
9941
+ * `realtimeUpdate` priority.
9891
9942
  * - Additional reconnects within `transportReconnectCooldownMs` are coalesced
9892
9943
  * into one trailing invalidation.
9893
- * - If the window is **not** focused, reconnect invalidation waits until the
9894
- * next window focus event.
9944
+ * - If the window is hidden, reconnect invalidation waits until the next
9945
+ * window visibility/resume event.
9895
9946
  */
9896
9947
  function onTransportReconnect() {
9897
9948
  if (isDisposed) return;
@@ -10270,6 +10321,45 @@ function setupListQueryPersistence(config, options = {}) {
10270
10321
  p: data.payload
10271
10322
  })
10272
10323
  });
10324
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
10325
+ function logQueryByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10326
+ const logger = config.logger;
10327
+ if (!logger) return;
10328
+ const evictedEntries = totalEntries - keptKeys.size;
10329
+ if (evictedEntries === 0) return;
10330
+ logPersistentStorageQuotaCleanup({
10331
+ adapter: quotaCleanupAdapter,
10332
+ logger,
10333
+ evictedEntries,
10334
+ keptEntries: keptKeys.size,
10335
+ maxBytes: maxQueryBytes,
10336
+ namespaceKind: "listQuery.query",
10337
+ phase,
10338
+ quota: "maxQueryBytes",
10339
+ storeName: config.storeName,
10340
+ totalEntries,
10341
+ unprotectedBytes
10342
+ });
10343
+ }
10344
+ function logItemByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10345
+ const logger = config.logger;
10346
+ if (!logger) return;
10347
+ const evictedEntries = totalEntries - keptKeys.size;
10348
+ if (evictedEntries === 0) return;
10349
+ logPersistentStorageQuotaCleanup({
10350
+ adapter: quotaCleanupAdapter,
10351
+ logger,
10352
+ evictedEntries,
10353
+ keptEntries: keptKeys.size,
10354
+ maxBytes: maxItemBytes,
10355
+ namespaceKind: "listQuery.item",
10356
+ phase,
10357
+ quota: "maxItemBytes",
10358
+ storeName: config.storeName,
10359
+ totalEntries,
10360
+ unprotectedBytes
10361
+ });
10362
+ }
10273
10363
  function getAsyncItemNamespaceScope() {
10274
10364
  if (asyncStorageAdapter === null) return null;
10275
10365
  const sessionKey = config.getSessionKey();
@@ -11055,7 +11145,8 @@ function setupListQueryPersistence(config, options = {}) {
11055
11145
  };
11056
11146
  });
11057
11147
  if (invalidPayloadQueryKeys.length > 0) await Promise.all(invalidPayloadQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11058
- const keptQueryKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11148
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11149
+ logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11059
11150
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11060
11151
  for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11061
11152
  knownPersistedQueryKeys = keptQueryKeys;
@@ -11079,7 +11170,8 @@ function setupListQueryPersistence(config, options = {}) {
11079
11170
  });
11080
11171
  }
11081
11172
  if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => queryNamespace.remove(queryKey)));
11082
- const keptQueryKeys = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11173
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11174
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
11083
11175
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11084
11176
  for (const entry of validEntries) {
11085
11177
  const { queryKey } = entry;
@@ -11118,7 +11210,8 @@ function setupListQueryPersistence(config, options = {}) {
11118
11210
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11119
11211
  }
11120
11212
  const persistedItemEntries = hydratedItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11121
- const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11213
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11214
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11122
11215
  const evictedItemKeys = /* @__PURE__ */ new Set();
11123
11216
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11124
11217
  evictedItemKeys.add(itemKey);
@@ -11168,7 +11261,8 @@ function setupListQueryPersistence(config, options = {}) {
11168
11261
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11169
11262
  }
11170
11263
  const persistedItemEntries = validItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11171
- const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11264
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11265
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11172
11266
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11173
11267
  for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11174
11268
  knownPersistedItemKeys = keptItemKeys;
@@ -11432,7 +11526,8 @@ function setupListQueryPersistence(config, options = {}) {
11432
11526
  sizeBytes
11433
11527
  });
11434
11528
  }
11435
- const keptQueryKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11529
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11530
+ logQueryByteBudgetCleanup("flush", candidateEntries.length, keptQueryKeys, queryUnprotectedBytes);
11436
11531
  finalPersistedQueryKeys.clear();
11437
11532
  for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11438
11533
  const evictedQueryKeys = [];
@@ -11524,7 +11619,8 @@ function setupListQueryPersistence(config, options = {}) {
11524
11619
  sizeBytes
11525
11620
  });
11526
11621
  }
11527
- const keptItemKeys = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11622
+ const { keptKeys: keptItemKeys, unprotectedBytes: itemUnprotectedBytes } = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11623
+ logItemByteBudgetCleanup("flush", itemCandidateEntries.length, keptItemKeys, itemUnprotectedBytes);
11528
11624
  finalPersistedItemKeys.clear();
11529
11625
  for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11530
11626
  const evictedItemKeys = [];
@@ -14635,7 +14731,8 @@ function createListQueryStore(storeOptions) {
14635
14731
  ...persistentStorageConfig.offline,
14636
14732
  session: resolvedOfflineSessionForPersistentStorage
14637
14733
  } : void 0,
14638
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
14734
+ debugLogger: storeManager.debugLogger,
14735
+ logger: storeManager.logger,
14639
14736
  getSessionKey: getSessionKeyForRuntime,
14640
14737
  storeName: id
14641
14738
  }) : null;
@@ -14719,6 +14816,7 @@ function createListQueryStore(storeOptions) {
14719
14816
  return false;
14720
14817
  }
14721
14818
  const getWindowIsFocused = testOptions?.getWindowIsFocused ?? isWindowFocused;
14819
+ const getWindowCanRunRevalidation = testOptions?.getWindowCanRunRevalidation ?? isWindowVisible;
14722
14820
  function runWithoutBroadcast(callback) {
14723
14821
  remoteApplyDepth++;
14724
14822
  try {
@@ -15273,7 +15371,7 @@ function createListQueryStore(storeOptions) {
15273
15371
  function useFindItem$1(findItemFn, options = {}) {
15274
15372
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
15275
15373
  }
15276
- const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
15374
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowCanRunRevalidation, testOptions?.onWindowFocus ?? onWindowFocus, testOptions?.onWindowCanRunRevalidation ?? onWindowVisible, () => {
15277
15375
  invalidateQueryAndItems({
15278
15376
  all: true,
15279
15377
  type: "lowPriority"
@@ -15308,12 +15406,12 @@ function createListQueryStore(storeOptions) {
15308
15406
  * queries and items need to be revalidated.
15309
15407
  *
15310
15408
  * - No-op when `usesRealTimeUpdates` is `false`.
15311
- * - If the window is focused, the first reconnect invalidates all queries
15409
+ * - If the window is visible, the first reconnect invalidates all queries
15312
15410
  * and items immediately with `realtimeUpdate` priority.
15313
15411
  * - Additional reconnects within `transportReconnectCooldownMs` are
15314
15412
  * coalesced into one trailing invalidation.
15315
- * - If the window is **not** focused, reconnect invalidation waits until the
15316
- * next window focus event.
15413
+ * - If the window is hidden, reconnect invalidation waits until the next
15414
+ * window visibility/resume event.
15317
15415
  */
15318
15416
  function onTransportReconnect() {
15319
15417
  if (isDisposed) return;
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-D3zaTTNQ.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-Brc4BAn4.js";
2
2
  export { opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-5jUV7H9_.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DobQJr0X.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-CNuCgLRs.js";
1
+ import { t as AsyncStorageAdapter } from "./types-CtltNSyd.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -1,5 +1,4 @@
1
- import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, I as getNamespaceId, L as getPayloadRecordKey, V as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter } from "./asyncStorageAdapter-BaojFC2B.js";
2
- import { n as getTSDFDebugTimingMs, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
1
+ import { B as getNamespaceId, G as parsePersistedAsyncNamespaceKind, V as getPayloadRecordKey, W as parseAsyncStorageRecordKey, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, z as encodePersistedAsyncNamespaceKind } from "./asyncStorageAdapter-B-pdNeAs.js";
3
2
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
4
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
5
4
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -11,7 +11,7 @@ type TSDFDebugLogArea = 'browser-tabs' | 'focus' | 'persistent-storage';
11
11
  /** Operations emitted by focus lifecycle handling. */
12
12
  type TSDFFocusDebugOperation = 'window-focus-revalidate';
13
13
  /** Operations emitted by the persistent storage subsystem. */
14
- type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'adapter-operation' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
14
+ type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'adapter-operation' | 'quota-cleanup' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
15
15
  /** Operations emitted by the browser-tab sync subsystem. */
16
16
  type TSDFBrowserTabsDebugOperation = 'leader-change' | 'publish' | 'publish-skipped' | 'receive' | 'receive-skipped' | 'session-change' | 'transport-close' | 'transport-open' | 'transport-unavailable';
17
17
  /** Structured debug log entry emitted by TSDF internals. */
@@ -24,8 +24,8 @@ type TSDFDebugLogEntry = {
24
24
  };
25
25
  /** Custom debug logger invoked for each emitted TSDF debug entry. */
26
26
  type TSDFDebugLogger = (entry: TSDFDebugLogEntry) => void;
27
- /** Enables manager-wide debug logging for browser-tab sync and persistence. */
28
- type TSDFDebugOptions = boolean | TSDFDebugLogger;
27
+ /** Logger option used by manager-wide debug and production-signal logging. */
28
+ type TSDFLoggerOptions = boolean | TSDFDebugLogger;
29
29
  //#endregion
30
30
  //#region src/requestScheduler.d.ts
31
31
  type RequestSchedulerEvents = 'scheduled-fetch-started' | 'rt-fetch-scheduled' | 'rt-fetch-cancelled' | 'scheduled-rt-fetch-started' | 'medium-priority-scheduled' | 'medium-priority-fetch-started' | 'medium-priority-cancelled' | 'batch-size-triggered';
@@ -1314,7 +1314,8 @@ type AsyncStorageDiscoveredScope = {
1314
1314
  };
1315
1315
  /** Low-level async backend contract implemented by custom storage drivers. */
1316
1316
  type AsyncStorageDriver = {
1317
- /** Mutable debug logger used by concrete adapters to emit operation timings. */debugLogger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
1317
+ /** Mutable debug logger used by concrete adapters to emit operation timings. */debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1318
+ logger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
1318
1319
  get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1319
1320
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
1320
1321
  remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
@@ -1347,7 +1348,8 @@ type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string,
1347
1348
  /** Managed async adapter consumed by TSDF persistence internals. */
1348
1349
  type AsyncStorageAdapter = {
1349
1350
  /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Mutable debug logger used by concrete adapters to emit operation timings. */
1350
- debugLogger?: TSDFDebugLogger; /** Open a logical namespace with managed batching and touch guarantees. */
1351
+ debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1352
+ logger?: TSDFDebugLogger; /** Open a logical namespace with managed batching and touch guarantees. */
1351
1353
  openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
1352
1354
  readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
1353
1355
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
@@ -1476,4 +1478,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
1476
1478
  /** Persistent storage config for ListQueryStore. */
1477
1479
  type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
1478
1480
  //#endregion
1479
- export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, PayloadDebounce as At, OfflineEntityMutationKind as B, mutationSkipped as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, TSDFStatus as Ft, OfflineMutationQueueingPolicy as G, ScheduleFetchResults as Gt, OfflineMutationInput as H, RequestSchedulerEventData as Ht, ListQueryOfflineOperationDefinition as I, UnwrapTSDFResult as It, OfflineReplayRetryConfig as J, TSDFDebugLogLevel as Jt, OfflineOperationKind as K, TSDFDebugLogArea as Kt, OfflineAccumulationConfig as L, ValidPayload as Lt, DocumentOfflineOperationDefinition as M, StoreFetchError as Mt, GlobalOfflineEntity as N, StoreMutationError as Nt, DefineCollectionOfflineOperations as O, MaybeTSDFResult as Ot, GlobalOfflineStatus as P, StoreMutationErrorOptions as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, ValidStoreState as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, RequestSchedulerEvents as Ut, OfflineMutationDescriptor as V, FetchType as Vt, OfflineMutationQueueingConfig as W, ScheduleFetchOptions as Wt, OfflineResolutionActionForOperation as X, TSDFDebugOptions as Xt, OfflineResolutionAction as Y, TSDFDebugLogger as Yt, OfflineResolutionConflictParseError as Z, TSDFFocusDebugOperation as Zt, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreError as jt, DefineDocumentOfflineOperations as k, MutationSkipped as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, TSDFDebugLogEntry as qt, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, fetchTypePriority as zt };
1481
+ export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, PayloadDebounce as At, OfflineEntityMutationKind as B, mutationSkipped as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, TSDFStatus as Ft, OfflineMutationQueueingPolicy as G, ScheduleFetchResults as Gt, OfflineMutationInput as H, RequestSchedulerEventData as Ht, ListQueryOfflineOperationDefinition as I, UnwrapTSDFResult as It, OfflineReplayRetryConfig as J, TSDFDebugLogLevel as Jt, OfflineOperationKind as K, TSDFDebugLogArea as Kt, OfflineAccumulationConfig as L, ValidPayload as Lt, DocumentOfflineOperationDefinition as M, StoreFetchError as Mt, GlobalOfflineEntity as N, StoreMutationError as Nt, DefineCollectionOfflineOperations as O, MaybeTSDFResult as Ot, GlobalOfflineStatus as P, StoreMutationErrorOptions as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, ValidStoreState as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, RequestSchedulerEvents as Ut, OfflineMutationDescriptor as V, FetchType as Vt, OfflineMutationQueueingConfig as W, ScheduleFetchOptions as Wt, OfflineResolutionActionForOperation as X, TSDFFocusDebugOperation as Xt, OfflineResolutionAction as Y, TSDFDebugLogger as Yt, OfflineResolutionConflictParseError as Z, TSDFLoggerOptions as Zt, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreError as jt, DefineDocumentOfflineOperations as k, MutationSkipped as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, TSDFDebugLogEntry as qt, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, fetchTypePriority as zt };
@@ -35,7 +35,7 @@ Tabs use a versioned message model so later snapshots do not overwrite fresher r
35
35
  - When `sessionKey` changes (for example, login/logout), sync state is refreshed for the new session.
36
36
  - If transport is unavailable, sync becomes inactive silently.
37
37
 
38
- Enable `createStoreManager({ debug: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debug` to route those entries to your own observability tool.
38
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes in development. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debugLogger` to route those entries to your own tooling.
39
39
 
40
40
  ## Required options
41
41
 
@@ -132,4 +132,4 @@ TSDF automatically invalidates data in these scenarios:
132
132
  - **Mutation error**: After a failed mutation, affected data is invalidated to revert optimistic updates
133
133
  - **Mutation success with `revalidateOnSuccess`**: Affected data is invalidated to fetch the server's actual state
134
134
  - **Window focus**: When `revalidateOnWindowFocus` is enabled, all data is invalidated with `lowPriority`
135
- - **Transport reconnect**: When `onTransportReconnect()` is called, all data is invalidated with `realtimeUpdate` priority. See [Real-Time Updates](./real-time-updates.md)
135
+ - **Transport reconnect**: When `onTransportReconnect()` is called, all data is invalidated with `realtimeUpdate` priority as soon as the document is visible. See [Real-Time Updates](./real-time-updates.md)
@@ -30,9 +30,6 @@ const taskStore = createListQueryStore<Task, TaskFilter, string>({
30
30
 
31
31
  // Where to add new items
32
32
  appendNewTo: 'start',
33
-
34
- // Trigger background revalidation when items are moved
35
- invalidateQueries: true,
36
33
  },
37
34
  {
38
35
  // Sort a specific query by priority
@@ -112,7 +109,9 @@ Sorting is applied only to queries that contain the updated item.
112
109
 
113
110
  ### invalidateQueries
114
111
 
115
- When `true`, queries affected by the optimistic update are invalidated in the background. This ensures the server's actual ordering/filtering is fetched eventually.
112
+ Schedules a background refetch of queries this rule mutated.
113
+
114
+ **Leave off by default.** Only enable when the optimistic update can't represent the final server state — e.g. sort depends on a server-assigned field (`updatedAt`, computed score), membership depends on server-only data (permissions, full-text match), or cursor pagination shifts the page window. If `filterItem` and `sort` already match the server, the extra refetch is just noise.
116
115
 
117
116
  ```ts
118
117
  invalidateQueries: true;
@@ -149,31 +148,28 @@ const taskStore = createListQueryStore<Task, { status: string }, string>({
149
148
  fetchItemFn: (id, { signal }) => api.getTask(id, signal),
150
149
 
151
150
  optimisticListUpdates: [
152
- {
153
- // Move tasks between status columns
154
- queries: (q) => true,
155
- filterItem: (item) => item.status === 'todo',
156
- // Only applies to queries where status matches
157
- },
151
+ // Membership follows status — the optimistic change is final.
158
152
  {
159
153
  queries: { status: 'todo' },
160
154
  filterItem: (item) => item.status === 'todo',
161
155
  appendNewTo: 'start',
162
- invalidateQueries: true,
163
156
  },
164
157
  {
165
158
  queries: { status: 'done' },
166
159
  filterItem: (item) => item.status === 'done',
167
160
  appendNewTo: 'end',
161
+ },
162
+ // Server sorts by `updatedAt`, which it assigns — refetch to settle order.
163
+ {
164
+ queries: (q) => true,
165
+ sort: { sortBy: (item) => item.updatedAt, order: 'desc' },
168
166
  invalidateQueries: true,
169
167
  },
170
168
  ],
171
169
  });
172
170
 
173
- // When a task is moved to "done", it's automatically:
174
- // 1. Removed from the "todo" query
175
- // 2. Added to the "done" query
176
- // 3. Both queries are revalidated in the background
171
+ // Moving "task-1" to done removes it from the todo query and adds it to the
172
+ // done query. Only the sort rule triggers a background refetch.
177
173
  taskStore.updateItemState('task-1', (draft) => {
178
174
  draft.status = 'done';
179
175
  });
@@ -64,7 +64,7 @@ Store-specific options:
64
64
 
65
65
  > `persistentStorage` automatically reuses the store's existing `id` for its storage namespace and the store manager's `getSessionKey` for session scoping. When `getSessionKey` returns `false`, no persistence operations run.
66
66
 
67
- Enable `createStoreManager({ debug: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work.
67
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations in development. Production-safe quota cleanup logs are emitted through the manager `logger` by default; they include the affected quota, configured byte budget, total unprotected bytes, and kept/evicted entry counts. Pass `logger: false` to disable them. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work in development.
68
68
 
69
69
  ## Converted Data Schemas
70
70
 
@@ -104,9 +104,9 @@ Store-level `store.onTransportReconnect()` remains available for stores backed b
104
104
 
105
105
  Behavior:
106
106
 
107
- - If the window is **focused**: all data is invalidated immediately with `realtimeUpdate` priority
108
- - If the window is **not focused**: invalidation is deferred until the window regains focus
109
- - Multiple reconnect calls while unfocused are coalesced (only one invalidation fires on focus)
107
+ - If the document is **visible**: all data is invalidated immediately with `realtimeUpdate` priority, even when the browser does not report strict focus
108
+ - If the document is **hidden**: invalidation is deferred until the app becomes visible or resumes
109
+ - Multiple reconnect calls while hidden are coalesced (only one invalidation fires on resume)
110
110
  - This is a no-op when `usesRealTimeUpdates` is `false`
111
111
 
112
112
  ## Pattern: WebSocket Integration
@@ -29,26 +29,27 @@ const storeManager = createStoreManager({
29
29
  onPersistentStorageError: (error) => {
30
30
  console.error('TSDF persistence failed', error);
31
31
  },
32
- debug: true,
32
+ debugLogger: true,
33
33
  });
34
34
  ```
35
35
 
36
36
  Options:
37
37
 
38
- | Option | Required | Description |
39
- | ----------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
- | `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
41
- | `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
42
- | `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to 40 minutes (`2_400_000ms`). |
43
- | `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `16ms`. |
44
- | `backgroundCoalescingDelayMs` | No | Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to `3000ms`. |
45
- | `dynamicRealtimeThrottleMs` | No | Default adaptive throttle for real-time updates in attached stores. Defaults to `100ms` focused and `1000ms` in the background. Store options override it. |
46
- | `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
47
- | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
48
- | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
49
- | `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
50
- | `debug` | No | Enables browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
51
- | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
38
+ | Option | Required | Description |
39
+ | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
40
+ | `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
41
+ | `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
42
+ | `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to 40 minutes (`2_400_000ms`). |
43
+ | `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `16ms`. |
44
+ | `backgroundCoalescingDelayMs` | No | Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to `3000ms`. |
45
+ | `dynamicRealtimeThrottleMs` | No | Default adaptive throttle for real-time updates in attached stores. Defaults to `100ms` focused and `1000ms` in the background. Store options override it. |
46
+ | `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
47
+ | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
48
+ | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
49
+ | `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
50
+ | `debugLogger` | No | Enables verbose development-only browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
51
+ | `logger` | No | Enables low-volume production-safe logs such as persistent-storage quota cleanup. Defaults to console logging; pass `false` to disable or a function to customize. |
52
+ | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
52
53
 
53
54
  The session key is used by browser-tab sync, persistent storage, and offline state. Stores with the same `id` but different session keys are isolated.
54
55
 
@@ -58,13 +59,18 @@ Store-level options can explicitly disable inherited defaults when the option su
58
59
 
59
60
  ## Debug Logging
60
61
 
61
- Pass `debug: true` to log browser-tab sync operations, focus revalidation decisions, and persistent-storage operations through `console.log`, `console.warn`, and `console.error`. Browser-tab sync logs include lifecycle, leader changes, publish/receive events, and skipped messages. Focus revalidation logs report when `revalidateOnWindowFocus` triggers, is dynamically disabled, or is skipped because real-time updates own freshness. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Async persistent storage adapters emit timed `adapter-operation` entries with `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
62
+ Pass `debugLogger: true` to log browser-tab sync operations, focus revalidation decisions, and persistent-storage operations through `console.log`, `console.warn`, and `console.error` in development. Browser-tab sync logs include lifecycle, leader changes, publish/receive events, and skipped messages. Focus revalidation logs report when `revalidateOnWindowFocus` triggers, is dynamically disabled, or is skipped because real-time updates own freshness. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Async persistent storage adapters emit timed `adapter-operation` entries with `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
63
+
64
+ Low-volume production-safe signals are logged by default through `console.log`, `console.warn`, and `console.error`. Today this includes persistent-storage `quota-cleanup` entries. Pass `logger: false` to disable them, or pass a function to route them to your own tooling.
62
65
 
63
66
  ```ts
64
67
  const storeManager = createStoreManager({
65
68
  getSessionKey: () => currentTenantId ?? false,
66
69
  errorNormalizer: normalizeError,
67
- debug: ({ level, message, details }) => {
70
+ debugLogger: ({ level, message, details }) => {
71
+ observability[level](message, details);
72
+ },
73
+ logger: ({ level, message, details }) => {
68
74
  observability[level](message, details);
69
75
  },
70
76
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "17.0.0-alpha.13",
3
+ "version": "17.0.0-alpha.15",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",
@@ -98,7 +98,7 @@
98
98
  "format": "oxfmt src/ tests/ apps/playground/src/",
99
99
  "tsc": "tsgo -p tsconfig.prod.json && tsgo -p tsconfig.playwright-fixture.json",
100
100
  "tsc:isolated": "tsgo -p tsconfig.isolated.json",
101
- "playground": "pnpm --filter @tsdf/playground dev",
101
+ "dev": "pnpm --filter @tsdf/playground dev",
102
102
  "playground:build": "pnpm --filter @tsdf/playground build",
103
103
  "build": "pnpm lint && pnpm test:all && pnpm build:no-test",
104
104
  "build:no-test": "tsdown",
@@ -1,34 +0,0 @@
1
- //#region src/debug.ts
2
- function defaultConsoleDebugLogger(entry) {
3
- if (import.meta.env.DEV) {
4
- const consoleForLevel = globalThis.console[entry.level];
5
- if (typeof consoleForLevel !== "function") return;
6
- const details = entry.details ? {
7
- operation: entry.operation,
8
- ...entry.details
9
- } : { operation: entry.operation };
10
- consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
11
- }
12
- }
13
- function resolveTSDFDebugLogger(debug) {
14
- if (!import.meta.env.DEV) return void 0;
15
- if (debug === void 0 || debug === false) return void 0;
16
- if (debug === true) return defaultConsoleDebugLogger;
17
- return debug;
18
- }
19
- function emitTSDFDebugLog(logger, entry) {
20
- if (import.meta.env.DEV) {
21
- if (!logger) return;
22
- try {
23
- logger(entry);
24
- } catch (error) {
25
- globalThis.console.error("[tsdf:debug] Debug logger failed", error);
26
- }
27
- }
28
- }
29
- function getTSDFDebugTimingMs() {
30
- if (!import.meta.env.DEV) return 0;
31
- return Date.now();
32
- }
33
- //#endregion
34
- export { getTSDFDebugTimingMs as n, resolveTSDFDebugLogger as r, emitTSDFDebugLog as t };