keyv 6.0.0-rc.1 → 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
  */
@@ -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;
@@ -1324,18 +1410,19 @@ var Keyv = class Keyv extends Hookified {
1324
1410
  this._encryption = encryption;
1325
1411
  }
1326
1412
  /**
1327
- * 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.
1328
1415
  * @returns {string | undefined} The current namespace.
1329
1416
  */
1330
1417
  get namespace() {
1331
- return this._namespace;
1418
+ return this._namespace ?? this._store.namespace;
1332
1419
  }
1333
1420
  /**
1334
1421
  * Set the current namespace.
1335
1422
  * @param {string | undefined} namespace The namespace to set.
1336
1423
  */
1337
1424
  set namespace(namespace) {
1338
- this._namespace = namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(namespace) : namespace;
1425
+ this._namespace = namespace && this._sanitize.enabled ? this.cleanNamespace(namespace) : namespace;
1339
1426
  this._store.namespace = this._namespace;
1340
1427
  }
1341
1428
  /**
@@ -1368,22 +1455,6 @@ var Keyv = class Keyv extends Hookified {
1368
1455
  this._serialization = serialization === false ? void 0 : serialization;
1369
1456
  }
1370
1457
  /**
1371
- * Get the current throwOnErrors value. When enabled, all errors with throw. By default, errors
1372
- * will only throw if there are no listeners to the error event.
1373
- * @return {boolean} The current throwOnErrors value.
1374
- */
1375
- get throwOnErrors() {
1376
- return this.throwOnEmitError;
1377
- }
1378
- /**
1379
- * Set the current throwOnErrors value. When enabled, all errors will throw. By default, errors
1380
- * will only throw if there are no listeners to the error event.
1381
- * @param {boolean} value The throwOnErrors value to set.
1382
- */
1383
- set throwOnErrors(value) {
1384
- this.throwOnEmitError = value;
1385
- }
1386
- /**
1387
1458
  * Get the current sanitize adapter. Sanitization is disabled by default. To
1388
1459
  * enable it `sanitize.keys` or `sanitize.namespace` to true or set KeyvSanitizePatterns
1389
1460
  * to each.
@@ -1393,13 +1464,17 @@ var Keyv = class Keyv extends Hookified {
1393
1464
  return this._sanitize;
1394
1465
  }
1395
1466
  /**
1396
- * 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.
1397
1469
  * @param {KeyvSanitizeAdapter} value The sanitize adapter to use.
1398
1470
  */
1399
1471
  set sanitize(value) {
1400
1472
  this._sanitize = value;
1401
- /* v8 ignore next -- @preserve */
1402
- 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();
1403
1478
  }
1404
1479
  /**
1405
1480
  * Get the stats. This is just for this instance
@@ -1434,7 +1509,9 @@ var Keyv = class Keyv extends Hookified {
1434
1509
  * with the `async` keyword is not mis-bridged).
1435
1510
  * 2. If the store implements the full async storage interface (but doesn't declare `expires`),
1436
1511
  * treat it as a legacy relative-`ttl` adapter and wrap it in KeyvBridgeAdapter.
1437
- * 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.
1438
1515
  * 4. If the store has async get/set/delete/clear, wrap it in KeyvBridgeAdapter.
1439
1516
  * 5. Otherwise, emit an error and fall back to a default in-memory KeyvMemoryAdapter.
1440
1517
  *
@@ -1446,20 +1523,25 @@ var Keyv = class Keyv extends Hookified {
1446
1523
  if (store?.capabilities?.expires === true) return store;
1447
1524
  const cap = detectKeyvStorage(store);
1448
1525
  if (cap.store === "keyvStorage") return new KeyvBridgeAdapter(store);
1449
- 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
+ }
1450
1530
  if (cap.store === "asyncMap") return new KeyvBridgeAdapter(store);
1451
1531
  this.emit("error", /* @__PURE__ */ new Error("Could not use the provided storage adapter, falling back to KeyvMemoryAdapter with Map"));
1452
1532
  return new KeyvMemoryAdapter(/* @__PURE__ */ new Map());
1453
1533
  }
1454
1534
  /**
1455
1535
  * Sets the storage adapter by resolving it via {@link resolveStore}, then wires up
1456
- * 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.
1457
1538
  * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
1458
1539
  */
1459
1540
  setStore(store) {
1460
1541
  this._store = this.resolveStore(store);
1461
1542
  if (typeof this._store.on === "function") this._store.on("error", (error) => this.emit("error", error));
1462
- this._store.namespace = this._namespace;
1543
+ if (this._namespace !== void 0) this._store.namespace = this._namespace;
1544
+ else this.sanitizeStoreNamespace();
1463
1545
  }
