tsdf 17.0.0-alpha.9 → 17.0.0-beta.2

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-BMYAF6rt.js";
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-CMohMeKm.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-BZSj1ZO5.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CGfnsd9m.js";
2
2
  export { createAsyncStorageAdapter };
@@ -20,6 +20,25 @@ function scheduleIdleCleanup(callback) {
20
20
  return () => clearTimeout(timeoutId);
21
21
  }
22
22
  }
23
+ const INITIAL_MAINTENANCE_CLEANUP_DELAY_MS = 1e4;
24
+ /**
25
+ * Gives startup maintenance a short grace period before using the regular
26
+ * idle cleanup scheduling.
27
+ */
28
+ function scheduleInitialMaintenanceCleanup(callback) {
29
+ if (typeof requestIdleCallback !== "function") {
30
+ const timeoutId = setTimeout(callback, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS + 2e3);
31
+ return () => clearTimeout(timeoutId);
32
+ }
33
+ let cancelIdleCleanup = null;
34
+ const timeoutId = setTimeout(() => {
35
+ cancelIdleCleanup = scheduleIdleCleanup(callback);
36
+ }, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS);
37
+ return () => {
38
+ clearTimeout(timeoutId);
39
+ cancelIdleCleanup?.();
40
+ };
41
+ }
23
42
  //#endregion
24
43
  //#region src/persistentStorage/asyncStorageShared.ts
25
44
  const PAYLOAD_RECORD_PREFIX = "__tsdf_payload__:";
@@ -324,47 +343,53 @@ function serializeJsonForStorage(value) {
324
343
  sizeBytes: getSerializedStringSize(rawValue)
325
344
  };
326
345
  }
