keyv 6.0.0-beta.4 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -61,6 +61,26 @@ function buildMethods(obj, names) {
61
61
  for (const name of names) methods[name] = obj ? resolveMethod(obj, name) : { ...noneMethod };
62
62
  return methods;
63
63
  }
64
+ /** The methods a full storage adapter implements. */
65
+ const keyvStorageRequiredMethods = [
66
+ "get",
67
+ "has",
68
+ "hasMany",
69
+ "set",
70
+ "setMany",
71
+ "delete",
72
+ "deleteMany",
73
+ "clear"
74
+ ];
75
+ /**
76
+ * Whether a detected store has every method of a full storage adapter, whether or not they are
77
+ * native `async` functions.
78
+ * @param capability - The result of {@link detectKeyvStorage}
79
+ * @returns `true` when all of the full storage adapter's methods exist
80
+ */
81
+ function hasKeyvStorageMethods(capability) {
82
+ return keyvStorageRequiredMethods.every((m) => capability.methods[m].exists);
83
+ }
64
84
  /**
65
85
  * Detect whether an object implements the full Keyv interface
66
86
  * @param obj - The object to check
@@ -132,16 +152,7 @@ function detectKeyvStorage(obj) {
132
152
  methods: buildMethods(null, keyvStorageMethodNames)
133
153
  };
134
154
  const methods = buildMethods(obj, keyvStorageMethodNames);
135
- if ([
136
- "get",
137
- "has",
138
- "hasMany",
139
- "set",
140
- "setMany",
141
- "delete",
142
- "deleteMany",
143
- "clear"
144
- ].every((k) => methods[k].exists && methods[k].methodType === "async")) return {
155
+ if (keyvStorageRequiredMethods.every((k) => methods[k].exists && methods[k].methodType === "async")) return {
145
156
  compatible: true,
146
157
  store: "keyvStorage",
147
158
  methods
@@ -369,7 +380,7 @@ function isDataExpired(data) {
369
380
  return typeof data.expires === "number" && Date.now() > data.expires;
370
381
  }
371
382
  /**
372
- * Calculate an absolute expiry timestamp from a TTL value.
383
+ * Calculate an absolute expiry timestamp from a TTL value, in whole milliseconds.
373
384
  * Returns `undefined` when `ttl` is absent, zero, negative, or non-finite
374
385
  * (meaning "no expiry").
375
386
  *
@@ -378,7 +389,19 @@ function isDataExpired(data) {
378
389
  */
379
390
  function calculateExpires(ttl) {
380
391
  if (typeof ttl !== "number" || ttl <= 0 || !Number.isFinite(ttl)) return;
381
- return Date.now() + ttl;
392
+ return toStoreExpires(Date.now() + ttl);
393
+ }
394
+ /**
395
+ * Convert an absolute expiry into the form stores accept: whole milliseconds, rounded up so an
396
+ * entry never expires early, or `undefined` (no expiry) when it is not a finite number. Stores
397
+ * such as PostgreSQL's `BIGINT` column and Redis's `PXAT` reject a fractional timestamp.
398
+ *
399
+ * @param expires - Absolute expiry timestamp (ms since epoch), or `undefined`
400
+ * @returns The expiry in whole milliseconds, or `undefined` for no expiry
401
+ */
402
+ function toStoreExpires(expires) {
403
+ if (typeof expires !== "number" || !Number.isFinite(expires)) return;
404
+ return Math.ceil(expires);
382
405
  }
383
406
  /**
384
407
  * Resolve a TTL value by falling back to a default when none is given,
@@ -407,6 +430,23 @@ function ttlFromExpires(expires) {
407
430
  return remaining > 0 ? remaining : void 0;
408
431
  }
409
432
  /**
433
+ * Calls a store's `has` once to see whether it returns a promise. A method that is not a native
434
+ * `async` function can still return one, such as an `async` method compiled to an older target.
435
+ * @param store - The store to check
436
+ * @returns `true` when `has` returned a promise
437
+ */
438
+ function returnsPromise(store) {
439
+ let result;
440
+ try {
441
+ result = store.has("keyv-probe");
442
+ } catch {
443
+ return false;
444
+ }
445
+ if (typeof result?.then !== "function") return false;
446
+ Promise.resolve(result).catch(() => {});
447
+ return true;
448
+ }
449
+ /**
410
450
  * Scan parallel `keys` and `data` arrays, nullify any expired entries in
411
451
  * `data`, and batch-delete the corresponding keys via `keyv.deleteMany()`.
412
452
  */