1464
1546
  /**
1465
1547
  * Sets the TTL, treating zero and negative values as undefined (no TTL).
@@ -1483,6 +1565,11 @@ var Keyv = class Keyv extends Hookified {
1483
1565
  } catch (error) {
1484
1566
  this.emit("error", error);
1485
1567
  this.emitTelemetry("stat:error", key);
1568
+ await this.hookWithDeprecated("after:get", {
1569
+ key,
1570
+ value: void 0
1571
+ });
1572
+ return;
1486
1573
  }
1487
1574
  let data;
1488
1575
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
@@ -1515,6 +1602,23 @@ var Keyv = class Keyv extends Hookified {
1515
1602
  return Promise.all(keys.map(async (key) => this._store.get(key)));
1516
1603
  }
1517
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
+ /**
1518
1622
  * Get many values for an array of keys.
1519
1623
  * @param {string[]} keys the keys to get
1520
1624
  * @returns {Promise<Array<Value | undefined>>} an array of values in the same order as the
@@ -1522,19 +1626,30 @@ var Keyv = class Keyv extends Hookified {
1522
1626
  */
1523
1627
  async getMany(keys) {
1524
1628
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1525
- await this.hookWithDeprecated("before:getMany", { keys });
1526
- const rawData = await this.storeGetMany(keys);
1527
- let deserialized;
1528
- if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1529
- else deserialized = await Promise.all(rawData.map(async (row) => {
1530
- if (row === void 0 || row === null) return;
1531
- return typeof row === "string" ? this.decode(row) : row;
1532
- }));
1533
- const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1534
- await this.hookWithDeprecated("after:getMany", result);
1535
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1536
- else this.emitTelemetry("stat:hit", keys[i]);
1537
- 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
+ });
1538
1653
  }
1539
1654
  /**
1540
1655
  * Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
@@ -1546,7 +1661,18 @@ var Keyv = class Keyv extends Hookified {
1546
1661
  key = this._sanitize.enabled ? this._sanitize.cleanKey(key) : key;
1547
1662
  if (key === "") return;
1548
1663
  await this.hookWithDeprecated("before:getRaw", { key });
1549
- 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
+ }
1550
1676
  let data;
1551
1677
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
1552
1678
  else data = rawData === void 0 || rawData === null ? void 0 : typeof rawData === "string" ? await this.decode(rawData) : rawData;
@@ -1573,29 +1699,43 @@ var Keyv = class Keyv extends Hookified {
1573
1699
  async getManyRaw(keys) {
1574
1700
  /* v8 ignore next -- @preserve */
1575
1701
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1576
- await this.hookWithDeprecated("before:getManyRaw", { keys });
1577
- if (keys.length === 0) {
1578
- 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]);
1579
1733
  await this.hookWithDeprecated("after:getManyRaw", {
1580
1734
  keys,
1581
1735
  values: result
1582
1736
  });
1583
1737
  return result;
1584
- }
1585
- const rawData = await this.storeGetMany(keys);
1586
- let result;
1587
- if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1588
- else result = await Promise.all(rawData.map(async (row) => {
1589
- if (row === void 0 || row === null) return;
1590
- return typeof row === "string" ? this.decode(row) : row;
1591
- }));
1592
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1593
- else this.emitTelemetry("stat:hit", keys[i]);
1594
- await this.hookWithDeprecated("after:getManyRaw", {
1595
- keys,
1596
- values: result
1597
1738
  });
1598
- return result;
1599
1739
  }
1600
1740
  /**
1601
1741
  * Set an item to the store
@@ -1652,51 +1792,54 @@ var Keyv = class Keyv extends Hookified {
1652
1792
  ...e,
1653
1793
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1654
1794
  }));
1655
- const data = { entries };
1656
- await this.hookWithDeprecated("before:setMany", data);
1657
- entries = data.entries;
1658
- let results = [];
1659
- try {
1660
- const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1661
- 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);
1662
1822
  /* v8 ignore next -- @preserve */
1663
- const expires = calculateExpires(ttl);
1664
- /* v8 ignore next -- @preserve */
1665
- if (typeof value === "symbol") {
1666
- this.emit("error", "symbol cannot be serialized");
1667
- this.emitTelemetry("stat:error", key);
1668
- throw new Error("symbol cannot be serialized");
1669
- }
1670
- const formattedValue = {
1671
- value,
1672
- expires
1673
- };
1674
- return {
1675
- key,
1676
- value: await this.encode(formattedValue),
1677
- expires
1678
- };
1679
- }));
1680
- const storeResult = await this._store.setMany(serializedEntries);
1681
- /* v8 ignore next -- @preserve */
1682
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1683
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1684
- } catch (error) {
1685
- this.emit("error", error);
1686
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1687
- results = entries.map(() => false);
1688
- }
1689
- await this.hookWithDeprecated("after:setMany", {
1690
- entries,
1691
- 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;
1692
1835
  });
