intial
This commit is contained in:
22
node_modules/keyv/LICENSE
generated
vendored
Normal file
22
node_modules/keyv/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017-2021 Luke Childs
|
||||
Copyright (c) 2021-2022 Jared Wray
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
828
node_modules/keyv/README.md
generated
vendored
Normal file
828
node_modules/keyv/README.md
generated
vendored
Normal file
@@ -0,0 +1,828 @@
|
||||
<h1 align="center"><img width="250" src="https://jaredwray.com/images/keyv.svg" alt="keyv"></h1>
|
||||
|
||||
> Simple key-value storage with support for multiple backends
|
||||
|
||||
[](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml)
|
||||
[](https://github.com/jaredwray/keyv/actions/workflows/bun-test.yaml)
|
||||
[](https://codecov.io/gh/jaredwray/keyv)
|
||||
[](https://www.npmjs.com/package/keyv)
|
||||
[](https://www.npmjs.com/package/keyv)
|
||||
|
||||
Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store.
|
||||
|
||||
# Features
|
||||
|
||||
There are a few existing modules similar to Keyv, however Keyv is different because it:
|
||||
|
||||
- Isn't bloated
|
||||
- Has a simple Promise based API
|
||||
- Suitable as a TTL based cache or persistent key-value store
|
||||
- [Easily embeddable](#add-cache-support-to-your-module) inside another module
|
||||
- Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API
|
||||
- Handles all JSON types plus `Buffer`
|
||||
- Supports namespaces
|
||||
- Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters
|
||||
- Connection errors are passed through (db failures won't kill your app)
|
||||
- Supports the current active LTS version of Node.js or higher
|
||||
|
||||
# Bun Support
|
||||
|
||||
We make a best effort to support [Bun](https://bun.sh/) as a runtime. Our default and primary target is Node.js, but we run tests against Bun to ensure compatibility. If you encounter any issues while using Keyv with Bun, please report them at our [GitHub issues](https://github.com/jaredwray/keyv/issues).
|
||||
|
||||
# Table of Contents
|
||||
- [Bun Support](#bun-support)
|
||||
- [Usage](#usage)
|
||||
- [Type-safe Usage](#type-safe-usage)
|
||||
- [Using Storage Adapters](#using-storage-adapters)
|
||||
- [Namespaces](#namespaces)
|
||||
- [Events](#events)
|
||||
- [Hooks](#hooks)
|
||||
- [Custom Serializers](#custom-serializers)
|
||||
- [Official Storage Adapters](#official-storage-adapters)
|
||||
- [Third-party Storage Adapters](#third-party-storage-adapters)
|
||||
- [Using BigMap to Scale](#using-bigmap-to-scale)
|
||||
- [Compression](#compression)
|
||||
- [API](#api)
|
||||
- [new Keyv([storage-adapter], [options]) or new Keyv([options])](#new-keyvstorage-adapter-options-or-new-keyvoptions)
|
||||
- [.namespace](#namespace)
|
||||
- [.ttl](#ttl)
|
||||
- [.store](#store)
|
||||
- [.serialize](#serialize)
|
||||
- [.deserialize](#deserialize)
|
||||
- [.compression](#compression)
|
||||
- [.useKeyPrefix](#usekeyprefix)
|
||||
- [.stats](#stats)
|
||||
- [Keyv Instance](#keyv-instance)
|
||||
- [.set(key, value, [ttl])](#setkey-value-ttl)
|
||||
- [.setMany(entries)](#setmanyentries)
|
||||
- [.get(key, [options])](#getkey-options)
|
||||
- [.getMany(keys, [options])](#getmanykeys-options)
|
||||
- [.getRaw(key)](#getrawkey)
|
||||
- [.getManyRaw(keys)](#getmanyrawkeys)
|
||||
- [.delete(key)](#deletekey)
|
||||
- [.deleteMany(keys)](#deletemanykeys)
|
||||
- [.clear()](#clear)
|
||||
- [.iterator()](#iterator)
|
||||
- [How to Contribute](#how-to-contribute)
|
||||
- [License](#license)
|
||||
|
||||
# Usage
|
||||
|
||||
Install Keyv.
|
||||
|
||||
```
|
||||
npm install --save keyv
|
||||
```
|
||||
|
||||
By default everything is stored in memory, you can optionally also install a storage adapter.
|
||||
|
||||
```
|
||||
npm install --save @keyv/redis
|
||||
npm install --save @keyv/valkey
|
||||
npm install --save @keyv/mongo
|
||||
npm install --save @keyv/sqlite
|
||||
npm install --save @keyv/postgres
|
||||
npm install --save @keyv/mysql
|
||||
npm install --save @keyv/etcd
|
||||
npm install --save @keyv/memcache
|
||||
npm install --save @keyv/dynamo
|
||||
```
|
||||
|
||||
First, create a new Keyv instance.
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
```
|
||||
|
||||
# Type-safe Usage
|
||||
|
||||
You can create a `Keyv` instance with a generic type to enforce type safety for the values stored. Additionally, both the `get` and `set` methods support specifying custom types for specific use cases.
|
||||
|
||||
## Example with Instance-level Generic Type:
|
||||
|
||||
```ts
|
||||
const keyv = new Keyv<number>(); // Instance handles only numbers
|
||||
await keyv.set('key1', 123);
|
||||
const value = await keyv.get('key1'); // value is inferred as number
|
||||
```
|
||||
|
||||
## Example with Method-level Generic Type:
|
||||
|
||||
You can also specify a type directly in the `get` or `set` methods, allowing flexibility for different types of values within the same instance.
|
||||
|
||||
```ts
|
||||
const keyv = new Keyv(); // Generic type not specified at instance level
|
||||
|
||||
await keyv.set<string>('key2', 'some string'); // Method-level type for this value
|
||||
const strValue = await keyv.get<string>('key2'); // Explicitly typed as string
|
||||
|
||||
await keyv.set<number>('key3', 456); // Storing a number in the same instance
|
||||
const numValue = await keyv.get<number>('key3'); // Explicitly typed as number
|
||||
```
|
||||
|
||||
This makes `Keyv` highly adaptable to different data types while maintaining type safety.
|
||||
|
||||
# Using Storage Adapters
|
||||
|
||||
Once you have created your Keyv instance you can use it as a simple key-value store with `in-memory` by default. To use a storage adapter, create an instance of the adapter and pass it to the Keyv constructor. Here are some examples:
|
||||
|
||||
```js
|
||||
// redis
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
|
||||
const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));
|
||||
```
|
||||
|
||||
You can also pass in a storage adapter with other options such as `ttl` and `namespace` (example using `sqlite`):
|
||||
|
||||
```js
|
||||
//sqlite
|
||||
import KeyvSqlite from '@keyv/sqlite';
|
||||
|
||||
const keyvSqlite = new KeyvSqlite('sqlite://path/to/database.sqlite');
|
||||
const keyv = new Keyv({ store: keyvSqlite, ttl: 5000, namespace: 'cache' });
|
||||
```
|
||||
|
||||
To handle an event you can do the following:
|
||||
|
||||
```js
|
||||
// Handle DB connection errors
|
||||
keyv.on('error', err => console.log('Connection Error', err));
|
||||
```
|
||||
|
||||
Now lets do an end-to-end example using `Keyv` and the `Redis` storage adapter:
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
|
||||
const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379');
|
||||
const keyv = new Keyv({ store: keyvRedis });
|
||||
|
||||
await keyv.set('foo', 'expires in 1 second', 1000); // true
|
||||
await keyv.set('foo', 'never expires'); // true
|
||||
await keyv.get('foo'); // 'never expires'
|
||||
await keyv.delete('foo'); // true
|
||||
await keyv.clear(); // undefined
|
||||
```
|
||||
|
||||
It's is just that simple! Keyv is designed to be simple and easy to use.
|
||||
|
||||
# Namespaces
|
||||
|
||||
You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database.
|
||||
|
||||
```js
|
||||
const users = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'users' });
|
||||
const cache = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'cache' });
|
||||
|
||||
await users.set('foo', 'users'); // true
|
||||
await cache.set('foo', 'cache'); // true
|
||||
await users.get('foo'); // 'users'
|
||||
await cache.get('foo'); // 'cache'
|
||||
await users.clear(); // undefined
|
||||
await users.get('foo'); // undefined
|
||||
await cache.get('foo'); // 'cache'
|
||||
```
|
||||
|
||||
# Events
|
||||
|
||||
Keyv is a custom `EventEmitter` and will emit an `'error'` event if there is an error.
|
||||
If there is no listener for the `'error'` event, an uncaught exception will be thrown.
|
||||
To disable the `'error'` event, pass `emitErrors: false` in the constructor options.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ emitErrors: false });
|
||||
```
|
||||
|
||||
In addition it will emit `clear` and `disconnect` events when the corresponding methods are called.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
const handleConnectionError = err => console.log('Connection Error', err);
|
||||
const handleClear = () => console.log('Cache Cleared');
|
||||
const handleDisconnect = () => console.log('Disconnected');
|
||||
|
||||
keyv.on('error', handleConnectionError);
|
||||
keyv.on('clear', handleClear);
|
||||
keyv.on('disconnect', handleDisconnect);
|
||||
```
|
||||
|
||||
# Hooks
|
||||
|
||||
Keyv supports hooks for `get`, `set`, and `delete` methods. Hooks are useful for logging, debugging, and other custom functionality. Here is a list of all the hooks:
|
||||
|
||||
```
|
||||
PRE_GET
|
||||
POST_GET
|
||||
PRE_GET_RAW
|
||||
POST_GET_RAW
|
||||
PRE_GET_MANY
|
||||
POST_GET_MANY
|
||||
PRE_GET_MANY_RAW
|
||||
POST_GET_MANY_RAW
|
||||
PRE_SET
|
||||
POST_SET
|
||||
PRE_DELETE
|
||||
POST_DELETE
|
||||
```
|
||||
|
||||
You can access this by importing `KeyvHooks` from the main Keyv package.
|
||||
|
||||
```js
|
||||
import Keyv, { KeyvHooks } from 'keyv';
|
||||
```
|
||||
|
||||
## Get Hooks
|
||||
|
||||
The `POST_GET` and `POST_GET_RAW` hooks fire on both cache hits and misses. When a cache miss occurs (key doesn't exist or is expired), the hooks receive `undefined` as the value.
|
||||
|
||||
```js
|
||||
// POST_GET hook - fires on both hits and misses
|
||||
const keyv = new Keyv();
|
||||
keyv.hooks.addHandler(KeyvHooks.POST_GET, (data) => {
|
||||
if (data.value === undefined) {
|
||||
console.log(`Cache miss for key: ${data.key}`);
|
||||
} else {
|
||||
console.log(`Cache hit for key: ${data.key}`, data.value);
|
||||
}
|
||||
});
|
||||
|
||||
await keyv.get('existing-key'); // Logs cache hit with value
|
||||
await keyv.get('missing-key'); // Logs cache miss with undefined
|
||||
```
|
||||
|
||||
```js
|
||||
// POST_GET_RAW hook - same behavior as POST_GET
|
||||
const keyv = new Keyv();
|
||||
keyv.hooks.addHandler(KeyvHooks.POST_GET_RAW, (data) => {
|
||||
console.log(`Key: ${data.key}, Value:`, data.value);
|
||||
});
|
||||
|
||||
await keyv.getRaw('foo'); // Logs with value or undefined
|
||||
```
|
||||
|
||||
## Set Hooks
|
||||
|
||||
```js
|
||||
//PRE_SET hook
|
||||
const keyv = new Keyv();
|
||||
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => console.log(`Setting key ${data.key} to ${data.value}`));
|
||||
|
||||
//POST_SET hook
|
||||
const keyv = new Keyv();
|
||||
keyv.hooks.addHandler(KeyvHooks.POST_SET, ({key, value}) => console.log(`Set key ${key} to ${value}`));
|
||||
```
|
||||
|
||||
In these examples you can also manipulate the value before it is set. For example, you could add a prefix to all keys.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => {
|
||||
console.log(`Manipulating key ${data.key} and ${data.value}`);
|
||||
data.key = `prefix-${data.key}`;
|
||||
data.value = `prefix-${data.value}`;
|
||||
});
|
||||
```
|
||||
|
||||
Now this key will have prefix- added to it before it is set.
|
||||
|
||||
## Delete Hooks
|
||||
|
||||
In `PRE_DELETE` and `POST_DELETE` hooks, the value could be a single item or an `Array`. This is based on the fact that `delete` can accept a single key or an `Array` of keys.
|
||||
|
||||
|
||||
# Custom Serializers
|
||||
|
||||
Keyv uses [`buffer`](https://nodejs.org/api/buffer.html) for data serialization to ensure consistency across different backends.
|
||||
|
||||
You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });
|
||||
```
|
||||
|
||||
**Warning:** Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine.
|
||||
|
||||
If you do not want to use serialization you can set the `serialize` and `deserialize` functions to `undefined`. This will also turn off compression.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
keyv.serialize = undefined;
|
||||
keyv.deserialize = undefined;
|
||||
```
|
||||
|
||||
# Official Storage Adapters
|
||||
|
||||
The official storage adapters are covered by [over 150 integration tests](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available.
|
||||
|
||||
Database | Adapter | Native TTL
|
||||
---|---|---
|
||||
Redis | [@keyv/redis](https://github.com/jaredwray/keyv/tree/master/packages/redis) | Yes
|
||||
Valkey | [@keyv/valkey](https://github.com/jaredwray/keyv/tree/master/packages/valkey) | Yes
|
||||
MongoDB | [@keyv/mongo](https://github.com/jaredwray/keyv/tree/master/packages/mongo) | Yes
|
||||
SQLite | [@keyv/sqlite](https://github.com/jaredwray/keyv/tree/master/packages/sqlite) | No
|
||||
PostgreSQL | [@keyv/postgres](https://github.com/jaredwray/keyv/tree/master/packages/postgres) | No
|
||||
MySQL | [@keyv/mysql](https://github.com/jaredwray/keyv/tree/master/packages/mysql) | No
|
||||
Etcd | [@keyv/etcd](https://github.com/jaredwray/keyv/tree/master/packages/etcd) | Yes
|
||||
Memcache | [@keyv/memcache](https://github.com/jaredwray/keyv/tree/master/packages/memcache) | Yes
|
||||
DynamoDB | [@keyv/dynamo](https://github.com/jaredwray/keyv/tree/master/packages/dynamo) | Yes
|
||||
|
||||
# Third-party Storage Adapters
|
||||
|
||||
We love the community and the third-party storage adapters they have built. They enable Keyv to be used with even more backends and use cases.
|
||||
|
||||
You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally.
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import myAdapter from 'my-adapter';
|
||||
|
||||
const keyv = new Keyv({ store: myAdapter });
|
||||
```
|
||||
|
||||
Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work.
|
||||
|
||||
```js
|
||||
new Keyv({ store: new Map() });
|
||||
```
|
||||
|
||||
For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API.
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import QuickLRU from 'quick-lru';
|
||||
|
||||
const lru = new QuickLRU({ maxSize: 1000 });
|
||||
const keyv = new Keyv({ store: lru });
|
||||
```
|
||||
|
||||
View the complete list of third-party storage adapters and learn how to build your own at https://keyv.org/docs/third-party-storage-adapters/
|
||||
|
||||
# Using BigMap to Scale
|
||||
|
||||
## Understanding JavaScript Map Limitations
|
||||
|
||||
JavaScript's built-in `Map` object has a practical limit of approximately **16.7 million entries** (2^24). When you try to store more entries than this limit, you'll encounter performance degradation or runtime errors. This limitation is due to how JavaScript engines internally manage Map objects.
|
||||
|
||||
For applications that need to cache millions of entries in memory, this becomes a significant constraint. Common scenarios include:
|
||||
- High-traffic caching layers
|
||||
- Session stores for large-scale applications
|
||||
- In-memory data processing of large datasets
|
||||
- Real-time analytics with millions of data points
|
||||
|
||||
## Why BigMap?
|
||||
|
||||
`@keyv/bigmap` solves this limitation by using a **distributed hash approach** with multiple internal Map instances. Instead of storing all entries in a single Map, BigMap distributes entries across multiple Maps using a hash function. This allows you to scale beyond the 16.7 million entry limit while maintaining the familiar Map API.
|
||||
|
||||
### Key Benefits:
|
||||
- **Scales beyond Map limits**: Store 20+ million entries without issues
|
||||
- **Map-compatible API**: Drop-in replacement for standard Map
|
||||
- **Performance**: Uses efficient DJB2 hashing for fast key distribution
|
||||
- **Type-safe**: Built with TypeScript and supports generics
|
||||
- **Customizable**: Configure store size and hash functions
|
||||
|
||||
## Using BigMap with Keyv
|
||||
|
||||
BigMap can be used directly with Keyv as a storage adapter, providing scalable in-memory storage with full TTL support.
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
npm install --save keyv @keyv/bigmap
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
The simplest way to use BigMap with Keyv is through the `createKeyv` helper function:
|
||||
|
||||
```js
|
||||
import { createKeyv } from '@keyv/bigmap';
|
||||
|
||||
const keyv = createKeyv();
|
||||
|
||||
// Set values with TTL (time in milliseconds)
|
||||
await keyv.set('user:1', { name: 'Alice', email: 'alice@example.com' }, 60000); // Expires in 60 seconds
|
||||
|
||||
// Get values
|
||||
const user = await keyv.get('user:1');
|
||||
console.log(user); // { name: 'Alice', email: 'alice@example.com' }
|
||||
|
||||
// Delete values
|
||||
await keyv.delete('user:1');
|
||||
|
||||
// Clear all values
|
||||
await keyv.clear();
|
||||
```
|
||||
|
||||
For more details about BigMap, see the [@keyv/bigmap documentation](https://github.com/jaredwray/keyv/tree/main/packages/bigmap).
|
||||
|
||||
# Compression
|
||||
|
||||
Keyv supports `gzip`, `brotli` and `lz4` compression. To enable compression, pass the `compress` option to the constructor.
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvGzip from '@keyv/compress-gzip';
|
||||
|
||||
const keyvGzip = new KeyvGzip();
|
||||
const keyv = new Keyv({ compression: keyvGzip });
|
||||
```
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvBrotli from '@keyv/compress-brotli';
|
||||
|
||||
const keyvBrotli = new KeyvBrotli();
|
||||
const keyv = new Keyv({ compression: keyvBrotli });
|
||||
```
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvLz4 from '@keyv/compress-lz4';
|
||||
|
||||
const keyvLz4 = new KeyvLz4();
|
||||
const keyv = new Keyv({ compression: keyvLz4 });
|
||||
```
|
||||
|
||||
You can also pass a custom compression function to the `compression` option. Following the pattern of the official compression adapters.
|
||||
|
||||
## Want to build your own CompressionAdapter?
|
||||
|
||||
Great! Keyv is designed to be easily extended. You can build your own compression adapter by following the pattern of the official compression adapters based on this interface:
|
||||
|
||||
```typescript
|
||||
interface CompressionAdapter {
|
||||
async compress(value: any, options?: any);
|
||||
async decompress(value: any, options?: any);
|
||||
async serialize(value: any);
|
||||
async deserialize(value: any);
|
||||
}
|
||||
```
|
||||
|
||||
In addition to the interface, you can test it with our compression test suite using @keyv/test-suite:
|
||||
|
||||
```js
|
||||
import { keyvCompresstionTests } from '@keyv/test-suite';
|
||||
import KeyvGzip from '@keyv/compress-gzip';
|
||||
|
||||
keyvCompresstionTests(test, new KeyvGzip());
|
||||
```
|
||||
|
||||
# API
|
||||
|
||||
## new Keyv([storage-adapter], [options]) or new Keyv([options])
|
||||
|
||||
Returns a new Keyv instance.
|
||||
|
||||
The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails.
|
||||
|
||||
## storage-adapter
|
||||
|
||||
Type: `KeyvStorageAdapter`<br />
|
||||
Default: `undefined`
|
||||
|
||||
The connection string URI.
|
||||
|
||||
Merged into the options object as options.uri.
|
||||
|
||||
## .namespace
|
||||
|
||||
Type: `String`
|
||||
Default: `'keyv'`
|
||||
|
||||
This is the namespace for the current instance. When you set it it will set it also on the storage adapter. This is the preferred way to set the namespace over `.opts.namespace`.
|
||||
|
||||
## options
|
||||
|
||||
Type: `Object`
|
||||
|
||||
The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.
|
||||
|
||||
## options.namespace
|
||||
|
||||
Type: `String`<br />
|
||||
Default: `'keyv'`
|
||||
|
||||
Namespace for the current instance.
|
||||
|
||||
## options.ttl
|
||||
|
||||
Type: `Number`<br />
|
||||
Default: `undefined`
|
||||
|
||||
Default TTL. Can be overridden by specififying a TTL on `.set()`.
|
||||
|
||||
## options.compression
|
||||
|
||||
Type: `@keyv/compress-<compression_package_name>`<br />
|
||||
Default: `undefined`
|
||||
|
||||
Compression package to use. See [Compression](#compression) for more details.
|
||||
|
||||
## options.serialize
|
||||
|
||||
Type: `Function`<br />
|
||||
Default: `JSON.stringify`
|
||||
|
||||
A custom serialization function.
|
||||
|
||||
## options.deserialize
|
||||
|
||||
Type: `Function`<br />
|
||||
Default: `JSON.parse`
|
||||
|
||||
A custom deserialization function.
|
||||
|
||||
## options.store
|
||||
|
||||
Type: `Storage adapter instance`<br />
|
||||
Default: `new Map()`
|
||||
|
||||
The storage adapter instance to be used by Keyv.
|
||||
|
||||
# Keyv Instance
|
||||
|
||||
Keys must always be strings. Values can be of any type.
|
||||
|
||||
## .set(key, value, [ttl])
|
||||
|
||||
Set a value.
|
||||
|
||||
By default keys are persistent. You can set an expiry TTL in milliseconds.
|
||||
|
||||
Returns a promise which resolves to `true`.
|
||||
|
||||
## .setMany(entries)
|
||||
|
||||
Set multiple values using KeyvEntrys `{ key: string, value: any, ttl?: number }`.
|
||||
|
||||
## .get(key, [options])
|
||||
|
||||
Returns a promise which resolves to the retrieved value.
|
||||
|
||||
## .getMany(keys, [options])
|
||||
|
||||
Returns a promise which resolves to an array of retrieved values.
|
||||
|
||||
### options.raw - (Will be deprecated in v6)
|
||||
|
||||
Type: `Boolean`<br />
|
||||
Default: `false`
|
||||
|
||||
If set to true the raw DB object Keyv stores internally will be returned instead of just the value.
|
||||
|
||||
This contains the TTL timestamp.
|
||||
|
||||
NOTE: This option will be deprecated in v6 and replaced with `.getRaw()` and `.getManyRaw()` methods.
|
||||
|
||||
## .getRaw(key)
|
||||
|
||||
Returns a promise which resolves to the raw stored data for the key or `undefined` if the key does not exist or is expired.
|
||||
|
||||
## .getManyRaw(keys)
|
||||
|
||||
Returns a promise which resolves to an array of raw stored data for the keys or `undefined` if the key does not exist or is expired.
|
||||
|
||||
## .delete(key)
|
||||
|
||||
Deletes an entry.
|
||||
|
||||
Returns a promise which resolves to `true` if the key existed, `false` if not.
|
||||
|
||||
## .deleteMany(keys)
|
||||
Deletes multiple entries.
|
||||
Returns a promise which resolves to an array of booleans indicating if the key existed or not.
|
||||
|
||||
## .clear()
|
||||
|
||||
Delete all entries in the current namespace.
|
||||
|
||||
Returns a promise which is resolved when the entries have been cleared.
|
||||
|
||||
## .iterator()
|
||||
|
||||
Iterate over all entries of the current namespace.
|
||||
|
||||
Returns a iterable that can be iterated by for-of loops. For example:
|
||||
|
||||
```js
|
||||
// please note that the "await" keyword should be used here
|
||||
for await (const [key, value] of this.keyv.iterator()) {
|
||||
console.log(key, value);
|
||||
};
|
||||
```
|
||||
|
||||
# API - Properties
|
||||
|
||||
## .namespace
|
||||
|
||||
Type: `String`
|
||||
|
||||
The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to `undefined` it will no longer do key prefixing.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ namespace: 'my-namespace' });
|
||||
console.log(keyv.namespace); // 'my-namespace'
|
||||
```
|
||||
|
||||
here is an example of setting the namespace to `undefined`:
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
console.log(keyv.namespace); // 'keyv' which is default
|
||||
keyv.namespace = undefined;
|
||||
console.log(keyv.namespace); // undefined
|
||||
```
|
||||
|
||||
## .ttl
|
||||
|
||||
Type: `Number`<br />
|
||||
Default: `undefined`
|
||||
|
||||
Default TTL. Can be overridden by specififying a TTL on `.set()`. If set to `undefined` it will never expire.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ ttl: 5000 });
|
||||
console.log(keyv.ttl); // 5000
|
||||
keyv.ttl = undefined;
|
||||
console.log(keyv.ttl); // undefined (never expires)
|
||||
```
|
||||
|
||||
## .store
|
||||
|
||||
Type: `Storage adapter instance`<br />
|
||||
Default: `new Map()`
|
||||
|
||||
The storage adapter instance to be used by Keyv. This will wire up the iterator, events, and more when a set happens. If it is not a valid Map or Storage Adapter it will throw an error.
|
||||
|
||||
```js
|
||||
import KeyvSqlite from '@keyv/sqlite';
|
||||
const keyv = new Keyv();
|
||||
console.log(keyv.store instanceof Map); // true
|
||||
keyv.store = new KeyvSqlite('sqlite://path/to/database.sqlite');
|
||||
console.log(keyv.store instanceof KeyvSqlite); // true
|
||||
```
|
||||
|
||||
## .serialize
|
||||
|
||||
Type: `Function`<br />
|
||||
Default: `JSON.stringify`
|
||||
|
||||
A custom serialization function used for any value.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
console.log(keyv.serialize); // JSON.stringify
|
||||
keyv.serialize = value => value.toString();
|
||||
console.log(keyv.serialize); // value => value.toString()
|
||||
```
|
||||
|
||||
## .deserialize
|
||||
|
||||
Type: `Function`<br />
|
||||
Default: `JSON.parse`
|
||||
|
||||
A custom deserialization function used for any value.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv();
|
||||
console.log(keyv.deserialize); // JSON.parse
|
||||
keyv.deserialize = value => parseInt(value);
|
||||
console.log(keyv.deserialize); // value => parseInt(value)
|
||||
```
|
||||
|
||||
## .compression
|
||||
|
||||
Type: `CompressionAdapter`<br />
|
||||
Default: `undefined`
|
||||
|
||||
this is the compression package to use. See [Compression](#compression) for more details. If it is undefined it will not compress (default).
|
||||
|
||||
```js
|
||||
import KeyvGzip from '@keyv/compress-gzip';
|
||||
|
||||
const keyv = new Keyv();
|
||||
console.log(keyv.compression); // undefined
|
||||
keyv.compression = new KeyvGzip();
|
||||
console.log(keyv.compression); // KeyvGzip
|
||||
```
|
||||
|
||||
## .useKeyPrefix
|
||||
|
||||
Type: `Boolean`<br />
|
||||
Default: `true`
|
||||
|
||||
If set to `true` Keyv will prefix all keys with the namespace. This is useful if you want to avoid collisions with other data in your storage.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ useKeyPrefix: false });
|
||||
console.log(keyv.useKeyPrefix); // false
|
||||
keyv.useKeyPrefix = true;
|
||||
console.log(keyv.useKeyPrefix); // true
|
||||
```
|
||||
|
||||
With many of the storage adapters you will also need to set the `namespace` option to `undefined` to have it work correctly. This is because in `v5` we started the transition to having the storage adapter handle the namespacing and `Keyv` will no longer handle it internally via KeyPrefixing. Here is an example of doing ith with `KeyvSqlite`:
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvSqlite from '@keyv/sqlite';
|
||||
|
||||
const store = new KeyvSqlite('sqlite://path/to/database.sqlite');
|
||||
const keyv = new Keyv({ store });
|
||||
keyv.useKeyPrefix = false; // disable key prefixing
|
||||
store.namespace = undefined; // disable namespacing in the storage adapter
|
||||
|
||||
await keyv.set('foo', 'bar'); // true
|
||||
await keyv.get('foo'); // 'bar'
|
||||
await keyv.clear();
|
||||
```
|
||||
|
||||
## .throwOnErrors
|
||||
|
||||
Type: `Boolean`<br />
|
||||
Default: `false`
|
||||
|
||||
If set to `true`, Keyv will throw an error if any operation fails. This is useful if you want to ensure that all operations are successful and you want to handle errors.
|
||||
|
||||
```js
|
||||
const keyv = new Keyv({ throwOnErrors: true });
|
||||
console.log(keyv.throwOnErrors); // true
|
||||
keyv.throwOnErrors = false;
|
||||
console.log(keyv.throwOnErrors); // false
|
||||
```
|
||||
|
||||
A good example of this is with the `@keyv/redis` storage adapter. If you want to handle connection errors, retries, and timeouts more gracefully, you can use the `throwOnErrors` option. This will throw an error if any operation fails, allowing you to catch it and handle it accordingly:
|
||||
|
||||
```js
|
||||
import Keyv from 'keyv';
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
|
||||
// create redis instance that will throw on connection error
|
||||
const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379', { throwOnConnectErrors: true });
|
||||
|
||||
const keyv = new Keyv({ store: keyvRedis, throwOnErrors: true });
|
||||
```
|
||||
|
||||
What this does is it only throw on connection errors with the Redis client.
|
||||
|
||||
## .stats
|
||||
Type: `StatsManager`<br />
|
||||
Default: `StatsManager` instance with `enabled: false`
|
||||
|
||||
The stats property provides access to statistics tracking for cache operations. When enabled via the `stats` option during initialization, it tracks hits, misses, sets, deletes, and errors.
|
||||
|
||||
### Enabling Stats:
|
||||
```js
|
||||
const keyv = new Keyv({ stats: true });
|
||||
console.log(keyv.stats.enabled); // true
|
||||
```
|
||||
|
||||
### Available Statistics:
|
||||
- `hits`: Number of successful cache retrievals
|
||||
- `misses`: Number of failed cache retrievals
|
||||
- `sets`: Number of set operations
|
||||
- `deletes`: Number of delete operations
|
||||
- `errors`: Number of errors encountered
|
||||
|
||||
### Accessing Stats:
|
||||
```js
|
||||
const keyv = new Keyv({ stats: true });
|
||||
|
||||
await keyv.set('foo', 'bar');
|
||||
await keyv.get('foo'); // cache hit
|
||||
await keyv.get('nonexistent'); // cache miss
|
||||
await keyv.delete('foo');
|
||||
|
||||
console.log(keyv.stats.hits); // 1
|
||||
console.log(keyv.stats.misses); // 1
|
||||
console.log(keyv.stats.sets); // 1
|
||||
console.log(keyv.stats.deletes); // 1
|
||||
```
|
||||
|
||||
### Resetting Stats:
|
||||
```js
|
||||
keyv.stats.reset();
|
||||
console.log(keyv.stats.hits); // 0
|
||||
```
|
||||
|
||||
### Manual Control:
|
||||
You can also manually enable/disable stats tracking at runtime:
|
||||
```js
|
||||
const keyv = new Keyv({ stats: false });
|
||||
keyv.stats.enabled = true; // Enable stats tracking
|
||||
// ... perform operations ...
|
||||
keyv.stats.enabled = false; // Disable stats tracking
|
||||
```
|
||||
|
||||
# How to Contribute
|
||||
|
||||
We welcome contributions to Keyv! 🎉 Here are some guides to get you started with contributing:
|
||||
|
||||
* [Contributing](https://github.com/jaredwray/keyv/blob/main/CONTRIBUTING.md) - Learn about how to contribute to Keyv
|
||||
* [Code of Conduct](https://github.com/jaredwray/keyv/blob/main/CODE_OF_CONDUCT.md) - Learn about the Keyv Code of Conduct
|
||||
* [How to Contribute](https://github.com/jaredwray/keyv/blob/main/README.md) - How do develop in the Keyv mono repo!
|
||||
|
||||
# License
|
||||
|
||||
[MIT © Jared Wray](LICENSE)
|
||||
990
node_modules/keyv/dist/index.cjs
generated
vendored
Normal file
990
node_modules/keyv/dist/index.cjs
generated
vendored
Normal file
@@ -0,0 +1,990 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/index.ts
|
||||
var index_exports = {};
|
||||
__export(index_exports, {
|
||||
Keyv: () => Keyv,
|
||||
KeyvHooks: () => KeyvHooks,
|
||||
default: () => index_default
|
||||
});
|
||||
module.exports = __toCommonJS(index_exports);
|
||||
var import_serialize = require("@keyv/serialize");
|
||||
|
||||
// src/event-manager.ts
|
||||
var EventManager = class {
|
||||
_eventListeners;
|
||||
_maxListeners;
|
||||
constructor() {
|
||||
this._eventListeners = /* @__PURE__ */ new Map();
|
||||
this._maxListeners = 100;
|
||||
}
|
||||
maxListeners() {
|
||||
return this._maxListeners;
|
||||
}
|
||||
// Add an event listener
|
||||
addListener(event, listener) {
|
||||
this.on(event, listener);
|
||||
}
|
||||
on(event, listener) {
|
||||
if (!this._eventListeners.has(event)) {
|
||||
this._eventListeners.set(event, []);
|
||||
}
|
||||
const listeners = this._eventListeners.get(event);
|
||||
if (listeners) {
|
||||
if (listeners.length >= this._maxListeners) {
|
||||
console.warn(
|
||||
`MaxListenersExceededWarning: Possible event memory leak detected. ${listeners.length + 1} ${event} listeners added. Use setMaxListeners() to increase limit.`
|
||||
);
|
||||
}
|
||||
listeners.push(listener);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
// Remove an event listener
|
||||
removeListener(event, listener) {
|
||||
this.off(event, listener);
|
||||
}
|
||||
off(event, listener) {
|
||||
const listeners = this._eventListeners.get(event) ?? [];
|
||||
const index = listeners.indexOf(listener);
|
||||
if (index !== -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
if (listeners.length === 0) {
|
||||
this._eventListeners.delete(event);
|
||||
}
|
||||
}
|
||||
once(event, listener) {
|
||||
const onceListener = (...arguments_) => {
|
||||
listener(...arguments_);
|
||||
this.off(event, onceListener);
|
||||
};
|
||||
this.on(event, onceListener);
|
||||
}
|
||||
// Emit an event
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
emit(event, ...arguments_) {
|
||||
const listeners = this._eventListeners.get(event);
|
||||
if (listeners && listeners.length > 0) {
|
||||
for (const listener of listeners) {
|
||||
listener(...arguments_);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get all listeners for a specific event
|
||||
listeners(event) {
|
||||
return this._eventListeners.get(event) ?? [];
|
||||
}
|
||||
// Remove all listeners for a specific event
|
||||
removeAllListeners(event) {
|
||||
if (event) {
|
||||
this._eventListeners.delete(event);
|
||||
} else {
|
||||
this._eventListeners.clear();
|
||||
}
|
||||
}
|
||||
// Set the maximum number of listeners for a single event
|
||||
setMaxListeners(n) {
|
||||
this._maxListeners = n;
|
||||
}
|
||||
};
|
||||
var event_manager_default = EventManager;
|
||||
|
||||
// src/hooks-manager.ts
|
||||
var HooksManager = class extends event_manager_default {
|
||||
_hookHandlers;
|
||||
constructor() {
|
||||
super();
|
||||
this._hookHandlers = /* @__PURE__ */ new Map();
|
||||
}
|
||||
// Adds a handler function for a specific event
|
||||
addHandler(event, handler) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
eventHandlers.push(handler);
|
||||
} else {
|
||||
this._hookHandlers.set(event, [handler]);
|
||||
}
|
||||
}
|
||||
// Removes a specific handler function for a specific event
|
||||
removeHandler(event, handler) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
const index = eventHandlers.indexOf(handler);
|
||||
if (index !== -1) {
|
||||
eventHandlers.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Triggers all handlers for a specific event with provided data
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
trigger(event, data) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
for (const handler of eventHandlers) {
|
||||
try {
|
||||
handler(data);
|
||||
} catch (error) {
|
||||
this.emit(
|
||||
"error",
|
||||
new Error(
|
||||
`Error in hook handler for event "${event}": ${error.message}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Provides read-only access to the current handlers
|
||||
get handlers() {
|
||||
return new Map(this._hookHandlers);
|
||||
}
|
||||
};
|
||||
var hooks_manager_default = HooksManager;
|
||||
|
||||
// src/stats-manager.ts
|
||||
var StatsManager = class extends event_manager_default {
|
||||
enabled = true;
|
||||
hits = 0;
|
||||
misses = 0;
|
||||
sets = 0;
|
||||
deletes = 0;
|
||||
errors = 0;
|
||||
constructor(enabled) {
|
||||
super();
|
||||
if (enabled !== void 0) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
this.reset();
|
||||
}
|
||||
hit() {
|
||||
if (this.enabled) {
|
||||
this.hits++;
|
||||
}
|
||||
}
|
||||
miss() {
|
||||
if (this.enabled) {
|
||||
this.misses++;
|
||||
}
|
||||
}
|
||||
set() {
|
||||
if (this.enabled) {
|
||||
this.sets++;
|
||||
}
|
||||
}
|
||||
delete() {
|
||||
if (this.enabled) {
|
||||
this.deletes++;
|
||||
}
|
||||
}
|
||||
hitsOrMisses(array) {
|
||||
for (const item of array) {
|
||||
if (item === void 0) {
|
||||
this.miss();
|
||||
} else {
|
||||
this.hit();
|
||||
}
|
||||
}
|
||||
}
|
||||
reset() {
|
||||
this.hits = 0;
|
||||
this.misses = 0;
|
||||
this.sets = 0;
|
||||
this.deletes = 0;
|
||||
this.errors = 0;
|
||||
}
|
||||
};
|
||||
var stats_manager_default = StatsManager;
|
||||
|
||||
// src/index.ts
|
||||
var KeyvHooks = /* @__PURE__ */ ((KeyvHooks2) => {
|
||||
KeyvHooks2["PRE_SET"] = "preSet";
|
||||
KeyvHooks2["POST_SET"] = "postSet";
|
||||
KeyvHooks2["PRE_GET"] = "preGet";
|
||||
KeyvHooks2["POST_GET"] = "postGet";
|
||||
KeyvHooks2["PRE_GET_MANY"] = "preGetMany";
|
||||
KeyvHooks2["POST_GET_MANY"] = "postGetMany";
|
||||
KeyvHooks2["PRE_GET_RAW"] = "preGetRaw";
|
||||
KeyvHooks2["POST_GET_RAW"] = "postGetRaw";
|
||||
KeyvHooks2["PRE_GET_MANY_RAW"] = "preGetManyRaw";
|
||||
KeyvHooks2["POST_GET_MANY_RAW"] = "postGetManyRaw";
|
||||
KeyvHooks2["PRE_DELETE"] = "preDelete";
|
||||
KeyvHooks2["POST_DELETE"] = "postDelete";
|
||||
return KeyvHooks2;
|
||||
})(KeyvHooks || {});
|
||||
var iterableAdapters = [
|
||||
"sqlite",
|
||||
"postgres",
|
||||
"mysql",
|
||||
"mongo",
|
||||
"redis",
|
||||
"valkey",
|
||||
"etcd"
|
||||
];
|
||||
var Keyv = class extends event_manager_default {
|
||||
opts;
|
||||
iterator;
|
||||
hooks = new hooks_manager_default();
|
||||
stats = new stats_manager_default(false);
|
||||
/**
|
||||
* Time to live in milliseconds
|
||||
*/
|
||||
_ttl;
|
||||
/**
|
||||
* Namespace
|
||||
*/
|
||||
_namespace;
|
||||
/**
|
||||
* Store
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
_store = /* @__PURE__ */ new Map();
|
||||
_serialize = import_serialize.defaultSerialize;
|
||||
_deserialize = import_serialize.defaultDeserialize;
|
||||
_compression;
|
||||
_useKeyPrefix = true;
|
||||
_throwOnErrors = false;
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvStoreAdapter | KeyvOptions} store
|
||||
* @param {Omit<KeyvOptions, 'store'>} [options] if you provide the store you can then provide the Keyv Options
|
||||
*/
|
||||
constructor(store, options) {
|
||||
super();
|
||||
options ??= {};
|
||||
store ??= {};
|
||||
this.opts = {
|
||||
namespace: "keyv",
|
||||
serialize: import_serialize.defaultSerialize,
|
||||
deserialize: import_serialize.defaultDeserialize,
|
||||
emitErrors: true,
|
||||
// @ts-expect-error - Map is not a KeyvStoreAdapter
|
||||
store: /* @__PURE__ */ new Map(),
|
||||
...options
|
||||
};
|
||||
if (store && store.get) {
|
||||
this.opts.store = store;
|
||||
} else {
|
||||
this.opts = {
|
||||
...this.opts,
|
||||
...store
|
||||
};
|
||||
}
|
||||
this._store = this.opts.store ?? /* @__PURE__ */ new Map();
|
||||
this._compression = this.opts.compression;
|
||||
this._serialize = this.opts.serialize;
|
||||
this._deserialize = this.opts.deserialize;
|
||||
if (this.opts.namespace) {
|
||||
this._namespace = this.opts.namespace;
|
||||
}
|
||||
if (this._store) {
|
||||
if (!this._isValidStorageAdapter(this._store)) {
|
||||
throw new Error("Invalid storage adapter");
|
||||
}
|
||||
if (typeof this._store.on === "function") {
|
||||
this._store.on("error", (error) => this.emit("error", error));
|
||||
}
|
||||
this._store.namespace = this._namespace;
|
||||
if (typeof this._store[Symbol.iterator] === "function" && this._store instanceof Map) {
|
||||
this.iterator = this.generateIterator(
|
||||
this._store
|
||||
);
|
||||
} else if ("iterator" in this._store && this._store.opts && this._checkIterableAdapter()) {
|
||||
this.iterator = this.generateIterator(
|
||||
// biome-ignore lint/style/noNonNullAssertion: need to fix
|
||||
this._store.iterator.bind(this._store)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (this.opts.stats) {
|
||||
this.stats.enabled = this.opts.stats;
|
||||
}
|
||||
if (this.opts.ttl) {
|
||||
this._ttl = this.opts.ttl;
|
||||
}
|
||||
if (this.opts.useKeyPrefix !== void 0) {
|
||||
this._useKeyPrefix = this.opts.useKeyPrefix;
|
||||
}
|
||||
if (this.opts.throwOnErrors !== void 0) {
|
||||
this._throwOnErrors = this.opts.throwOnErrors;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current store
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
get store() {
|
||||
return this._store;
|
||||
}
|
||||
/**
|
||||
* Set the current store. This will also set the namespace, event error handler, and generate the iterator. If the store is not valid it will throw an error.
|
||||
* @param {KeyvStoreAdapter | Map<any, any> | any} store the store to set
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
set store(store) {
|
||||
if (this._isValidStorageAdapter(store)) {
|
||||
this._store = store;
|
||||
this.opts.store = store;
|
||||
if (typeof store.on === "function") {
|
||||
store.on("error", (error) => this.emit("error", error));
|
||||
}
|
||||
if (this._namespace) {
|
||||
this._store.namespace = this._namespace;
|
||||
}
|
||||
if (typeof store[Symbol.iterator] === "function" && store instanceof Map) {
|
||||
this.iterator = this.generateIterator(
|
||||
store
|
||||
);
|
||||
} else if ("iterator" in store && store.opts && this._checkIterableAdapter()) {
|
||||
this.iterator = this.generateIterator(store.iterator?.bind(store));
|
||||
}
|
||||
} else {
|
||||
throw new Error("Invalid storage adapter");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current compression function
|
||||
* @returns {CompressionAdapter} The current compression function
|
||||
*/
|
||||
get compression() {
|
||||
return this._compression;
|
||||
}
|
||||
/**
|
||||
* Set the current compression function
|
||||
* @param {CompressionAdapter} compress The compression function to set
|
||||
*/
|
||||
set compression(compress) {
|
||||
this._compression = compress;
|
||||
}
|
||||
/**
|
||||
* Get the current namespace.
|
||||
* @returns {string | undefined} The current namespace.
|
||||
*/
|
||||
get namespace() {
|
||||
return this._namespace;
|
||||
}
|
||||
/**
|
||||
* Set the current namespace.
|
||||
* @param {string | undefined} namespace The namespace to set.
|
||||
*/
|
||||
set namespace(namespace) {
|
||||
this._namespace = namespace;
|
||||
this.opts.namespace = namespace;
|
||||
this._store.namespace = namespace;
|
||||
if (this.opts.store) {
|
||||
this.opts.store.namespace = namespace;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current TTL.
|
||||
* @returns {number} The current TTL in milliseconds.
|
||||
*/
|
||||
get ttl() {
|
||||
return this._ttl;
|
||||
}
|
||||
/**
|
||||
* Set the current TTL.
|
||||
* @param {number} ttl The TTL to set in milliseconds.
|
||||
*/
|
||||
set ttl(ttl) {
|
||||
this.opts.ttl = ttl;
|
||||
this._ttl = ttl;
|
||||
}
|
||||
/**
|
||||
* Get the current serialize function.
|
||||
* @returns {Serialize} The current serialize function.
|
||||
*/
|
||||
get serialize() {
|
||||
return this._serialize;
|
||||
}
|
||||
/**
|
||||
* Set the current serialize function.
|
||||
* @param {Serialize} serialize The serialize function to set.
|
||||
*/
|
||||
set serialize(serialize) {
|
||||
this.opts.serialize = serialize;
|
||||
this._serialize = serialize;
|
||||
}
|
||||
/**
|
||||
* Get the current deserialize function.
|
||||
* @returns {Deserialize} The current deserialize function.
|
||||
*/
|
||||
get deserialize() {
|
||||
return this._deserialize;
|
||||
}
|
||||
/**
|
||||
* Set the current deserialize function.
|
||||
* @param {Deserialize} deserialize The deserialize function to set.
|
||||
*/
|
||||
set deserialize(deserialize) {
|
||||
this.opts.deserialize = deserialize;
|
||||
this._deserialize = deserialize;
|
||||
}
|
||||
/**
|
||||
* Get the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @returns {boolean} The current useKeyPrefix value.
|
||||
* @default true
|
||||
*/
|
||||
get useKeyPrefix() {
|
||||
return this._useKeyPrefix;
|
||||
}
|
||||
/**
|
||||
* Set the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @param {boolean} value The useKeyPrefix value to set.
|
||||
*/
|
||||
set useKeyPrefix(value) {
|
||||
this._useKeyPrefix = value;
|
||||
this.opts.useKeyPrefix = value;
|
||||
}
|
||||
/**
|
||||
* Get the current throwErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @return {boolean} The current throwOnErrors value.
|
||||
*/
|
||||
get throwOnErrors() {
|
||||
return this._throwOnErrors;
|
||||
}
|
||||
/**
|
||||
* Set the current throwOnErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @param {boolean} value The throwOnErrors value to set.
|
||||
*/
|
||||
set throwOnErrors(value) {
|
||||
this._throwOnErrors = value;
|
||||
this.opts.throwOnErrors = value;
|
||||
}
|
||||
generateIterator(iterator) {
|
||||
const function_ = async function* () {
|
||||
for await (const [key, raw] of typeof iterator === "function" ? iterator(this._store.namespace) : iterator) {
|
||||
const data = await this.deserializeData(raw);
|
||||
if (this._useKeyPrefix && this._store.namespace && !key.includes(this._store.namespace)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof data.expires === "number" && Date.now() > data.expires) {
|
||||
await this.delete(key);
|
||||
continue;
|
||||
}
|
||||
yield [this._getKeyUnprefix(key), data.value];
|
||||
}
|
||||
};
|
||||
return function_.bind(this);
|
||||
}
|
||||
_checkIterableAdapter() {
|
||||
return iterableAdapters.includes(this._store.opts.dialect) || iterableAdapters.some(
|
||||
(element) => this._store.opts.url.includes(element)
|
||||
);
|
||||
}
|
||||
_getKeyPrefix(key) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return key;
|
||||
}
|
||||
if (!this._namespace) {
|
||||
return key;
|
||||
}
|
||||
if (key.startsWith(`${this._namespace}:`)) {
|
||||
return key;
|
||||
}
|
||||
return `${this._namespace}:${key}`;
|
||||
}
|
||||
_getKeyPrefixArray(keys) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return keys;
|
||||
}
|
||||
if (!this._namespace) {
|
||||
return keys;
|
||||
}
|
||||
return keys.map((key) => `${this._namespace}:${key}`);
|
||||
}
|
||||
_getKeyUnprefix(key) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return key;
|
||||
}
|
||||
return key.split(":").splice(1).join(":");
|
||||
}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
_isValidStorageAdapter(store) {
|
||||
return store instanceof Map || typeof store.get === "function" && typeof store.set === "function" && typeof store.delete === "function" && typeof store.clear === "function";
|
||||
}
|
||||
// eslint-disable-next-line @stylistic/max-len
|
||||
async get(key, options) {
|
||||
const { store } = this.opts;
|
||||
const isArray = Array.isArray(key);
|
||||
const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
if (isArray) {
|
||||
if (options?.raw === true) {
|
||||
return this.getMany(key, { raw: true });
|
||||
}
|
||||
return this.getMany(key, { raw: false });
|
||||
}
|
||||
this.hooks.trigger("preGet" /* PRE_GET */, { key: keyPrefixed });
|
||||
let rawData;
|
||||
try {
|
||||
rawData = await store.get(keyPrefixed);
|
||||
} catch (error) {
|
||||
if (this.throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const deserializedData = typeof rawData === "string" || this.opts.compression ? await this.deserializeData(rawData) : rawData;
|
||||
if (deserializedData === void 0 || deserializedData === null) {
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
if (isDataExpired(deserializedData)) {
|
||||
await this.delete(key);
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: deserializedData
|
||||
});
|
||||
this.stats.hit();
|
||||
return options?.raw ? deserializedData : deserializedData.value;
|
||||
}
|
||||
async getMany(keys, options) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
this.hooks.trigger("preGetMany" /* PRE_GET_MANY */, { keys: keyPrefixed });
|
||||
if (store.getMany === void 0) {
|
||||
const promises = keyPrefixed.map(async (key) => {
|
||||
const rawData2 = await store.get(key);
|
||||
const deserializedRow = typeof rawData2 === "string" || this.opts.compression ? await this.deserializeData(rawData2) : rawData2;
|
||||
if (deserializedRow === void 0 || deserializedRow === null) {
|
||||
return void 0;
|
||||
}
|
||||
if (isDataExpired(deserializedRow)) {
|
||||
await this.delete(key);
|
||||
return void 0;
|
||||
}
|
||||
return options?.raw ? deserializedRow : deserializedRow.value;
|
||||
});
|
||||
const deserializedRows = await Promise.allSettled(promises);
|
||||
const result2 = deserializedRows.map(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
(row) => row.value
|
||||
);
|
||||
this.hooks.trigger("postGetMany" /* POST_GET_MANY */, result2);
|
||||
if (result2.length > 0) {
|
||||
this.stats.hit();
|
||||
}
|
||||
return result2;
|
||||
}
|
||||
const rawData = await store.getMany(keyPrefixed);
|
||||
const result = [];
|
||||
const expiredKeys = [];
|
||||
for (const index in rawData) {
|
||||
let row = rawData[index];
|
||||
if (typeof row === "string") {
|
||||
row = await this.deserializeData(row);
|
||||
}
|
||||
if (row === void 0 || row === null) {
|
||||
result.push(void 0);
|
||||
continue;
|
||||
}
|
||||
if (isDataExpired(row)) {
|
||||
expiredKeys.push(keys[index]);
|
||||
result.push(void 0);
|
||||
continue;
|
||||
}
|
||||
const value = options?.raw ? row : row.value;
|
||||
result.push(value);
|
||||
}
|
||||
if (expiredKeys.length > 0) {
|
||||
await this.deleteMany(expiredKeys);
|
||||
}
|
||||
this.hooks.trigger("postGetMany" /* POST_GET_MANY */, result);
|
||||
if (result.length > 0) {
|
||||
this.stats.hit();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
|
||||
* @param {string} key the key to get
|
||||
* @returns {Promise<StoredDataRaw<Value> | undefined>} will return a StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
async getRaw(key) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
this.hooks.trigger("preGetRaw" /* PRE_GET_RAW */, { key: keyPrefixed });
|
||||
const rawData = await store.get(keyPrefixed);
|
||||
if (rawData === void 0 || rawData === null) {
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
const deserializedData = typeof rawData === "string" || this.opts.compression ? await this.deserializeData(rawData) : rawData;
|
||||
if (deserializedData !== void 0 && deserializedData.expires !== void 0 && deserializedData.expires !== null && // biome-ignore lint/style/noNonNullAssertion: need to fix
|
||||
deserializedData.expires < Date.now()) {
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
await this.delete(key);
|
||||
return void 0;
|
||||
}
|
||||
this.stats.hit();
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: deserializedData
|
||||
});
|
||||
return deserializedData;
|
||||
}
|
||||
/**
|
||||
* Get the raw values of many keys. This is the replacement for setting raw to true in the getMany() method.
|
||||
* @param {string[]} keys the keys to get
|
||||
* @returns {Promise<Array<StoredDataRaw<Value>>>} will return an array of StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
async getManyRaw(keys) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
if (keys.length === 0) {
|
||||
const result2 = Array.from({ length: keys.length }).fill(
|
||||
void 0
|
||||
);
|
||||
this.stats.misses += keys.length;
|
||||
this.hooks.trigger("postGetManyRaw" /* POST_GET_MANY_RAW */, {
|
||||
keys: keyPrefixed,
|
||||
values: result2
|
||||
});
|
||||
return result2;
|
||||
}
|
||||
let result = [];
|
||||
if (store.getMany === void 0) {
|
||||
const promises = keyPrefixed.map(async (key) => {
|
||||
const rawData = await store.get(key);
|
||||
if (rawData !== void 0 && rawData !== null) {
|
||||
return this.deserializeData(rawData);
|
||||
}
|
||||
return void 0;
|
||||
});
|
||||
const deserializedRows = await Promise.allSettled(promises);
|
||||
result = deserializedRows.map(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
(row) => row.value
|
||||
);
|
||||
} else {
|
||||
const rawData = await store.getMany(keyPrefixed);
|
||||
for (const row of rawData) {
|
||||
if (row !== void 0 && row !== null) {
|
||||
result.push(await this.deserializeData(row));
|
||||
} else {
|
||||
result.push(void 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
const expiredKeys = [];
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
for (const [index, row] of result.entries()) {
|
||||
if (row !== void 0 && isDataExpired(row)) {
|
||||
expiredKeys.push(keyPrefixed[index]);
|
||||
result[index] = void 0;
|
||||
}
|
||||
}
|
||||
if (expiredKeys.length > 0) {
|
||||
await this.deleteMany(expiredKeys);
|
||||
}
|
||||
this.stats.hitsOrMisses(result);
|
||||
this.hooks.trigger("postGetManyRaw" /* POST_GET_MANY_RAW */, {
|
||||
keys: keyPrefixed,
|
||||
values: result
|
||||
});
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Set an item to the store
|
||||
* @param {string | Array<KeyvEntry>} key the key to use. If you pass in an array of KeyvEntry it will set many items
|
||||
* @param {Value} value the value of the key
|
||||
* @param {number} [ttl] time to live in milliseconds
|
||||
* @returns {boolean} if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
async set(key, value, ttl) {
|
||||
const data = { key, value, ttl };
|
||||
this.hooks.trigger("preSet" /* PRE_SET */, data);
|
||||
const keyPrefixed = this._getKeyPrefix(data.key);
|
||||
data.ttl ??= this._ttl;
|
||||
if (data.ttl === 0) {
|
||||
data.ttl = void 0;
|
||||
}
|
||||
const { store } = this.opts;
|
||||
const expires = typeof data.ttl === "number" ? Date.now() + data.ttl : void 0;
|
||||
if (typeof data.value === "symbol") {
|
||||
this.emit("error", "symbol cannot be serialized");
|
||||
throw new Error("symbol cannot be serialized");
|
||||
}
|
||||
const formattedValue = { value: data.value, expires };
|
||||
const serializedValue = await this.serializeData(formattedValue);
|
||||
let result = true;
|
||||
try {
|
||||
const value2 = await store.set(keyPrefixed, serializedValue, data.ttl);
|
||||
if (typeof value2 === "boolean") {
|
||||
result = value2;
|
||||
}
|
||||
} catch (error) {
|
||||
result = false;
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
this.hooks.trigger("postSet" /* POST_SET */, {
|
||||
key: keyPrefixed,
|
||||
value: serializedValue,
|
||||
ttl
|
||||
});
|
||||
this.stats.set();
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Set many items to the store
|
||||
* @param {Array<KeyvEntry>} entries the entries to set
|
||||
* @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
// biome-ignore lint/correctness/noUnusedVariables: type format
|
||||
async setMany(entries) {
|
||||
let results = [];
|
||||
try {
|
||||
if (this._store.setMany === void 0) {
|
||||
const promises = [];
|
||||
for (const entry of entries) {
|
||||
promises.push(this.set(entry.key, entry.value, entry.ttl));
|
||||
}
|
||||
const promiseResults = await Promise.all(promises);
|
||||
results = promiseResults;
|
||||
} else {
|
||||
const serializedEntries = await Promise.all(
|
||||
entries.map(async ({ key, value, ttl }) => {
|
||||
ttl ??= this._ttl;
|
||||
if (ttl === 0) {
|
||||
ttl = void 0;
|
||||
}
|
||||
const expires = typeof ttl === "number" ? Date.now() + ttl : void 0;
|
||||
if (typeof value === "symbol") {
|
||||
this.emit("error", "symbol cannot be serialized");
|
||||
throw new Error("symbol cannot be serialized");
|
||||
}
|
||||
const formattedValue = { value, expires };
|
||||
const serializedValue = await this.serializeData(formattedValue);
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
return { key: keyPrefixed, value: serializedValue, ttl };
|
||||
})
|
||||
);
|
||||
results = await this._store.setMany(serializedEntries);
|
||||
}
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
results = entries.map(() => false);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Delete an Entry
|
||||
* @param {string | string[]} key the key to be deleted. if an array it will delete many items
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
async delete(key) {
|
||||
const { store } = this.opts;
|
||||
if (Array.isArray(key)) {
|
||||
return this.deleteMany(key);
|
||||
}
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
this.hooks.trigger("preDelete" /* PRE_DELETE */, { key: keyPrefixed });
|
||||
let result = true;
|
||||
try {
|
||||
const value = await store.delete(keyPrefixed);
|
||||
if (typeof value === "boolean") {
|
||||
result = value;
|
||||
}
|
||||
} catch (error) {
|
||||
result = false;
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
this.hooks.trigger("postDelete" /* POST_DELETE */, {
|
||||
key: keyPrefixed,
|
||||
value: result
|
||||
});
|
||||
this.stats.delete();
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Delete many items from the store
|
||||
* @param {string[]} keys the keys to be deleted
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
async deleteMany(keys) {
|
||||
try {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
this.hooks.trigger("preDelete" /* PRE_DELETE */, { key: keyPrefixed });
|
||||
if (store.deleteMany !== void 0) {
|
||||
return await store.deleteMany(keyPrefixed);
|
||||
}
|
||||
const promises = keyPrefixed.map(async (key) => store.delete(key));
|
||||
const results = await Promise.all(promises);
|
||||
const returnResult = results.every(Boolean);
|
||||
this.hooks.trigger("postDelete" /* POST_DELETE */, {
|
||||
key: keyPrefixed,
|
||||
value: returnResult
|
||||
});
|
||||
return returnResult;
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clear the store
|
||||
* @returns {void}
|
||||
*/
|
||||
async clear() {
|
||||
this.emit("clear");
|
||||
const { store } = this.opts;
|
||||
try {
|
||||
await store.clear();
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
async has(key) {
|
||||
if (Array.isArray(key)) {
|
||||
return this.hasMany(key);
|
||||
}
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
const { store } = this.opts;
|
||||
if (store.has !== void 0 && !(store instanceof Map)) {
|
||||
return store.has(keyPrefixed);
|
||||
}
|
||||
let rawData;
|
||||
try {
|
||||
rawData = await store.get(keyPrefixed);
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (rawData) {
|
||||
const data = await this.deserializeData(rawData);
|
||||
if (data) {
|
||||
if (data.expires === void 0 || data.expires === null) {
|
||||
return true;
|
||||
}
|
||||
return data.expires > Date.now();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Check if many keys exist
|
||||
* @param {string[]} keys the keys to check
|
||||
* @returns {boolean[]} will return an array of booleans if the keys exist
|
||||
*/
|
||||
async hasMany(keys) {
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
const { store } = this.opts;
|
||||
if (store.hasMany !== void 0) {
|
||||
return store.hasMany(keyPrefixed);
|
||||
}
|
||||
const results = [];
|
||||
for (const key of keys) {
|
||||
results.push(await this.has(key));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Will disconnect the store. This is only available if the store has a disconnect method
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async disconnect() {
|
||||
const { store } = this.opts;
|
||||
this.emit("disconnect");
|
||||
if (typeof store.disconnect === "function") {
|
||||
return store.disconnect();
|
||||
}
|
||||
}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
emit(event, ...arguments_) {
|
||||
if (event === "error" && !this.opts.emitErrors) {
|
||||
return;
|
||||
}
|
||||
super.emit(event, ...arguments_);
|
||||
}
|
||||
async serializeData(data) {
|
||||
if (!this._serialize) {
|
||||
return data;
|
||||
}
|
||||
if (this._compression?.compress) {
|
||||
return this._serialize({
|
||||
value: await this._compression.compress(data.value),
|
||||
expires: data.expires
|
||||
});
|
||||
}
|
||||
return this._serialize(data);
|
||||
}
|
||||
async deserializeData(data) {
|
||||
if (!this._deserialize) {
|
||||
return data;
|
||||
}
|
||||
if (this._compression?.decompress && typeof data === "string") {
|
||||
const result = await this._deserialize(data);
|
||||
return {
|
||||
value: await this._compression.decompress(result?.value),
|
||||
expires: result?.expires
|
||||
};
|
||||
}
|
||||
if (typeof data === "string") {
|
||||
return this._deserialize(data);
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
};
|
||||
var index_default = Keyv;
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Keyv,
|
||||
KeyvHooks
|
||||
});
|
||||
/* v8 ignore next -- @preserve */
|
||||
378
node_modules/keyv/dist/index.d.cts
generated
vendored
Normal file
378
node_modules/keyv/dist/index.d.cts
generated
vendored
Normal file
@@ -0,0 +1,378 @@
|
||||
type EventListener = (...arguments_: any[]) => void;
|
||||
declare class EventManager {
|
||||
_eventListeners: Map<string, EventListener[]>;
|
||||
_maxListeners: number;
|
||||
constructor();
|
||||
maxListeners(): number;
|
||||
addListener(event: string, listener: EventListener): void;
|
||||
on(event: string, listener: EventListener): this;
|
||||
removeListener(event: string, listener: EventListener): void;
|
||||
off(event: string, listener: EventListener): void;
|
||||
once(event: string, listener: EventListener): void;
|
||||
emit(event: string, ...arguments_: any[]): void;
|
||||
listeners(event: string): EventListener[];
|
||||
removeAllListeners(event?: string): void;
|
||||
setMaxListeners(n: number): void;
|
||||
}
|
||||
|
||||
type HookHandler = (...arguments_: any[]) => void;
|
||||
declare class HooksManager extends EventManager {
|
||||
_hookHandlers: Map<string, HookHandler[]>;
|
||||
constructor();
|
||||
addHandler(event: string, handler: HookHandler): void;
|
||||
removeHandler(event: string, handler: HookHandler): void;
|
||||
trigger(event: string, data: any): void;
|
||||
get handlers(): Map<string, HookHandler[]>;
|
||||
}
|
||||
|
||||
declare class StatsManager extends EventManager {
|
||||
enabled: boolean;
|
||||
hits: number;
|
||||
misses: number;
|
||||
sets: number;
|
||||
deletes: number;
|
||||
errors: number;
|
||||
constructor(enabled?: boolean);
|
||||
hit(): void;
|
||||
miss(): void;
|
||||
set(): void;
|
||||
delete(): void;
|
||||
hitsOrMisses<T>(array: Array<T | undefined>): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
type DeserializedData<Value> = {
|
||||
value?: Value;
|
||||
expires?: number | undefined;
|
||||
};
|
||||
type CompressionAdapter = {
|
||||
compress(value: any, options?: any): Promise<any>;
|
||||
decompress(value: any, options?: any): Promise<any>;
|
||||
serialize<Value>(data: DeserializedData<Value>): Promise<string> | string;
|
||||
deserialize<Value>(data: string): Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;
|
||||
};
|
||||
type Serialize = <Value>(data: DeserializedData<Value>) => Promise<string> | string;
|
||||
type Deserialize = <Value>(data: string) => Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;
|
||||
declare enum KeyvHooks {
|
||||
PRE_SET = "preSet",
|
||||
POST_SET = "postSet",
|
||||
PRE_GET = "preGet",
|
||||
POST_GET = "postGet",
|
||||
PRE_GET_MANY = "preGetMany",
|
||||
POST_GET_MANY = "postGetMany",
|
||||
PRE_GET_RAW = "preGetRaw",
|
||||
POST_GET_RAW = "postGetRaw",
|
||||
PRE_GET_MANY_RAW = "preGetManyRaw",
|
||||
POST_GET_MANY_RAW = "postGetManyRaw",
|
||||
PRE_DELETE = "preDelete",
|
||||
POST_DELETE = "postDelete"
|
||||
}
|
||||
type KeyvEntry = {
|
||||
/**
|
||||
* Key to set.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Value to set.
|
||||
*/
|
||||
value: any;
|
||||
/**
|
||||
* Time to live in milliseconds.
|
||||
*/
|
||||
ttl?: number;
|
||||
};
|
||||
type StoredDataNoRaw<Value> = Value | undefined;
|
||||
type StoredDataRaw<Value> = DeserializedData<Value> | undefined;
|
||||
type StoredData<Value> = StoredDataNoRaw<Value> | StoredDataRaw<Value>;
|
||||
type IEventEmitter = {
|
||||
on(event: string, listener: (...arguments_: any[]) => void): IEventEmitter;
|
||||
};
|
||||
type KeyvStoreAdapter = {
|
||||
opts: any;
|
||||
namespace?: string | undefined;
|
||||
get<Value>(key: string): Promise<StoredData<Value> | undefined>;
|
||||
set(key: string, value: any, ttl?: number): any;
|
||||
setMany?(values: Array<{
|
||||
key: string;
|
||||
value: any;
|
||||
ttl?: number;
|
||||
}>): Promise<void>;
|
||||
delete(key: string): Promise<boolean>;
|
||||
clear(): Promise<void>;
|
||||
has?(key: string): Promise<boolean>;
|
||||
hasMany?(keys: string[]): Promise<boolean[]>;
|
||||
getMany?<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
|
||||
disconnect?(): Promise<void>;
|
||||
deleteMany?(key: string[]): Promise<boolean>;
|
||||
iterator?<Value>(namespace?: string): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
|
||||
} & IEventEmitter;
|
||||
type KeyvOptions = {
|
||||
/**
|
||||
* Emit errors
|
||||
* @default true
|
||||
*/
|
||||
emitErrors?: boolean;
|
||||
/**
|
||||
* Namespace for the current instance.
|
||||
* @default 'keyv'
|
||||
*/
|
||||
namespace?: string;
|
||||
/**
|
||||
* A custom serialization function.
|
||||
* @default defaultSerialize using JSON.stringify
|
||||
*/
|
||||
serialize?: Serialize;
|
||||
/**
|
||||
* A custom deserialization function.
|
||||
* @default defaultDeserialize using JSON.parse
|
||||
*/
|
||||
deserialize?: Deserialize;
|
||||
/**
|
||||
* The storage adapter instance to be used by Keyv.
|
||||
* @default new Map() - in-memory store
|
||||
*/
|
||||
store?: KeyvStoreAdapter | Map<any, any> | any;
|
||||
/**
|
||||
* Default TTL in milliseconds. Can be overridden by specifying a TTL on `.set()`.
|
||||
* @default undefined
|
||||
*/
|
||||
ttl?: number;
|
||||
/**
|
||||
* Enable compression option
|
||||
* @default false
|
||||
*/
|
||||
compression?: CompressionAdapter | any;
|
||||
/**
|
||||
* Enable or disable statistics (default is false)
|
||||
* @default false
|
||||
*/
|
||||
stats?: boolean;
|
||||
/**
|
||||
* Enable or disable key prefixing (default is true)
|
||||
* @default true
|
||||
*/
|
||||
useKeyPrefix?: boolean;
|
||||
/**
|
||||
* Will enable throwing errors on methods in addition to emitting them.
|
||||
* @default false
|
||||
*/
|
||||
throwOnErrors?: boolean;
|
||||
};
|
||||
type KeyvOptions_ = Omit<KeyvOptions, "store"> & {
|
||||
store: KeyvStoreAdapter | (Map<any, any> & KeyvStoreAdapter);
|
||||
};
|
||||
type IteratorFunction = (argument: any) => AsyncGenerator<any, void>;
|
||||
declare class Keyv<GenericValue = any> extends EventManager {
|
||||
opts: KeyvOptions_;
|
||||
iterator?: IteratorFunction;
|
||||
hooks: HooksManager;
|
||||
stats: StatsManager;
|
||||
/**
|
||||
* Time to live in milliseconds
|
||||
*/
|
||||
private _ttl?;
|
||||
/**
|
||||
* Namespace
|
||||
*/
|
||||
private _namespace?;
|
||||
/**
|
||||
* Store
|
||||
*/
|
||||
private _store;
|
||||
private _serialize;
|
||||
private _deserialize;
|
||||
private _compression;
|
||||
private _useKeyPrefix;
|
||||
private _throwOnErrors;
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvStoreAdapter | KeyvOptions | Map<any, any>} store to be provided or just the options
|
||||
* @param {Omit<KeyvOptions, 'store'>} [options] if you provide the store you can then provide the Keyv Options
|
||||
*/
|
||||
constructor(store?: KeyvStoreAdapter | KeyvOptions | Map<any, any>, options?: Omit<KeyvOptions, "store">);
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvOptions} options to be provided
|
||||
*/
|
||||
constructor(options?: KeyvOptions);
|
||||
/**
|
||||
* Get the current store
|
||||
*/
|
||||
get store(): KeyvStoreAdapter | Map<any, any> | any;
|
||||
/**
|
||||
* Set the current store. This will also set the namespace, event error handler, and generate the iterator. If the store is not valid it will throw an error.
|
||||
* @param {KeyvStoreAdapter | Map<any, any> | any} store the store to set
|
||||
*/
|
||||
set store(store: KeyvStoreAdapter | Map<any, any> | any);
|
||||
/**
|
||||
* Get the current compression function
|
||||
* @returns {CompressionAdapter} The current compression function
|
||||
*/
|
||||
get compression(): CompressionAdapter | undefined;
|
||||
/**
|
||||
* Set the current compression function
|
||||
* @param {CompressionAdapter} compress The compression function to set
|
||||
*/
|
||||
set compression(compress: CompressionAdapter | undefined);
|
||||
/**
|
||||
* Get the current namespace.
|
||||
* @returns {string | undefined} The current namespace.
|
||||
*/
|
||||
get namespace(): string | undefined;
|
||||
/**
|
||||
* Set the current namespace.
|
||||
* @param {string | undefined} namespace The namespace to set.
|
||||
*/
|
||||
set namespace(namespace: string | undefined);
|
||||
/**
|
||||
* Get the current TTL.
|
||||
* @returns {number} The current TTL in milliseconds.
|
||||
*/
|
||||
get ttl(): number | undefined;
|
||||
/**
|
||||
* Set the current TTL.
|
||||
* @param {number} ttl The TTL to set in milliseconds.
|
||||
*/
|
||||
set ttl(ttl: number | undefined);
|
||||
/**
|
||||
* Get the current serialize function.
|
||||
* @returns {Serialize} The current serialize function.
|
||||
*/
|
||||
get serialize(): Serialize | undefined;
|
||||
/**
|
||||
* Set the current serialize function.
|
||||
* @param {Serialize} serialize The serialize function to set.
|
||||
*/
|
||||
set serialize(serialize: Serialize | undefined);
|
||||
/**
|
||||
* Get the current deserialize function.
|
||||
* @returns {Deserialize} The current deserialize function.
|
||||
*/
|
||||
get deserialize(): Deserialize | undefined;
|
||||
/**
|
||||
* Set the current deserialize function.
|
||||
* @param {Deserialize} deserialize The deserialize function to set.
|
||||
*/
|
||||
set deserialize(deserialize: Deserialize | undefined);
|
||||
/**
|
||||
* Get the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @returns {boolean} The current useKeyPrefix value.
|
||||
* @default true
|
||||
*/
|
||||
get useKeyPrefix(): boolean;
|
||||
/**
|
||||
* Set the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @param {boolean} value The useKeyPrefix value to set.
|
||||
*/
|
||||
set useKeyPrefix(value: boolean);
|
||||
/**
|
||||
* Get the current throwErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @return {boolean} The current throwOnErrors value.
|
||||
*/
|
||||
get throwOnErrors(): boolean;
|
||||
/**
|
||||
* Set the current throwOnErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @param {boolean} value The throwOnErrors value to set.
|
||||
*/
|
||||
set throwOnErrors(value: boolean);
|
||||
generateIterator(iterator: IteratorFunction): IteratorFunction;
|
||||
_checkIterableAdapter(): boolean;
|
||||
_getKeyPrefix(key: string): string;
|
||||
_getKeyPrefixArray(keys: string[]): string[];
|
||||
_getKeyUnprefix(key: string): string;
|
||||
_isValidStorageAdapter(store: KeyvStoreAdapter | any): boolean;
|
||||
/**
|
||||
* Get the Value of a Key
|
||||
* @param {string | string[]} key passing in a single key or multiple as an array
|
||||
* @param {{raw: boolean} | undefined} options can pass in to return the raw value by setting { raw: true }
|
||||
*/
|
||||
get<Value = GenericValue>(key: string, options?: {
|
||||
raw: false;
|
||||
}): Promise<StoredDataNoRaw<Value>>;
|
||||
get<Value = GenericValue>(key: string, options?: {
|
||||
raw: true;
|
||||
}): Promise<StoredDataRaw<Value>>;
|
||||
get<Value = GenericValue>(key: string[], options?: {
|
||||
raw: false;
|
||||
}): Promise<Array<StoredDataNoRaw<Value>>>;
|
||||
get<Value = GenericValue>(key: string[], options?: {
|
||||
raw: true;
|
||||
}): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Get many values of keys
|
||||
* @param {string[]} keys passing in a single key or multiple as an array
|
||||
* @param {{raw: boolean} | undefined} options can pass in to return the raw value by setting { raw: true }
|
||||
*/
|
||||
getMany<Value = GenericValue>(keys: string[], options?: {
|
||||
raw: false;
|
||||
}): Promise<Array<StoredDataNoRaw<Value>>>;
|
||||
getMany<Value = GenericValue>(keys: string[], options?: {
|
||||
raw: true;
|
||||
}): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
|
||||
* @param {string} key the key to get
|
||||
* @returns {Promise<StoredDataRaw<Value> | undefined>} will return a StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
getRaw<Value = GenericValue>(key: string): Promise<StoredDataRaw<Value> | undefined>;
|
||||
/**
|
||||
* Get the raw values of many keys. This is the replacement for setting raw to true in the getMany() method.
|
||||
* @param {string[]} keys the keys to get
|
||||
* @returns {Promise<Array<StoredDataRaw<Value>>>} will return an array of StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
getManyRaw<Value = GenericValue>(keys: string[]): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Set an item to the store
|
||||
* @param {string | Array<KeyvEntry>} key the key to use. If you pass in an array of KeyvEntry it will set many items
|
||||
* @param {Value} value the value of the key
|
||||
* @param {number} [ttl] time to live in milliseconds
|
||||
* @returns {boolean} if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
set<Value = GenericValue>(key: string, value: Value, ttl?: number): Promise<boolean>;
|
||||
/**
|
||||
* Set many items to the store
|
||||
* @param {Array<KeyvEntry>} entries the entries to set
|
||||
* @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
setMany<Value = GenericValue>(entries: KeyvEntry[]): Promise<boolean[]>;
|
||||
/**
|
||||
* Delete an Entry
|
||||
* @param {string | string[]} key the key to be deleted. if an array it will delete many items
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
delete(key: string | string[]): Promise<boolean>;
|
||||
/**
|
||||
* Delete many items from the store
|
||||
* @param {string[]} keys the keys to be deleted
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
deleteMany(keys: string[]): Promise<boolean>;
|
||||
/**
|
||||
* Clear the store
|
||||
* @returns {void}
|
||||
*/
|
||||
clear(): Promise<void>;
|
||||
/**
|
||||
* Has a key
|
||||
* @param {string} key the key to check
|
||||
* @returns {boolean} will return true if the key exists
|
||||
*/
|
||||
has(key: string[]): Promise<boolean[]>;
|
||||
has(key: string): Promise<boolean>;
|
||||
/**
|
||||
* Check if many keys exist
|
||||
* @param {string[]} keys the keys to check
|
||||
* @returns {boolean[]} will return an array of booleans if the keys exist
|
||||
*/
|
||||
hasMany(keys: string[]): Promise<boolean[]>;
|
||||
/**
|
||||
* Will disconnect the store. This is only available if the store has a disconnect method
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
disconnect(): Promise<void>;
|
||||
emit(event: string, ...arguments_: any[]): void;
|
||||
serializeData<T>(data: DeserializedData<T>): Promise<string | DeserializedData<T>>;
|
||||
deserializeData<T>(data: string | DeserializedData<T>): Promise<DeserializedData<T> | undefined>;
|
||||
}
|
||||
|
||||
export { type CompressionAdapter, type Deserialize, type DeserializedData, type IEventEmitter, Keyv, type KeyvEntry, KeyvHooks, type KeyvOptions, type KeyvStoreAdapter, type Serialize, type StoredData, type StoredDataNoRaw, type StoredDataRaw, Keyv as default };
|
||||
378
node_modules/keyv/dist/index.d.ts
generated
vendored
Normal file
378
node_modules/keyv/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,378 @@
|
||||
type EventListener = (...arguments_: any[]) => void;
|
||||
declare class EventManager {
|
||||
_eventListeners: Map<string, EventListener[]>;
|
||||
_maxListeners: number;
|
||||
constructor();
|
||||
maxListeners(): number;
|
||||
addListener(event: string, listener: EventListener): void;
|
||||
on(event: string, listener: EventListener): this;
|
||||
removeListener(event: string, listener: EventListener): void;
|
||||
off(event: string, listener: EventListener): void;
|
||||
once(event: string, listener: EventListener): void;
|
||||
emit(event: string, ...arguments_: any[]): void;
|
||||
listeners(event: string): EventListener[];
|
||||
removeAllListeners(event?: string): void;
|
||||
setMaxListeners(n: number): void;
|
||||
}
|
||||
|
||||
type HookHandler = (...arguments_: any[]) => void;
|
||||
declare class HooksManager extends EventManager {
|
||||
_hookHandlers: Map<string, HookHandler[]>;
|
||||
constructor();
|
||||
addHandler(event: string, handler: HookHandler): void;
|
||||
removeHandler(event: string, handler: HookHandler): void;
|
||||
trigger(event: string, data: any): void;
|
||||
get handlers(): Map<string, HookHandler[]>;
|
||||
}
|
||||
|
||||
declare class StatsManager extends EventManager {
|
||||
enabled: boolean;
|
||||
hits: number;
|
||||
misses: number;
|
||||
sets: number;
|
||||
deletes: number;
|
||||
errors: number;
|
||||
constructor(enabled?: boolean);
|
||||
hit(): void;
|
||||
miss(): void;
|
||||
set(): void;
|
||||
delete(): void;
|
||||
hitsOrMisses<T>(array: Array<T | undefined>): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
type DeserializedData<Value> = {
|
||||
value?: Value;
|
||||
expires?: number | undefined;
|
||||
};
|
||||
type CompressionAdapter = {
|
||||
compress(value: any, options?: any): Promise<any>;
|
||||
decompress(value: any, options?: any): Promise<any>;
|
||||
serialize<Value>(data: DeserializedData<Value>): Promise<string> | string;
|
||||
deserialize<Value>(data: string): Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;
|
||||
};
|
||||
type Serialize = <Value>(data: DeserializedData<Value>) => Promise<string> | string;
|
||||
type Deserialize = <Value>(data: string) => Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;
|
||||
declare enum KeyvHooks {
|
||||
PRE_SET = "preSet",
|
||||
POST_SET = "postSet",
|
||||
PRE_GET = "preGet",
|
||||
POST_GET = "postGet",
|
||||
PRE_GET_MANY = "preGetMany",
|
||||
POST_GET_MANY = "postGetMany",
|
||||
PRE_GET_RAW = "preGetRaw",
|
||||
POST_GET_RAW = "postGetRaw",
|
||||
PRE_GET_MANY_RAW = "preGetManyRaw",
|
||||
POST_GET_MANY_RAW = "postGetManyRaw",
|
||||
PRE_DELETE = "preDelete",
|
||||
POST_DELETE = "postDelete"
|
||||
}
|
||||
type KeyvEntry = {
|
||||
/**
|
||||
* Key to set.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Value to set.
|
||||
*/
|
||||
value: any;
|
||||
/**
|
||||
* Time to live in milliseconds.
|
||||
*/
|
||||
ttl?: number;
|
||||
};
|
||||
type StoredDataNoRaw<Value> = Value | undefined;
|
||||
type StoredDataRaw<Value> = DeserializedData<Value> | undefined;
|
||||
type StoredData<Value> = StoredDataNoRaw<Value> | StoredDataRaw<Value>;
|
||||
type IEventEmitter = {
|
||||
on(event: string, listener: (...arguments_: any[]) => void): IEventEmitter;
|
||||
};
|
||||
type KeyvStoreAdapter = {
|
||||
opts: any;
|
||||
namespace?: string | undefined;
|
||||
get<Value>(key: string): Promise<StoredData<Value> | undefined>;
|
||||
set(key: string, value: any, ttl?: number): any;
|
||||
setMany?(values: Array<{
|
||||
key: string;
|
||||
value: any;
|
||||
ttl?: number;
|
||||
}>): Promise<void>;
|
||||
delete(key: string): Promise<boolean>;
|
||||
clear(): Promise<void>;
|
||||
has?(key: string): Promise<boolean>;
|
||||
hasMany?(keys: string[]): Promise<boolean[]>;
|
||||
getMany?<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
|
||||
disconnect?(): Promise<void>;
|
||||
deleteMany?(key: string[]): Promise<boolean>;
|
||||
iterator?<Value>(namespace?: string): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
|
||||
} & IEventEmitter;
|
||||
type KeyvOptions = {
|
||||
/**
|
||||
* Emit errors
|
||||
* @default true
|
||||
*/
|
||||
emitErrors?: boolean;
|
||||
/**
|
||||
* Namespace for the current instance.
|
||||
* @default 'keyv'
|
||||
*/
|
||||
namespace?: string;
|
||||
/**
|
||||
* A custom serialization function.
|
||||
* @default defaultSerialize using JSON.stringify
|
||||
*/
|
||||
serialize?: Serialize;
|
||||
/**
|
||||
* A custom deserialization function.
|
||||
* @default defaultDeserialize using JSON.parse
|
||||
*/
|
||||
deserialize?: Deserialize;
|
||||
/**
|
||||
* The storage adapter instance to be used by Keyv.
|
||||
* @default new Map() - in-memory store
|
||||
*/
|
||||
store?: KeyvStoreAdapter | Map<any, any> | any;
|
||||
/**
|
||||
* Default TTL in milliseconds. Can be overridden by specifying a TTL on `.set()`.
|
||||
* @default undefined
|
||||
*/
|
||||
ttl?: number;
|
||||
/**
|
||||
* Enable compression option
|
||||
* @default false
|
||||
*/
|
||||
compression?: CompressionAdapter | any;
|
||||
/**
|
||||
* Enable or disable statistics (default is false)
|
||||
* @default false
|
||||
*/
|
||||
stats?: boolean;
|
||||
/**
|
||||
* Enable or disable key prefixing (default is true)
|
||||
* @default true
|
||||
*/
|
||||
useKeyPrefix?: boolean;
|
||||
/**
|
||||
* Will enable throwing errors on methods in addition to emitting them.
|
||||
* @default false
|
||||
*/
|
||||
throwOnErrors?: boolean;
|
||||
};
|
||||
type KeyvOptions_ = Omit<KeyvOptions, "store"> & {
|
||||
store: KeyvStoreAdapter | (Map<any, any> & KeyvStoreAdapter);
|
||||
};
|
||||
type IteratorFunction = (argument: any) => AsyncGenerator<any, void>;
|
||||
declare class Keyv<GenericValue = any> extends EventManager {
|
||||
opts: KeyvOptions_;
|
||||
iterator?: IteratorFunction;
|
||||
hooks: HooksManager;
|
||||
stats: StatsManager;
|
||||
/**
|
||||
* Time to live in milliseconds
|
||||
*/
|
||||
private _ttl?;
|
||||
/**
|
||||
* Namespace
|
||||
*/
|
||||
private _namespace?;
|
||||
/**
|
||||
* Store
|
||||
*/
|
||||
private _store;
|
||||
private _serialize;
|
||||
private _deserialize;
|
||||
private _compression;
|
||||
private _useKeyPrefix;
|
||||
private _throwOnErrors;
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvStoreAdapter | KeyvOptions | Map<any, any>} store to be provided or just the options
|
||||
* @param {Omit<KeyvOptions, 'store'>} [options] if you provide the store you can then provide the Keyv Options
|
||||
*/
|
||||
constructor(store?: KeyvStoreAdapter | KeyvOptions | Map<any, any>, options?: Omit<KeyvOptions, "store">);
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvOptions} options to be provided
|
||||
*/
|
||||
constructor(options?: KeyvOptions);
|
||||
/**
|
||||
* Get the current store
|
||||
*/
|
||||
get store(): KeyvStoreAdapter | Map<any, any> | any;
|
||||
/**
|
||||
* Set the current store. This will also set the namespace, event error handler, and generate the iterator. If the store is not valid it will throw an error.
|
||||
* @param {KeyvStoreAdapter | Map<any, any> | any} store the store to set
|
||||
*/
|
||||
set store(store: KeyvStoreAdapter | Map<any, any> | any);
|
||||
/**
|
||||
* Get the current compression function
|
||||
* @returns {CompressionAdapter} The current compression function
|
||||
*/
|
||||
get compression(): CompressionAdapter | undefined;
|
||||
/**
|
||||
* Set the current compression function
|
||||
* @param {CompressionAdapter} compress The compression function to set
|
||||
*/
|
||||
set compression(compress: CompressionAdapter | undefined);
|
||||
/**
|
||||
* Get the current namespace.
|
||||
* @returns {string | undefined} The current namespace.
|
||||
*/
|
||||
get namespace(): string | undefined;
|
||||
/**
|
||||
* Set the current namespace.
|
||||
* @param {string | undefined} namespace The namespace to set.
|
||||
*/
|
||||
set namespace(namespace: string | undefined);
|
||||
/**
|
||||
* Get the current TTL.
|
||||
* @returns {number} The current TTL in milliseconds.
|
||||
*/
|
||||
get ttl(): number | undefined;
|
||||
/**
|
||||
* Set the current TTL.
|
||||
* @param {number} ttl The TTL to set in milliseconds.
|
||||
*/
|
||||
set ttl(ttl: number | undefined);
|
||||
/**
|
||||
* Get the current serialize function.
|
||||
* @returns {Serialize} The current serialize function.
|
||||
*/
|
||||
get serialize(): Serialize | undefined;
|
||||
/**
|
||||
* Set the current serialize function.
|
||||
* @param {Serialize} serialize The serialize function to set.
|
||||
*/
|
||||
set serialize(serialize: Serialize | undefined);
|
||||
/**
|
||||
* Get the current deserialize function.
|
||||
* @returns {Deserialize} The current deserialize function.
|
||||
*/
|
||||
get deserialize(): Deserialize | undefined;
|
||||
/**
|
||||
* Set the current deserialize function.
|
||||
* @param {Deserialize} deserialize The deserialize function to set.
|
||||
*/
|
||||
set deserialize(deserialize: Deserialize | undefined);
|
||||
/**
|
||||
* Get the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @returns {boolean} The current useKeyPrefix value.
|
||||
* @default true
|
||||
*/
|
||||
get useKeyPrefix(): boolean;
|
||||
/**
|
||||
* Set the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @param {boolean} value The useKeyPrefix value to set.
|
||||
*/
|
||||
set useKeyPrefix(value: boolean);
|
||||
/**
|
||||
* Get the current throwErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @return {boolean} The current throwOnErrors value.
|
||||
*/
|
||||
get throwOnErrors(): boolean;
|
||||
/**
|
||||
* Set the current throwOnErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @param {boolean} value The throwOnErrors value to set.
|
||||
*/
|
||||
set throwOnErrors(value: boolean);
|
||||
generateIterator(iterator: IteratorFunction): IteratorFunction;
|
||||
_checkIterableAdapter(): boolean;
|
||||
_getKeyPrefix(key: string): string;
|
||||
_getKeyPrefixArray(keys: string[]): string[];
|
||||
_getKeyUnprefix(key: string): string;
|
||||
_isValidStorageAdapter(store: KeyvStoreAdapter | any): boolean;
|
||||
/**
|
||||
* Get the Value of a Key
|
||||
* @param {string | string[]} key passing in a single key or multiple as an array
|
||||
* @param {{raw: boolean} | undefined} options can pass in to return the raw value by setting { raw: true }
|
||||
*/
|
||||
get<Value = GenericValue>(key: string, options?: {
|
||||
raw: false;
|
||||
}): Promise<StoredDataNoRaw<Value>>;
|
||||
get<Value = GenericValue>(key: string, options?: {
|
||||
raw: true;
|
||||
}): Promise<StoredDataRaw<Value>>;
|
||||
get<Value = GenericValue>(key: string[], options?: {
|
||||
raw: false;
|
||||
}): Promise<Array<StoredDataNoRaw<Value>>>;
|
||||
get<Value = GenericValue>(key: string[], options?: {
|
||||
raw: true;
|
||||
}): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Get many values of keys
|
||||
* @param {string[]} keys passing in a single key or multiple as an array
|
||||
* @param {{raw: boolean} | undefined} options can pass in to return the raw value by setting { raw: true }
|
||||
*/
|
||||
getMany<Value = GenericValue>(keys: string[], options?: {
|
||||
raw: false;
|
||||
}): Promise<Array<StoredDataNoRaw<Value>>>;
|
||||
getMany<Value = GenericValue>(keys: string[], options?: {
|
||||
raw: true;
|
||||
}): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
|
||||
* @param {string} key the key to get
|
||||
* @returns {Promise<StoredDataRaw<Value> | undefined>} will return a StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
getRaw<Value = GenericValue>(key: string): Promise<StoredDataRaw<Value> | undefined>;
|
||||
/**
|
||||
* Get the raw values of many keys. This is the replacement for setting raw to true in the getMany() method.
|
||||
* @param {string[]} keys the keys to get
|
||||
* @returns {Promise<Array<StoredDataRaw<Value>>>} will return an array of StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
getManyRaw<Value = GenericValue>(keys: string[]): Promise<Array<StoredDataRaw<Value>>>;
|
||||
/**
|
||||
* Set an item to the store
|
||||
* @param {string | Array<KeyvEntry>} key the key to use. If you pass in an array of KeyvEntry it will set many items
|
||||
* @param {Value} value the value of the key
|
||||
* @param {number} [ttl] time to live in milliseconds
|
||||
* @returns {boolean} if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
set<Value = GenericValue>(key: string, value: Value, ttl?: number): Promise<boolean>;
|
||||
/**
|
||||
* Set many items to the store
|
||||
* @param {Array<KeyvEntry>} entries the entries to set
|
||||
* @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
setMany<Value = GenericValue>(entries: KeyvEntry[]): Promise<boolean[]>;
|
||||
/**
|
||||
* Delete an Entry
|
||||
* @param {string | string[]} key the key to be deleted. if an array it will delete many items
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
delete(key: string | string[]): Promise<boolean>;
|
||||
/**
|
||||
* Delete many items from the store
|
||||
* @param {string[]} keys the keys to be deleted
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
deleteMany(keys: string[]): Promise<boolean>;
|
||||
/**
|
||||
* Clear the store
|
||||
* @returns {void}
|
||||
*/
|
||||
clear(): Promise<void>;
|
||||
/**
|
||||
* Has a key
|
||||
* @param {string} key the key to check
|
||||
* @returns {boolean} will return true if the key exists
|
||||
*/
|
||||
has(key: string[]): Promise<boolean[]>;
|
||||
has(key: string): Promise<boolean>;
|
||||
/**
|
||||
* Check if many keys exist
|
||||
* @param {string[]} keys the keys to check
|
||||
* @returns {boolean[]} will return an array of booleans if the keys exist
|
||||
*/
|
||||
hasMany(keys: string[]): Promise<boolean[]>;
|
||||
/**
|
||||
* Will disconnect the store. This is only available if the store has a disconnect method
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
disconnect(): Promise<void>;
|
||||
emit(event: string, ...arguments_: any[]): void;
|
||||
serializeData<T>(data: DeserializedData<T>): Promise<string | DeserializedData<T>>;
|
||||
deserializeData<T>(data: string | DeserializedData<T>): Promise<DeserializedData<T> | undefined>;
|
||||
}
|
||||
|
||||
export { type CompressionAdapter, type Deserialize, type DeserializedData, type IEventEmitter, Keyv, type KeyvEntry, KeyvHooks, type KeyvOptions, type KeyvStoreAdapter, type Serialize, type StoredData, type StoredDataNoRaw, type StoredDataRaw, Keyv as default };
|
||||
964
node_modules/keyv/dist/index.js
generated
vendored
Normal file
964
node_modules/keyv/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,964 @@
|
||||
// src/index.ts
|
||||
import { defaultDeserialize, defaultSerialize } from "@keyv/serialize";
|
||||
|
||||
// src/event-manager.ts
|
||||
var EventManager = class {
|
||||
_eventListeners;
|
||||
_maxListeners;
|
||||
constructor() {
|
||||
this._eventListeners = /* @__PURE__ */ new Map();
|
||||
this._maxListeners = 100;
|
||||
}
|
||||
maxListeners() {
|
||||
return this._maxListeners;
|
||||
}
|
||||
// Add an event listener
|
||||
addListener(event, listener) {
|
||||
this.on(event, listener);
|
||||
}
|
||||
on(event, listener) {
|
||||
if (!this._eventListeners.has(event)) {
|
||||
this._eventListeners.set(event, []);
|
||||
}
|
||||
const listeners = this._eventListeners.get(event);
|
||||
if (listeners) {
|
||||
if (listeners.length >= this._maxListeners) {
|
||||
console.warn(
|
||||
`MaxListenersExceededWarning: Possible event memory leak detected. ${listeners.length + 1} ${event} listeners added. Use setMaxListeners() to increase limit.`
|
||||
);
|
||||
}
|
||||
listeners.push(listener);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
// Remove an event listener
|
||||
removeListener(event, listener) {
|
||||
this.off(event, listener);
|
||||
}
|
||||
off(event, listener) {
|
||||
const listeners = this._eventListeners.get(event) ?? [];
|
||||
const index = listeners.indexOf(listener);
|
||||
if (index !== -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
if (listeners.length === 0) {
|
||||
this._eventListeners.delete(event);
|
||||
}
|
||||
}
|
||||
once(event, listener) {
|
||||
const onceListener = (...arguments_) => {
|
||||
listener(...arguments_);
|
||||
this.off(event, onceListener);
|
||||
};
|
||||
this.on(event, onceListener);
|
||||
}
|
||||
// Emit an event
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
emit(event, ...arguments_) {
|
||||
const listeners = this._eventListeners.get(event);
|
||||
if (listeners && listeners.length > 0) {
|
||||
for (const listener of listeners) {
|
||||
listener(...arguments_);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get all listeners for a specific event
|
||||
listeners(event) {
|
||||
return this._eventListeners.get(event) ?? [];
|
||||
}
|
||||
// Remove all listeners for a specific event
|
||||
removeAllListeners(event) {
|
||||
if (event) {
|
||||
this._eventListeners.delete(event);
|
||||
} else {
|
||||
this._eventListeners.clear();
|
||||
}
|
||||
}
|
||||
// Set the maximum number of listeners for a single event
|
||||
setMaxListeners(n) {
|
||||
this._maxListeners = n;
|
||||
}
|
||||
};
|
||||
var event_manager_default = EventManager;
|
||||
|
||||
// src/hooks-manager.ts
|
||||
var HooksManager = class extends event_manager_default {
|
||||
_hookHandlers;
|
||||
constructor() {
|
||||
super();
|
||||
this._hookHandlers = /* @__PURE__ */ new Map();
|
||||
}
|
||||
// Adds a handler function for a specific event
|
||||
addHandler(event, handler) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
eventHandlers.push(handler);
|
||||
} else {
|
||||
this._hookHandlers.set(event, [handler]);
|
||||
}
|
||||
}
|
||||
// Removes a specific handler function for a specific event
|
||||
removeHandler(event, handler) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
const index = eventHandlers.indexOf(handler);
|
||||
if (index !== -1) {
|
||||
eventHandlers.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Triggers all handlers for a specific event with provided data
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
trigger(event, data) {
|
||||
const eventHandlers = this._hookHandlers.get(event);
|
||||
if (eventHandlers) {
|
||||
for (const handler of eventHandlers) {
|
||||
try {
|
||||
handler(data);
|
||||
} catch (error) {
|
||||
this.emit(
|
||||
"error",
|
||||
new Error(
|
||||
`Error in hook handler for event "${event}": ${error.message}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Provides read-only access to the current handlers
|
||||
get handlers() {
|
||||
return new Map(this._hookHandlers);
|
||||
}
|
||||
};
|
||||
var hooks_manager_default = HooksManager;
|
||||
|
||||
// src/stats-manager.ts
|
||||
var StatsManager = class extends event_manager_default {
|
||||
enabled = true;
|
||||
hits = 0;
|
||||
misses = 0;
|
||||
sets = 0;
|
||||
deletes = 0;
|
||||
errors = 0;
|
||||
constructor(enabled) {
|
||||
super();
|
||||
if (enabled !== void 0) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
this.reset();
|
||||
}
|
||||
hit() {
|
||||
if (this.enabled) {
|
||||
this.hits++;
|
||||
}
|
||||
}
|
||||
miss() {
|
||||
if (this.enabled) {
|
||||
this.misses++;
|
||||
}
|
||||
}
|
||||
set() {
|
||||
if (this.enabled) {
|
||||
this.sets++;
|
||||
}
|
||||
}
|
||||
delete() {
|
||||
if (this.enabled) {
|
||||
this.deletes++;
|
||||
}
|
||||
}
|
||||
hitsOrMisses(array) {
|
||||
for (const item of array) {
|
||||
if (item === void 0) {
|
||||
this.miss();
|
||||
} else {
|
||||
this.hit();
|
||||
}
|
||||
}
|
||||
}
|
||||
reset() {
|
||||
this.hits = 0;
|
||||
this.misses = 0;
|
||||
this.sets = 0;
|
||||
this.deletes = 0;
|
||||
this.errors = 0;
|
||||
}
|
||||
};
|
||||
var stats_manager_default = StatsManager;
|
||||
|
||||
// src/index.ts
|
||||
var KeyvHooks = /* @__PURE__ */ ((KeyvHooks2) => {
|
||||
KeyvHooks2["PRE_SET"] = "preSet";
|
||||
KeyvHooks2["POST_SET"] = "postSet";
|
||||
KeyvHooks2["PRE_GET"] = "preGet";
|
||||
KeyvHooks2["POST_GET"] = "postGet";
|
||||
KeyvHooks2["PRE_GET_MANY"] = "preGetMany";
|
||||
KeyvHooks2["POST_GET_MANY"] = "postGetMany";
|
||||
KeyvHooks2["PRE_GET_RAW"] = "preGetRaw";
|
||||
KeyvHooks2["POST_GET_RAW"] = "postGetRaw";
|
||||
KeyvHooks2["PRE_GET_MANY_RAW"] = "preGetManyRaw";
|
||||
KeyvHooks2["POST_GET_MANY_RAW"] = "postGetManyRaw";
|
||||
KeyvHooks2["PRE_DELETE"] = "preDelete";
|
||||
KeyvHooks2["POST_DELETE"] = "postDelete";
|
||||
return KeyvHooks2;
|
||||
})(KeyvHooks || {});
|
||||
var iterableAdapters = [
|
||||
"sqlite",
|
||||
"postgres",
|
||||
"mysql",
|
||||
"mongo",
|
||||
"redis",
|
||||
"valkey",
|
||||
"etcd"
|
||||
];
|
||||
var Keyv = class extends event_manager_default {
|
||||
opts;
|
||||
iterator;
|
||||
hooks = new hooks_manager_default();
|
||||
stats = new stats_manager_default(false);
|
||||
/**
|
||||
* Time to live in milliseconds
|
||||
*/
|
||||
_ttl;
|
||||
/**
|
||||
* Namespace
|
||||
*/
|
||||
_namespace;
|
||||
/**
|
||||
* Store
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
_store = /* @__PURE__ */ new Map();
|
||||
_serialize = defaultSerialize;
|
||||
_deserialize = defaultDeserialize;
|
||||
_compression;
|
||||
_useKeyPrefix = true;
|
||||
_throwOnErrors = false;
|
||||
/**
|
||||
* Keyv Constructor
|
||||
* @param {KeyvStoreAdapter | KeyvOptions} store
|
||||
* @param {Omit<KeyvOptions, 'store'>} [options] if you provide the store you can then provide the Keyv Options
|
||||
*/
|
||||
constructor(store, options) {
|
||||
super();
|
||||
options ??= {};
|
||||
store ??= {};
|
||||
this.opts = {
|
||||
namespace: "keyv",
|
||||
serialize: defaultSerialize,
|
||||
deserialize: defaultDeserialize,
|
||||
emitErrors: true,
|
||||
// @ts-expect-error - Map is not a KeyvStoreAdapter
|
||||
store: /* @__PURE__ */ new Map(),
|
||||
...options
|
||||
};
|
||||
if (store && store.get) {
|
||||
this.opts.store = store;
|
||||
} else {
|
||||
this.opts = {
|
||||
...this.opts,
|
||||
...store
|
||||
};
|
||||
}
|
||||
this._store = this.opts.store ?? /* @__PURE__ */ new Map();
|
||||
this._compression = this.opts.compression;
|
||||
this._serialize = this.opts.serialize;
|
||||
this._deserialize = this.opts.deserialize;
|
||||
if (this.opts.namespace) {
|
||||
this._namespace = this.opts.namespace;
|
||||
}
|
||||
if (this._store) {
|
||||
if (!this._isValidStorageAdapter(this._store)) {
|
||||
throw new Error("Invalid storage adapter");
|
||||
}
|
||||
if (typeof this._store.on === "function") {
|
||||
this._store.on("error", (error) => this.emit("error", error));
|
||||
}
|
||||
this._store.namespace = this._namespace;
|
||||
if (typeof this._store[Symbol.iterator] === "function" && this._store instanceof Map) {
|
||||
this.iterator = this.generateIterator(
|
||||
this._store
|
||||
);
|
||||
} else if ("iterator" in this._store && this._store.opts && this._checkIterableAdapter()) {
|
||||
this.iterator = this.generateIterator(
|
||||
// biome-ignore lint/style/noNonNullAssertion: need to fix
|
||||
this._store.iterator.bind(this._store)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (this.opts.stats) {
|
||||
this.stats.enabled = this.opts.stats;
|
||||
}
|
||||
if (this.opts.ttl) {
|
||||
this._ttl = this.opts.ttl;
|
||||
}
|
||||
if (this.opts.useKeyPrefix !== void 0) {
|
||||
this._useKeyPrefix = this.opts.useKeyPrefix;
|
||||
}
|
||||
if (this.opts.throwOnErrors !== void 0) {
|
||||
this._throwOnErrors = this.opts.throwOnErrors;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current store
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
get store() {
|
||||
return this._store;
|
||||
}
|
||||
/**
|
||||
* Set the current store. This will also set the namespace, event error handler, and generate the iterator. If the store is not valid it will throw an error.
|
||||
* @param {KeyvStoreAdapter | Map<any, any> | any} store the store to set
|
||||
*/
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
set store(store) {
|
||||
if (this._isValidStorageAdapter(store)) {
|
||||
this._store = store;
|
||||
this.opts.store = store;
|
||||
if (typeof store.on === "function") {
|
||||
store.on("error", (error) => this.emit("error", error));
|
||||
}
|
||||
if (this._namespace) {
|
||||
this._store.namespace = this._namespace;
|
||||
}
|
||||
if (typeof store[Symbol.iterator] === "function" && store instanceof Map) {
|
||||
this.iterator = this.generateIterator(
|
||||
store
|
||||
);
|
||||
} else if ("iterator" in store && store.opts && this._checkIterableAdapter()) {
|
||||
this.iterator = this.generateIterator(store.iterator?.bind(store));
|
||||
}
|
||||
} else {
|
||||
throw new Error("Invalid storage adapter");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current compression function
|
||||
* @returns {CompressionAdapter} The current compression function
|
||||
*/
|
||||
get compression() {
|
||||
return this._compression;
|
||||
}
|
||||
/**
|
||||
* Set the current compression function
|
||||
* @param {CompressionAdapter} compress The compression function to set
|
||||
*/
|
||||
set compression(compress) {
|
||||
this._compression = compress;
|
||||
}
|
||||
/**
|
||||
* Get the current namespace.
|
||||
* @returns {string | undefined} The current namespace.
|
||||
*/
|
||||
get namespace() {
|
||||
return this._namespace;
|
||||
}
|
||||
/**
|
||||
* Set the current namespace.
|
||||
* @param {string | undefined} namespace The namespace to set.
|
||||
*/
|
||||
set namespace(namespace) {
|
||||
this._namespace = namespace;
|
||||
this.opts.namespace = namespace;
|
||||
this._store.namespace = namespace;
|
||||
if (this.opts.store) {
|
||||
this.opts.store.namespace = namespace;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the current TTL.
|
||||
* @returns {number} The current TTL in milliseconds.
|
||||
*/
|
||||
get ttl() {
|
||||
return this._ttl;
|
||||
}
|
||||
/**
|
||||
* Set the current TTL.
|
||||
* @param {number} ttl The TTL to set in milliseconds.
|
||||
*/
|
||||
set ttl(ttl) {
|
||||
this.opts.ttl = ttl;
|
||||
this._ttl = ttl;
|
||||
}
|
||||
/**
|
||||
* Get the current serialize function.
|
||||
* @returns {Serialize} The current serialize function.
|
||||
*/
|
||||
get serialize() {
|
||||
return this._serialize;
|
||||
}
|
||||
/**
|
||||
* Set the current serialize function.
|
||||
* @param {Serialize} serialize The serialize function to set.
|
||||
*/
|
||||
set serialize(serialize) {
|
||||
this.opts.serialize = serialize;
|
||||
this._serialize = serialize;
|
||||
}
|
||||
/**
|
||||
* Get the current deserialize function.
|
||||
* @returns {Deserialize} The current deserialize function.
|
||||
*/
|
||||
get deserialize() {
|
||||
return this._deserialize;
|
||||
}
|
||||
/**
|
||||
* Set the current deserialize function.
|
||||
* @param {Deserialize} deserialize The deserialize function to set.
|
||||
*/
|
||||
set deserialize(deserialize) {
|
||||
this.opts.deserialize = deserialize;
|
||||
this._deserialize = deserialize;
|
||||
}
|
||||
/**
|
||||
* Get the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @returns {boolean} The current useKeyPrefix value.
|
||||
* @default true
|
||||
*/
|
||||
get useKeyPrefix() {
|
||||
return this._useKeyPrefix;
|
||||
}
|
||||
/**
|
||||
* Set the current useKeyPrefix value. This will enable or disable key prefixing.
|
||||
* @param {boolean} value The useKeyPrefix value to set.
|
||||
*/
|
||||
set useKeyPrefix(value) {
|
||||
this._useKeyPrefix = value;
|
||||
this.opts.useKeyPrefix = value;
|
||||
}
|
||||
/**
|
||||
* Get the current throwErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @return {boolean} The current throwOnErrors value.
|
||||
*/
|
||||
get throwOnErrors() {
|
||||
return this._throwOnErrors;
|
||||
}
|
||||
/**
|
||||
* Set the current throwOnErrors value. This will enable or disable throwing errors on methods in addition to emitting them.
|
||||
* @param {boolean} value The throwOnErrors value to set.
|
||||
*/
|
||||
set throwOnErrors(value) {
|
||||
this._throwOnErrors = value;
|
||||
this.opts.throwOnErrors = value;
|
||||
}
|
||||
generateIterator(iterator) {
|
||||
const function_ = async function* () {
|
||||
for await (const [key, raw] of typeof iterator === "function" ? iterator(this._store.namespace) : iterator) {
|
||||
const data = await this.deserializeData(raw);
|
||||
if (this._useKeyPrefix && this._store.namespace && !key.includes(this._store.namespace)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof data.expires === "number" && Date.now() > data.expires) {
|
||||
await this.delete(key);
|
||||
continue;
|
||||
}
|
||||
yield [this._getKeyUnprefix(key), data.value];
|
||||
}
|
||||
};
|
||||
return function_.bind(this);
|
||||
}
|
||||
_checkIterableAdapter() {
|
||||
return iterableAdapters.includes(this._store.opts.dialect) || iterableAdapters.some(
|
||||
(element) => this._store.opts.url.includes(element)
|
||||
);
|
||||
}
|
||||
_getKeyPrefix(key) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return key;
|
||||
}
|
||||
if (!this._namespace) {
|
||||
return key;
|
||||
}
|
||||
if (key.startsWith(`${this._namespace}:`)) {
|
||||
return key;
|
||||
}
|
||||
return `${this._namespace}:${key}`;
|
||||
}
|
||||
_getKeyPrefixArray(keys) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return keys;
|
||||
}
|
||||
if (!this._namespace) {
|
||||
return keys;
|
||||
}
|
||||
return keys.map((key) => `${this._namespace}:${key}`);
|
||||
}
|
||||
_getKeyUnprefix(key) {
|
||||
if (!this._useKeyPrefix) {
|
||||
return key;
|
||||
}
|
||||
return key.split(":").splice(1).join(":");
|
||||
}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
_isValidStorageAdapter(store) {
|
||||
return store instanceof Map || typeof store.get === "function" && typeof store.set === "function" && typeof store.delete === "function" && typeof store.clear === "function";
|
||||
}
|
||||
// eslint-disable-next-line @stylistic/max-len
|
||||
async get(key, options) {
|
||||
const { store } = this.opts;
|
||||
const isArray = Array.isArray(key);
|
||||
const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
if (isArray) {
|
||||
if (options?.raw === true) {
|
||||
return this.getMany(key, { raw: true });
|
||||
}
|
||||
return this.getMany(key, { raw: false });
|
||||
}
|
||||
this.hooks.trigger("preGet" /* PRE_GET */, { key: keyPrefixed });
|
||||
let rawData;
|
||||
try {
|
||||
rawData = await store.get(keyPrefixed);
|
||||
} catch (error) {
|
||||
if (this.throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const deserializedData = typeof rawData === "string" || this.opts.compression ? await this.deserializeData(rawData) : rawData;
|
||||
if (deserializedData === void 0 || deserializedData === null) {
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
if (isDataExpired(deserializedData)) {
|
||||
await this.delete(key);
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
this.hooks.trigger("postGet" /* POST_GET */, {
|
||||
key: keyPrefixed,
|
||||
value: deserializedData
|
||||
});
|
||||
this.stats.hit();
|
||||
return options?.raw ? deserializedData : deserializedData.value;
|
||||
}
|
||||
async getMany(keys, options) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
this.hooks.trigger("preGetMany" /* PRE_GET_MANY */, { keys: keyPrefixed });
|
||||
if (store.getMany === void 0) {
|
||||
const promises = keyPrefixed.map(async (key) => {
|
||||
const rawData2 = await store.get(key);
|
||||
const deserializedRow = typeof rawData2 === "string" || this.opts.compression ? await this.deserializeData(rawData2) : rawData2;
|
||||
if (deserializedRow === void 0 || deserializedRow === null) {
|
||||
return void 0;
|
||||
}
|
||||
if (isDataExpired(deserializedRow)) {
|
||||
await this.delete(key);
|
||||
return void 0;
|
||||
}
|
||||
return options?.raw ? deserializedRow : deserializedRow.value;
|
||||
});
|
||||
const deserializedRows = await Promise.allSettled(promises);
|
||||
const result2 = deserializedRows.map(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
(row) => row.value
|
||||
);
|
||||
this.hooks.trigger("postGetMany" /* POST_GET_MANY */, result2);
|
||||
if (result2.length > 0) {
|
||||
this.stats.hit();
|
||||
}
|
||||
return result2;
|
||||
}
|
||||
const rawData = await store.getMany(keyPrefixed);
|
||||
const result = [];
|
||||
const expiredKeys = [];
|
||||
for (const index in rawData) {
|
||||
let row = rawData[index];
|
||||
if (typeof row === "string") {
|
||||
row = await this.deserializeData(row);
|
||||
}
|
||||
if (row === void 0 || row === null) {
|
||||
result.push(void 0);
|
||||
continue;
|
||||
}
|
||||
if (isDataExpired(row)) {
|
||||
expiredKeys.push(keys[index]);
|
||||
result.push(void 0);
|
||||
continue;
|
||||
}
|
||||
const value = options?.raw ? row : row.value;
|
||||
result.push(value);
|
||||
}
|
||||
if (expiredKeys.length > 0) {
|
||||
await this.deleteMany(expiredKeys);
|
||||
}
|
||||
this.hooks.trigger("postGetMany" /* POST_GET_MANY */, result);
|
||||
if (result.length > 0) {
|
||||
this.stats.hit();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
|
||||
* @param {string} key the key to get
|
||||
* @returns {Promise<StoredDataRaw<Value> | undefined>} will return a StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
async getRaw(key) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
this.hooks.trigger("preGetRaw" /* PRE_GET_RAW */, { key: keyPrefixed });
|
||||
const rawData = await store.get(keyPrefixed);
|
||||
if (rawData === void 0 || rawData === null) {
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
return void 0;
|
||||
}
|
||||
const deserializedData = typeof rawData === "string" || this.opts.compression ? await this.deserializeData(rawData) : rawData;
|
||||
if (deserializedData !== void 0 && deserializedData.expires !== void 0 && deserializedData.expires !== null && // biome-ignore lint/style/noNonNullAssertion: need to fix
|
||||
deserializedData.expires < Date.now()) {
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: void 0
|
||||
});
|
||||
this.stats.miss();
|
||||
await this.delete(key);
|
||||
return void 0;
|
||||
}
|
||||
this.stats.hit();
|
||||
this.hooks.trigger("postGetRaw" /* POST_GET_RAW */, {
|
||||
key: keyPrefixed,
|
||||
value: deserializedData
|
||||
});
|
||||
return deserializedData;
|
||||
}
|
||||
/**
|
||||
* Get the raw values of many keys. This is the replacement for setting raw to true in the getMany() method.
|
||||
* @param {string[]} keys the keys to get
|
||||
* @returns {Promise<Array<StoredDataRaw<Value>>>} will return an array of StoredDataRaw<Value> or undefined if the key does not exist or is expired.
|
||||
*/
|
||||
async getManyRaw(keys) {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
if (keys.length === 0) {
|
||||
const result2 = Array.from({ length: keys.length }).fill(
|
||||
void 0
|
||||
);
|
||||
this.stats.misses += keys.length;
|
||||
this.hooks.trigger("postGetManyRaw" /* POST_GET_MANY_RAW */, {
|
||||
keys: keyPrefixed,
|
||||
values: result2
|
||||
});
|
||||
return result2;
|
||||
}
|
||||
let result = [];
|
||||
if (store.getMany === void 0) {
|
||||
const promises = keyPrefixed.map(async (key) => {
|
||||
const rawData = await store.get(key);
|
||||
if (rawData !== void 0 && rawData !== null) {
|
||||
return this.deserializeData(rawData);
|
||||
}
|
||||
return void 0;
|
||||
});
|
||||
const deserializedRows = await Promise.allSettled(promises);
|
||||
result = deserializedRows.map(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
(row) => row.value
|
||||
);
|
||||
} else {
|
||||
const rawData = await store.getMany(keyPrefixed);
|
||||
for (const row of rawData) {
|
||||
if (row !== void 0 && row !== null) {
|
||||
result.push(await this.deserializeData(row));
|
||||
} else {
|
||||
result.push(void 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
const expiredKeys = [];
|
||||
const isDataExpired = (data) => typeof data.expires === "number" && Date.now() > data.expires;
|
||||
for (const [index, row] of result.entries()) {
|
||||
if (row !== void 0 && isDataExpired(row)) {
|
||||
expiredKeys.push(keyPrefixed[index]);
|
||||
result[index] = void 0;
|
||||
}
|
||||
}
|
||||
if (expiredKeys.length > 0) {
|
||||
await this.deleteMany(expiredKeys);
|
||||
}
|
||||
this.stats.hitsOrMisses(result);
|
||||
this.hooks.trigger("postGetManyRaw" /* POST_GET_MANY_RAW */, {
|
||||
keys: keyPrefixed,
|
||||
values: result
|
||||
});
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Set an item to the store
|
||||
* @param {string | Array<KeyvEntry>} key the key to use. If you pass in an array of KeyvEntry it will set many items
|
||||
* @param {Value} value the value of the key
|
||||
* @param {number} [ttl] time to live in milliseconds
|
||||
* @returns {boolean} if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
async set(key, value, ttl) {
|
||||
const data = { key, value, ttl };
|
||||
this.hooks.trigger("preSet" /* PRE_SET */, data);
|
||||
const keyPrefixed = this._getKeyPrefix(data.key);
|
||||
data.ttl ??= this._ttl;
|
||||
if (data.ttl === 0) {
|
||||
data.ttl = void 0;
|
||||
}
|
||||
const { store } = this.opts;
|
||||
const expires = typeof data.ttl === "number" ? Date.now() + data.ttl : void 0;
|
||||
if (typeof data.value === "symbol") {
|
||||
this.emit("error", "symbol cannot be serialized");
|
||||
throw new Error("symbol cannot be serialized");
|
||||
}
|
||||
const formattedValue = { value: data.value, expires };
|
||||
const serializedValue = await this.serializeData(formattedValue);
|
||||
let result = true;
|
||||
try {
|
||||
const value2 = await store.set(keyPrefixed, serializedValue, data.ttl);
|
||||
if (typeof value2 === "boolean") {
|
||||
result = value2;
|
||||
}
|
||||
} catch (error) {
|
||||
result = false;
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
this.hooks.trigger("postSet" /* POST_SET */, {
|
||||
key: keyPrefixed,
|
||||
value: serializedValue,
|
||||
ttl
|
||||
});
|
||||
this.stats.set();
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Set many items to the store
|
||||
* @param {Array<KeyvEntry>} entries the entries to set
|
||||
* @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
|
||||
*/
|
||||
// biome-ignore lint/correctness/noUnusedVariables: type format
|
||||
async setMany(entries) {
|
||||
let results = [];
|
||||
try {
|
||||
if (this._store.setMany === void 0) {
|
||||
const promises = [];
|
||||
for (const entry of entries) {
|
||||
promises.push(this.set(entry.key, entry.value, entry.ttl));
|
||||
}
|
||||
const promiseResults = await Promise.all(promises);
|
||||
results = promiseResults;
|
||||
} else {
|
||||
const serializedEntries = await Promise.all(
|
||||
entries.map(async ({ key, value, ttl }) => {
|
||||
ttl ??= this._ttl;
|
||||
if (ttl === 0) {
|
||||
ttl = void 0;
|
||||
}
|
||||
const expires = typeof ttl === "number" ? Date.now() + ttl : void 0;
|
||||
if (typeof value === "symbol") {
|
||||
this.emit("error", "symbol cannot be serialized");
|
||||
throw new Error("symbol cannot be serialized");
|
||||
}
|
||||
const formattedValue = { value, expires };
|
||||
const serializedValue = await this.serializeData(formattedValue);
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
return { key: keyPrefixed, value: serializedValue, ttl };
|
||||
})
|
||||
);
|
||||
results = await this._store.setMany(serializedEntries);
|
||||
}
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
results = entries.map(() => false);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Delete an Entry
|
||||
* @param {string | string[]} key the key to be deleted. if an array it will delete many items
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
async delete(key) {
|
||||
const { store } = this.opts;
|
||||
if (Array.isArray(key)) {
|
||||
return this.deleteMany(key);
|
||||
}
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
this.hooks.trigger("preDelete" /* PRE_DELETE */, { key: keyPrefixed });
|
||||
let result = true;
|
||||
try {
|
||||
const value = await store.delete(keyPrefixed);
|
||||
if (typeof value === "boolean") {
|
||||
result = value;
|
||||
}
|
||||
} catch (error) {
|
||||
result = false;
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
this.hooks.trigger("postDelete" /* POST_DELETE */, {
|
||||
key: keyPrefixed,
|
||||
value: result
|
||||
});
|
||||
this.stats.delete();
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Delete many items from the store
|
||||
* @param {string[]} keys the keys to be deleted
|
||||
* @returns {boolean} will return true if item or items are deleted. false if there is an error
|
||||
*/
|
||||
async deleteMany(keys) {
|
||||
try {
|
||||
const { store } = this.opts;
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
this.hooks.trigger("preDelete" /* PRE_DELETE */, { key: keyPrefixed });
|
||||
if (store.deleteMany !== void 0) {
|
||||
return await store.deleteMany(keyPrefixed);
|
||||
}
|
||||
const promises = keyPrefixed.map(async (key) => store.delete(key));
|
||||
const results = await Promise.all(promises);
|
||||
const returnResult = results.every(Boolean);
|
||||
this.hooks.trigger("postDelete" /* POST_DELETE */, {
|
||||
key: keyPrefixed,
|
||||
value: returnResult
|
||||
});
|
||||
return returnResult;
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clear the store
|
||||
* @returns {void}
|
||||
*/
|
||||
async clear() {
|
||||
this.emit("clear");
|
||||
const { store } = this.opts;
|
||||
try {
|
||||
await store.clear();
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
async has(key) {
|
||||
if (Array.isArray(key)) {
|
||||
return this.hasMany(key);
|
||||
}
|
||||
const keyPrefixed = this._getKeyPrefix(key);
|
||||
const { store } = this.opts;
|
||||
if (store.has !== void 0 && !(store instanceof Map)) {
|
||||
return store.has(keyPrefixed);
|
||||
}
|
||||
let rawData;
|
||||
try {
|
||||
rawData = await store.get(keyPrefixed);
|
||||
} catch (error) {
|
||||
this.emit("error", error);
|
||||
if (this._throwOnErrors) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (rawData) {
|
||||
const data = await this.deserializeData(rawData);
|
||||
if (data) {
|
||||
if (data.expires === void 0 || data.expires === null) {
|
||||
return true;
|
||||
}
|
||||
return data.expires > Date.now();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Check if many keys exist
|
||||
* @param {string[]} keys the keys to check
|
||||
* @returns {boolean[]} will return an array of booleans if the keys exist
|
||||
*/
|
||||
async hasMany(keys) {
|
||||
const keyPrefixed = this._getKeyPrefixArray(keys);
|
||||
const { store } = this.opts;
|
||||
if (store.hasMany !== void 0) {
|
||||
return store.hasMany(keyPrefixed);
|
||||
}
|
||||
const results = [];
|
||||
for (const key of keys) {
|
||||
results.push(await this.has(key));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Will disconnect the store. This is only available if the store has a disconnect method
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async disconnect() {
|
||||
const { store } = this.opts;
|
||||
this.emit("disconnect");
|
||||
if (typeof store.disconnect === "function") {
|
||||
return store.disconnect();
|
||||
}
|
||||
}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: type format
|
||||
emit(event, ...arguments_) {
|
||||
if (event === "error" && !this.opts.emitErrors) {
|
||||
return;
|
||||
}
|
||||
super.emit(event, ...arguments_);
|
||||
}
|
||||
async serializeData(data) {
|
||||
if (!this._serialize) {
|
||||
return data;
|
||||
}
|
||||
if (this._compression?.compress) {
|
||||
return this._serialize({
|
||||
value: await this._compression.compress(data.value),
|
||||
expires: data.expires
|
||||
});
|
||||
}
|
||||
return this._serialize(data);
|
||||
}
|
||||
async deserializeData(data) {
|
||||
if (!this._deserialize) {
|
||||
return data;
|
||||
}
|
||||
if (this._compression?.decompress && typeof data === "string") {
|
||||
const result = await this._deserialize(data);
|
||||
return {
|
||||
value: await this._compression.decompress(result?.value),
|
||||
expires: result?.expires
|
||||
};
|
||||
}
|
||||
if (typeof data === "string") {
|
||||
return this._deserialize(data);
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
};
|
||||
var index_default = Keyv;
|
||||
export {
|
||||
Keyv,
|
||||
KeyvHooks,
|
||||
index_default as default
|
||||
};
|
||||
/* v8 ignore next -- @preserve */
|
||||
88
node_modules/keyv/package.json
generated
vendored
Normal file
88
node_modules/keyv/package.json
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"name": "keyv",
|
||||
"version": "5.6.0",
|
||||
"description": "Simple key-value storage with support for multiple backends",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"module": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/jaredwray/keyv.git"
|
||||
},
|
||||
"keywords": [
|
||||
"key",
|
||||
"value",
|
||||
"store",
|
||||
"cache",
|
||||
"ttl",
|
||||
"key-value",
|
||||
"storage",
|
||||
"backend",
|
||||
"adapter",
|
||||
"redis",
|
||||
"mongodb",
|
||||
"sqlite",
|
||||
"mysql",
|
||||
"postgresql",
|
||||
"memory",
|
||||
"node-cache",
|
||||
"lru-cache",
|
||||
"lru",
|
||||
"cache-manager"
|
||||
],
|
||||
"author": "Jared Wray <me@jaredwray.com> (http://jaredwray.com)",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jaredwray/keyv/issues"
|
||||
},
|
||||
"homepage": "https://github.com/jaredwray/keyv",
|
||||
"dependencies": {
|
||||
"@keyv/serialize": "^1.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"lru.min": "^1.1.1",
|
||||
"quick-lru": "^7.0.0",
|
||||
"@biomejs/biome": "^2.3.8",
|
||||
"@faker-js/faker": "^10.1.0",
|
||||
"@vitest/coverage-v8": "^4.0.14",
|
||||
"rimraf": "^6.1.2",
|
||||
"timekeeper": "^2.3.1",
|
||||
"tsd": "^0.33.0",
|
||||
"vitest": "^4.0.14",
|
||||
"@keyv/compress-gzip": "^2.0.3",
|
||||
"@keyv/sqlite": "^4.0.6",
|
||||
"@keyv/test-suite": "^2.1.2",
|
||||
"@keyv/mongo": "^3.1.0",
|
||||
"@keyv/compress-brotli": "^2.0.5",
|
||||
"@keyv/compress-lz4": "^1.0.1",
|
||||
"@keyv/memcache": "^2.0.2"
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"LISCENCE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
|
||||
"lint": "biome check --write --error-on-warnings",
|
||||
"lint:ci": "biome check --error-on-warnings",
|
||||
"test": "pnpm lint && vitest run --coverage",
|
||||
"test:ci": "pnpm lint:ci && vitest --run --sequence.setupFiles=list --coverage",
|
||||
"clean": "rimraf ./node_modules ./coverage ./test/testdb.sqlite ./dist"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user