tsdf 17.0.0-alpha.13 → 17.0.0-alpha.14

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-C1ouzZYD.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-B1kF0Ojl.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.prodLogger, {
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
+ #prodLogger;
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 prodLogger() {
912
+ return this.#prodLogger;
913
+ }
914
+ set prodLogger(prodLogger) {
915
+ this.#prodLogger = prodLogger;
916
+ this.#driver.prodLogger = prodLogger;
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 prodLogger = args.driver.prodLogger;
1835
+ const evictedEntries = candidateEntries.length - keptKeys.size;
1836
+ if (prodLogger && evictedEntries > 0) {
1837
+ const scopeKind = args.scope.kind;
1838
+ logPersistentStorageQuotaCleanup({
1839
+ adapter: "async",
1840
+ prodLogger,
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-hwf0jXKv.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-DcODOOJk.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-BMgsTNPP.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-hwf0jXKv.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-BMgsTNPP.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-B1kF0Ojl.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-hwf0jXKv.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
+ prodLogger?: 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. Pass `true` to use console logging, or pass a logger function. */
105
+ prodLogger?: 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-B1kF0Ojl.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-DcODOOJk.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.prodLogger = config.prodLogger;
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.prodLogger = config.prodLogger;
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-CxkAFJbY.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 prodLogger = config.prodLogger;
2307
+ if (!prodLogger) return;
2308
+ const evictedEntries = totalEntries - keptKeys.size;
2309
+ if (evictedEntries === 0) return;
2310
+ logPersistentStorageQuotaCleanup({
2311
+ adapter: quotaCleanupAdapter,
2312
+ prodLogger,
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 prodLogger = resolveTSDFLogger(options.prodLogger);
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.prodLogger = prodLogger;
7592
7619
  storeManagerRegistry.set(storeManager, registry);
7593
7620
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7594
7621
  return storeManager;
@@ -8501,7 +8528,8 @@ function createCollectionStore(storeOptions) {
8501
8528
  ...persistentStorageConfig.offline,
8502
8529
  session: resolvedOfflineSessionForPersistentStorage
8503
8530
  } : void 0,
8504
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8531
+ debugLogger: storeManager.debugLogger,
8532
+ prodLogger: storeManager.prodLogger,
8505
8533
  getSessionKey: getSessionKeyForRuntime,
8506
8534
  storeName: id
8507
8535
  }) : null;
@@ -9588,7 +9616,8 @@ function createDocumentStore(storeOptions) {
9588
9616
  ...persistentStorageConfig.offline,
9589
9617
  session: resolvedOfflineSessionForPersistentStorage
9590
9618
  } : void 0,
9591
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9619
+ debugLogger: storeManager.debugLogger,
9620
+ prodLogger: storeManager.prodLogger,
9592
9621
  getSessionKey: getSessionKeyForRuntime,
9593
9622
  storeName: id
9594
9623
  }) : null;
@@ -10270,6 +10299,45 @@ function setupListQueryPersistence(config, options = {}) {
10270
10299
  p: data.payload
10271
10300
  })
10272
10301
  });
10302
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
10303
+ function logQueryByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10304
+ const prodLogger = config.prodLogger;
10305
+ if (!prodLogger) return;
10306
+ const evictedEntries = totalEntries - keptKeys.size;
10307
+ if (evictedEntries === 0) return;
10308
+ logPersistentStorageQuotaCleanup({
10309
+ adapter: quotaCleanupAdapter,
10310
+ prodLogger,
10311
+ evictedEntries,
10312
+ keptEntries: keptKeys.size,
10313
+ maxBytes: maxQueryBytes,
10314
+ namespaceKind: "listQuery.query",
10315
+ phase,
10316
+ quota: "maxQueryBytes",
10317
+ storeName: config.storeName,
10318
+ totalEntries,
10319
+ unprotectedBytes
10320
+ });
10321
+ }
10322
+ function logItemByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10323
+ const prodLogger = config.prodLogger;
10324
+ if (!prodLogger) return;
10325
+ const evictedEntries = totalEntries - keptKeys.size;
10326
+ if (evictedEntries === 0) return;
10327
+ logPersistentStorageQuotaCleanup({
10328
+ adapter: quotaCleanupAdapter,
10329
+ prodLogger,
10330
+ evictedEntries,
10331
+ keptEntries: keptKeys.size,
10332
+ maxBytes: maxItemBytes,
10333
+ namespaceKind: "listQuery.item",
10334
+ phase,
10335
+ quota: "maxItemBytes",
10336
+ storeName: config.storeName,
10337
+ totalEntries,
10338
+ unprotectedBytes
10339
+ });
10340
+ }
10273
10341
  function getAsyncItemNamespaceScope() {
10274
10342
  if (asyncStorageAdapter === null) return null;
10275
10343
  const sessionKey = config.getSessionKey();
@@ -11055,7 +11123,8 @@ function setupListQueryPersistence(config, options = {}) {
11055
11123
  };
11056
11124
  });