1693
- return results;
1694
1836
  }
1695
1837
  /**
1696
1838
  * Set a raw value to the store without wrapping or serialization. This is the write-side counterpart to getRaw().
1697
1839
  * The value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1698
1840
  * set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`).
1699
- * 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).
1700
1843
  * @param {string} key the key to set
1701
1844
  * @param {KeyvValue<Value>} value the raw value envelope to store
1702
1845
  * @returns {Promise<boolean>} `true` if it was set successfully, `false` on failure.
@@ -1709,7 +1852,7 @@ var Keyv = class Keyv extends Hookified {
1709
1852
  value
1710
1853
  };
1711
1854
  await this.hookWithDeprecated("before:setRaw", data);
1712
- const expires = data.value.expires;
1855
+ const expires = toStoreExpires(data.value.expires);
1713
1856
  const ttl = ttlFromExpires(expires);
1714
1857
  let result = true;
1715
1858
  try {
@@ -1732,7 +1875,8 @@ var Keyv = class Keyv extends Hookified {
1732
1875
  /**
1733
1876
  * Set many raw values to the store without wrapping or serialization. This is the write-side counterpart to getManyRaw().
1734
1877
  * Each entry's value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1735
- * 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).
1736
1880
  * @param {KeyvEntry<KeyvValue<Value>>[]} entries the raw entries to set
1737
1881
  * @returns {Promise<boolean[]>} an array of booleans, one per entry: `true` if set successfully, `false` on failure.
1738
1882
  */
@@ -1742,29 +1886,31 @@ var Keyv = class Keyv extends Hookified {
1742
1886
  /* v8 ignore next -- @preserve */
1743
1887
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1744
1888
  }));
1745
- let results = [];
1746
- await this.hookWithDeprecated("before:setManyRaw", { entries });
1747
- try {
1748
- const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1749
- return {
1750
- key,
1751
- value: await this.encode(value),
1752
- expires: value.expires
1753
- };
1754
- }));
1755
- const storeResult = await this._store.setMany(rawEntries);
1756
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1757
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1758
- } catch (error) {
1759
- this.emit("error", error);
1760
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1761
- results = entries.map(() => false);
1762
- }
1763
- await this.hookWithDeprecated("after:setManyRaw", {
1764
- entries,
1765
- 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;
1766
1913
  });
1767
- return results;
1768
1914
  }