327
- function keepEntriesWithinByteBudget(args) {
346
+ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBytes, isPinned, isProtected, maxBytes) {
328
347
  const keptKeys = /* @__PURE__ */ new Set();
329
348
  let unprotectedBytes = 0;
330
- for (const entry of args.entries) {
331
- if (args.isProtected(entry)) continue;
332
- unprotectedBytes += args.getSizeBytes(entry);
349
+ for (const entry of entries) {
350
+ if (isProtected(entry)) continue;
351
+ unprotectedBytes += getSizeBytes(entry);
333
352
  }
334
- if (unprotectedBytes <= args.maxBytes) {
335
- for (const entry of args.entries) keptKeys.add(args.getKey(entry));
336
- return keptKeys;
353
+ if (unprotectedBytes <= maxBytes) {
354
+ for (const entry of entries) keptKeys.add(getKey(entry));
355
+ return {
356
+ keptKeys,
357
+ unprotectedBytes
358
+ };
337
359
  }
338
- const sortedEntries = [...args.entries].sort((a, b) => {
339
- const aProtected = args.isProtected(a);
340
- const bProtected = args.isProtected(b);
360
+ const sortedEntries = [...entries].sort((a, b) => {
361
+ const aProtected = isProtected(a);
362
+ const bProtected = isProtected(b);
341
363
  if (aProtected && !bProtected) return -1;
342
364
  if (!aProtected && bProtected) return 1;
343
- const aPinned = args.isPinned(a);
344
- const bPinned = args.isPinned(b);
365
+ const aPinned = isPinned(a);
366
+ const bPinned = isPinned(b);
345
367
  if (aPinned && !bPinned) return -1;
346
368
  if (!aPinned && bPinned) return 1;
347
- return args.getLastAccessAt(b) - args.getLastAccessAt(a);
369
+ return getLastAccessAt(b) - getLastAccessAt(a);
348
370
  });
349
371
  let keptUnprotectedBytes = 0;
350
372
  for (const entry of sortedEntries) {
351
- const key = args.getKey(entry);
352
- if (args.isProtected(entry)) {
373
+ const key = getKey(entry);
374
+ if (isProtected(entry)) {
353
375
  keptKeys.add(key);
354
376
  continue;
355
377
  }
356
- const sizeBytes = args.getSizeBytes(entry);
357
- if (args.isPinned(entry)) {
378
+ const sizeBytes = getSizeBytes(entry);
379
+ if (isPinned(entry)) {
358
380
  keptKeys.add(key);
359
381
  keptUnprotectedBytes += sizeBytes;
360
382
  continue;
361
383
  }
362
- if (keptUnprotectedBytes + sizeBytes <= args.maxBytes) {
384
+ if (keptUnprotectedBytes + sizeBytes <= maxBytes) {
363
385
  keptKeys.add(key);
364
386
  keptUnprotectedBytes += sizeBytes;
365
387
  }
366
388
  }
367
- return keptKeys;
389
+ return {
390
+ keptKeys,
391
+ unprotectedBytes
392
+ };
368
393
  }
369
394
  //#endregion
370
395
  //#region src/persistentStorage/persistentStorageDefaults.ts
@@ -390,13 +415,61 @@ function getDefaultMaxBytesKindForScope(scopeKind) {
390
415
  case "listQuery.query": return "listQuery";
391
416
  }
392
417
  }
393
- function getDefaultMaxBytesForAdapter(args) {
394
- return defaultMaxBytes[getDefaultMaxBytesProfile(args.adapter)][args.kind];
418
+ function getDefaultMaxBytesForAdapter(adapter, kind) {
419
+ return defaultMaxBytes[getDefaultMaxBytesProfile(adapter)][kind];
420
+ }
421
+ function getDefaultMaxBytesForScope(adapter, scopeKind) {
422
+ return getDefaultMaxBytesForAdapter(adapter, getDefaultMaxBytesKindForScope(scopeKind));
423
+ }
424
+ //#endregion
425
+ //#region src/debug.ts
426
+ function defaultConsoleDebugLogger(entry) {
427
+ const consoleForLevel = globalThis.console[entry.level];
428
+ if (typeof consoleForLevel !== "function") return;
429
+ const details = entry.details ? {
430
+ operation: entry.operation,
431
+ ...entry.details
432
+ } : { operation: entry.operation };
433
+ consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
434
+ }
435
+ function resolveTSDFLogger(logger) {
436
+ if (logger === void 0 || logger === false) return void 0;
437
+ if (logger === true) return defaultConsoleDebugLogger;
438
+ return logger;
439
+ }
440
+ function emitTSDFDebugLog(logger, entry) {
441
+ if (!logger) return;
442
+ try {
443
+ logger(entry);
444
+ } catch (error) {
445
+ globalThis.console.error("[tsdf:debug] Debug logger failed", error);
446
+ }
447
+ }
448
+ function getTSDFDebugTimingMs() {
449
+ if (!import.meta.env.DEV) return 0;
450
+ return Date.now();
395
451
  }
396
- function getDefaultMaxBytesForScope(args) {
397
- return getDefaultMaxBytesForAdapter({
398
- adapter: args.adapter,
399
- kind: getDefaultMaxBytesKindForScope(args.scopeKind)
452
+ //#endregion
453
+ //#region src/persistentStorage/quotaDebug.ts
454
+ function logPersistentStorageQuotaCleanup(args) {
455
+ emitTSDFDebugLog(args.logger, {
456
+ area: "persistent-storage",
457
+ details: {
458
+ adapter: args.adapter,
459
+ evictedEntries: args.evictedEntries,
460
+ keptEntries: args.keptEntries,
461
+ maxBytes: args.maxBytes,
462
+ namespaceKind: args.namespaceKind,
463
+ phase: args.phase,
464
+ quota: args.quota,
465
+ status: "success",
466
+ storeName: args.storeName,
467
+ totalEntries: args.totalEntries,
468
+ unprotectedBytes: args.unprotectedBytes
469
+ },
470
+ level: "log",
471
+ message: "persistent storage quota-cleanup success",
472
+ operation: "quota-cleanup"
400
473
  });
401
474
  }
402
475
  //#endregion
@@ -456,17 +529,17 @@ function setOfflineProtectionMetadata(customMetadata, offlineProtected) {
456
529
  const { o: _ignored, ...withoutOfflineMarker } = customMetadata ?? {};
457
530
  return Object.keys(withoutOfflineMarker).length > 0 ? withoutOfflineMarker : void 0;
458
531
  }
459
- function mergeManagedAsyncStorageCustomMetadata(args) {
532
+ function mergeManagedAsyncStorageCustomMetadata(currentCustomMetadata, nextCustomMetadata, protectedKeysSnapshotSet, scope, key) {
460
533
  const merged = {
461
- ...args.currentCustomMetadata ?? {},
462
- ...args.nextCustomMetadata ?? {}
534
+ ...currentCustomMetadata ?? {},
535
+ ...nextCustomMetadata ?? {}
463
536
  };
464
537
  const mergedCustomMetadata = Object.keys(merged).length > 0 ? merged : void 0;
465
- if (args.protectedKeysSnapshotSet !== null) return setOfflineProtectionMetadata(mergedCustomMetadata, args.protectedKeysSnapshotSet?.has(serializeProtectedRef({
466
- ...args.scope,
467
- key: args.key
468
- })) === true || isOfflineProtectedMetadata(args.nextCustomMetadata) || isOfflineProtectedMetadata(args.currentCustomMetadata));
469
- return setOfflineProtectionMetadata(mergedCustomMetadata, isOfflineProtectedMetadata(args.nextCustomMetadata) || isOfflineProtectedMetadata(args.currentCustomMetadata));
538
+ if (protectedKeysSnapshotSet !== null) return setOfflineProtectionMetadata(mergedCustomMetadata, protectedKeysSnapshotSet?.has(serializeProtectedRef({
539
+ ...scope,
540
+ key
541
+ })) === true || isOfflineProtectedMetadata(nextCustomMetadata) || isOfflineProtectedMetadata(currentCustomMetadata));
542
+ return setOfflineProtectionMetadata(mergedCustomMetadata, isOfflineProtectedMetadata(nextCustomMetadata) || isOfflineProtectedMetadata(currentCustomMetadata));
470
543
  }
471
544
  const ASYNC_METADATA_LAST_ACCESS_AT_KEY = "a";
472
545
  const ASYNC_METADATA_VERSION_KEY = "v";
@@ -505,12 +578,12 @@ function serializeInternalManagedMetadataRecord(metadata) {
505
578
  ...customMetadata
506
579
  };
507
580
  }
508
- function estimateManagedAsyncStorageEntrySizeBytes(args) {
509
- return getSerializedStringSize(args.serializedValue) + getSerializedStringSize(JSON.stringify(serializeInternalManagedMetadataRecord({
510
- lastAccessAt: args.lastAccessAt,
581
+ function estimateManagedAsyncStorageEntrySizeBytes(serializedValue, lastAccessAt, version, customMetadata) {
582
+ return getSerializedStringSize(serializedValue) + getSerializedStringSize(JSON.stringify(serializeInternalManagedMetadataRecord({
583
+ lastAccessAt,
511
584
  sizeBytes: void 0,
512
- version: args.version,
513
- ...args.customMetadata ? { customMetadata: args.customMetadata } : {}
585
+ version,
586
+ ...customMetadata ? { customMetadata } : {}
514
587
  })));
515
588
  }
516
589
  function parseIndexEntries(value) {
@@ -561,18 +634,9 @@ function serializeIndexState(state) {
561
634
  }
562
635
  function getDefaultStaticPolicyForScope(scope) {
563
636
  switch (scope.kind) {
564
- case "collection.item": return { maxBytes: getDefaultMaxBytesForScope({
565
- adapter: "async",
566
- scopeKind: "collection.item"
567
- }) };
568
- case "listQuery.item": return { maxBytes: getDefaultMaxBytesForScope({
569
- adapter: "async",
570
- scopeKind: "listQuery.item"
571
- }) };
572
- case "listQuery.query": return { maxBytes: getDefaultMaxBytesForScope({
573
- adapter: "async",
574
- scopeKind: "listQuery.query"
575
- }) };
637
+ case "collection.item": return { maxBytes: getDefaultMaxBytesForScope("async", "collection.item") };
638
+ case "listQuery.item": return { maxBytes: getDefaultMaxBytesForScope("async", "listQuery.item") };
639
+ case "listQuery.query": return { maxBytes: getDefaultMaxBytesForScope("async", "listQuery.query") };
576
640
  default: return null;
577
641
  }
578
642
  }
@@ -842,6 +906,8 @@ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
842
906
  var ManagedAsyncStorageAdapter = class {
843
907
  kind = "async";
844
908
  #driver;
909
+ #debugLogger;
910
+ #logger;
845
911
  #cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
846
912
  #cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
847
913
  #namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
@@ -849,11 +915,26 @@ var ManagedAsyncStorageAdapter = class {
849
915
  #pendingNamespaceCommits = /* @__PURE__ */ new Map();
850
916
  #readCacheGeneration = 0;
851
917
  #recentTouchedBuckets = /* @__PURE__ */ new Map();
918
+ #cancelStartupCleanup = null;
852
919
  #startupCleanupScheduled = false;
853
920
  constructor(driver) {
854
921
  this.#driver = driver;
855
922
  registerAsyncStorageReadCacheParticipant(this);
856
923
  }
924
+ get debugLogger() {
925
+ return this.#debugLogger;
926
+ }
927
+ set debugLogger(debugLogger) {
928
+ this.#debugLogger = debugLogger;
929
+ this.#driver.debugLogger = debugLogger;
930
+ }
931
+ get logger() {
932
+ return this.#logger;
933
+ }
934
+ set logger(logger) {
935
+ this.#logger = logger;
936
+ this.#driver.logger = logger;
937
+ }
857
938
  async #runWithSessionWriterLock(sessionKey, callback) {
858
939
  return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
859
940
  }
@@ -958,6 +1039,8 @@ var ManagedAsyncStorageAdapter = class {
958
1039
  this.#observedScopes.clear();
959
1040
  this.#pendingNamespaceCommits.clear();
960
1041
  this.#recentTouchedBuckets.clear();
1042
+ this.#cancelStartupCleanup?.();
1043
+ this.#cancelStartupCleanup = null;
961
1044
  this.#startupCleanupScheduled = false;
962
1045
  this.#driver.__resetForTests?.();
963
1046
  }
@@ -1228,13 +1311,7 @@ var ManagedAsyncStorageAdapter = class {
1228
1311
  const touchedKeys = [...new Set(touches.map((touch) => touch.key))];
1229
1312
  const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1230
1313
  if (managedCapabilities?.applyManagedCommit !== void 0) {
1231
- await managedCapabilities.applyManagedCommit(scope, args, { mergeOfflineProtectionMetadata: (key, nextCustomMetadata, currentCustomMetadata) => mergeManagedAsyncStorageCustomMetadata({
1232
- currentCustomMetadata,
1233
- key,
1234
- nextCustomMetadata,
1235
- protectedKeysSnapshotSet: getSessionProtectedKeysSnapshot(scope.sessionKey),
1236
- scope
1237
- }) });
1314
+ await managedCapabilities.applyManagedCommit(scope, args, { mergeOfflineProtectionMetadata: (key, nextCustomMetadata, currentCustomMetadata) => mergeManagedAsyncStorageCustomMetadata(currentCustomMetadata, nextCustomMetadata, getSessionProtectedKeysSnapshot(scope.sessionKey), scope, key) });
1238
1315
  this.#advanceNamespaceReadCacheGeneration(scope);
1239
1316
  this.#invalidateCachedNamespaceIndexState(scope);
1240
1317
  for (const key of removes) this.#invalidateCachedPayloadValue(scope, key);
@@ -1261,21 +1338,10 @@ var ManagedAsyncStorageAdapter = class {
1261
1338
  const protectedKeysSnapshotSet = getSessionProtectedKeysSnapshot(scope.sessionKey);
1262
1339
  for (const upsert of upserts) {
1263
1340
  const existingMetadata = indexEntries.get(upsert.key);
1264
- const customMetadata = mergeManagedAsyncStorageCustomMetadata({
1265
- currentCustomMetadata: existingMetadata?.customMetadata,
1266
- key: upsert.key,
1267
- nextCustomMetadata: upsert.metadata,
1268
- protectedKeysSnapshotSet,
1269
- scope
1270
- });
1341
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(existingMetadata?.customMetadata, upsert.metadata, protectedKeysSnapshotSet, scope, upsert.key);
1271
1342
  const nextLastAccessAt = touchesByKey.get(upsert.key) ?? existingMetadata?.lastAccessAt ?? now;
1272
1343
  const serializedValue = upsert.serializedValue !== void 0 ? { rawValue: upsert.serializedValue } : serializeJsonForStorage(upsert.value);
1273
- const nextSizeBytes = scope.kind !== "document" ? estimateManagedAsyncStorageEntrySizeBytes({
1274
- customMetadata,
1275
- lastAccessAt: nextLastAccessAt,
1276
- serializedValue: serializedValue.rawValue,
1277
- version: upsert.version
1278
- }) : void 0;
1344
+ const nextSizeBytes = scope.kind !== "document" ? estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, nextLastAccessAt, upsert.version, customMetadata) : void 0;
1279
1345
  const nextMetadata = {
1280
1346
  lastAccessAt: nextLastAccessAt,
1281
1347
  version: upsert.version,
@@ -1493,7 +1559,8 @@ var ManagedAsyncStorageAdapter = class {
1493
1559
  #scheduleStartupCleanupIfNeeded() {
1494
1560
  if (this.#startupCleanupScheduled) return;
1495
1561
  this.#startupCleanupScheduled = true;
1496
- scheduleIdleCleanup(() => {
1562
+ this.#cancelStartupCleanup = scheduleInitialMaintenanceCleanup(() => {
1563
+ this.#cancelStartupCleanup = null;
1497
1564
  this.#runStartupCleanupIfDue().catch(() => {});
1498
1565
  });
1499
1566
  }
@@ -1786,15 +1853,25 @@ var ManagedAsyncStorageAdapter = class {
1786
1853
  for (const payloadKey of payloadKeys) if (!indexState.entries.has(payloadKey)) payloadRecordKeysToRemove.add(getPayloadRecordKey(payloadKey));
1787
1854
  if (effectiveStaticPolicy?.maxBytes !== void 0) {
1788
1855
  const pinnedKeys = new Set(effectiveStaticPolicy.pinnedKeys ?? []);
1789
- const keptKeys = keepEntriesWithinByteBudget({
1790
- entries: candidateEntries,
1791
- getKey: (entry) => entry.itemKey,
1792
- getLastAccessAt: (entry) => entry.lastAccessAt,
1793
- getSizeBytes: (entry) => entry.sizeBytes,
1794
- isPinned: (entry) => pinnedKeys.has(entry.itemKey),
1795
- isProtected: (entry) => entry.protected,
1796
- maxBytes: effectiveStaticPolicy.maxBytes
1797
- });
1856
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1857
+ const logger = args.driver.logger;
1858
+ const evictedEntries = candidateEntries.length - keptKeys.size;
1859
+ if (logger && evictedEntries > 0) {
1860
+ const scopeKind = args.scope.kind;
1861
+ logPersistentStorageQuotaCleanup({
1862
+ adapter: "async",
1863
+ logger,
1864
+ evictedEntries,
1865
+ keptEntries: keptKeys.size,
1866
+ maxBytes: effectiveStaticPolicy.maxBytes,
1867
+ namespaceKind: scopeKind,
1868
+ phase: "startup-cleanup",
1869
+ quota: scopeKind === "listQuery.item" ? "maxItemBytes" : scopeKind === "listQuery.query" ? "maxQueryBytes" : "maxBytes",
1870
+ storeName: args.scope.storeName,
1871
+ totalEntries: candidateEntries.length,
1872
+ unprotectedBytes
1873
+ });
1874
+ }
1798
1875
  for (const { itemKey } of candidateEntries) {
1799
1876
  if (keptKeys.has(itemKey)) continue;
1800
1877
  payloadRecordKeysToRemove.add(getPayloadRecordKey(itemKey));
@@ -1865,4 +1942,4 @@ function serializeProtectedRef(ref) {
1865
1942
  return serializeProtectedRef$1(ref);
1866
1943
  }
1867
1944
  //#endregion
1868
- 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 };
1945
+ 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, scheduleIdleCleanup as J, 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, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS 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-2zQlbxtw.js";
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-D0ttVGmj.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-BO_uDxe4.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DlUjN1qY.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DqJXzF7M.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DC9GsYHH.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-2zQlbxtw.js";
1
+ import { t as AsyncStorageAdapter } from "./types-D0ttVGmj.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-DlUjN1qY.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-DC9GsYHH.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +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-BZSj1ZO5.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-CGfnsd9m.js";
2
2
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
3
3
  import { isObject } from "@ls-stack/utils/typeGuards";
4
4
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
@@ -107,9 +107,7 @@ function toPublicMetadata(key, record) {
107
107
  const INDEXED_DB_ENTRY_RECORD_KEYS = new Set([
108
108
  "a",
109
109
  "d",
110
- "f",
111
110
  "g",
112
- "h",
113
111
  "i",
114
112
  "m",
115
113
  "o",
@@ -162,8 +160,7 @@ function isValidEntryRecord(record) {
162
160
  if (!isObject(record)) return false;
163
161
  const recordValue = toRecordValue(record);
164
162
  if (Object.keys(recordValue).some((key) => !INDEXED_DB_ENTRY_RECORD_KEYS.has(key))) return false;
165
- const loadedFields = recordValue.f;
166
- return typeof recordValue.i === "string" && typeof recordValue.a === "number" && "d" in recordValue && (recordValue.v === void 0 || typeof recordValue.v === "number") && (recordValue.z === void 0 || typeof recordValue.z === "number") && (recordValue.m === void 0 || isObject(recordValue.m)) && (recordValue.g === void 0 || typeof recordValue.g === "string") && (recordValue.o === void 0 || recordValue.o === 1) && (loadedFields === void 0 || loadedFields instanceof Array && loadedFields.every((value) => typeof value === "string")) && (recordValue.h === void 0 || recordValue.h === 1);
163
+ return typeof recordValue.i === "string" && typeof recordValue.a === "number" && "d" in recordValue && (recordValue.v === void 0 || typeof recordValue.v === "number") && (recordValue.z === void 0 || typeof recordValue.z === "number") && (recordValue.m === void 0 || isObject(recordValue.m)) && (recordValue.g === void 0 || typeof recordValue.g === "string") && (recordValue.o === void 0 || recordValue.o === 1);
167
164
  }
168
165
  function isValidNamespacePolicyRecord(record) {
169
166
  if (!isObject(record)) return false;
@@ -180,12 +177,7 @@ function compactEntryValue(scope, value) {
180
177
  return { d: value };
181
178
  }
182
179
  function estimateIndexedDbManagedEntrySizeBytes(args) {
183
- return estimateManagedAsyncStorageEntrySizeBytes({
184
- customMetadata: args.customMetadata,
185
- lastAccessAt: args.lastAccessAt,
186
- serializedValue: args.serializedValue ?? serializeJsonForStorage(args.value).rawValue,
187
- version: args.version
188
- });
180
+ return estimateManagedAsyncStorageEntrySizeBytes(args.serializedValue ?? serializeJsonForStorage(args.value).rawValue, args.lastAccessAt, args.version, args.customMetadata);
189
181
  }
190
182
  function expandEntryValue(scope, record) {
191
183
  return record.d;
@@ -249,6 +241,7 @@ async function setMaintenanceState(database, value) {
249
241
  await transactionDone(transaction);
250
242
  }
251
243
  var IndexedDbAsyncStorageDriver = class {
244
+ debugLogger;
252
245
  __tsdfManagedStorage = {
253
246
  applyManagedCommit: this.applyManagedCommit.bind(this),
254
247
  clearManagedNamespace: this.clearManagedNamespace.bind(this),
@@ -320,6 +313,7 @@ var IndexedDbAsyncStorageDriver = class {
320
313
  }
321
314
  }
322
315
  async removeMany(scope, keys) {
316
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
323
317
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
324
318
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
325
319
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -344,6 +338,10 @@ var IndexedDbAsyncStorageDriver = class {
344
338
  };
345
339
  }
346
340
  await transactionDone(transaction);
341
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-records", startTime, {
342
+ keyCount: keys.length,
343
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE]
344
+ });
347
345
  this.#instrumentation?.onRemoveMany?.(scope, keys);
348
346
  this.#instrumentation?.record({
349
347
  keys: [...keys].sort((left, right) => left.localeCompare(right)),
@@ -366,6 +364,7 @@ var IndexedDbAsyncStorageDriver = class {
366
364
  return (await this.listScopesWithKnownRecordKeys(sessionKey)).map(({ scope }) => scope);
367
365
  }
368
366
  async listScopesWithKnownRecordKeys(sessionKey) {
367
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
369
368
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
370
369
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
371
370
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -385,6 +384,11 @@ var IndexedDbAsyncStorageDriver = class {
385
384
  });
386
385
  });
387
386
  await transactionDone(transaction);
387
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(void 0, "list-scopes", startTime, {
388
+ count: discoveredScopes.length,
389
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
390
+ ...sessionKey !== void 0 ? { sessionKey } : {}
391
+ });
388
392
  discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
389
393
  this.#instrumentation?.record({
390
394
  scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
@@ -395,6 +399,7 @@ var IndexedDbAsyncStorageDriver = class {
395
399
  return discoveredScopes;
396
400
  }
397
401
  async readManagedEntries(scope, keys) {
402
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
398
403
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
399
404
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
400
405
  const uniqueKeys = [...new Set(keys)];
@@ -412,6 +417,11 @@ var IndexedDbAsyncStorageDriver = class {
412
417
  });
413
418
  }));
414
419
  await transactionDone(transaction);
420
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "read-records", startTime, {
421
+ hitCount: [...result.values()].filter((value) => value !== null).length,
422
+ keyCount: uniqueKeys.length,
423
+ objectStores: [INDEXED_DB_ENTRY_STORE]
424
+ });
415
425
  this.#instrumentation?.record({
416
426
  keys: uniqueKeys,
417
427
  resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
@@ -422,6 +432,7 @@ var IndexedDbAsyncStorageDriver = class {
422
432
  return result;
423
433
  }
424
434
  async listManagedMetadata(scope, args = {}) {
435
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
425
436
  const order = args.order ?? "key";
426
437
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
427
438
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
@@ -453,6 +464,12 @@ var IndexedDbAsyncStorageDriver = class {
453
464
  const filter = args.filter;
454
465
  const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
455
466
  if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
467
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-record-metadata", startTime, {
468
+ count: filteredEntries.length,
469
+ objectStores: [INDEXED_DB_ENTRY_STORE],
470
+ order,
471
+ usedIndex
472
+ });
456
473
  this.#instrumentation?.record({
457
474
  order,
458
475
  resultKeys: filteredEntries.map((entry) => entry.key),
@@ -467,6 +484,7 @@ var IndexedDbAsyncStorageDriver = class {
467
484
  return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
468
485
  }
469
486
  async clearManagedNamespace(scope) {
487
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
470
488
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
471
489
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
472
490
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -475,6 +493,7 @@ var IndexedDbAsyncStorageDriver = class {
475
493
  });
476
494
  policyStore.delete(createScopePolicyKey(scope));
477
495
  await transactionDone(transaction);
496
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "clear-records", startTime, { objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE] });
478
497
  this.#instrumentation?.onClearManagedNamespace?.(scope);
479
498
  this.#instrumentation?.record({
480
499
  scope,
@@ -483,6 +502,7 @@ var IndexedDbAsyncStorageDriver = class {
483
502
  });
484
503
  }
485
504
  async applyManagedCommit(scope, args, helpers) {
505
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
486
506
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
487
507
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
488
508
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -549,6 +569,12 @@ var IndexedDbAsyncStorageDriver = class {
549
569
  s: scope.sessionKey
550
570
  }, createScopePolicyKey(scope)));
551
571
  await transactionDone(transaction);
572
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-records", startTime, {
573
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
574
+ removes: removes.length,
575
+ touches: touches.length,
576
+ upserts: upserts.length
577
+ });
552
578
  this.#instrumentation?.onApplyManagedCommit?.(scope, args);
553
579
  this.#instrumentation?.record({
554
580
  removes,
@@ -888,6 +914,32 @@ var IndexedDbAsyncStorageDriver = class {
888
914
  });
889
915
  return this.#databasePromise;
890
916
  }
917
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
918
+ if (!import.meta.env.DEV) return;
919
+ if (startTime === null) return;
920
+ if (!this.debugLogger) return;
921
+ const status = typeof details.status === "string" ? details.status : "success";
922
+ emitTSDFDebugLog(this.debugLogger, {
923
+ area: "persistent-storage",
924
+ level: "log",
925
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
926
+ operation: "adapter-operation",
927
+ details: {
928
+ adapter: "async",
929
+ adapterName: "indexeddb",
930
+ adapterOperation,
931
+ databaseName: this.databaseName,
932
+ durationMs: getTSDFDebugTimingMs() - startTime,
933
+ status,
934
+ ...scope !== void 0 ? {
935
+ namespaceKind: scope.kind,
936
+ sessionKey: scope.sessionKey,
937
+ storeName: scope.storeName
938
+ } : {},
939
+ ...details
940
+ }
941
+ });
942
+ }
891
943
  };
892
944
  function createIndexedDbPersistentStorage$1(options = {}) {
893
945
  return createAsyncStorageAdapter(new IndexedDbAsyncStorageDriver(options.databaseName));