@@ -421,7 +461,7 @@ async function deleteExpiredKeys(keys, data, keyv) {
421
461
  /**
422
462
  * Maps new hook names to their deprecated equivalents so both fire during migration.
423
463
  */
424
- const deprecatedHookAliases = new Map([
464
+ const deprecatedHookAliases = /* @__PURE__ */ new Map([
425
465
  ["before:set", "preSet"],
426
466
  ["after:set", "postSet"],
427
467
  ["before:get", "preGet"],
@@ -447,7 +487,7 @@ const deprecatedHookAliases = new Map([
447
487
  * Build the deprecated-hooks map used by Hookified to warn when old PRE_/POST_ hook names are registered.
448
488
  */
449
489
  function buildDeprecatedHooks() {
450
- return new Map([
490
+ return /* @__PURE__ */ new Map([
451
491
  ["preSet", "Use KeyvHooks.BEFORE_SET ('before:set') instead"],
452
492
  ["postSet", "Use KeyvHooks.AFTER_SET ('after:set') instead"],
453
493
  ["preGet", "Use KeyvHooks.BEFORE_GET ('before:get') instead"],
@@ -492,7 +532,7 @@ function buildDeprecatedHooks() {
492
532
  var KeyvBridgeAdapter = class extends Hookified {
493
533
  _store;
494
534
  _namespace;
495
- _keySeparator = ":";
535
+ _namespaceSeparator = "::";
496
536
  _capabilities;
497
537
  /**
498
538
  * Whether the wrapped store manages its own namespace (exposes a `namespace` property).
@@ -509,10 +549,11 @@ var KeyvBridgeAdapter = class extends Hookified {
509
549
  super({ throwOnHookError: false });
510
550
  this._store = store;
511
551
  this._capabilities = detectKeyvStorage(store);
512
- this._storeHandlesNamespace = this._capabilities.store === "keyvStorage" && "namespace" in store;
513
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
552
+ this._storeHandlesNamespace = hasKeyvStorageMethods(this._capabilities) && "namespace" in store;
553
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
514
554
  if (options?.namespace) this._namespace = options.namespace;
515
- if (this._storeHandlesNamespace) this._store.namespace = this._namespace;
555
+ if (this._storeHandlesNamespace) if (options?.namespace === void 0) this._namespace = this._store.namespace;
556
+ else this._store.namespace = this._namespace;
516
557
  if (typeof store.on === "function") store.on("error", (error) => this.emit("error", error));
517
558
  }
518
559
  /**
@@ -539,16 +580,16 @@ var KeyvBridgeAdapter = class extends Hookified {
539
580
  };
540
581
  }
541
582
  /**
542
- * Gets the current key separator used between namespace and key.
583
+ * Gets the separator between the namespace and the key. Defaults to `::`.
543
584
  */
544
- get keySeparator() {
545
- return this._keySeparator;
585
+ get namespaceSeparator() {
586
+ return this._namespaceSeparator;
546
587
  }
547
588
  /**
548
- * Sets the key separator used between namespace and key.
589
+ * Sets the separator between the namespace and the key.
549
590
  */
550
- set keySeparator(separator) {
551
- this._keySeparator = separator;
591
+ set namespaceSeparator(separator) {
592
+ this._namespaceSeparator = separator;
552
593
  }
553
594
  /**
554
595
  * Gets the current namespace.
@@ -572,7 +613,7 @@ var KeyvBridgeAdapter = class extends Hookified {
572
613
  */
573
614
  getKeyPrefix(key, namespace) {
574
615
  if (this._storeHandlesNamespace) return key;
575
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
616
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
576
617
  return key;
577
618
  }
578
619
  /**
@@ -581,9 +622,9 @@ var KeyvBridgeAdapter = class extends Hookified {
581
622
  * @returns An object containing the namespace (if present) and the original key
582
623
  */
583
624
  getKeyPrefixData(key) {
584
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
625
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
585
626
  namespace: this._namespace,
586
- key: key.slice(this._namespace.length + this._keySeparator.length)
627
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
587
628
  };
588
629
  return { key };
589
630
  }
@@ -663,25 +704,30 @@ var KeyvBridgeAdapter = class extends Hookified {
663
704
  * Stores multiple entries in the store at once.
664
705
  * Delegates to the store's native setMany if available, otherwise loops over set.
665
706
  * @param entries - Array of entries containing key, value, and optional absolute `expires`
707
+ * @returns One boolean per entry, `false` where the store reported that the write failed
666
708
  */
667
709
  async setMany(entries) {
668
710
  if (this._capabilities.methods.setMany.exists) {
669
711
  const now = Date.now();
670
712
  const isExpired = (entry) => typeof entry.expires === "number" && entry.expires <= now;
671
713
  const live = entries.filter((entry) => !isExpired(entry));
672
- if (live.length > 0) await this._store.setMany?.(live.map((entry) => ({
714
+ let liveResults;
715
+ if (live.length > 0) liveResults = await this._store.setMany?.(live.map((entry) => ({
673
716
  key: this.getKeyPrefix(entry.key, this._namespace),
674
717
  value: entry.value,
675
718
  ttl: ttlFromExpires(entry.expires)
676
719
  })));
677
720
  for (const entry of entries) if (isExpired(entry)) await this._store.delete(this.getKeyPrefix(entry.key, this._namespace));
678
- return entries.map(() => true);
721
+ let liveIndex = 0;
722
+ return entries.map((entry) => {
723
+ if (isExpired(entry)) return true;
724
+ const result = Array.isArray(liveResults) ? liveResults[liveIndex] : liveResults;
725
+ liveIndex++;
726
+ return result !== false;
727
+ });
679
728
  }
680
729
  const results = [];
681
- for (const entry of entries) {
682
- await this.set(entry.key, entry.value, entry.expires);
683
- results.push(true);
684
- }
730
+ for (const entry of entries) results.push(await this.set(entry.key, entry.value, entry.expires));
685
731
  return results;
686
732
  }
687
733
  /**
@@ -748,20 +794,20 @@ var KeyvBridgeAdapter = class extends Hookified {
748
794
  return results;
749
795
  }
750
796
  /**
751
- * Clears entries from the store. If a namespace is set and the store supports
752
- * iteration, only entries within that namespace are removed. Otherwise, the
753
- * entire store is cleared.
797
+ * Clears entries from the store. With no namespace, the whole store is cleared. With a
798
+ * namespace, only that namespace's entries are removed: a store that manages its own
799
+ * namespace clears them itself, and otherwise the bridge finds them with the store's
800
+ * `iterator()`. A store with neither can't tell namespaces apart, so this throws rather
801
+ * than call the store's `clear()` and delete every namespace's entries.
802
+ * @throws {Error} If a namespace is set and the store neither manages it nor has `iterator()`.
754
803
  */
755
804
  async clear() {
756
- if (this._namespace && this._storeHandlesNamespace) {
757
- await this._store.clear();
758
- return;
759
- }
760
- if (!this._namespace || !this._capabilities.methods.iterator.exists) {
805
+ if (!this._namespace || this._storeHandlesNamespace) {
761
806
  await this._store.clear();
762
807
  return;
763
808
  }
764
- const prefix = `${this._namespace}${this._keySeparator}`;
809
+ if (!this._capabilities.methods.iterator.exists) throw new Error(`Can't clear namespace "${this._namespace}": the store has no iterator() to find that namespace's keys, and its clear() would delete every namespace. Give the store an iterator(), or clear it without a namespace.`);
810
+ const prefix = `${this._namespace}${this._namespaceSeparator}`;
765
811
  const keysToDelete = [];
766
812
  /* v8 ignore next -- @preserve */
767
813
  for await (const entry of this._store.iterator?.(this._namespace) ?? []) {
@@ -778,7 +824,7 @@ var KeyvBridgeAdapter = class extends Hookified {
778
824
  async *iterator() {
779
825
  if (!this._capabilities.methods.iterator.exists) return;
780
826
  const namespace = this._namespace;
781
- const prefix = namespace && !this._storeHandlesNamespace ? `${namespace}${this._keySeparator}` : void 0;
827
+ const prefix = namespace && !this._storeHandlesNamespace ? `${namespace}${this._namespaceSeparator}` : void 0;
782
828
  /* v8 ignore next -- @preserve */
783
829
  for await (const entry of this._store.iterator?.(this._namespace) ?? []) {
784
830
  const [key, data] = Array.isArray(entry) ? entry : [entry];
@@ -834,7 +880,7 @@ function prepare(value) {
834
880
  if (Array.isArray(value)) return value.map((item) => prepare(item));
835
881
  if (typeof value === "object") {
836
882
  if (typeof value.toJSON === "function") return prepare(value.toJSON());
837
- const result = {};
883
+ const result = Object.create(null);
838
884
  for (const key of Object.keys(value)) if (value[key] !== void 0) result[key] = prepare(value[key]);
839
885
  return result;
840
886
  }
@@ -882,15 +928,50 @@ function buildPatterns(options) {
882
928
  return patterns.length > 0 ? patterns : void 0;
883
929
  }
884
930
  /**
885
- * Run all patterns against a string, stripping matched sequences.
931
+ * Run all patterns against a string, stripping matched sequences. Stripping one match can form
932
+ * another, as `..././` becomes `../`, so when a match remains, {@link stripRemaining} finishes
933
+ * the job.
886
934
  */
887
- function applyPatterns(value, patterns) {
935
+ function applyPatterns(value, patterns, options) {
888
936
  for (const pattern of patterns) {
889
937
  pattern.lastIndex = 0;
890
938
  value = value.replace(pattern, "");
891
939
  }
940
+ if (patterns.some((pattern) => value.search(pattern) !== -1)) return stripRemaining(value, options);
892
941
  return value;
893
942
  }
943
+ /**
944
+ * Strip the matches a single pass of {@link applyPatterns} left behind. It reads the string once,
945
+ * left to right, and drops a pattern as soon as its last character arrives, so a pattern formed by
946
+ * an earlier removal is caught without scanning the string again. The result contains no match.
947
+ */
948
+ function stripRemaining(value, options) {
949
+ const kept = [];
950
+ for (const char of value) {
951
+ const length = matchLength(kept, char, options);
952
+ if (length === 0) kept.push(char);
953
+ else kept.length -= length - 1;
954
+ }
955
+ return kept.join("");
956
+ }
957
+ const whitespace = /\s/;
958
+ /**
959
+ * The length of the pattern that `char` completes at the end of `kept`, counting `char` itself, or
960
+ * 0 when it completes none. `;`, `\0`, `\r` and `\n` need no check: the single pass before this
961
+ * removes every one of them, and removing characters never adds one back.
962
+ */
963
+ function matchLength(kept, char, options) {
964
+ const last = kept.length - 1;
965
+ if (options.sql && (char === "-" && kept[last] === "-" || char === "*" && kept[last] === "/")) return 2;
966
+ if (options.mongo && char === "$") {
967
+ if (kept.length === 0) return 1;
968
+ let start = kept.length;
969
+ while (start > 0 && whitespace.test(kept[start - 1])) start--;
970
+ if (kept[start - 1] === "{") return kept.length - start + 2;
971
+ }
972
+ if (options.path && (char === "/" || char === "\\") && kept[last] === "." && kept[last - 1] === ".") return 3;
973
+ return 0;
974
+ }
894
975
  const allOn = {
895
976
  escape: true,
896
977
  mongo: true,
@@ -959,7 +1040,7 @@ var KeyvSanitize = class {
959
1040
  this._cacheKeys.set(key, cached);
960
1041
  return cached;
961
1042
  }
962
- const result = applyPatterns(key, this._keyPatterns);
1043
+ const result = applyPatterns(key, this._keyPatterns, this._keys);
963
1044
  this._cacheKeys.set(key, result);
964
1045
  if (this._cacheKeys.size > this._cacheMax) {
965
1046
  const first = this._cacheKeys.keys().next().value;
@@ -985,7 +1066,7 @@ var KeyvSanitize = class {
985
1066
  this._cacheNamespaces.set(ns, cached);
986
1067
  return cached;
987
1068
  }
988
- const result = applyPatterns(ns, this._namespacePatterns);
1069
+ const result = applyPatterns(ns, this._namespacePatterns, this._namespace);
989
1070
  this._cacheNamespaces.set(ns, result);
990
1071
  if (this._cacheNamespaces.size > this._cacheMax) {
991
1072
  const first = this._cacheNamespaces.keys().next().value;
@@ -1131,10 +1212,10 @@ var KeyvStats = class {
1131
1212
  }
1132
1213
  /**
1133
1214
  * Build a composite key from a telemetry event.
1134
- * Format: "namespace:key" if namespace is present, otherwise just "key".
1215
+ * Format: "namespace::key" if namespace is present, otherwise just "key".
1135
1216
  */
1136
1217
  buildKeyEventName(event) {
1137
- if (event.namespace && event.key) return `${event.namespace}:${event.key}`;
1218
+ if (event.namespace && event.key) return `${event.namespace}::${event.key}`;
1138
1219
  return event.key ?? "";
1139
1220
  }
1140
1221
  /**
@@ -1217,6 +1298,12 @@ var KeyvStats = class {
1217
1298
  };
1218
1299
  //#endregion
1219
1300
  //#region src/keyv.ts
1301
+ /**
1302
+ * The namespace Keyv uses when sanitizing a namespace leaves nothing. An empty namespace would
1303
+ * turn namespacing off, mixing the instance's keys with unrelated ones and letting `clear()`
1304
+ * remove them.
1305
+ */
1306
+ const emptiedNamespace = "keyv-sanitized";
1220
1307
  var Keyv = class Keyv extends Hookified {
1221
1308
  /**
1222
1309
  * Keyv Constructor
@@ -1227,8 +1314,7 @@ var Keyv = class Keyv extends Hookified {
1227
1314
  const mergedOptions = Keyv.resolveOptions(store, options);
1228
1315
  super({
1229
1316
  throwOnHookError: false,
1230
- throwOnEmptyListeners: true,
1231
- throwOnEmitError: mergedOptions.throwOnErrors ?? false
1317
+ throwOnEmptyListeners: true
1232
1318
  });
1233
1319
  this.deprecatedHooks = buildDeprecatedHooks();
1234
1320
  this._compression = mergedOptions.compression;
@@ -1239,7 +1325,7 @@ var Keyv = class Keyv extends Hookified {
1239
1325
  this.initStats(mergedOptions);
1240
1326
  if (mergedOptions.store) this.setStore(mergedOptions.store);
1241
1327
  this.setTtl(mergedOptions.ttl);
1242
- this._checkExpired = mergedOptions.checkExpired ?? false;
1328
+ this._checkExpired = mergedOptions.checkExpired ?? true;
1243
1329
  }
1244
1330
  /**
1245
1331
  * Stats manager for tracking cache operation metrics (hits, misses, sets, deletes, errors).
@@ -1277,8 +1363,10 @@ var Keyv = class Keyv extends Hookified {
1277
1363
  _sanitize;
1278
1364
  /**
1279
1365
  * When true, Keyv checks expiry at its layer on get/getMany/has/hasMany.
1366
+ * Defaults to true so reads stay millisecond-precise even on adapters whose
1367
+ * native expiry is coarse or lazily swept (e.g. Memcached, DynamoDB).
1280
1368
  */
1281
- _checkExpired = false;
1369
+ _checkExpired = true;
1282
1370
  /**
1283
1371
  * Get the current storage adapter.
1284
1372
  * @returns {KeyvStorageAdapter} The current storage adapter.
@@ -1322,18 +1410,19 @@ var Keyv = class Keyv extends Hookified {
1322
1410
  this._encryption = encryption;
1323
1411
  }
1324
1412
  /**
1325
- * Get the current namespace.
1413
+ * Get the current namespace. When Keyv has no namespace of its own, this is the namespace
1414
+ * configured on the storage adapter.
1326
1415
  * @returns {string | undefined} The current namespace.
1327
1416
  */
1328
1417
  get namespace() {
1329
- return this._namespace;
1418
+ return this._namespace ?? this._store.namespace;
1330
1419
  }
1331
1420
  /**
1332
1421
  * Set the current namespace.
1333
1422
  * @param {string | undefined} namespace The namespace to set.
1334
1423
  */
1335
1424
  set namespace(namespace) {
1336
- this._namespace = namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(namespace) : namespace;
1425
+ this._namespace = namespace && this._sanitize.enabled ? this.cleanNamespace(namespace) : namespace;
1337
1426
  this._store.namespace = this._namespace;
1338
1427
  }
1339
1428
  /**
@@ -1366,22 +1455,6 @@ var Keyv = class Keyv extends Hookified {
1366
1455
  this._serialization = serialization === false ? void 0 : serialization;
1367
1456
  }
1368
1457
  /**
1369
- * Get the current throwOnErrors value. When enabled, all errors with throw. By default, errors
1370
- * will only throw if there are no listeners to the error event.
1371
- * @return {boolean} The current throwOnErrors value.
1372
- */
1373
- get throwOnErrors() {
1374
- return this.throwOnEmitError;
1375
- }
1376
- /**
1377
- * Set the current throwOnErrors value. When enabled, all errors will throw. By default, errors
1378
- * will only throw if there are no listeners to the error event.
1379
- * @param {boolean} value The throwOnErrors value to set.
1380
- */
1381
- set throwOnErrors(value) {
1382
- this.throwOnEmitError = value;
1383
- }
1384
- /**
1385
1458
  * Get the current sanitize adapter. Sanitization is disabled by default. To
1386
1459
  * enable it `sanitize.keys` or `sanitize.namespace` to true or set KeyvSanitizePatterns
1387
1460
  * to each.
@@ -1391,13 +1464,17 @@ var Keyv = class Keyv extends Hookified {
1391
1464
  return this._sanitize;
1392
1465
  }
1393
1466
  /**
1394
- * Set the sanitize adapter directly and will run sanitization on namespace.
1467
+ * Set the sanitize adapter directly and will run sanitization on namespace, including a
1468
+ * namespace kept from the storage adapter, and apply the result to the adapter.
1395
1469
  * @param {KeyvSanitizeAdapter} value The sanitize adapter to use.
1396
1470
  */
1397
1471
  set sanitize(value) {
1398
1472
  this._sanitize = value;
1399
- /* v8 ignore next -- @preserve */
1400
- this._namespace = this._namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(this._namespace) : this._namespace;
1473
+ if (this._namespace && this._sanitize.enabled) {
1474
+ this._namespace = this.cleanNamespace(this._namespace);
1475
+ this._store.namespace = this._namespace;
1476
+ }
1477
+ this.sanitizeStoreNamespace();
1401
1478
  }
1402
1479
  /**
1403
1480
  * Get the stats. This is just for this instance
@@ -1418,7 +1495,8 @@ var Keyv = class Keyv extends Hookified {
1418
1495
  }
1419
1496
  /**
1420
1497
  * Get whether Keyv checks expiry at its own layer on get/getMany/has/hasMany.
1421
- * When false (default), it trusts the storage adapter to handle expiry.
1498
+ * When true (default), expired entries are filtered (and deleted) by Keyv regardless of
1499
+ * the adapter. Set to false to trust the storage adapter to handle expiry on its own.
1422
1500
  * @returns {boolean} `true` if Keyv checks expiry at its layer.
1423
1501
  */
1424
1502
  get checkExpired() {
@@ -1431,7 +1509,9 @@ var Keyv = class Keyv extends Hookified {
1431
1509
  * with the `async` keyword is not mis-bridged).
1432
1510
  * 2. If the store implements the full async storage interface (but doesn't declare `expires`),
1433
1511
  * treat it as a legacy relative-`ttl` adapter and wrap it in KeyvBridgeAdapter.
1434
- * 3. If the store is map-like (synchronous get/set/delete/has), wrap it in KeyvMemoryAdapter.
1512
+ * 3. If the store is map-like (get/set/delete/has that aren't native `async` functions), wrap it
1513
+ * in KeyvMemoryAdapter. A store other than a Map is first asked once, through `has`, whether
1514
+ * it returns promises; if it does, wrap it in KeyvBridgeAdapter instead.
1435
1515
  * 4. If the store has async get/set/delete/clear, wrap it in KeyvBridgeAdapter.
1436
1516
  * 5. Otherwise, emit an error and fall back to a default in-memory KeyvMemoryAdapter.
1437
1517
  *
@@ -1443,20 +1523,25 @@ var Keyv = class Keyv extends Hookified {
1443
1523
  if (store?.capabilities?.expires === true) return store;
1444
1524
  const cap = detectKeyvStorage(store);
1445
1525
  if (cap.store === "keyvStorage") return new KeyvBridgeAdapter(store);
1446
- if (cap.store === "mapLike") return new KeyvMemoryAdapter(store);
1526
+ if (cap.store === "mapLike") {
1527
+ if (!(store instanceof Map) && returnsPromise(store)) return new KeyvBridgeAdapter(store);
1528
+ return new KeyvMemoryAdapter(store);
1529
+ }
1447
1530
  if (cap.store === "asyncMap") return new KeyvBridgeAdapter(store);
1448
1531
  this.emit("error", /* @__PURE__ */ new Error("Could not use the provided storage adapter, falling back to KeyvMemoryAdapter with Map"));
1449
1532
  return new KeyvMemoryAdapter(/* @__PURE__ */ new Map());
1450
1533
  }
1451
1534
  /**
1452
1535
  * Sets the storage adapter by resolving it via {@link resolveStore}, then wires up
1453
- * error forwarding and namespace propagation.
1536
+ * error forwarding and namespace propagation. Keyv's namespace, when set, is applied to the
1537
+ * adapter. Without one, the adapter keeps the namespace it was configured with.
1454
1538
  * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
1455
1539
  */
1456
1540
  setStore(store) {
1457
1541
  this._store = this.resolveStore(store);
1458
1542
  if (typeof this._store.on === "function") this._store.on("error", (error) => this.emit("error", error));
1459
- this._store.namespace = this._namespace;
1543
+ if (this._namespace !== void 0) this._store.namespace = this._namespace;
1544
+ else this.sanitizeStoreNamespace();
1460
1545
  }
1461
1546
  /**
1462
1547
  * Sets the TTL, treating zero and negative values as undefined (no TTL).
@@ -1480,6 +1565,11 @@ var Keyv = class Keyv extends Hookified {
1480
1565
  } catch (error) {
1481
1566
  this.emit("error", error);
1482
1567
  this.emitTelemetry("stat:error", key);
1568
+ await this.hookWithDeprecated("after:get", {
1569
+ key,
1570
+ value: void 0
1571
+ });
1572
+ return;
1483
1573
  }
1484
1574
  let data;
1485
1575
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
@@ -1512,6 +1602,23 @@ var Keyv = class Keyv extends Hookified {
1512
1602
  return Promise.all(keys.map(async (key) => this._store.get(key)));
1513
1603
  }
1514
1604
  /**
1605
+ * Runs a batch operation without the keys or entries whose key is empty, then returns its results
1606
+ * in the original order with `fallback` for each empty key. As with the single-key methods, an
1607
+ * empty key never reaches hooks, telemetry or the store.
1608
+ * @param items - the keys or entries of the batch
1609
+ * @param fallback - the result for an item whose key is empty
1610
+ * @param run - runs the batch operation on the items whose key is not empty
1611
+ * @returns one result per item, in the same order as `items`
1612
+ */
1613
+ async skipEmptyKeys(items, fallback, run) {
1614
+ const isEmpty = (item) => (typeof item === "string" ? item : item.key) === "";
1615
+ const kept = items.filter((item) => !isEmpty(item));
1616
+ if (kept.length === items.length) return run(items);
1617
+ const results = kept.length > 0 ? await run(kept) : [];
1618
+ let next = 0;
1619
+ return items.map((item) => isEmpty(item) ? fallback : results[next++]);
1620
+ }
1621
+ /**
1515
1622
  * Get many values for an array of keys.
1516
1623
  * @param {string[]} keys the keys to get
1517
1624
  * @returns {Promise<Array<Value | undefined>>} an array of values in the same order as the
@@ -1519,19 +1626,30 @@ var Keyv = class Keyv extends Hookified {
1519
1626
  */
1520
1627
  async getMany(keys) {
1521
1628
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1522
- await this.hookWithDeprecated("before:getMany", { keys });
1523
- const rawData = await this.storeGetMany(keys);
1524
- let deserialized;
1525
- if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1526
- else deserialized = await Promise.all(rawData.map(async (row) => {
1527
- if (row === void 0 || row === null) return;
1528
- return typeof row === "string" ? this.decode(row) : row;
1529
- }));
1530
- const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1531
- await this.hookWithDeprecated("after:getMany", result);
1532
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1533
- else this.emitTelemetry("stat:hit", keys[i]);
1534
- return result;
1629
+ return this.skipEmptyKeys(keys, void 0, async (keys) => {
1630
+ await this.hookWithDeprecated("before:getMany", { keys });
1631
+ let rawData;
1632
+ try {
1633
+ rawData = await this.storeGetMany(keys);
1634
+ } catch (error) {
1635
+ this.emit("error", error);
1636
+ this.emitTelemetry("stat:error", keys);
1637
+ const failed = keys.map(() => void 0);
1638
+ await this.hookWithDeprecated("after:getMany", failed);
1639
+ return failed;
1640
+ }
1641
+ let deserialized;
1642
+ if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1643
+ else deserialized = await Promise.all(rawData.map(async (row) => {
1644
+ if (row === void 0 || row === null) return;
1645
+ return typeof row === "string" ? this.decode(row) : row;
1646
+ }));
1647
+ const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1648
+ await this.hookWithDeprecated("after:getMany", result);
1649
+ for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1650
+ else this.emitTelemetry("stat:hit", keys[i]);
1651
+ return result;
1652
+ });
1535
1653
  }
1536
1654
  /**
1537
1655
  * Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
@@ -1543,7 +1661,18 @@ var Keyv = class Keyv extends Hookified {
1543
1661
  key = this._sanitize.enabled ? this._sanitize.cleanKey(key) : key;
1544
1662
  if (key === "") return;
1545
1663
  await this.hookWithDeprecated("before:getRaw", { key });
1546
- const rawData = await this._store.get(key);
1664
+ let rawData;
1665
+ try {
1666
+ rawData = await this._store.get(key);
1667
+ } catch (error) {
1668
+ this.emit("error", error);
1669
+ this.emitTelemetry("stat:error", key);
1670
+ await this.hookWithDeprecated("after:getRaw", {
1671
+ key,
1672
+ value: void 0
1673
+ });
1674
+ return;
1675
+ }
1547
1676
  let data;
1548
1677
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
1549
1678
  else data = rawData === void 0 || rawData === null ? void 0 : typeof rawData === "string" ? await this.decode(rawData) : rawData;
@@ -1570,29 +1699,43 @@ var Keyv = class Keyv extends Hookified {
1570
1699
  async getManyRaw(keys) {
1571
1700
  /* v8 ignore next -- @preserve */
1572
1701
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1573
- await this.hookWithDeprecated("before:getManyRaw", { keys });
1574
- if (keys.length === 0) {
1575
- const result = [];
1702
+ return this.skipEmptyKeys(keys, void 0, async (keys) => {
1703
+ await this.hookWithDeprecated("before:getManyRaw", { keys });
1704
+ if (keys.length === 0) {
1705
+ const result = [];
1706
+ await this.hookWithDeprecated("after:getManyRaw", {
1707
+ keys,
1708
+ values: result
1709
+ });
1710
+ return result;
1711
+ }
1712
+ let rawData;
1713
+ try {
1714
+ rawData = await this.storeGetMany(keys);
1715
+ } catch (error) {
1716
+ this.emit("error", error);
1717
+ this.emitTelemetry("stat:error", keys);
1718
+ const failed = keys.map(() => void 0);
1719
+ await this.hookWithDeprecated("after:getManyRaw", {
1720
+ keys,
1721
+ values: failed
1722
+ });
1723
+ return failed;
1724
+ }
1725
+ let result;
1726
+ if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1727
+ else result = await Promise.all(rawData.map(async (row) => {
1728
+ if (row === void 0 || row === null) return;
1729
+ return typeof row === "string" ? this.decode(row) : row;
1730
+ }));
1731
+ for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1732
+ else this.emitTelemetry("stat:hit", keys[i]);
1576
1733
  await this.hookWithDeprecated("after:getManyRaw", {
1577
1734
  keys,
1578
1735
  values: result
1579
1736
  });
1580
1737
  return result;
1581
- }
1582
- const rawData = await this.storeGetMany(keys);
1583
- let result;
1584
- if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1585
- else result = await Promise.all(rawData.map(async (row) => {
1586
- if (row === void 0 || row === null) return;
1587
- return typeof row === "string" ? this.decode(row) : row;
1588
- }));
1589
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1590
- else this.emitTelemetry("stat:hit", keys[i]);
1591
- await this.hookWithDeprecated("after:getManyRaw", {
1592
- keys,
1593
- values: result
1594
1738
  });
1595
- return result;
1596
1739
  }
1597
1740
  /**
1598
1741
  * Set an item to the store
@@ -1649,51 +1792,54 @@ var Keyv = class Keyv extends Hookified {
1649
1792
  ...e,
1650
1793
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1651
1794
  }));
1652
- const data = { entries };
1653
- await this.hookWithDeprecated("before:setMany", data);
1654
- entries = data.entries;
1655
- let results = [];
1656
- try {
1657
- const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1658
- ttl = resolveTtl(ttl, this._ttl);
1795
+ return this.skipEmptyKeys(entries, false, async (entries) => {
1796
+ const data = { entries };
1797
+ await this.hookWithDeprecated("before:setMany", data);
1798
+ entries = data.entries;
1799
+ let results = [];
1800
+ try {
1801
+ const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1802
+ ttl = resolveTtl(ttl, this._ttl);
1803
+ /* v8 ignore next -- @preserve */
1804
+ const expires = calculateExpires(ttl);
1805
+ /* v8 ignore next -- @preserve */
1806
+ if (typeof value === "symbol") {
1807
+ this.emit("error", "symbol cannot be serialized");
1808
+ this.emitTelemetry("stat:error", key);
1809
+ throw new Error("symbol cannot be serialized");
1810
+ }
1811
+ const formattedValue = {
1812
+ value,
1813
+ expires
1814
+ };
1815
+ return {
1816
+ key,
1817
+ value: await this.encode(formattedValue),
1818
+ expires
1819
+ };
1820
+ }));
1821
+ const storeResult = await this._store.setMany(serializedEntries);
1659
1822
  /* v8 ignore next -- @preserve */
1660
- const expires = calculateExpires(ttl);
1661
- /* v8 ignore next -- @preserve */
1662
- if (typeof value === "symbol") {
1663
- this.emit("error", "symbol cannot be serialized");
1664
- this.emitTelemetry("stat:error", key);
1665
- throw new Error("symbol cannot be serialized");
1666
- }
1667
- const formattedValue = {
1668
- value,
1669
- expires
1670
- };
1671
- return {
1672
- key,
1673
- value: await this.encode(formattedValue),
1674
- expires
1675
- };
1676
- }));
1677
- const storeResult = await this._store.setMany(serializedEntries);
1678
- /* v8 ignore next -- @preserve */
1679
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1680
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1681
- } catch (error) {
1682
- this.emit("error", error);
1683
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1684
- results = entries.map(() => false);
1685
- }
1686
- await this.hookWithDeprecated("after:setMany", {
1687
- entries,
1688
- values: results
1823
+ results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1824
+ this.emitTelemetry("stat:set", entries.map((e) => e.key));
1825
+ } catch (error) {
1826
+ this.emit("error", error);
1827
+ this.emitTelemetry("stat:error", entries.map((e) => e.key));
1828
+ results = entries.map(() => false);
1829
+ }
1830
+ await this.hookWithDeprecated("after:setMany", {
1831
+ entries,
1832
+ values: results
1833
+ });
1834
+ return results;
1689
1835
  });
1690
- return results;
1691
1836
  }
1692
1837
  /**
1693
1838
  * Set a raw value to the store without wrapping or serialization. This is the write-side counterpart to getRaw().
1694
1839
  * The value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1695
1840
  * set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`).
1696
- * The store-level TTL is derived automatically from `value.expires`.
1841
+ * The store-level expiry is derived automatically from `value.expires`, rounded up to a whole millisecond
1842
+ * (a non-finite `expires` means no store-level expiry).
1697
1843
  * @param {string} key the key to set
1698
1844
  * @param {KeyvValue<Value>} value the raw value envelope to store
1699
1845
  * @returns {Promise<boolean>} `true` if it was set successfully, `false` on failure.
@@ -1706,7 +1852,7 @@ var Keyv = class Keyv extends Hookified {
1706
1852
  value
1707
1853
  };
1708
1854
  await this.hookWithDeprecated("before:setRaw", data);
1709
- const expires = data.value.expires;
1855
+ const expires = toStoreExpires(data.value.expires);
1710
1856
  const ttl = ttlFromExpires(expires);
1711
1857
  let result = true;
1712
1858
  try {
@@ -1729,7 +1875,8 @@ var Keyv = class Keyv extends Hookified {
1729
1875
  /**
1730
1876
  * Set many raw values to the store without wrapping or serialization. This is the write-side counterpart to getManyRaw().
1731
1877
  * Each entry's value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1732
- * set `expires` on each value directly. The store-level TTL is derived automatically from `value.expires`.
1878
+ * set `expires` on each value directly. The store-level expiry is derived automatically from `value.expires`,
1879
+ * rounded up to a whole millisecond (a non-finite `expires` means no store-level expiry).
1733
1880
  * @param {KeyvEntry<KeyvValue<Value>>[]} entries the raw entries to set
1734
1881
  * @returns {Promise<boolean[]>} an array of booleans, one per entry: `true` if set successfully, `false` on failure.
1735
1882
  */
@@ -1739,29 +1886,31 @@ var Keyv = class Keyv extends Hookified {
1739
1886
  /* v8 ignore next -- @preserve */
1740
1887
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1741
1888
  }));
1742
- let results = [];
1743
- await this.hookWithDeprecated("before:setManyRaw", { entries });
1744
- try {
1745
- const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1746
- return {
1747
- key,
1748
- value: await this.encode(value),
1749
- expires: value.expires
1750
- };
1751
- }));
1752
- const storeResult = await this._store.setMany(rawEntries);
1753
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1754
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1755
- } catch (error) {
1756
- this.emit("error", error);
1757
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1758
- results = entries.map(() => false);
1759
- }
1760
- await this.hookWithDeprecated("after:setManyRaw", {
1761
- entries,
1762
- results
1889
+ return this.skipEmptyKeys(entries, false, async (entries) => {
1890
+ let results = [];
1891
+ await this.hookWithDeprecated("before:setManyRaw", { entries });
1892
+ try {
1893
+ const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1894
+ return {
1895
+ key,
1896
+ value: await this.encode(value),
1897
+ expires: toStoreExpires(value.expires)
1898
+ };
1899
+ }));
1900
+ const storeResult = await this._store.setMany(rawEntries);
1901
+ results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1902
+ this.emitTelemetry("stat:set", entries.map((e) => e.key));
1903
+ } catch (error) {
1904
+ this.emit("error", error);
1905
+ this.emitTelemetry("stat:error", entries.map((e) => e.key));
1906
+ results = entries.map(() => false);
1907
+ }
1908
+ await this.hookWithDeprecated("after:setManyRaw", {
1909
+ entries,
1910
+ results
1911
+ });
1912
+ return results;
1763
1913
  });
1764
- return results;
1765
1914
  }
1766
1915
  async delete(key) {
1767
1916
  if (Array.isArray(key)) return this.deleteMany(key);
@@ -1791,26 +1940,28 @@ var Keyv = class Keyv extends Hookified {
1791
1940
  async deleteMany(keys) {
1792
1941
  /* v8 ignore next -- @preserve */
1793
1942
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1794
- await this.hookWithDeprecated("before:deleteMany", { keys });
1795
- await this.hookWithDeprecated("before:delete", { key: keys });
1796
- let results;
1797
- try {
1798
- results = await this._store.deleteMany(keys);
1799
- this.emitTelemetry("stat:delete", keys);
1800
- } catch (error) {
1801
- this.emit("error", error);
1802
- this.emitTelemetry("stat:error", keys);
1803
- results = keys.map(() => false);
1804
- }
1805
- await this.hookWithDeprecated("after:deleteMany", {
1806
- keys,
1807
- values: results
1808
- });
1809
- await this.hookWithDeprecated("after:delete", {
1810
- key: keys,
1811
- value: results
1943
+ return this.skipEmptyKeys(keys, false, async (keys) => {
1944
+ await this.hookWithDeprecated("before:deleteMany", { keys });
1945
+ await this.hookWithDeprecated("before:delete", { key: keys });
1946
+ let results;
1947
+ try {
1948
+ results = await this._store.deleteMany(keys);
1949
+ this.emitTelemetry("stat:delete", keys);
1950
+ } catch (error) {
1951
+ this.emit("error", error);
1952
+ this.emitTelemetry("stat:error", keys);
1953
+ results = keys.map(() => false);
1954
+ }
1955
+ await this.hookWithDeprecated("after:deleteMany", {
1956
+ keys,
1957
+ values: results
1958
+ });
1959
+ await this.hookWithDeprecated("after:delete", {
1960
+ key: keys,
1961
+ value: results
1962
+ });
1963
+ return results;
1812
1964
  });
1813
- return results;
1814
1965
  }
1815
1966
  async has(key) {
1816
1967
  if (Array.isArray(key)) return this.hasMany(key);
@@ -1843,39 +1994,42 @@ var Keyv = class Keyv extends Hookified {
1843
1994
  */
1844
1995
  async hasMany(keys) {
1845
1996
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1846
- await this.hookWithDeprecated("before:hasMany", { keys });
1847
- let results = [];
1848
- try {
1849
- if (this._checkExpired) {
1850
- const rawData = await this._store.getMany(keys);
1851
- results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
1852
- } else results = await this._store.hasMany(keys);
1853
- } catch (error) {
1854
- this.emit("error", error);
1855
- this.emitTelemetry("stat:error", keys);
1856
- results = keys.map(() => false);
1857
- }
1858
- await this.hookWithDeprecated("after:hasMany", {
1859
- keys,
1860
- values: results
1997
+ return this.skipEmptyKeys(keys, false, async (keys) => {
1998
+ await this.hookWithDeprecated("before:hasMany", { keys });
1999
+ let results = [];
2000
+ try {
2001
+ if (this._checkExpired) {
2002
+ const rawData = await this.storeGetMany(keys);
2003
+ results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
2004
+ } else results = await this._store.hasMany(keys);
2005
+ } catch (error) {
2006
+ this.emit("error", error);
2007
+ this.emitTelemetry("stat:error", keys);
2008
+ results = keys.map(() => false);
2009
+ }
2010
+ await this.hookWithDeprecated("after:hasMany", {
2011
+ keys,
2012
+ values: results
2013
+ });
2014
+ return results;
1861
2015
  });
1862
- return results;
1863
2016
  }
1864
2017
  /**
1865
- * Clear the store. If a namespace is set only entries in that namespace are removed.
2018
+ * Clear the store. If a namespace is set only entries in that namespace are removed. When the
2019
+ * store can't limit the removal to the namespace, nothing is removed and `error` is emitted.
1866
2020
  * Emits a `clear` event.
1867
2021
  * @returns {Promise<void>} resolves once the entries have been cleared.
1868
2022
  */
1869
2023
  async clear() {
1870
2024
  this.emit("clear");
1871
- await this.hook("before:clear", { namespace: this._namespace });
2025
+ await this.hook("before:clear", { namespace: this.namespace });
1872
2026
  try {
1873
2027
  await this._store.clear();
1874
2028
  } catch (error) {
1875
2029
  this.emit("error", error);
1876
2030
  this.emitTelemetry("stat:error");
1877
2031
  }
1878
- await this.hook("after:clear", { namespace: this._namespace });
2032
+ await this.hook("after:clear", { namespace: this.namespace });
1879
2033
  }
1880
2034
  /**
1881
2035
  * Will disconnect the store. This is only available if the store has a disconnect method
@@ -1883,13 +2037,13 @@ var Keyv = class Keyv extends Hookified {
1883
2037
  */
1884
2038
  async disconnect() {
1885
2039
  this.emit("disconnect");
1886
- await this.hook("before:disconnect", { namespace: this._namespace });
2040
+ await this.hook("before:disconnect", { namespace: this.namespace });
1887
2041
  try {
1888
2042
  if (this._store.disconnect) await this._store.disconnect();
1889
2043
  } catch (error) {
1890
2044
  this.emit("error", error);
1891
2045
  }
1892
- await this.hook("after:disconnect", { namespace: this._namespace });
2046
+ await this.hook("after:disconnect", { namespace: this.namespace });
1893
2047
  }
1894
2048
  /**
1895
2049
  * Iterate over all key-value pairs in the store. Automatically deserializes values,
@@ -1899,23 +2053,34 @@ var Keyv = class Keyv extends Hookified {
1899
2053
  async *iterator() {
1900
2054
  /* v8 ignore next 3 -- @preserve */
1901
2055
  if (this._store.iterator === void 0) return;
1902
- for await (const [key, raw] of this._store.iterator()) {
1903
- const data = await this.decode(raw);
1904
- if (this._checkExpired && data && isDataExpired(data)) {
1905
- await this.delete(key);
1906
- continue;
2056
+ try {
2057
+ for await (const [key, raw] of this._store.iterator()) {
2058
+ const data = await this.decode(raw);
2059
+ if (this._checkExpired && data && isDataExpired(data)) {
2060
+ await this.delete(key);
2061
+ continue;
2062
+ }
2063
+ yield [key, data?.value];
1907
2064
  }
1908
- yield [key, data?.value];
2065
+ } catch (error) {
2066
+ this.emit("error", error);
2067
+ this.emitTelemetry("stat:error");
1909
2068
  }
1910
2069
  }
1911
2070
  /**
1912
2071
  * Encodes a value for storage. Pipeline: serialize → compress → encrypt.
1913
- * If serialization is not configured, returns the data as-is.
2072
+ * If serialization is not configured, returns the data as-is, skipping compression. With an
2073
+ * encryption adapter set, it throws instead, since the value can't be encrypted and storing it
2074
+ * unencrypted would defeat the adapter.
1914
2075
  * @param {KeyvValue<T>} data The value envelope to encode.
1915
- * @returns {Promise<unknown>} The encoded value, or the original data on failure.
2076
+ * @returns {Promise<unknown>} The encoded value.
2077
+ * @throws {Error} If an encryption adapter is set while serialization is disabled.
1916
2078
  */
1917
2079
  async encode(data) {
1918
- if (!this._serialization) return data;
2080
+ if (!this._serialization) {
2081
+ if (this._encryption?.encrypt) throw new Error("Encryption needs serialization, which is disabled, so Keyv won't store the value unencrypted. Remove `serialization: false` or the encryption adapter.");
2082
+ return data;
2083
+ }
1919
2084
  let result = await this._serialization.stringify(data);
1920
2085
  if (this._compression?.compress) result = await this._compression.compress(result);
1921
2086
  if (this._encryption?.encrypt) result = await this._encryption.encrypt(result);
@@ -1986,7 +2151,7 @@ var Keyv = class Keyv extends Hookified {
1986
2151
  if (key === void 0) {
1987
2152
  this.emit(event, {
1988
2153
  event: event.replace("stat:", ""),
1989
- namespace: this._namespace,
2154
+ namespace: this.namespace,
1990
2155
  timestamp: Date.now()
1991
2156
  });
1992
2157
  return;
@@ -1995,7 +2160,7 @@ var Keyv = class Keyv extends Hookified {
1995
2160
  for (const k of keys) this.emit(event, {
1996
2161
  event: event.replace("stat:", ""),
1997
2162
  key: k,
1998
- namespace: this._namespace,
2163
+ namespace: this.namespace,
1999
2164
  timestamp: Date.now()
2000
2165
  });
2001
2166
  }
@@ -2039,7 +2204,20 @@ var Keyv = class Keyv extends Hookified {
2039
2204
  */
2040
2205
  initNamespace(namespace) {
2041
2206
  this._namespace = namespace;
2042
- if (this._namespace && this._sanitize.enabled) this._namespace = this._sanitize.cleanNamespace(this._namespace);
2207
+ if (this._namespace && this._sanitize.enabled) this._namespace = this.cleanNamespace(this._namespace);
2208
+ }
2209
+ /**
2210
+ * Sanitizes a namespace. When sanitizing leaves nothing, it returns {@link emptiedNamespace} so
2211
+ * the instance keeps a namespace of its own.
2212
+ */
2213
+ cleanNamespace(namespace) {
2214
+ return this._sanitize.cleanNamespace(namespace) || emptiedNamespace;
2215
+ }
2216
+ /**
2217
+ * Sanitizes the namespace kept from the storage adapter when Keyv has none of its own.
2218
+ */
2219
+ sanitizeStoreNamespace() {
2220
+ if (this._namespace === void 0 && this._store.namespace && this._sanitize.enabled) this._store.namespace = this.cleanNamespace(this._store.namespace);
2043
2221
  }
2044
2222
  };
2045
2223
  //#endregion
@@ -2058,14 +2236,14 @@ var Keyv = class Keyv extends Hookified {
2058
2236
  * // Using with a custom store
2059
2237
  * const customStore = new KeyvMemoryAdapter(myCustomMapLikeStore, {
2060
2238
  * namespace: 'tenant-123',
2061
- * keySeparator: ':'
2239
+ * namespaceSeparator: '::'
2062
2240
  * });
2063
2241
  * ```
2064
2242
  */
2065
2243
  var KeyvMemoryAdapter = class extends Hookified {
2066
2244
  _store;
2067
2245
  _namespace;
2068
- _keySeparator = ":";
2246
+ _namespaceSeparator = "::";
2069
2247
  _capabilities;
2070
2248
  /**
2071
2249
  * Creates a new KeyvMemoryAdapter instance.
@@ -2076,7 +2254,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2076
2254
  super({ throwOnHookError: false });
2077
2255
  this._store = store;
2078
2256
  this._capabilities = detectKeyvStorage(store);
2079
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
2257
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
2080
2258
  if (options?.namespace) this._namespace = options?.namespace;
2081
2259
  }
2082
2260
  /**
@@ -2102,16 +2280,16 @@ var KeyvMemoryAdapter = class extends Hookified {
2102
2280
  this._store = store;
2103
2281
  }
2104
2282
  /**
2105
- * Gets the current key separator used between namespace and key.
2283
+ * Gets the separator between the namespace and the key. Defaults to `::`.
2106
2284
  */
2107
- get keySeparator() {
2108
- return this._keySeparator;
2285
+ get namespaceSeparator() {
2286
+ return this._namespaceSeparator;
2109
2287
  }
2110
2288
  /**
2111
- * Sets the key separator used between namespace and key.
2289
+ * Sets the separator between the namespace and the key.
2112
2290
  */
2113
- set keySeparator(separator) {
2114
- this._keySeparator = separator;
2291
+ set namespaceSeparator(separator) {
2292
+ this._namespaceSeparator = separator;
2115
2293
  }
2116
2294
  /**
2117
2295
  * Gets the current namespace.
@@ -2132,7 +2310,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2132
2310
  * @returns The prefixed key if namespace is provided, otherwise the original key
2133
2311
  */
2134
2312
  getKeyPrefix(key, namespace) {
2135
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
2313
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
2136
2314
  return key;
2137
2315
  }
2138
2316
  /**
@@ -2141,9 +2319,9 @@ var KeyvMemoryAdapter = class extends Hookified {
2141
2319
  * @returns An object containing the namespace (if present) and the original key
2142
2320
  */
2143
2321
  getKeyPrefixData(key) {
2144
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
2322
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
2145
2323
  namespace: this._namespace,
2146
- key: key.slice(this._namespace.length + this._keySeparator.length)
2324
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
2147
2325
  };
2148
2326
  return { key };
2149
2327
  }
@@ -2206,16 +2384,19 @@ var KeyvMemoryAdapter = class extends Hookified {
2206
2384
  return this._store.delete(keyPrefix);
2207
2385
  }
2208
2386
  /**
2209
- * Clears entries from the store. If a namespace is set, only entries
2210
- * within that namespace are removed. Otherwise, the entire store is cleared.
2211
- * NOTE: if there is no `keys()` then we just do a full clear.
2387
+ * Clears entries from the store. With no namespace, the whole store is cleared. With a
2388
+ * namespace, only that namespace's entries are removed, found through the store's `keys()`.
2389
+ * A store without `keys()` can't tell namespaces apart, so this throws rather than call the
2390
+ * store's `clear()` and delete every namespace's entries.
2391
+ * @throws {Error} If a namespace is set and the store has no `keys()`.
2212
2392
  */
2213
2393
  async clear() {
2214
- if (!this._namespace || typeof this._store.keys !== "function") {
2394
+ if (!this._namespace) {
2215
2395
  this._store.clear();
2216
2396
  return;
2217
2397
  }
2218
- const prefix = `${this._namespace}${this._keySeparator}`;
2398
+ if (typeof this._store.keys !== "function") throw new Error(`Can't clear namespace "${this._namespace}": the store has no keys() to find that namespace's keys, and its clear() would delete every namespace. Use a store with keys(), such as a Map, or clear it without a namespace.`);
2399
+ const prefix = `${this._namespace}${this._namespaceSeparator}`;
2219
2400
  const keysToDelete = [];
2220
2401
  for (const key of this._store.keys()) if (key.startsWith(prefix)) keysToDelete.push(key);
2221
2402
  for (const key of keysToDelete) this._store.delete(key);
@@ -2296,14 +2477,14 @@ var KeyvMemoryAdapter = class extends Hookified {
2296
2477
  const namespace = this._namespace;
2297
2478
  for (const [key, raw] of this._store.entries()) {
2298
2479
  if (namespace) {
2299
- if (!key.startsWith(`${namespace}${this._keySeparator}`)) continue;
2480
+ if (!key.startsWith(`${namespace}${this._namespaceSeparator}`)) continue;
2300
2481
  }
2301
2482
  const entry = raw;
2302
2483
  if (entry?.expires !== void 0 && Date.now() > entry.expires) {
2303
2484
  this._store.delete(key);
2304
2485
  continue;
2305
2486
  }
2306
- yield [namespace ? key.slice(namespace.length + this._keySeparator.length) : key, entry?.value];
2487
+ yield [namespace ? key.slice(namespace.length + this._namespaceSeparator.length) : key, entry?.value];
2307
2488
  }
2308
2489
  }
2309
2490
  /**
@@ -2331,7 +2512,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2331
2512
  * // Create with namespace for multi-tenant scenarios
2332
2513
  * const tenantCache = createKeyv(new Map(), {
2333
2514
  * namespace: 'tenant-123',
2334
- * keySeparator: ':'
2515
+ * namespaceSeparator: '::'
2335
2516
  * });
2336
2517
  * ```
2337
2518
  */