@kikiutils/shared 15.0.1 → 15.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -119
- package/dist/crypto-hash.d.ts +145 -0
- package/dist/crypto-hash.d.ts.map +1 -1
- package/dist/crypto-hash.js +137 -7
- package/dist/crypto-hash.js.map +1 -1
- package/dist/datetime.d.ts +0 -2
- package/dist/datetime.d.ts.map +1 -1
- package/dist/datetime.js +0 -2
- package/dist/datetime.js.map +1 -1
- package/dist/env.d.ts +2 -0
- package/dist/env.d.ts.map +1 -1
- package/dist/env.js +2 -0
- package/dist/env.js.map +1 -1
- package/dist/event-awaiter.js +1 -1
- package/dist/event-awaiter.js.map +1 -1
- package/dist/hash.d.ts +48 -5
- package/dist/hash.d.ts.map +1 -1
- package/dist/hash.js +49 -6
- package/dist/hash.js.map +1 -1
- package/dist/math.js +1 -1
- package/dist/math.js.map +1 -1
- package/dist/object.d.ts +4 -0
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +4 -0
- package/dist/object.js.map +1 -1
- package/dist/random.js +2 -0
- package/dist/random.js.map +1 -1
- package/dist/storages/lru/keyed-store.d.ts +22 -0
- package/dist/storages/lru/keyed-store.d.ts.map +1 -1
- package/dist/storages/lru/keyed-store.js +22 -0
- package/dist/storages/lru/keyed-store.js.map +1 -1
- package/dist/storages/redis/keyed-store.d.ts +25 -0
- package/dist/storages/redis/keyed-store.d.ts.map +1 -1
- package/dist/storages/redis/keyed-store.js +25 -0
- package/dist/storages/redis/keyed-store.js.map +1 -1
- package/dist/storages/redis/msgpack.d.ts +20 -0
- package/dist/storages/redis/msgpack.d.ts.map +1 -1
- package/dist/storages/redis/msgpack.js +20 -0
- package/dist/storages/redis/msgpack.js.map +1 -1
- package/dist/storages/redis/types.d.ts +42 -0
- package/dist/storages/redis/types.d.ts.map +1 -1
- package/dist/time.d.ts +17 -0
- package/dist/time.d.ts.map +1 -1
- package/dist/time.js +17 -0
- package/dist/time.js.map +1 -1
- package/dist/url.d.ts +3 -0
- package/dist/url.d.ts.map +1 -1
- package/dist/url.js +8 -2
- package/dist/url.js.map +1 -1
- package/dist/vue.d.ts +6 -0
- package/dist/vue.d.ts.map +1 -1
- package/dist/vue.js +6 -0
- package/dist/vue.js.map +1 -1
- package/package.json +2 -2
- package/src/crypto-hash.ts +143 -14
- package/src/datetime.ts +0 -2
- package/src/env.ts +2 -0
- package/src/event-awaiter.ts +1 -1
- package/src/hash.ts +56 -14
- package/src/math.ts +2 -1
- package/src/object.ts +4 -0
- package/src/random.ts +3 -0
- package/src/storages/lru/keyed-store.ts +22 -0
- package/src/storages/redis/keyed-store.ts +25 -0
- package/src/storages/redis/msgpack.ts +20 -0
- package/src/storages/redis/types.ts +52 -0
- package/src/time.ts +17 -0
- package/src/url.ts +13 -2
- package/src/vue.ts +6 -0
package/dist/event-awaiter.js
CHANGED
|
@@ -76,7 +76,7 @@ var EventAwaiter = class {
|
|
|
76
76
|
}
|
|
77
77
|
resolvers.push(resolve);
|
|
78
78
|
this.#promiseResolvers.set(key, resolvers);
|
|
79
|
-
if (timeoutMs) setTimeout(() => {
|
|
79
|
+
if (timeoutMs != null) setTimeout(() => {
|
|
80
80
|
const resolvers = this.#promiseResolvers.get(key);
|
|
81
81
|
if (resolvers?.includes(resolve)) {
|
|
82
82
|
resolve(void 0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-awaiter.js","names":["#promiseResolvers"],"sources":["../src/event-awaiter.ts"],"sourcesContent":["/**\n * EventAwaiter provides a mechanism to wait for events (by key) asynchronously.\n *\n * This class allows multiple consumers to `wait` for a specific key\n * and be resolved when `trigger` is called for that key, or automatically\n * resolved with `undefined` if a timeout occurs or an AbortSignal is triggered.\n *\n * Typical use cases include long-polling, request coordination,\n * or implementing event-driven primitives in applications or services.\n *\n * @template T - The type of value that will be resolved when the event is triggered\n */\nexport class EventAwaiter<T> {\n #promiseResolvers = new Map<string, ((value: PromiseLike<T | undefined> | T | undefined) => void)[]>();\n\n /**\n * Triggers all pending promises waiting for the given key.\n * Each promise will be resolved with the provided value.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {T | undefined} value - The value to resolve the awaiting promises with.\n * May be `undefined` to indicate no result or a timeout-like behavior.\n */\n trigger(key: string, value: T | undefined) {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers) {\n this.#promiseResolvers.delete(key);\n resolvers?.forEach((resolve) => resolve(value));\n }\n }\n\n /**\n * Triggers and resolves all pending promises across all keys.\n *\n * This is typically used during shutdown or cleanup to ensure that\n * no consumer is left waiting indefinitely.\n *\n * @param {T | undefined} [value] - Optional value to resolve all waiters with.\n * Defaults to `undefined`, which usually indicates cancellation or shutdown.\n */\n triggerAll(value: T | undefined = undefined) {\n for (const [_, resolvers] of this.#promiseResolvers.entries()) resolvers.forEach((resolve) => resolve(value));\n this.#promiseResolvers.clear();\n }\n\n /**\n * Waits for an event associated with the given key.\n *\n * The returned promise will resolve when:\n * - `trigger(key)` is called, in which case it resolves with the provided value.\n * - The optional timeout is reached, in which case it resolves with `undefined`.\n * - The optional `AbortSignal` is aborted, in which case it resolves with `undefined`.\n *\n * Behavior when multiple waiters exist for the same key:\n * - Default (no mode): multiple waiters are allowed, all will be resolved when triggered.\n * - `strict` mode: throws an error if a waiter already exists for the given key.\n * - `override` mode: cancels all existing waiters (resolving them with `undefined`)\n * and only keeps the latest one.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {'override' | 'strict'} [mode] - Optional behavior mode for handling multiple waiters\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n *\n * @returns {Promise<T | undefined>} A promise that resolves with the triggered value,\n * or `undefined` if timeout or abort occurs\n */\n wait(key: string, timeoutMs?: number, mode?: 'override' | 'strict', signal?: AbortSignal) {\n return new Promise<T | undefined>((resolve) => {\n const resolvers = this.#promiseResolvers.get(key) || [];\n if (resolvers.length) {\n switch (mode) {\n case 'override':\n resolvers.forEach((r) => r(undefined));\n resolvers.length = 0;\n break;\n case 'strict':\n throw new Error(`Duplicate wait detected for key: ${key}`);\n }\n }\n\n resolvers.push(resolve);\n this.#promiseResolvers.set(key, resolvers);\n if (timeoutMs) {\n setTimeout(\n () => {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers?.includes(resolve)) {\n resolve(undefined);\n const newResolvers = resolvers.filter((r) => r !== resolve);\n if (newResolvers.length) this.#promiseResolvers.set(key, newResolvers);\n else this.#promiseResolvers.delete(key);\n }\n },\n timeoutMs,\n );\n }\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers?.includes(resolve)) {\n resolve(undefined);\n const newResolvers = resolvers.filter((r) => r !== resolve);\n if (newResolvers.length) this.#promiseResolvers.set(key, newResolvers);\n else this.#promiseResolvers.delete(key);\n }\n },\n { once: true },\n );\n }\n });\n }\n\n /**\n * Waits for an event in strict mode.\n * Only one waiter is allowed per key. If another waiter already exists,\n * this method will throw an error.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n */\n waitExclusive(key: string, timeoutMs?: number, signal?: AbortSignal) {\n return this.wait(key, timeoutMs, 'strict', signal);\n }\n\n /**\n * Waits for an event in override mode.\n * If another waiter already exists for the given key, it will be canceled\n * (resolved with `undefined`) and replaced by the new waiter.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n */\n waitLatest(key: string, timeoutMs?: number, signal?: AbortSignal) {\n return this.wait(key, timeoutMs, 'override', signal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,IAAa,eAAb,MAA6B;CACzB,oCAAoB,IAAI,KAA8E;;;;;;;;;CAUtG,QAAQ,KAAa,OAAsB;EACvC,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI;AACjD,MAAI,WAAW;AACX,SAAA,iBAAuB,OAAO,IAAI;AAClC,cAAW,SAAS,YAAY,QAAQ,MAAM,CAAC;;;;;;;;;;;;CAavD,WAAW,QAAuB,KAAA,GAAW;AACzC,OAAK,MAAM,CAAC,GAAG,cAAc,MAAA,iBAAuB,SAAS,CAAE,WAAU,SAAS,YAAY,QAAQ,MAAM,CAAC;AAC7G,QAAA,iBAAuB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;CA0BlC,KAAK,KAAa,WAAoB,MAA8B,QAAsB;AACtF,SAAO,IAAI,SAAwB,YAAY;GAC3C,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI,IAAI,EAAE;AACvD,OAAI,UAAU,OACV,SAAQ,MAAR;IACI,KAAK;AACD,eAAU,SAAS,MAAM,EAAE,KAAA,EAAU,CAAC;AACtC,eAAU,SAAS;AACnB;IACJ,KAAK,SACD,OAAM,IAAI,MAAM,oCAAoC,MAAM;;AAItE,aAAU,KAAK,QAAQ;AACvB,SAAA,iBAAuB,IAAI,KAAK,UAAU;AAC1C,OAAI,
|
|
1
|
+
{"version":3,"file":"event-awaiter.js","names":["#promiseResolvers"],"sources":["../src/event-awaiter.ts"],"sourcesContent":["/**\n * EventAwaiter provides a mechanism to wait for events (by key) asynchronously.\n *\n * This class allows multiple consumers to `wait` for a specific key\n * and be resolved when `trigger` is called for that key, or automatically\n * resolved with `undefined` if a timeout occurs or an AbortSignal is triggered.\n *\n * Typical use cases include long-polling, request coordination,\n * or implementing event-driven primitives in applications or services.\n *\n * @template T - The type of value that will be resolved when the event is triggered\n */\nexport class EventAwaiter<T> {\n #promiseResolvers = new Map<string, ((value: PromiseLike<T | undefined> | T | undefined) => void)[]>();\n\n /**\n * Triggers all pending promises waiting for the given key.\n * Each promise will be resolved with the provided value.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {T | undefined} value - The value to resolve the awaiting promises with.\n * May be `undefined` to indicate no result or a timeout-like behavior.\n */\n trigger(key: string, value: T | undefined) {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers) {\n this.#promiseResolvers.delete(key);\n resolvers?.forEach((resolve) => resolve(value));\n }\n }\n\n /**\n * Triggers and resolves all pending promises across all keys.\n *\n * This is typically used during shutdown or cleanup to ensure that\n * no consumer is left waiting indefinitely.\n *\n * @param {T | undefined} [value] - Optional value to resolve all waiters with.\n * Defaults to `undefined`, which usually indicates cancellation or shutdown.\n */\n triggerAll(value: T | undefined = undefined) {\n for (const [_, resolvers] of this.#promiseResolvers.entries()) resolvers.forEach((resolve) => resolve(value));\n this.#promiseResolvers.clear();\n }\n\n /**\n * Waits for an event associated with the given key.\n *\n * The returned promise will resolve when:\n * - `trigger(key)` is called, in which case it resolves with the provided value.\n * - The optional timeout is reached, in which case it resolves with `undefined`.\n * - The optional `AbortSignal` is aborted, in which case it resolves with `undefined`.\n *\n * Behavior when multiple waiters exist for the same key:\n * - Default (no mode): multiple waiters are allowed, all will be resolved when triggered.\n * - `strict` mode: throws an error if a waiter already exists for the given key.\n * - `override` mode: cancels all existing waiters (resolving them with `undefined`)\n * and only keeps the latest one.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {'override' | 'strict'} [mode] - Optional behavior mode for handling multiple waiters\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n *\n * @returns {Promise<T | undefined>} A promise that resolves with the triggered value,\n * or `undefined` if timeout or abort occurs\n */\n wait(key: string, timeoutMs?: number, mode?: 'override' | 'strict', signal?: AbortSignal) {\n return new Promise<T | undefined>((resolve) => {\n const resolvers = this.#promiseResolvers.get(key) || [];\n if (resolvers.length) {\n switch (mode) {\n case 'override':\n resolvers.forEach((r) => r(undefined));\n resolvers.length = 0;\n break;\n case 'strict':\n throw new Error(`Duplicate wait detected for key: ${key}`);\n }\n }\n\n resolvers.push(resolve);\n this.#promiseResolvers.set(key, resolvers);\n if (timeoutMs != null) {\n setTimeout(\n () => {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers?.includes(resolve)) {\n resolve(undefined);\n const newResolvers = resolvers.filter((r) => r !== resolve);\n if (newResolvers.length) this.#promiseResolvers.set(key, newResolvers);\n else this.#promiseResolvers.delete(key);\n }\n },\n timeoutMs,\n );\n }\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n const resolvers = this.#promiseResolvers.get(key);\n if (resolvers?.includes(resolve)) {\n resolve(undefined);\n const newResolvers = resolvers.filter((r) => r !== resolve);\n if (newResolvers.length) this.#promiseResolvers.set(key, newResolvers);\n else this.#promiseResolvers.delete(key);\n }\n },\n { once: true },\n );\n }\n });\n }\n\n /**\n * Waits for an event in strict mode.\n * Only one waiter is allowed per key. If another waiter already exists,\n * this method will throw an error.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n */\n waitExclusive(key: string, timeoutMs?: number, signal?: AbortSignal) {\n return this.wait(key, timeoutMs, 'strict', signal);\n }\n\n /**\n * Waits for an event in override mode.\n * If another waiter already exists for the given key, it will be canceled\n * (resolved with `undefined`) and replaced by the new waiter.\n *\n * @param {string} key - Identifier for the awaited event\n * @param {number} [timeoutMs] - Optional timeout (in milliseconds).\n * If reached, the promise resolves with `undefined`.\n * @param {AbortSignal} [signal] - Optional AbortSignal. If aborted, the promise resolves with `undefined`\n */\n waitLatest(key: string, timeoutMs?: number, signal?: AbortSignal) {\n return this.wait(key, timeoutMs, 'override', signal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,IAAa,eAAb,MAA6B;CACzB,oCAAoB,IAAI,KAA8E;;;;;;;;;CAUtG,QAAQ,KAAa,OAAsB;EACvC,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI;AACjD,MAAI,WAAW;AACX,SAAA,iBAAuB,OAAO,IAAI;AAClC,cAAW,SAAS,YAAY,QAAQ,MAAM,CAAC;;;;;;;;;;;;CAavD,WAAW,QAAuB,KAAA,GAAW;AACzC,OAAK,MAAM,CAAC,GAAG,cAAc,MAAA,iBAAuB,SAAS,CAAE,WAAU,SAAS,YAAY,QAAQ,MAAM,CAAC;AAC7G,QAAA,iBAAuB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;CA0BlC,KAAK,KAAa,WAAoB,MAA8B,QAAsB;AACtF,SAAO,IAAI,SAAwB,YAAY;GAC3C,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI,IAAI,EAAE;AACvD,OAAI,UAAU,OACV,SAAQ,MAAR;IACI,KAAK;AACD,eAAU,SAAS,MAAM,EAAE,KAAA,EAAU,CAAC;AACtC,eAAU,SAAS;AACnB;IACJ,KAAK,SACD,OAAM,IAAI,MAAM,oCAAoC,MAAM;;AAItE,aAAU,KAAK,QAAQ;AACvB,SAAA,iBAAuB,IAAI,KAAK,UAAU;AAC1C,OAAI,aAAa,KACb,kBACU;IACF,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI;AACjD,QAAI,WAAW,SAAS,QAAQ,EAAE;AAC9B,aAAQ,KAAA,EAAU;KAClB,MAAM,eAAe,UAAU,QAAQ,MAAM,MAAM,QAAQ;AAC3D,SAAI,aAAa,OAAQ,OAAA,iBAAuB,IAAI,KAAK,aAAa;SACjE,OAAA,iBAAuB,OAAO,IAAI;;MAG/C,UACH;AAGL,OAAI,OACA,QAAO,iBACH,eACM;IACF,MAAM,YAAY,MAAA,iBAAuB,IAAI,IAAI;AACjD,QAAI,WAAW,SAAS,QAAQ,EAAE;AAC9B,aAAQ,KAAA,EAAU;KAClB,MAAM,eAAe,UAAU,QAAQ,MAAM,MAAM,QAAQ;AAC3D,SAAI,aAAa,OAAQ,OAAA,iBAAuB,IAAI,KAAK,aAAa;SACjE,OAAA,iBAAuB,OAAO,IAAI;;MAG/C,EAAE,MAAM,MAAM,CACjB;IAEP;;;;;;;;;;;;CAaN,cAAc,KAAa,WAAoB,QAAsB;AACjE,SAAO,KAAK,KAAK,KAAK,WAAW,UAAU,OAAO;;;;;;;;;;;;CAatD,WAAW,KAAa,WAAoB,QAAsB;AAC9D,SAAO,KAAK,KAAK,KAAK,WAAW,YAAY,OAAO"}
|
package/dist/hash.d.ts
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
//#region src/hash.d.ts
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* Computes the SHA-3 hash of the given data using the 224-bit digest.
|
|
4
|
+
*
|
|
5
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
6
|
+
*
|
|
7
|
+
* @returns {string} The hexadecimal hash digest
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { sha3224 } from '@kikiutils/shared/hash';
|
|
12
|
+
*
|
|
13
|
+
* console.log(sha3224('test')); // 0qW8FoqDcFmkpuqR9J3uT8YXVb3pWnLYgA4JqyprhqZ5H...
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
declare function sha3224(data: string | Uint8Array): string;
|
|
17
|
+
/**
|
|
18
|
+
* Computes the SHA-3 hash of the given data using the 256-bit digest.
|
|
19
|
+
*
|
|
20
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
21
|
+
*
|
|
22
|
+
* @returns {string} The hexadecimal hash digest
|
|
7
23
|
*
|
|
8
24
|
* @example
|
|
9
25
|
* ```typescript
|
|
@@ -12,9 +28,36 @@
|
|
|
12
28
|
* console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80
|
|
13
29
|
* ```
|
|
14
30
|
*/
|
|
15
|
-
declare function sha3224(data: string | Uint8Array): string;
|
|
16
31
|
declare function sha3256(data: string | Uint8Array): string;
|
|
32
|
+
/**
|
|
33
|
+
* Computes the SHA-3 hash of the given data using the 384-bit digest.
|
|
34
|
+
*
|
|
35
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
36
|
+
*
|
|
37
|
+
* @returns {string} The hexadecimal hash digest
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```typescript
|
|
41
|
+
* import { sha3384 } from '@kikiutils/shared/hash';
|
|
42
|
+
*
|
|
43
|
+
* console.log(sha3384('test')); // 1Q2wQAYaZ4o8vWX5bEB2n3Y...
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
17
46
|
declare function sha3384(data: string | Uint8Array): string;
|
|
47
|
+
/**
|
|
48
|
+
* Computes the SHA-3 hash of the given data using the 512-bit digest.
|
|
49
|
+
*
|
|
50
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
51
|
+
*
|
|
52
|
+
* @returns {string} The hexadecimal hash digest
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* import { sha3512 } from '@kikiutils/shared/hash';
|
|
57
|
+
*
|
|
58
|
+
* console.log(sha3512('test')); // b_NQJ8FJBY9dIjm1q7...
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
18
61
|
declare function sha3512(data: string | Uint8Array): string;
|
|
19
62
|
//#endregion
|
|
20
63
|
export { sha3224, sha3256, sha3384, sha3512 };
|
package/dist/hash.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.d.ts","names":[],"sources":["../src/hash.ts"],"mappings":";;AAyBA;;;;;
|
|
1
|
+
{"version":3,"file":"hash.d.ts","names":[],"sources":["../src/hash.ts"],"mappings":";;AAyBA;;;;;AAkBA;;;;;AAkBA;;;iBApCgB,OAAA,CAAQ,IAAA,WAAe,UAAA;;AAsDvC;;;;;;;;;;;;;iBApCgB,OAAA,CAAQ,IAAA,WAAe,UAAA;;;;;;;;;;;;;;;iBAkBvB,OAAA,CAAQ,IAAA,WAAe,UAAA;;;;;;;;;;;;;;;iBAkBvB,OAAA,CAAQ,IAAA,WAAe,UAAA"}
|
package/dist/hash.js
CHANGED
|
@@ -2,27 +2,70 @@ import { sha3_224, sha3_256, sha3_384, sha3_512 } from "@noble/hashes/sha3.js";
|
|
|
2
2
|
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
3
3
|
//#region src/hash.ts
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* Computes the SHA-3 hash of the given data using the 224-bit digest.
|
|
6
|
+
*
|
|
7
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
8
|
+
*
|
|
9
|
+
* @returns {string} The hexadecimal hash digest
|
|
9
10
|
*
|
|
10
11
|
* @example
|
|
11
12
|
* ```typescript
|
|
12
|
-
* import {
|
|
13
|
+
* import { sha3224 } from '@kikiutils/shared/hash';
|
|
13
14
|
*
|
|
14
|
-
* console.log(
|
|
15
|
+
* console.log(sha3224('test')); // 0qW8FoqDcFmkpuqR9J3uT8YXVb3pWnLYgA4JqyprhqZ5H...
|
|
15
16
|
* ```
|
|
16
17
|
*/
|
|
17
18
|
function sha3224(data) {
|
|
18
19
|
return bytesToHex(sha3_224(typeof data === "string" ? utf8ToBytes(data) : data));
|
|
19
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* Computes the SHA-3 hash of the given data using the 256-bit digest.
|
|
23
|
+
*
|
|
24
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
25
|
+
*
|
|
26
|
+
* @returns {string} The hexadecimal hash digest
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* import { sha3256 } from '@kikiutils/shared/hash';
|
|
31
|
+
*
|
|
32
|
+
* console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
20
35
|
function sha3256(data) {
|
|
21
36
|
return bytesToHex(sha3_256(typeof data === "string" ? utf8ToBytes(data) : data));
|
|
22
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Computes the SHA-3 hash of the given data using the 384-bit digest.
|
|
40
|
+
*
|
|
41
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
42
|
+
*
|
|
43
|
+
* @returns {string} The hexadecimal hash digest
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { sha3384 } from '@kikiutils/shared/hash';
|
|
48
|
+
*
|
|
49
|
+
* console.log(sha3384('test')); // 1Q2wQAYaZ4o8vWX5bEB2n3Y...
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
23
52
|
function sha3384(data) {
|
|
24
53
|
return bytesToHex(sha3_384(typeof data === "string" ? utf8ToBytes(data) : data));
|
|
25
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Computes the SHA-3 hash of the given data using the 512-bit digest.
|
|
57
|
+
*
|
|
58
|
+
* @param {string | Uint8Array} data - The input data to hash
|
|
59
|
+
*
|
|
60
|
+
* @returns {string} The hexadecimal hash digest
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* import { sha3512 } from '@kikiutils/shared/hash';
|
|
65
|
+
*
|
|
66
|
+
* console.log(sha3512('test')); // b_NQJ8FJBY9dIjm1q7...
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
26
69
|
function sha3512(data) {
|
|
27
70
|
return bytesToHex(sha3_512(typeof data === "string" ? utf8ToBytes(data) : data));
|
|
28
71
|
}
|
package/dist/hash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.js","names":[],"sources":["../src/hash.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"hash.js","names":[],"sources":["../src/hash.ts"],"sourcesContent":["import {\n sha3_224,\n sha3_256,\n sha3_384,\n sha3_512,\n} from '@noble/hashes/sha3.js';\nimport {\n bytesToHex,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\n\n/**\n * Computes the SHA-3 hash of the given data using the 224-bit digest.\n *\n * @param {string | Uint8Array} data - The input data to hash\n *\n * @returns {string} The hexadecimal hash digest\n *\n * @example\n * ```typescript\n * import { sha3224 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3224('test')); // 0qW8FoqDcFmkpuqR9J3uT8YXVb3pWnLYgA4JqyprhqZ5H...\n * ```\n */\nexport function sha3224(data: string | Uint8Array) {\n return bytesToHex(sha3_224(typeof data === 'string' ? utf8ToBytes(data) : data));\n}\n\n/**\n * Computes the SHA-3 hash of the given data using the 256-bit digest.\n *\n * @param {string | Uint8Array} data - The input data to hash\n *\n * @returns {string} The hexadecimal hash digest\n *\n * @example\n * ```typescript\n * import { sha3256 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n * ```\n */\nexport function sha3256(data: string | Uint8Array) {\n return bytesToHex(sha3_256(typeof data === 'string' ? utf8ToBytes(data) : data));\n}\n\n/**\n * Computes the SHA-3 hash of the given data using the 384-bit digest.\n *\n * @param {string | Uint8Array} data - The input data to hash\n *\n * @returns {string} The hexadecimal hash digest\n *\n * @example\n * ```typescript\n * import { sha3384 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3384('test')); // 1Q2wQAYaZ4o8vWX5bEB2n3Y...\n * ```\n */\nexport function sha3384(data: string | Uint8Array) {\n return bytesToHex(sha3_384(typeof data === 'string' ? utf8ToBytes(data) : data));\n}\n\n/**\n * Computes the SHA-3 hash of the given data using the 512-bit digest.\n *\n * @param {string | Uint8Array} data - The input data to hash\n *\n * @returns {string} The hexadecimal hash digest\n *\n * @example\n * ```typescript\n * import { sha3512 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3512('test')); // b_NQJ8FJBY9dIjm1q7...\n * ```\n */\nexport function sha3512(data: string | Uint8Array) {\n return bytesToHex(sha3_512(typeof data === 'string' ? utf8ToBytes(data) : data));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAAQ,MAA2B;AAC/C,QAAO,WAAW,SAAS,OAAO,SAAS,WAAW,YAAY,KAAK,GAAG,KAAK,CAAC;;;;;;;;;;;;;;;;AAiBpF,SAAgB,QAAQ,MAA2B;AAC/C,QAAO,WAAW,SAAS,OAAO,SAAS,WAAW,YAAY,KAAK,GAAG,KAAK,CAAC;;;;;;;;;;;;;;;;AAiBpF,SAAgB,QAAQ,MAA2B;AAC/C,QAAO,WAAW,SAAS,OAAO,SAAS,WAAW,YAAY,KAAK,GAAG,KAAK,CAAC;;;;;;;;;;;;;;;;AAiBpF,SAAgB,QAAQ,MAA2B;AAC/C,QAAO,WAAW,SAAS,OAAO,SAAS,WAAW,YAAY,KAAK,GAAG,KAAK,CAAC"}
|
package/dist/math.js
CHANGED
|
@@ -26,7 +26,7 @@ function toPercentageString(molecular, denominator, options) {
|
|
|
26
26
|
const molecularDecimal = new Decimal(molecular.toString());
|
|
27
27
|
const denominatorDecimal = new Decimal(denominator.toString());
|
|
28
28
|
const calculationResult = molecularDecimal.div(denominatorDecimal);
|
|
29
|
-
const result = calculationResult.isNaN() ? "0.00" : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);
|
|
29
|
+
const result = calculationResult.isNaN() || !calculationResult.isFinite() ? "0.00" : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);
|
|
30
30
|
return options?.withSymbol ?? true ? `${result}%` : result;
|
|
31
31
|
}
|
|
32
32
|
//#endregion
|
package/dist/math.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.js","names":[],"sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction\n * @param {CalculableValue} denominator - The denominator of the fraction\n * @param {ToPercentageStringOptions} [options] - Optional output settings\n *\n * @returns {string} Formatted percentage string\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n const result = calculationResult.isNaN()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mBACZ,WACA,aACA,SACF;CACE,MAAM,mBAAmB,IAAI,QAAQ,UAAU,UAAU,CAAC;CAC1D,MAAM,qBAAqB,IAAI,QAAQ,YAAY,UAAU,CAAC;CAC9D,MAAM,oBAAoB,iBAAiB,IAAI,mBAAmB;
|
|
1
|
+
{"version":3,"file":"math.js","names":[],"sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction\n * @param {CalculableValue} denominator - The denominator of the fraction\n * @param {ToPercentageStringOptions} [options] - Optional output settings\n *\n * @returns {string} Formatted percentage string\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n\n const result = calculationResult.isNaN() || !calculationResult.isFinite()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mBACZ,WACA,aACA,SACF;CACE,MAAM,mBAAmB,IAAI,QAAQ,UAAU,UAAU,CAAC;CAC1D,MAAM,qBAAqB,IAAI,QAAQ,YAAY,UAAU,CAAC;CAC9D,MAAM,oBAAoB,iBAAiB,IAAI,mBAAmB;CAElE,MAAM,SAAS,kBAAkB,OAAO,IAAI,CAAC,kBAAkB,UAAU,GACnE,SACA,kBAAkB,MAAM,IAAI,CAAC,QAAQ,SAAS,iBAAiB,EAAE;AAEvE,QAAO,SAAS,cAAc,OAAO,GAAG,OAAO,KAAK"}
|
package/dist/object.d.ts
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
* It is designed for use cases such as signature generation, cache key construction,
|
|
10
10
|
* or any context requiring consistent and predictable object serialization.
|
|
11
11
|
*
|
|
12
|
+
* Note: Empty objects and arrays produce an empty string, which is useful for
|
|
13
|
+
* generating deterministic signature payloads.
|
|
14
|
+
*
|
|
12
15
|
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays
|
|
13
16
|
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=')
|
|
14
17
|
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&')
|
|
@@ -20,6 +23,7 @@
|
|
|
20
23
|
*
|
|
21
24
|
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
22
25
|
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
26
|
+
* console.log(stringifyObjectDeterministically({})); // ''
|
|
23
27
|
* ```
|
|
24
28
|
*/
|
|
25
29
|
declare function stringifyObjectDeterministically(input: Record<string, any>, kvSeparator?: string, pairSeparator?: string): string;
|
package/dist/object.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object.d.ts","names":[],"sources":["../src/object.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"object.d.ts","names":[],"sources":["../src/object.ts"],"mappings":";;AA2BA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,gCAAA,CACZ,KAAA,EAAO,MAAA,eACP,WAAA,WACA,aAAA"}
|
package/dist/object.js
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
* It is designed for use cases such as signature generation, cache key construction,
|
|
10
10
|
* or any context requiring consistent and predictable object serialization.
|
|
11
11
|
*
|
|
12
|
+
* Note: Empty objects and arrays produce an empty string, which is useful for
|
|
13
|
+
* generating deterministic signature payloads.
|
|
14
|
+
*
|
|
12
15
|
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays
|
|
13
16
|
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=')
|
|
14
17
|
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&')
|
|
@@ -20,6 +23,7 @@
|
|
|
20
23
|
*
|
|
21
24
|
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
22
25
|
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
26
|
+
* console.log(stringifyObjectDeterministically({})); // ''
|
|
23
27
|
* ```
|
|
24
28
|
*/
|
|
25
29
|
function stringifyObjectDeterministically(input, kvSeparator = "=", pairSeparator = "&") {
|
package/dist/object.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object.js","names":[],"sources":["../src/object.ts"],"sourcesContent":["/**\n * Serializes a nested object into a deterministic, flat string format.\n *\n * This function recursively traverses the input object (including nested objects and arrays),\n * flattens it into key paths using dot notation (e.g. \"a.b.0.c\"), sorts all keys,\n * and joins each key-value pair into a string with customizable separators.\n *\n * It is designed for use cases such as signature generation, cache key construction,\n * or any context requiring consistent and predictable object serialization.\n *\n * @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays\n * @param {string} kvSeparator - The string used to separate each key from its value (default: '=')\n * @param {string} pairSeparator - The string used to separate each key-value pair (default: '&')\n * @returns {string} A deterministic string representation of the input object\n *\n * @example\n * ```typescript\n * import { stringifyObjectDeterministically } from '@kikiutils/shared/object';\n *\n * console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2\n * console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar\n * ```\n */\nexport function stringifyObjectDeterministically(\n input: Record<string, any>,\n kvSeparator: string = '=',\n pairSeparator: string = '&',\n) {\n const entries: string[] = [];\n\n function walk(object: any, path: string[] = []) {\n if (Array.isArray(object)) {\n object.forEach((value, i) => {\n walk(\n value,\n [\n ...path,\n i.toString(),\n ],\n );\n });\n } else if (\n object !== null\n && typeof object === 'object'\n && Object.prototype.toString.call(object) === '[object Object]'\n ) {\n Object.keys(object).sort().forEach((key) => {\n walk(\n object[key],\n [\n ...path,\n key,\n ],\n );\n });\n } else entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);\n }\n\n walk(input);\n return entries.sort().join(pairSeparator);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"object.js","names":[],"sources":["../src/object.ts"],"sourcesContent":["/**\n * Serializes a nested object into a deterministic, flat string format.\n *\n * This function recursively traverses the input object (including nested objects and arrays),\n * flattens it into key paths using dot notation (e.g. \"a.b.0.c\"), sorts all keys,\n * and joins each key-value pair into a string with customizable separators.\n *\n * It is designed for use cases such as signature generation, cache key construction,\n * or any context requiring consistent and predictable object serialization.\n *\n * Note: Empty objects and arrays produce an empty string, which is useful for\n * generating deterministic signature payloads.\n *\n * @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays\n * @param {string} kvSeparator - The string used to separate each key from its value (default: '=')\n * @param {string} pairSeparator - The string used to separate each key-value pair (default: '&')\n * @returns {string} A deterministic string representation of the input object\n *\n * @example\n * ```typescript\n * import { stringifyObjectDeterministically } from '@kikiutils/shared/object';\n *\n * console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2\n * console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar\n * console.log(stringifyObjectDeterministically({})); // ''\n * ```\n */\nexport function stringifyObjectDeterministically(\n input: Record<string, any>,\n kvSeparator: string = '=',\n pairSeparator: string = '&',\n) {\n const entries: string[] = [];\n\n function walk(object: any, path: string[] = []) {\n if (Array.isArray(object)) {\n object.forEach((value, i) => {\n walk(\n value,\n [\n ...path,\n i.toString(),\n ],\n );\n });\n } else if (\n object !== null\n && typeof object === 'object'\n && Object.prototype.toString.call(object) === '[object Object]'\n ) {\n Object.keys(object).sort().forEach((key) => {\n walk(\n object[key],\n [\n ...path,\n key,\n ],\n );\n });\n } else entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);\n }\n\n walk(input);\n return entries.sort().join(pairSeparator);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iCACZ,OACA,cAAsB,KACtB,gBAAwB,KAC1B;CACE,MAAM,UAAoB,EAAE;CAE5B,SAAS,KAAK,QAAa,OAAiB,EAAE,EAAE;AAC5C,MAAI,MAAM,QAAQ,OAAO,CACrB,QAAO,SAAS,OAAO,MAAM;AACzB,QACI,OACA,CACI,GAAG,MACH,EAAE,UAAU,CACf,CACJ;IACH;WAEF,WAAW,QACR,OAAO,WAAW,YAClB,OAAO,UAAU,SAAS,KAAK,OAAO,KAAK,kBAE9C,QAAO,KAAK,OAAO,CAAC,MAAM,CAAC,SAAS,QAAQ;AACxC,QACI,OAAO,MACP,CACI,GAAG,MACH,IACH,CACJ;IACH;MACC,SAAQ,KAAK,GAAG,KAAK,KAAK,IAAI,GAAG,cAAc,OAAO,OAAO,GAAG;;AAG3E,MAAK,MAAM;AACX,QAAO,QAAQ,MAAM,CAAC,KAAK,cAAc"}
|
package/dist/random.js
CHANGED
|
@@ -20,6 +20,8 @@
|
|
|
20
20
|
* @returns {T} The result of the generator function using the computed final length
|
|
21
21
|
*/
|
|
22
22
|
function generateWithNestedRandomLength(generator, minMin, minMax, maxMin, maxMax) {
|
|
23
|
+
if (minMin > minMax) throw new Error(`Invalid range: minMin (${minMin}) cannot be greater than minMax (${minMax})`);
|
|
24
|
+
if (maxMin > maxMax) throw new Error(`Invalid range: maxMin (${maxMin}) cannot be greater than maxMax (${maxMax})`);
|
|
23
25
|
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
|
24
26
|
const innerMin = random(minMin, minMax);
|
|
25
27
|
return generator(random(Math.max(innerMin, maxMin), maxMax));
|
package/dist/random.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"random.js","names":[],"sources":["../src/random.ts"],"sourcesContent":["/**\n * Generates a value using a provided generator function, where the input length\n * is determined by two levels of nested random ranges:\n *\n * 1. First, a random number (`innerMin`) is chosen between `minMin` and `minMax`.\n * 2. Then, a final length is chosen between `Math.max(innerMin, maxMin)` and `maxMax`.\n * 3. The generator is called with the final length and its result is returned.\n *\n * This function supports any return type by using a generic type parameter.\n *\n * @template T - The return type of the generator function\n *\n * @param {(length: number) => T} generator - A function that accepts a length and returns a value of type T\n * @param {number} minMin - Lower bound of the first random range\n * @param {number} minMax - Upper bound of the first random range\n * @param {number} maxMin - Lower bound of the second random range\n * @param {number} maxMax - Upper bound of the second random range\n *\n * @returns {T} The result of the generator function using the computed final length\n */\nexport function generateWithNestedRandomLength<T = string>(\n generator: (length: number) => T,\n minMin: number,\n minMax: number,\n maxMin: number,\n maxMax: number,\n) {\n const random = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;\n const innerMin = random(minMin, minMax);\n const finalLength = random(Math.max(innerMin, maxMin), maxMax);\n return generator(finalLength);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,+BACZ,WACA,QACA,QACA,QACA,QACF;
|
|
1
|
+
{"version":3,"file":"random.js","names":[],"sources":["../src/random.ts"],"sourcesContent":["/**\n * Generates a value using a provided generator function, where the input length\n * is determined by two levels of nested random ranges:\n *\n * 1. First, a random number (`innerMin`) is chosen between `minMin` and `minMax`.\n * 2. Then, a final length is chosen between `Math.max(innerMin, maxMin)` and `maxMax`.\n * 3. The generator is called with the final length and its result is returned.\n *\n * This function supports any return type by using a generic type parameter.\n *\n * @template T - The return type of the generator function\n *\n * @param {(length: number) => T} generator - A function that accepts a length and returns a value of type T\n * @param {number} minMin - Lower bound of the first random range\n * @param {number} minMax - Upper bound of the first random range\n * @param {number} maxMin - Lower bound of the second random range\n * @param {number} maxMax - Upper bound of the second random range\n *\n * @returns {T} The result of the generator function using the computed final length\n */\nexport function generateWithNestedRandomLength<T = string>(\n generator: (length: number) => T,\n minMin: number,\n minMax: number,\n maxMin: number,\n maxMax: number,\n) {\n if (minMin > minMax) throw new Error(`Invalid range: minMin (${minMin}) cannot be greater than minMax (${minMax})`);\n if (maxMin > maxMax) throw new Error(`Invalid range: maxMin (${maxMin}) cannot be greater than maxMax (${maxMax})`);\n\n const random = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;\n const innerMin = random(minMin, minMax);\n const finalLength = random(Math.max(innerMin, maxMin), maxMax);\n return generator(finalLength);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,+BACZ,WACA,QACA,QACA,QACA,QACF;AACE,KAAI,SAAS,OAAQ,OAAM,IAAI,MAAM,0BAA0B,OAAO,mCAAmC,OAAO,GAAG;AACnH,KAAI,SAAS,OAAQ,OAAM,IAAI,MAAM,0BAA0B,OAAO,mCAAmC,OAAO,GAAG;CAEnH,MAAM,UAAU,KAAa,QAAgB,KAAK,MAAM,KAAK,QAAQ,IAAI,MAAM,MAAM,GAAG,GAAG;CAC3F,MAAM,WAAW,OAAO,QAAQ,OAAO;AAEvC,QAAO,UADa,OAAO,KAAK,IAAI,UAAU,OAAO,EAAE,OAAO,CACjC"}
|
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
import { LRUCache } from "lru-cache";
|
|
2
2
|
|
|
3
3
|
//#region src/storages/lru/keyed-store.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Creates a keyed store wrapper around an LRU cache instance.
|
|
6
|
+
*
|
|
7
|
+
* @template D - The data type stored in the keyed store
|
|
8
|
+
*
|
|
9
|
+
* @param {LRUCache<any, any, any>} lruInstance - The underlying lru-cache instance
|
|
10
|
+
*
|
|
11
|
+
* @returns {(keyFn: (...args: P) => string) => Readonly<{
|
|
12
|
+
* getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem
|
|
13
|
+
* }>} A keyed store factory that takes a key resolution function
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* import { createLruKeyedStore } from '@kikiutils/shared/storages/lru/keyed-store';
|
|
18
|
+
* import { LRUCache } from 'lru-cache';
|
|
19
|
+
*
|
|
20
|
+
* const lru = new LRUCache({ max: 100 });
|
|
21
|
+
* const keyedStore = createLruKeyedStore(lru)((userId: string) => `user:${userId}`);
|
|
22
|
+
* await keyedStore.setItem({ name: 'Alice' }, 'user-123');
|
|
23
|
+
* const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
4
26
|
declare function createLruKeyedStore<D = unknown>(lruInstance: LRUCache<any, any, any>): <P extends any[]>(keyFn: (...args: P) => string) => Readonly<{
|
|
5
27
|
/**
|
|
6
28
|
* Return a value from the cache. Will update the recency of the cache entry found.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyed-store.d.ts","names":[],"sources":["../../../src/storages/lru/keyed-store.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"keyed-store.d.ts","names":[],"sources":["../../../src/storages/lru/keyed-store.ts"],"mappings":";;;;;AAwBA;;;;;;;;;;;;;;;;;;;;iBAAgB,mBAAA,aAAA,CAAiC,WAAA,EAAa,QAAA,oCACjC,KAAA,MAAW,IAAA,EAAM,CAAA,gBAAY,QAAA;EAA9C;;;;;mBAMa,CAAA,GAAC,WAAA,CAAA,CAAA;wBAII,CAAA;qBACH,CAAA;wBACG,CAAA;EANJ;;;wBAUI,CAAA;mBACL,CAAA,KAAC,IAAA,EAAW,CAAA,KAAC,QAAA;AAAA"}
|
|
@@ -1,4 +1,26 @@
|
|
|
1
1
|
//#region src/storages/lru/keyed-store.ts
|
|
2
|
+
/**
|
|
3
|
+
* Creates a keyed store wrapper around an LRU cache instance.
|
|
4
|
+
*
|
|
5
|
+
* @template D - The data type stored in the keyed store
|
|
6
|
+
*
|
|
7
|
+
* @param {LRUCache<any, any, any>} lruInstance - The underlying lru-cache instance
|
|
8
|
+
*
|
|
9
|
+
* @returns {(keyFn: (...args: P) => string) => Readonly<{
|
|
10
|
+
* getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem
|
|
11
|
+
* }>} A keyed store factory that takes a key resolution function
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { createLruKeyedStore } from '@kikiutils/shared/storages/lru/keyed-store';
|
|
16
|
+
* import { LRUCache } from 'lru-cache';
|
|
17
|
+
*
|
|
18
|
+
* const lru = new LRUCache({ max: 100 });
|
|
19
|
+
* const keyedStore = createLruKeyedStore(lru)((userId: string) => `user:${userId}`);
|
|
20
|
+
* await keyedStore.setItem({ name: 'Alice' }, 'user-123');
|
|
21
|
+
* const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
2
24
|
function createLruKeyedStore(lruInstance) {
|
|
3
25
|
return (keyFn) => Object.freeze({
|
|
4
26
|
getItem(...args) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyed-store.js","names":[],"sources":["../../../src/storages/lru/keyed-store.ts"],"sourcesContent":["import type { LRUCache } from 'lru-cache';\n\nexport function createLruKeyedStore<D = unknown>(lruInstance: LRUCache<any, any, any>) {\n return <P extends any[]>(keyFn: (...args: P) => string) => Object.freeze({\n /**\n * Return a value from the cache. Will update the recency of the cache entry found.\n *\n * If the key is not found, returns `null`.\n */\n getItem(...args: P) {\n const rawValue = lruInstance.get(keyFn(...args));\n return rawValue as D ?? null;\n },\n getItemTtl: (...args: P) => lruInstance.getRemainingTTL(keyFn(...args)),\n hasItem: (...args: P) => lruInstance.has(keyFn(...args)),\n removeItem: (...args: P) => lruInstance.delete(keyFn(...args)),\n /**\n * Resolves the full cache key from the given arguments.\n */\n resolveKey: (...args: P) => keyFn(...args),\n setItem: (value: D, ...args: P) => lruInstance.set(keyFn(...args), value),\n });\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"keyed-store.js","names":[],"sources":["../../../src/storages/lru/keyed-store.ts"],"sourcesContent":["import type { LRUCache } from 'lru-cache';\n\n/**\n * Creates a keyed store wrapper around an LRU cache instance.\n *\n * @template D - The data type stored in the keyed store\n *\n * @param {LRUCache<any, any, any>} lruInstance - The underlying lru-cache instance\n *\n * @returns {(keyFn: (...args: P) => string) => Readonly<{\n * getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem\n * }>} A keyed store factory that takes a key resolution function\n *\n * @example\n * ```typescript\n * import { createLruKeyedStore } from '@kikiutils/shared/storages/lru/keyed-store';\n * import { LRUCache } from 'lru-cache';\n *\n * const lru = new LRUCache({ max: 100 });\n * const keyedStore = createLruKeyedStore(lru)((userId: string) => `user:${userId}`);\n * await keyedStore.setItem({ name: 'Alice' }, 'user-123');\n * const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }\n * ```\n */\nexport function createLruKeyedStore<D = unknown>(lruInstance: LRUCache<any, any, any>) {\n return <P extends any[]>(keyFn: (...args: P) => string) => Object.freeze({\n /**\n * Return a value from the cache. Will update the recency of the cache entry found.\n *\n * If the key is not found, returns `null`.\n */\n getItem(...args: P) {\n const rawValue = lruInstance.get(keyFn(...args));\n return rawValue as D ?? null;\n },\n getItemTtl: (...args: P) => lruInstance.getRemainingTTL(keyFn(...args)),\n hasItem: (...args: P) => lruInstance.has(keyFn(...args)),\n removeItem: (...args: P) => lruInstance.delete(keyFn(...args)),\n /**\n * Resolves the full cache key from the given arguments.\n */\n resolveKey: (...args: P) => keyFn(...args),\n setItem: (value: D, ...args: P) => lruInstance.set(keyFn(...args), value),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,oBAAiC,aAAsC;AACnF,SAAyB,UAAkC,OAAO,OAAO;EAMrE,QAAQ,GAAG,MAAS;AAEhB,UADiB,YAAY,IAAI,MAAM,GAAG,KAAK,CAAC,IACxB;;EAE5B,aAAa,GAAG,SAAY,YAAY,gBAAgB,MAAM,GAAG,KAAK,CAAC;EACvE,UAAU,GAAG,SAAY,YAAY,IAAI,MAAM,GAAG,KAAK,CAAC;EACxD,aAAa,GAAG,SAAY,YAAY,OAAO,MAAM,GAAG,KAAK,CAAC;EAI9D,aAAa,GAAG,SAAY,MAAM,GAAG,KAAK;EAC1C,UAAU,OAAU,GAAG,SAAY,YAAY,IAAI,MAAM,GAAG,KAAK,EAAE,MAAM;EAC5E,CAAC"}
|
|
@@ -2,6 +2,31 @@ import { MaybeReadonly, Nullable } from "../../types/index.js";
|
|
|
2
2
|
import { RedisLikeStorage } from "./types.js";
|
|
3
3
|
|
|
4
4
|
//#region src/storages/redis/keyed-store.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Creates a keyed store wrapper around a Redis-like storage.
|
|
7
|
+
*
|
|
8
|
+
* @template D - The data type stored in the keyed store
|
|
9
|
+
*
|
|
10
|
+
* @param {MaybeReadonly<RedisLikeStorage>} storage - The underlying Redis-like storage instance
|
|
11
|
+
*
|
|
12
|
+
* @returns {(keyFn: (...args: P) => string) => Readonly<{
|
|
13
|
+
* getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem, setItemWithTtl
|
|
14
|
+
* }>} A keyed store factory that takes a key resolution function
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { createRedisKeyedStore } from '@kikiutils/shared/storages/redis/keyed-store';
|
|
19
|
+
* import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';
|
|
20
|
+
* import { createClient } from 'redis';
|
|
21
|
+
*
|
|
22
|
+
* const client = createClient();
|
|
23
|
+
* await client.connect();
|
|
24
|
+
* const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);
|
|
25
|
+
* const keyedStore = createRedisKeyedStore(storage)((userId: string) => `user:${userId}`);
|
|
26
|
+
* await keyedStore.setItem({ name: 'Alice' }, 'user-123');
|
|
27
|
+
* const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
5
30
|
declare function createRedisKeyedStore<D = unknown>(storage: MaybeReadonly<RedisLikeStorage>): <P extends any[]>(keyFn: (...args: P) => string) => Readonly<{
|
|
6
31
|
getItem: (...args: P) => Promise<Nullable<D>>;
|
|
7
32
|
getItemTtl: (...args: P) => Promise<number>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyed-store.d.ts","names":[],"sources":["../../../src/storages/redis/keyed-store.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"keyed-store.d.ts","names":[],"sources":["../../../src/storages/redis/keyed-store.ts"],"mappings":";;;;;;AA6BA;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,qBAAA,aAAA,CAAmC,OAAA,EAAS,aAAA,CAAc,gBAAA,sBAC7C,KAAA,MAAW,IAAA,EAAM,CAAA,gBAAY,QAAA;qBAC/B,CAAA,KAAC,OAAA,CAAA,QAAA,CAAA,CAAA;wBACE,CAAA,KAAC,OAAA;qBACJ,CAAA,KAAC,OAAA;wBACE,CAAA,KAAC,OAAA;wBACD,CAAA;mBACL,CAAA,KAAC,IAAA,EAAW,CAAA,KAAC,OAAA;qCACG,KAAA,EAAS,CAAA,KAAC,IAAA,EAAW,CAAA,GAAC,OAAA;AAAA"}
|
|
@@ -1,4 +1,29 @@
|
|
|
1
1
|
//#region src/storages/redis/keyed-store.ts
|
|
2
|
+
/**
|
|
3
|
+
* Creates a keyed store wrapper around a Redis-like storage.
|
|
4
|
+
*
|
|
5
|
+
* @template D - The data type stored in the keyed store
|
|
6
|
+
*
|
|
7
|
+
* @param {MaybeReadonly<RedisLikeStorage>} storage - The underlying Redis-like storage instance
|
|
8
|
+
*
|
|
9
|
+
* @returns {(keyFn: (...args: P) => string) => Readonly<{
|
|
10
|
+
* getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem, setItemWithTtl
|
|
11
|
+
* }>} A keyed store factory that takes a key resolution function
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { createRedisKeyedStore } from '@kikiutils/shared/storages/redis/keyed-store';
|
|
16
|
+
* import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';
|
|
17
|
+
* import { createClient } from 'redis';
|
|
18
|
+
*
|
|
19
|
+
* const client = createClient();
|
|
20
|
+
* await client.connect();
|
|
21
|
+
* const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);
|
|
22
|
+
* const keyedStore = createRedisKeyedStore(storage)((userId: string) => `user:${userId}`);
|
|
23
|
+
* await keyedStore.setItem({ name: 'Alice' }, 'user-123');
|
|
24
|
+
* const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
2
27
|
function createRedisKeyedStore(storage) {
|
|
3
28
|
return (keyFn) => Object.freeze({
|
|
4
29
|
getItem: (...args) => storage.getItem(keyFn(...args)),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyed-store.js","names":[],"sources":["../../../src/storages/redis/keyed-store.ts"],"sourcesContent":["import type { MaybeReadonly } from '../../types';\n\nimport type { RedisLikeStorage } from './types';\n\nexport function createRedisKeyedStore<D = unknown>(storage: MaybeReadonly<RedisLikeStorage>) {\n return <P extends any[]>(keyFn: (...args: P) => string) => Object.freeze({\n getItem: (...args: P) => storage.getItem<D>(keyFn(...args)),\n getItemTtl: (...args: P) => storage.getItemTtl(keyFn(...args)),\n hasItem: (...args: P) => storage.hasItem(keyFn(...args)),\n removeItem: (...args: P) => storage.removeItem(keyFn(...args)),\n resolveKey: (...args: P) => keyFn(...args),\n setItem: (value: D, ...args: P) => storage.setItem(keyFn(...args), value),\n setItemWithTtl(ttlSeconds: number, value: D, ...args: P) {\n return storage.setItemWithTtl(keyFn(...args), ttlSeconds, value);\n },\n });\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"keyed-store.js","names":[],"sources":["../../../src/storages/redis/keyed-store.ts"],"sourcesContent":["import type { MaybeReadonly } from '../../types';\n\nimport type { RedisLikeStorage } from './types';\n\n/**\n * Creates a keyed store wrapper around a Redis-like storage.\n *\n * @template D - The data type stored in the keyed store\n *\n * @param {MaybeReadonly<RedisLikeStorage>} storage - The underlying Redis-like storage instance\n *\n * @returns {(keyFn: (...args: P) => string) => Readonly<{\n * getItem, getItemTtl, hasItem, removeItem, resolveKey, setItem, setItemWithTtl\n * }>} A keyed store factory that takes a key resolution function\n *\n * @example\n * ```typescript\n * import { createRedisKeyedStore } from '@kikiutils/shared/storages/redis/keyed-store';\n * import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';\n * import { createClient } from 'redis';\n *\n * const client = createClient();\n * await client.connect();\n * const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);\n * const keyedStore = createRedisKeyedStore(storage)((userId: string) => `user:${userId}`);\n * await keyedStore.setItem({ name: 'Alice' }, 'user-123');\n * const user = await keyedStore.getItem('user-123'); // { name: 'Alice' }\n * ```\n */\nexport function createRedisKeyedStore<D = unknown>(storage: MaybeReadonly<RedisLikeStorage>) {\n return <P extends any[]>(keyFn: (...args: P) => string) => Object.freeze({\n getItem: (...args: P) => storage.getItem<D>(keyFn(...args)),\n getItemTtl: (...args: P) => storage.getItemTtl(keyFn(...args)),\n hasItem: (...args: P) => storage.hasItem(keyFn(...args)),\n removeItem: (...args: P) => storage.removeItem(keyFn(...args)),\n resolveKey: (...args: P) => keyFn(...args),\n setItem: (value: D, ...args: P) => storage.setItem(keyFn(...args), value),\n setItemWithTtl(ttlSeconds: number, value: D, ...args: P) {\n return storage.setItemWithTtl(keyFn(...args), ttlSeconds, value);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,sBAAmC,SAA0C;AACzF,SAAyB,UAAkC,OAAO,OAAO;EACrE,UAAU,GAAG,SAAY,QAAQ,QAAW,MAAM,GAAG,KAAK,CAAC;EAC3D,aAAa,GAAG,SAAY,QAAQ,WAAW,MAAM,GAAG,KAAK,CAAC;EAC9D,UAAU,GAAG,SAAY,QAAQ,QAAQ,MAAM,GAAG,KAAK,CAAC;EACxD,aAAa,GAAG,SAAY,QAAQ,WAAW,MAAM,GAAG,KAAK,CAAC;EAC9D,aAAa,GAAG,SAAY,MAAM,GAAG,KAAK;EAC1C,UAAU,OAAU,GAAG,SAAY,QAAQ,QAAQ,MAAM,GAAG,KAAK,EAAE,MAAM;EACzE,eAAe,YAAoB,OAAU,GAAG,MAAS;AACrD,UAAO,QAAQ,eAAe,MAAM,GAAG,KAAK,EAAE,YAAY,MAAM;;EAEvE,CAAC"}
|
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
import { RedisLikeAdapter, RedisLikeStorage } from "./types.js";
|
|
2
2
|
|
|
3
3
|
//#region src/storages/redis/msgpack.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Creates a Redis-like storage using msgpack serialization.
|
|
6
|
+
*
|
|
7
|
+
* @param {RedisLikeAdapter} adapter - The Redis-like adapter to use for raw buffer operations
|
|
8
|
+
*
|
|
9
|
+
* @returns {Readonly<RedisLikeStorage>} A readonly storage instance
|
|
10
|
+
* with getItem, setItem, hasItem, removeItem, getItemTtl, setItemWithTtl
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';
|
|
15
|
+
* import { createClient } from 'redis';
|
|
16
|
+
*
|
|
17
|
+
* const client = createClient();
|
|
18
|
+
* await client.connect();
|
|
19
|
+
* const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);
|
|
20
|
+
* await storage.setItem('key', { foo: 'bar' });
|
|
21
|
+
* const value = await storage.getItem('key'); // { foo: 'bar' }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
4
24
|
declare function createRedisMsgpackStorage(adapter: RedisLikeAdapter): Readonly<RedisLikeStorage>;
|
|
5
25
|
//#endregion
|
|
6
26
|
export { createRedisMsgpackStorage };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"msgpack.d.ts","names":[],"sources":["../../../src/storages/redis/msgpack.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"msgpack.d.ts","names":[],"sources":["../../../src/storages/redis/msgpack.ts"],"mappings":";;;;;AAmCA;;;;;;;;;;;;;;;;;;iBAAgB,yBAAA,CAA0B,OAAA,EAAS,gBAAA,GAAmB,QAAA,CAAS,gBAAA"}
|
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
import { decode, encode, isNativeAccelerationEnabled } from "msgpackr";
|
|
2
2
|
//#region src/storages/redis/msgpack.ts
|
|
3
3
|
if (!isNativeAccelerationEnabled) console.warn("Native acceleration not enabled for msgpackr, verify that install finished properly");
|
|
4
|
+
/**
|
|
5
|
+
* Creates a Redis-like storage using msgpack serialization.
|
|
6
|
+
*
|
|
7
|
+
* @param {RedisLikeAdapter} adapter - The Redis-like adapter to use for raw buffer operations
|
|
8
|
+
*
|
|
9
|
+
* @returns {Readonly<RedisLikeStorage>} A readonly storage instance
|
|
10
|
+
* with getItem, setItem, hasItem, removeItem, getItemTtl, setItemWithTtl
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';
|
|
15
|
+
* import { createClient } from 'redis';
|
|
16
|
+
*
|
|
17
|
+
* const client = createClient();
|
|
18
|
+
* await client.connect();
|
|
19
|
+
* const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);
|
|
20
|
+
* await storage.setItem('key', { foo: 'bar' });
|
|
21
|
+
* const value = await storage.getItem('key'); // { foo: 'bar' }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
4
24
|
function createRedisMsgpackStorage(adapter) {
|
|
5
25
|
return Object.freeze({
|
|
6
26
|
async getItem(key) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"msgpack.js","names":[],"sources":["../../../src/storages/redis/msgpack.ts"],"sourcesContent":["import {\n decode,\n encode,\n isNativeAccelerationEnabled,\n} from 'msgpackr';\n\nimport type {\n RedisLikeAdapter,\n RedisLikeStorage,\n} from './types';\n\nif (!isNativeAccelerationEnabled) {\n console.warn('Native acceleration not enabled for msgpackr, verify that install finished properly');\n}\n\nexport function createRedisMsgpackStorage(adapter: RedisLikeAdapter): Readonly<RedisLikeStorage> {\n return Object.freeze({\n async getItem<T = unknown>(key: string) {\n const rawValue = await adapter.getBuffer(key);\n return rawValue ? decode(rawValue) as T : null;\n },\n getItemTtl: (key: string) => adapter.ttl(key),\n hasItem: (key: string) => adapter.has(key),\n removeItem: async (key: string) => await adapter.delete(key) === 1,\n setItem: async (key: string, value: any) => await adapter.setBuffer(key, encode(value)) === 'OK',\n async setItemWithTtl(key: string, ttlSeconds: number, value: any) {\n return await adapter.setBufferEx(key, ttlSeconds, encode(value)) === 'OK';\n },\n });\n}\n"],"mappings":";;AAWA,IAAI,CAAC,4BACD,SAAQ,KAAK,sFAAsF
|
|
1
|
+
{"version":3,"file":"msgpack.js","names":[],"sources":["../../../src/storages/redis/msgpack.ts"],"sourcesContent":["import {\n decode,\n encode,\n isNativeAccelerationEnabled,\n} from 'msgpackr';\n\nimport type {\n RedisLikeAdapter,\n RedisLikeStorage,\n} from './types';\n\nif (!isNativeAccelerationEnabled) {\n console.warn('Native acceleration not enabled for msgpackr, verify that install finished properly');\n}\n\n/**\n * Creates a Redis-like storage using msgpack serialization.\n *\n * @param {RedisLikeAdapter} adapter - The Redis-like adapter to use for raw buffer operations\n *\n * @returns {Readonly<RedisLikeStorage>} A readonly storage instance\n * with getItem, setItem, hasItem, removeItem, getItemTtl, setItemWithTtl\n *\n * @example\n * ```typescript\n * import { createRedisMsgpackStorage } from '@kikiutils/shared/storages/redis/msgpack';\n * import { createClient } from 'redis';\n *\n * const client = createClient();\n * await client.connect();\n * const storage = createRedisMsgpackStorage(client as unknown as RedisLikeAdapter);\n * await storage.setItem('key', { foo: 'bar' });\n * const value = await storage.getItem('key'); // { foo: 'bar' }\n * ```\n */\nexport function createRedisMsgpackStorage(adapter: RedisLikeAdapter): Readonly<RedisLikeStorage> {\n return Object.freeze({\n async getItem<T = unknown>(key: string) {\n const rawValue = await adapter.getBuffer(key);\n return rawValue ? decode(rawValue) as T : null;\n },\n getItemTtl: (key: string) => adapter.ttl(key),\n hasItem: (key: string) => adapter.has(key),\n removeItem: async (key: string) => await adapter.delete(key) === 1,\n setItem: async (key: string, value: any) => await adapter.setBuffer(key, encode(value)) === 'OK',\n async setItemWithTtl(key: string, ttlSeconds: number, value: any) {\n return await adapter.setBufferEx(key, ttlSeconds, encode(value)) === 'OK';\n },\n });\n}\n"],"mappings":";;AAWA,IAAI,CAAC,4BACD,SAAQ,KAAK,sFAAsF;;;;;;;;;;;;;;;;;;;;;AAuBvG,SAAgB,0BAA0B,SAAuD;AAC7F,QAAO,OAAO,OAAO;EACjB,MAAM,QAAqB,KAAa;GACpC,MAAM,WAAW,MAAM,QAAQ,UAAU,IAAI;AAC7C,UAAO,WAAW,OAAO,SAAS,GAAQ;;EAE9C,aAAa,QAAgB,QAAQ,IAAI,IAAI;EAC7C,UAAU,QAAgB,QAAQ,IAAI,IAAI;EAC1C,YAAY,OAAO,QAAgB,MAAM,QAAQ,OAAO,IAAI,KAAK;EACjE,SAAS,OAAO,KAAa,UAAe,MAAM,QAAQ,UAAU,KAAK,OAAO,MAAM,CAAC,KAAK;EAC5F,MAAM,eAAe,KAAa,YAAoB,OAAY;AAC9D,UAAO,MAAM,QAAQ,YAAY,KAAK,YAAY,OAAO,MAAM,CAAC,KAAK;;EAE5E,CAAC"}
|
|
@@ -1,20 +1,62 @@
|
|
|
1
1
|
import { Nullable } from "../../types/index.js";
|
|
2
2
|
|
|
3
3
|
//#region src/storages/redis/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Low-level Redis-like adapter interface for raw buffer operations.
|
|
6
|
+
*/
|
|
4
7
|
interface RedisLikeAdapter {
|
|
8
|
+
/**
|
|
9
|
+
* Deletes a key and returns the number of keys deleted.
|
|
10
|
+
*/
|
|
5
11
|
delete: (key: string) => Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* Gets the raw buffer value for a key.
|
|
14
|
+
*/
|
|
6
15
|
getBuffer: (key: string) => Promise<Nullable<Uint8Array>>;
|
|
16
|
+
/**
|
|
17
|
+
* Checks if a key exists.
|
|
18
|
+
*/
|
|
7
19
|
has: (key: string) => Promise<boolean>;
|
|
20
|
+
/**
|
|
21
|
+
* Sets a raw buffer value for a key.
|
|
22
|
+
*/
|
|
8
23
|
setBuffer: (key: string, value: Uint8Array) => Promise<'OK' | void>;
|
|
24
|
+
/**
|
|
25
|
+
* Sets a raw buffer value for a key with a TTL.
|
|
26
|
+
*/
|
|
9
27
|
setBufferEx: (key: string, ttlSeconds: number, value: Uint8Array) => Promise<'OK' | void>;
|
|
28
|
+
/**
|
|
29
|
+
* Gets the TTL of a key in seconds.
|
|
30
|
+
*/
|
|
10
31
|
ttl: (key: string) => Promise<number>;
|
|
11
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* High-level Redis-like storage interface with typed get/set operations.
|
|
35
|
+
*/
|
|
12
36
|
interface RedisLikeStorage {
|
|
37
|
+
/**
|
|
38
|
+
* Gets a deserialized value by key.
|
|
39
|
+
*/
|
|
13
40
|
getItem: <T = unknown>(key: string) => Promise<Nullable<T>>;
|
|
41
|
+
/**
|
|
42
|
+
* Gets the TTL of a key in seconds.
|
|
43
|
+
*/
|
|
14
44
|
getItemTtl: (key: string) => Promise<number>;
|
|
45
|
+
/**
|
|
46
|
+
* Checks if a key exists.
|
|
47
|
+
*/
|
|
15
48
|
hasItem: (key: string) => Promise<boolean>;
|
|
49
|
+
/**
|
|
50
|
+
* Removes a key.
|
|
51
|
+
*/
|
|
16
52
|
removeItem: (key: string) => Promise<boolean>;
|
|
53
|
+
/**
|
|
54
|
+
* Sets a value for a key.
|
|
55
|
+
*/
|
|
17
56
|
setItem: (key: string, value: any) => Promise<boolean>;
|
|
57
|
+
/**
|
|
58
|
+
* Sets a value for a key with a TTL.
|
|
59
|
+
*/
|
|
18
60
|
setItemWithTtl: (key: string, ttlSeconds: number, value: any) => Promise<boolean>;
|
|
19
61
|
}
|
|
20
62
|
//#endregion
|