1769
1915
  async delete(key) {
1770
1916
  if (Array.isArray(key)) return this.deleteMany(key);
@@ -1794,26 +1940,28 @@ var Keyv = class Keyv extends Hookified {
1794
1940
  async deleteMany(keys) {
1795
1941
  /* v8 ignore next -- @preserve */
1796
1942
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1797
- await this.hookWithDeprecated("before:deleteMany", { keys });
1798
- await this.hookWithDeprecated("before:delete", { key: keys });
1799
- let results;
1800
- try {
1801
- results = await this._store.deleteMany(keys);
1802
- this.emitTelemetry("stat:delete", keys);
1803
- } catch (error) {
1804
- this.emit("error", error);
1805
- this.emitTelemetry("stat:error", keys);
1806
- results = keys.map(() => false);
1807
- }
1808
- await this.hookWithDeprecated("after:deleteMany", {
1809
- keys,
1810
- values: results
1811
- });
1812
- await this.hookWithDeprecated("after:delete", {
1813
- key: keys,
1814
- 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;
1815
1964
  });
1816
- return results;
1817
1965
  }
1818
1966
  async has(key) {
1819
1967
  if (Array.isArray(key)) return this.hasMany(key);
@@ -1846,39 +1994,42 @@ var Keyv = class Keyv extends Hookified {
1846
1994
  */
1847
1995
  async hasMany(keys) {
1848
1996
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1849
- await this.hookWithDeprecated("before:hasMany", { keys });
1850
- let results = [];
1851
- try {
1852
- if (this._checkExpired) {
1853
- const rawData = await this.storeGetMany(keys);
1854
- results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
1855
- } else results = await this._store.hasMany(keys);
1856
- } catch (error) {
1857
- this.emit("error", error);
1858
- this.emitTelemetry("stat:error", keys);
1859
- results = keys.map(() => false);
1860
- }
1861
- await this.hookWithDeprecated("after:hasMany", {
1862
- keys,
1863
- 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;
1864
2015
  });
1865
- return results;
1866
2016
  }
1867
2017
  /**
1868
- * 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.
1869
2020
  * Emits a `clear` event.
1870
2021
  * @returns {Promise<void>} resolves once the entries have been cleared.
1871
2022
  */
1872
2023
  async clear() {
1873
2024
  this.emit("clear");
1874
- await this.hook("before:clear", { namespace: this._namespace });
2025
+ await this.hook("before:clear", { namespace: this.namespace });
1875
2026
  try {
1876
2027
  await this._store.clear();
1877
2028
  } catch (error) {
1878
2029
  this.emit("error", error);
1879
2030
  this.emitTelemetry("stat:error");
1880
2031
  }
1881
- await this.hook("after:clear", { namespace: this._namespace });
2032
+ await this.hook("after:clear", { namespace: this.namespace });
1882
2033
  }
1883
2034
  /**
1884
2035
  * Will disconnect the store. This is only available if the store has a disconnect method
@@ -1886,13 +2037,13 @@ var Keyv = class Keyv extends Hookified {
1886
2037
  */
1887
2038
  async disconnect() {
1888
2039
  this.emit("disconnect");
1889
- await this.hook("before:disconnect", { namespace: this._namespace });
2040
+ await this.hook("before:disconnect", { namespace: this.namespace });
1890
2041
  try {
1891
2042
  if (this._store.disconnect) await this._store.disconnect();
1892
2043
  } catch (error) {
1893
2044
  this.emit("error", error);
1894
2045
  }
1895
- await this.hook("after:disconnect", { namespace: this._namespace });
2046
+ await this.hook("after:disconnect", { namespace: this.namespace });
1896
2047
  }
1897
2048
  /**
1898
2049
  * Iterate over all key-value pairs in the store. Automatically deserializes values,
@@ -1902,23 +2053,34 @@ var Keyv = class Keyv extends Hookified {
1902
2053
  async *iterator() {
1903
2054
  /* v8 ignore next 3 -- @preserve */
1904
2055
  if (this._store.iterator === void 0) return;
1905
- for await (const [key, raw] of this._store.iterator()) {
1906
- const data = await this.decode(raw);
1907
- if (this._checkExpired && data && isDataExpired(data)) {
1908
- await this.delete(key);
1909
- 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];
1910
2064
  }
1911
- yield [key, data?.value];
2065
+ } catch (error) {
2066
+ this.emit("error", error);
2067
+ this.emitTelemetry("stat:error");
1912
2068
  }
1913
2069
  }
1914
2070
  /**
1915
2071
  * Encodes a value for storage. Pipeline: serialize → compress → encrypt.
1916
- * 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.
1917
2075
  * @param {KeyvValue<T>} data The value envelope to encode.
1918
- * @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.
1919
2078
  */
1920
2079
  async encode(data) {
1921
- 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
+ }
1922
2084
  let result = await this._serialization.stringify(data);
1923
2085
  if (this._compression?.compress) result = await this._compression.compress(result);
1924
2086
  if (this._encryption?.encrypt) result = await this._encryption.encrypt(result);
@@ -1989,7 +2151,7 @@ var Keyv = class Keyv extends Hookified {
1989
2151
  if (key === void 0) {
1990
2152
  this.emit(event, {
1991
2153
  event: event.replace("stat:", ""),
1992
- namespace: this._namespace,
2154
+ namespace: this.namespace,
1993
2155
  timestamp: Date.now()
1994
2156
  });
1995
2157
  return;
@@ -1998,7 +2160,7 @@ var Keyv = class Keyv extends Hookified {
1998
2160
  for (const k of keys) this.emit(event, {
1999
2161
  event: event.replace("stat:", ""),
2000
2162
  key: k,
2001
- namespace: this._namespace,
2163
+ namespace: this.namespace,
2002
2164
  timestamp: Date.now()
2003
2165
  });
2004
2166
  }
@@ -2042,7 +2204,20 @@ var Keyv = class Keyv extends Hookified {
2042
2204
  */
2043
2205
  initNamespace(namespace) {
2044
2206
  this._namespace = namespace;
2045
- 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);
2046
2221
  }
2047
2222
  };
2048
2223
  //#endregion
@@ -2061,14 +2236,14 @@ var Keyv = class Keyv extends Hookified {
2061
2236
  * // Using with a custom store
2062
2237
  * const customStore = new KeyvMemoryAdapter(myCustomMapLikeStore, {
2063
2238
  * namespace: 'tenant-123',
2064
- * keySeparator: ':'
2239
+ * namespaceSeparator: '::'
2065
2240
  * });
2066
2241
  * ```
2067
2242
  */
2068
2243
  var KeyvMemoryAdapter = class extends Hookified {
2069
2244
  _store;
2070
2245
  _namespace;
2071
- _keySeparator = ":";
2246
+ _namespaceSeparator = "::";
2072
2247
  _capabilities;
2073
2248
  /**
2074
2249
  * Creates a new KeyvMemoryAdapter instance.
@@ -2079,7 +2254,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2079
2254
  super({ throwOnHookError: false });
2080
2255
  this._store = store;
2081
2256
  this._capabilities = detectKeyvStorage(store);
2082
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
2257
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
2083
2258
  if (options?.namespace) this._namespace = options?.namespace;
2084
2259
  }
2085
2260
  /**
@@ -2105,16 +2280,16 @@ var KeyvMemoryAdapter = class extends Hookified {
2105
2280
  this._store = store;
2106
2281
  }
2107
2282
  /**
2108
- * Gets the current key separator used between namespace and key.
2283
+ * Gets the separator between the namespace and the key. Defaults to `::`.
2109
2284
  */
2110
- get keySeparator() {
2111
- return this._keySeparator;
2285
+ get namespaceSeparator() {
2286
+ return this._namespaceSeparator;
2112
2287
  }
2113
2288
  /**
2114
- * Sets the key separator used between namespace and key.
2289
+ * Sets the separator between the namespace and the key.
2115
2290
  */
2116
- set keySeparator(separator) {
2117
- this._keySeparator = separator;
2291
+ set namespaceSeparator(separator) {
2292
+ this._namespaceSeparator = separator;
2118
2293
  }
2119
2294
  /**
2120
2295
  * Gets the current namespace.
@@ -2135,7 +2310,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2135
2310
  * @returns The prefixed key if namespace is provided, otherwise the original key
2136
2311
  */
2137
2312
  getKeyPrefix(key, namespace) {
2138
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
2313
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
2139
2314
  return key;
2140
2315
  }
2141
2316
  /**
@@ -2144,9 +2319,9 @@ var KeyvMemoryAdapter = class extends Hookified {
2144
2319
  * @returns An object containing the namespace (if present) and the original key
2145
2320
  */
2146
2321
  getKeyPrefixData(key) {
2147
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
2322
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
2148
2323
  namespace: this._namespace,
2149
- key: key.slice(this._namespace.length + this._keySeparator.length)
2324
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
2150
2325
  };
2151
2326
  return { key };
2152
2327
  }
@@ -2209,16 +2384,19 @@ var KeyvMemoryAdapter = class extends Hookified {
2209
2384
  return this._store.delete(keyPrefix);
2210
2385
  }
2211
2386
  /**
2212
- * Clears entries from the store. If a namespace is set, only entries
2213
- * within that namespace are removed. Otherwise, the entire store is cleared.
2214
- * 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()`.
2215
2392
  */
2216
2393
  async clear() {
2217
- if (!this._namespace || typeof this._store.keys !== "function") {
2394
+ if (!this._namespace) {
2218
2395
  this._store.clear();
2219
2396
  return;
2220
2397
  }
2221
- 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}`;
2222
2400
  const keysToDelete = [];
2223
2401
  for (const key of this._store.keys()) if (key.startsWith(prefix)) keysToDelete.push(key);
2224
2402
  for (const key of keysToDelete) this._store.delete(key);
@@ -2299,14 +2477,14 @@ var KeyvMemoryAdapter = class extends Hookified {
2299
2477
  const namespace = this._namespace;
2300
2478
  for (const [key, raw] of this._store.entries()) {
2301
2479
  if (namespace) {
2302
- if (!key.startsWith(`${namespace}${this._keySeparator}`)) continue;
2480
+ if (!key.startsWith(`${namespace}${this._namespaceSeparator}`)) continue;
2303
2481
  }
2304
2482
  const entry = raw;
2305
2483
  if (entry?.expires !== void 0 && Date.now() > entry.expires) {
2306
2484
  this._store.delete(key);
2307
2485
  continue;
2308
2486
  }
2309
- 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];
2310
2488
  }
2311
2489
  }
2312
2490
  /**
@@ -2334,7 +2512,7 @@ var KeyvMemoryAdapter = class extends Hookified {
2334
2512
  * // Create with namespace for multi-tenant scenarios
2335
2513
  * const tenantCache = createKeyv(new Map(), {
2336
2514
  * namespace: 'tenant-123',
2337
- * keySeparator: ':'
2515
+ * namespaceSeparator: '::'
2338
2516
  * });
2339
2517
  * ```
2340
2518
  */