You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

@cacheable/utils

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cacheable/utils - npm Package Compare versions

Comparing version
2.2.0
to
2.3.0
+66
-58
dist/index.cjs
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;

@@ -20,10 +18,2 @@ var __export = (target, all) => {

};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -43,3 +33,5 @@

hash: () => hash,
hashSync: () => hashSync,
hashToNumber: () => hashToNumber,
hashToNumberSync: () => hashToNumberSync,
isKeyvInstance: () => isKeyvInstance,

@@ -181,35 +173,37 @@ isObject: () => isObject,

// src/hash.ts
var crypto = __toESM(require("crypto"), 1);
var import_hashery = require("hashery");
var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
HashAlgorithm2["SHA256"] = "sha256";
HashAlgorithm2["SHA512"] = "sha512";
HashAlgorithm2["MD5"] = "md5";
HashAlgorithm2["SHA256"] = "SHA-256";
HashAlgorithm2["SHA384"] = "SHA-384";
HashAlgorithm2["SHA512"] = "SHA-512";
HashAlgorithm2["DJB2"] = "djb2";
HashAlgorithm2["FNV1"] = "fnv1";
HashAlgorithm2["MURMER"] = "murmer";
HashAlgorithm2["CRC32"] = "crc32";
return HashAlgorithm2;
})(HashAlgorithm || {});
function hash(object, options = {
algorithm: "sha256" /* SHA256 */,
async function hash(object, options = {
algorithm: "SHA-256" /* SHA256 */,
serialize: JSON.stringify
}) {
if (!options?.algorithm) {
options.algorithm = "sha256" /* SHA256 */;
}
if (!options?.serialize) {
options.serialize = JSON.stringify;
}
const objectString = options.serialize(object);
if (options?.algorithm === "djb2" /* DJB2 */) {
return djb2Hash(objectString);
}
if (!crypto.getHashes().includes(options.algorithm)) {
throw new Error(`Unsupported hash algorithm: '${options?.algorithm}'`);
}
const hasher = crypto.createHash(options.algorithm);
hasher.update(objectString);
return hasher.digest("hex");
const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
const serialize = options?.serialize ?? JSON.stringify;
const objectString = serialize(object);
const hashery = new import_hashery.Hashery();
return hashery.toHash(objectString, { algorithm });
}
function hashToNumber(object, options = {
function hashSync(object, options = {
algorithm: "djb2" /* DJB2 */,
serialize: JSON.stringify
}) {
const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
const serialize = options?.serialize ?? JSON.stringify;
const objectString = serialize(object);
const hashery = new import_hashery.Hashery();
return hashery.toHashSync(objectString, { algorithm });
}
async function hashToNumber(object, options = {
min: 0,
max: 10,
algorithm: "sha256" /* SHA256 */,
algorithm: "SHA-256" /* SHA256 */,
serialize: JSON.stringify

@@ -219,2 +213,5 @@ }) {

const max = options?.max ?? 10;
const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
const serialize = options?.serialize ?? JSON.stringify;
const hashLength = options?.hashLength ?? 16;
if (min >= max) {

@@ -225,26 +222,35 @@ throw new Error(

}
if (!options?.algorithm) {
options.algorithm = "sha256" /* SHA256 */;
}
if (!options?.serialize) {
options.serialize = JSON.stringify;
}
const hashResult = hash(object, options);
const hashNumber = Number.parseInt(hashResult, 16);
const range = max - min + 1;
const result = min + hashNumber % range;
if (result < min) {
return min;
}
if (result > max) {
return max;
}
return result;
const objectString = serialize(object);
const hashery = new import_hashery.Hashery();
return hashery.toNumber(objectString, {
algorithm,
min,
max,
hashLength
});
}
function djb2Hash(string_) {
let hash2 = 5381;
for (let i = 0; i < string_.length; i++) {
hash2 = hash2 * 33 ^ string_.charCodeAt(i);
function hashToNumberSync(object, options = {
min: 0,
max: 10,
algorithm: "djb2" /* DJB2 */,
serialize: JSON.stringify
}) {
const min = options?.min ?? 0;
const max = options?.max ?? 10;
const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
const serialize = options?.serialize ?? JSON.stringify;
const hashLength = options?.hashLength ?? 16;
if (min >= max) {
throw new Error(
`Invalid range: min (${min}) must be less than max (${max})`
);
}
return hash2.toString();
const objectString = serialize(object);
const hashery = new import_hashery.Hashery();
return hashery.toNumberSync(objectString, {
algorithm,
min,
max,
hashLength
});
}

@@ -359,5 +365,5 @@

if (!keyPrefix) {
return `${function_.name}::${hash(arguments_, { serialize })}`;
return `${function_.name}::${hashSync(arguments_, { serialize })}`;
}
return `${keyPrefix}::${function_.name}::${hash(arguments_, { serialize })}`;
return `${keyPrefix}::${function_.name}::${hashSync(arguments_, { serialize })}`;
}

@@ -632,3 +638,5 @@

hash,
hashSync,
hashToNumber,
hashToNumberSync,
isKeyvInstance,

@@ -635,0 +643,0 @@ isObject,

@@ -69,6 +69,9 @@ /**

declare enum HashAlgorithm {
SHA256 = "sha256",
SHA512 = "sha512",
MD5 = "md5",
DJB2 = "djb2"
SHA256 = "SHA-256",
SHA384 = "SHA-384",
SHA512 = "SHA-512",
DJB2 = "djb2",
FNV1 = "fnv1",
MURMER = "murmer",
CRC32 = "crc32"
}

@@ -79,14 +82,43 @@ type HashOptions = {

};
type hashToNumberOptions = HashOptions & {
type HashToNumberOptions = HashOptions & {
min?: number;
max?: number;
hashLength?: number;
};
/**
* Hashes an object using the specified algorithm. The default algorithm is 'sha256'.
* Hashes an object asynchronously using the specified cryptographic algorithm.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashSync() for better performance.
* @param object The object to hash
* @param options The hash options to use
* @returns {Promise<string>} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): Promise<string>;
/**
* Hashes an object synchronously using the specified non-cryptographic algorithm.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hash() instead.
* @param object The object to hash
* @param options The hash options to use
* @returns {string} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): string;
declare function hashToNumber(object: any, options?: hashToNumberOptions): number;
declare function hashSync(object: any, options?: HashOptions): string;
/**
* Hashes an object asynchronously and converts it to a number within a specified range.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashToNumberSync() for better performance.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {Promise<number>} A number within the specified range
*/
declare function hashToNumber(object: any, options?: HashToNumberOptions): Promise<number>;
/**
* Hashes an object synchronously and converts it to a number within a specified range.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hashToNumber() instead.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {number} A number within the specified range
*/
declare function hashToNumberSync(object: any, options?: HashToNumberOptions): number;

@@ -265,2 +297,2 @@ declare function isKeyvInstance(keyv: any): boolean;

export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashToNumber, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };
export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, type HashOptions, type HashToNumberOptions, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashSync, hashToNumber, hashToNumberSync, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };

@@ -69,6 +69,9 @@ /**

declare enum HashAlgorithm {
SHA256 = "sha256",
SHA512 = "sha512",
MD5 = "md5",
DJB2 = "djb2"
SHA256 = "SHA-256",
SHA384 = "SHA-384",
SHA512 = "SHA-512",
DJB2 = "djb2",
FNV1 = "fnv1",
MURMER = "murmer",
CRC32 = "crc32"
}

@@ -79,14 +82,43 @@ type HashOptions = {

};
type hashToNumberOptions = HashOptions & {
type HashToNumberOptions = HashOptions & {
min?: number;
max?: number;
hashLength?: number;
};
/**
* Hashes an object using the specified algorithm. The default algorithm is 'sha256'.
* Hashes an object asynchronously using the specified cryptographic algorithm.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashSync() for better performance.
* @param object The object to hash
* @param options The hash options to use
* @returns {Promise<string>} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): Promise<string>;
/**
* Hashes an object synchronously using the specified non-cryptographic algorithm.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hash() instead.
* @param object The object to hash
* @param options The hash options to use
* @returns {string} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): string;
declare function hashToNumber(object: any, options?: hashToNumberOptions): number;
declare function hashSync(object: any, options?: HashOptions): string;
/**
* Hashes an object asynchronously and converts it to a number within a specified range.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashToNumberSync() for better performance.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {Promise<number>} A number within the specified range
*/
declare function hashToNumber(object: any, options?: HashToNumberOptions): Promise<number>;
/**
* Hashes an object synchronously and converts it to a number within a specified range.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hashToNumber() instead.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {number} A number within the specified range
*/
declare function hashToNumberSync(object: any, options?: HashToNumberOptions): number;

@@ -265,2 +297,2 @@ declare function isKeyvInstance(keyv: any): boolean;

export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashToNumber, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };
export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, type HashOptions, type HashToNumberOptions, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashSync, hashToNumber, hashToNumberSync, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };

@@ -125,35 +125,37 @@ // src/shorthand-time.ts

// src/hash.ts
import * as crypto from "crypto";
import { Hashery } from "hashery";
var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
HashAlgorithm2["SHA256"] = "sha256";
HashAlgorithm2["SHA512"] = "sha512";
HashAlgorithm2["MD5"] = "md5";
HashAlgorithm2["SHA256"] = "SHA-256";
HashAlgorithm2["SHA384"] = "SHA-384";
HashAlgorithm2["SHA512"] = "SHA-512";
HashAlgorithm2["DJB2"] = "djb2";
HashAlgorithm2["FNV1"] = "fnv1";
HashAlgorithm2["MURMER"] = "murmer";
HashAlgorithm2["CRC32"] = "crc32";
return HashAlgorithm2;
})(HashAlgorithm || {});
function hash(object, options = {
algorithm: "sha256" /* SHA256 */,
async function hash(object, options = {
algorithm: "SHA-256" /* SHA256 */,
serialize: JSON.stringify
}) {
if (!options?.algorithm) {
options.algorithm = "sha256" /* SHA256 */;
}
if (!options?.serialize) {
options.serialize = JSON.stringify;
}
const objectString = options.serialize(object);
if (options?.algorithm === "djb2" /* DJB2 */) {
return djb2Hash(objectString);
}
if (!crypto.getHashes().includes(options.algorithm)) {
throw new Error(`Unsupported hash algorithm: '${options?.algorithm}'`);
}
const hasher = crypto.createHash(options.algorithm);
hasher.update(objectString);
return hasher.digest("hex");
const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
const serialize = options?.serialize ?? JSON.stringify;
const objectString = serialize(object);
const hashery = new Hashery();
return hashery.toHash(objectString, { algorithm });
}
function hashToNumber(object, options = {
function hashSync(object, options = {
algorithm: "djb2" /* DJB2 */,
serialize: JSON.stringify
}) {
const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
const serialize = options?.serialize ?? JSON.stringify;
const objectString = serialize(object);
const hashery = new Hashery();
return hashery.toHashSync(objectString, { algorithm });
}
async function hashToNumber(object, options = {
min: 0,
max: 10,
algorithm: "sha256" /* SHA256 */,
algorithm: "SHA-256" /* SHA256 */,
serialize: JSON.stringify

@@ -163,2 +165,5 @@ }) {

const max = options?.max ?? 10;
const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
const serialize = options?.serialize ?? JSON.stringify;
const hashLength = options?.hashLength ?? 16;
if (min >= max) {

@@ -169,26 +174,35 @@ throw new Error(

}
if (!options?.algorithm) {
options.algorithm = "sha256" /* SHA256 */;
}
if (!options?.serialize) {
options.serialize = JSON.stringify;
}
const hashResult = hash(object, options);
const hashNumber = Number.parseInt(hashResult, 16);
const range = max - min + 1;
const result = min + hashNumber % range;
if (result < min) {
return min;
}
if (result > max) {
return max;
}
return result;
const objectString = serialize(object);
const hashery = new Hashery();
return hashery.toNumber(objectString, {
algorithm,
min,
max,
hashLength
});
}
function djb2Hash(string_) {
let hash2 = 5381;
for (let i = 0; i < string_.length; i++) {
hash2 = hash2 * 33 ^ string_.charCodeAt(i);
function hashToNumberSync(object, options = {
min: 0,
max: 10,
algorithm: "djb2" /* DJB2 */,
serialize: JSON.stringify
}) {
const min = options?.min ?? 0;
const max = options?.max ?? 10;
const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
const serialize = options?.serialize ?? JSON.stringify;
const hashLength = options?.hashLength ?? 16;
if (min >= max) {
throw new Error(
`Invalid range: min (${min}) must be less than max (${max})`
);
}
return hash2.toString();
const objectString = serialize(object);
const hashery = new Hashery();
return hashery.toNumberSync(objectString, {
algorithm,
min,
max,
hashLength
});
}

@@ -303,5 +317,5 @@

if (!keyPrefix) {
return `${function_.name}::${hash(arguments_, { serialize })}`;
return `${function_.name}::${hashSync(arguments_, { serialize })}`;
}
return `${keyPrefix}::${function_.name}::${hash(arguments_, { serialize })}`;
return `${keyPrefix}::${function_.name}::${hashSync(arguments_, { serialize })}`;
}

@@ -575,3 +589,5 @@

hash,
hashSync,
hashToNumber,
hashToNumberSync,
isKeyvInstance,

@@ -578,0 +594,0 @@ isObject,

{
"name": "@cacheable/utils",
"version": "2.2.0",
"version": "2.3.0",
"description": "Cacheable Utilities for Caching Libraries",

@@ -24,11 +24,11 @@ "type": "module",

"devDependencies": {
"@biomejs/biome": "^2.3.0",
"@biomejs/biome": "^2.3.5",
"@faker-js/faker": "^10.1.0",
"@types/node": "^24.9.1",
"@vitest/coverage-v8": "^4.0.3",
"@types/node": "^24.10.1",
"@vitest/coverage-v8": "^4.0.9",
"lru-cache": "^11.2.2",
"rimraf": "^6.0.1",
"tsup": "^8.5.0",
"rimraf": "^6.1.0",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^4.0.3"
"vitest": "^4.0.9"
},

@@ -48,4 +48,7 @@ "keywords": [

"dependencies": {
"keyv": "^5.5.3"
"hashery": "^1.2.0"
},
"peerDependencies": {
"keyv": "^5.5.4"
},
"scripts": {

@@ -52,0 +55,0 @@ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",

@@ -103,21 +103,59 @@ [<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)

The hashing API provides both **async** (for cryptographic algorithms) and **sync** (for non-cryptographic algorithms) methods.
## Async Hashing (Cryptographic Algorithms)
Use `hash()` and `hashToNumber()` for cryptographic algorithms like SHA-256, SHA-384, and SHA-512:
```typescript
import { hash } from '@cacheable/utils';
import { hash, hashToNumber, HashAlgorithm } from '@cacheable/utils';
const key = hash('my-cache-key');
// Hash using SHA-256 (default)
const key = await hash('my-cache-key');
console.log(key); // Unique hash for 'my-cache-key'
// Hash with specific algorithm
const sha512Hash = await hash('my-data', { algorithm: HashAlgorithm.SHA512 });
// Convert hash to number within range
const min = 0;
const max = 10;
const result = await hashToNumber({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.SHA256 });
console.log(result); // A number between 0 and 10 based on the hash value
```
If you want to get a number hash you can use the `hashToNumber` function:
## Sync Hashing (Non-Cryptographic Algorithms)
Use `hashSync()` and `hashToNumberSync()` for faster, non-cryptographic algorithms like DJB2, FNV1, MURMER, and CRC32:
```typescript
import { hash, hashToNumber } from '@cacheable/utils';
import { hashSync, hashToNumberSync, HashAlgorithm } from '@cacheable/utils';
// Hash using DJB2 (default for sync)
const key = hashSync('my-cache-key');
console.log(key); // Unique hash for 'my-cache-key'
// Hash with specific algorithm
const fnv1Hash = hashSync('my-data', { algorithm: HashAlgorithm.FNV1 });
// Convert hash to number within range
const min = 0;
const max = 10;
const result = hashToNumber({foo: 'bar'}, min, max, HashAlgorithm.DJB2);
const result = hashToNumberSync({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.DJB2 });
console.log(result); // A number between 0 and 10 based on the hash value
```
## Available Hash Algorithms
**Cryptographic (Async):**
- `HashAlgorithm.SHA256` - SHA-256 (default for async methods)
- `HashAlgorithm.SHA384` - SHA-384
- `HashAlgorithm.SHA512` - SHA-512
**Non-Cryptographic (Sync):**
- `HashAlgorithm.DJB2` - DJB2 (default for sync methods)
- `HashAlgorithm.FNV1` - FNV-1
- `HashAlgorithm.MURMER` - Murmur hash
- `HashAlgorithm.CRC32` - CRC32
# Shorthand Time Helpers

@@ -124,0 +162,0 @@