11057
11125
  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);
11126
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11127
+ logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11059
11128
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11060
11129
  for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11061
11130
  knownPersistedQueryKeys = keptQueryKeys;
@@ -11079,7 +11148,8 @@ function setupListQueryPersistence(config, options = {}) {
11079
11148
  });
11080
11149
  }
11081
11150
  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);
11151
+ 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);
11152
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
11083
11153
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11084
11154
  for (const entry of validEntries) {
11085
11155
  const { queryKey } = entry;
@@ -11118,7 +11188,8 @@ function setupListQueryPersistence(config, options = {}) {
11118
11188
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11119
11189
  }
11120
11190
  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);
11191
+ 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);
11192
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11122
11193
  const evictedItemKeys = /* @__PURE__ */ new Set();
11123
11194
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11124
11195
  evictedItemKeys.add(itemKey);
@@ -11168,7 +11239,8 @@ function setupListQueryPersistence(config, options = {}) {
11168
11239
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11169
11240
  }
11170
11241
  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);
11242
+ 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);
11243
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11172
11244
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11173
11245
  for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11174
11246
  knownPersistedItemKeys = keptItemKeys;
@@ -11432,7 +11504,8 @@ function setupListQueryPersistence(config, options = {}) {
11432
11504
  sizeBytes
11433
11505
  });
11434
11506
  }
11435
- const keptQueryKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11507
+ 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);
11508
+ logQueryByteBudgetCleanup("flush", candidateEntries.length, keptQueryKeys, queryUnprotectedBytes);
11436
11509
  finalPersistedQueryKeys.clear();
11437
11510
  for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11438
11511
  const evictedQueryKeys = [];
@@ -11524,7 +11597,8 @@ function setupListQueryPersistence(config, options = {}) {
11524
11597
  sizeBytes
11525
11598
  });
11526
11599
  }
11527
- const keptItemKeys = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11600
+ 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);
11601
+ logItemByteBudgetCleanup("flush", itemCandidateEntries.length, keptItemKeys, itemUnprotectedBytes);
11528
11602
  finalPersistedItemKeys.clear();
11529
11603
  for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11530
11604
  const evictedItemKeys = [];
@@ -14635,7 +14709,8 @@ function createListQueryStore(storeOptions) {
14635
14709
  ...persistentStorageConfig.offline,
14636
14710
  session: resolvedOfflineSessionForPersistentStorage
14637
14711
  } : void 0,
14638
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
14712
+ debugLogger: storeManager.debugLogger,
14713
+ prodLogger: storeManager.prodLogger,
14639
14714
  getSessionKey: getSessionKeyForRuntime,
14640
14715
  storeName: id
14641
14716
  }) : null;
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-D3zaTTNQ.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-B0QmznAg.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-DcODOOJk.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-hwf0jXKv.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-B1kF0Ojl.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
+ prodLogger?: 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
+ prodLogger?: 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
 
@@ -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. Enable `createStoreManager({ prodLogger: true, ... })` to receive production-safe quota cleanup logs; they include the affected quota, configured byte budget, total unprotected bytes, and kept/evicted entry counts. 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
 
@@ -29,7 +29,8 @@ const storeManager = createStoreManager({
29
29
  onPersistentStorageError: (error) => {
30
30
  console.error('TSDF persistence failed', error);
31
31
  },
32
- debug: true,
32
+ debugLogger: true,
33
+ prodLogger: true,
33
34
  });
34
35
  ```
35
36
 
@@ -47,7 +48,8 @@ Options:
47
48
  | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
48
49
  | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
49
50
  | `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
+ | `debugLogger` | No | Enables verbose development-only browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
52
+ | `prodLogger` | No | Enables low-volume production-safe logs such as persistent-storage quota cleanup. Pass `true` or a logger function. |
51
53
  | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
52
54
 
53
55
  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.
@@ -58,13 +60,18 @@ Store-level options can explicitly disable inherited defaults when the option su
58
60
 
59
61
  ## Debug Logging
60
62
 
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.
63
+ 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.
64
+
65
+ Pass `prodLogger: true` to log low-volume production-safe signals. Today this includes persistent-storage `quota-cleanup` entries.
62
66
 
63
67
  ```ts
64
68
  const storeManager = createStoreManager({
65
69
  getSessionKey: () => currentTenantId ?? false,
66
70
  errorNormalizer: normalizeError,
67
- debug: ({ level, message, details }) => {
71
+ debugLogger: ({ level, message, details }) => {
72
+ observability[level](message, details);
73
+ },
74
+ prodLogger: ({ level, message, details }) => {
68
75
  observability[level](message, details);
69
76
  },
70
77
  });
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.14",
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 };