@catbee/utils 0.0.8-rc.2 → 0.0.8-rc.4

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.
Files changed (66) hide show
  1. package/build/index.cjs +6591 -0
  2. package/build/index.d.ts +5131 -0
  3. package/build/index.mjs +6321 -0
  4. package/package.json +12 -36
  5. package/build/esm/config.d.ts +0 -121
  6. package/build/esm/config.js +0 -132
  7. package/build/esm/index.d.ts +0 -26
  8. package/build/esm/index.js +0 -49
  9. package/build/esm/servers/server.builder.d.ts +0 -507
  10. package/build/esm/servers/server.builder.js +0 -654
  11. package/build/esm/servers/server.d.ts +0 -255
  12. package/build/esm/servers/server.js +0 -963
  13. package/build/esm/types/api-response.d.ts +0 -151
  14. package/build/esm/types/api-response.js +0 -33
  15. package/build/esm/types/index.d.ts +0 -124
  16. package/build/esm/types/index.js +0 -24
  17. package/build/esm/types/server.d.ts +0 -267
  18. package/build/esm/types/server.js +0 -24
  19. package/build/esm/utils/array.utils.d.ts +0 -167
  20. package/build/esm/utils/array.utils.js +0 -344
  21. package/build/esm/utils/async.utils.d.ts +0 -264
  22. package/build/esm/utils/async.utils.js +0 -619
  23. package/build/esm/utils/cache.utils.d.ts +0 -152
  24. package/build/esm/utils/cache.utils.js +0 -294
  25. package/build/esm/utils/context-store.utils.d.ts +0 -188
  26. package/build/esm/utils/context-store.utils.js +0 -290
  27. package/build/esm/utils/crypto.utils.d.ts +0 -159
  28. package/build/esm/utils/crypto.utils.js +0 -278
  29. package/build/esm/utils/date.utils.d.ts +0 -158
  30. package/build/esm/utils/date.utils.js +0 -383
  31. package/build/esm/utils/decorators.utils.d.ts +0 -511
  32. package/build/esm/utils/decorators.utils.js +0 -1013
  33. package/build/esm/utils/dir.utils.d.ts +0 -195
  34. package/build/esm/utils/dir.utils.js +0 -476
  35. package/build/esm/utils/env.utils.d.ts +0 -376
  36. package/build/esm/utils/env.utils.js +0 -782
  37. package/build/esm/utils/exception.utils.d.ts +0 -229
  38. package/build/esm/utils/exception.utils.js +0 -382
  39. package/build/esm/utils/fs.utils.d.ts +0 -163
  40. package/build/esm/utils/fs.utils.js +0 -348
  41. package/build/esm/utils/http-status-codes.d.ts +0 -265
  42. package/build/esm/utils/http-status-codes.js +0 -294
  43. package/build/esm/utils/id.utils.d.ts +0 -35
  44. package/build/esm/utils/id.utils.js +0 -83
  45. package/build/esm/utils/logger.utils.d.ts +0 -159
  46. package/build/esm/utils/logger.utils.js +0 -304
  47. package/build/esm/utils/middleware.utils.d.ts +0 -99
  48. package/build/esm/utils/middleware.utils.js +0 -235
  49. package/build/esm/utils/obj.utils.d.ts +0 -123
  50. package/build/esm/utils/obj.utils.js +0 -412
  51. package/build/esm/utils/performance.utils.d.ts +0 -135
  52. package/build/esm/utils/performance.utils.js +0 -273
  53. package/build/esm/utils/request.utils.d.ts +0 -85
  54. package/build/esm/utils/request.utils.js +0 -190
  55. package/build/esm/utils/response.utils.d.ts +0 -162
  56. package/build/esm/utils/response.utils.js +0 -261
  57. package/build/esm/utils/stream.utils.d.ts +0 -87
  58. package/build/esm/utils/stream.utils.js +0 -209
  59. package/build/esm/utils/string.utils.d.ts +0 -92
  60. package/build/esm/utils/string.utils.js +0 -164
  61. package/build/esm/utils/type.utils.d.ts +0 -89
  62. package/build/esm/utils/type.utils.js +0 -186
  63. package/build/esm/utils/url.utils.d.ts +0 -140
  64. package/build/esm/utils/url.utils.js +0 -303
  65. package/build/esm/utils/validate.utils.d.ts +0 -176
  66. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,290 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import { AsyncLocalStorage } from 'async_hooks';
25
- /**
26
- * Predefined symbols used as keys in AsyncLocalStorage.
27
- * Add new symbols here to avoid duplication.
28
- */
29
- export const StoreKeys = {
30
- LOGGER: Symbol('LOGGER'),
31
- REQUEST_ID: Symbol('REQUEST_ID'),
32
- USER: Symbol('USER'),
33
- SESSION: Symbol('SESSION'),
34
- TRANSACTION_ID: Symbol('TRANSACTION_ID'),
35
- USER_ID: Symbol('USER_ID'),
36
- TENANT_ID: Symbol('TENANT_ID'),
37
- TRACE_ID: Symbol('TRACE_ID'),
38
- CORRELATION_ID: Symbol('CORRELATION_ID')
39
- };
40
- /**
41
- * Retrieves the current request ID from the async context, if available.
42
- *
43
- * @returns {string | undefined} The request ID string or undefined if not present in the current context.
44
- */
45
- export function getRequestId() {
46
- return ContextStore.get(StoreKeys.REQUEST_ID);
47
- }
48
- /**
49
- * Type-safe getter for common context values.
50
- *
51
- * @param key The store key symbol
52
- * @returns The typed value from the store
53
- */
54
- export function getFromContext(key) {
55
- return ContextStore.get(key);
56
- }
57
- /**
58
- * ContextStore manages per-request scoped context using AsyncLocalStorage.
59
- * It allows storing and retrieving data across async calls (e.g., request ID, logger).
60
- *
61
- * Example (Express middleware):
62
- * ```
63
- * // Middleware to initialize context and logger
64
- * app.use((req, res, next) => {
65
- * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
66
- * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
67
- * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
68
- * next();
69
- * });
70
- * });
71
- * ```
72
- */
73
- export class ContextStore {
74
- /**
75
- * The underlying AsyncLocalStorage instance for context.
76
- * @private
77
- */
78
- static storage = new AsyncLocalStorage();
79
- /**
80
- * Returns the raw AsyncLocalStorage instance for advanced access.
81
- *
82
- * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
83
- */
84
- static getInstance() {
85
- return this.storage;
86
- }
87
- /**
88
- * Retrieves a value from the async context store by symbol key.
89
- *
90
- * @typeParam T - The expected return type of the value.
91
- * @param {symbol} key - Unique symbol used as the store key.
92
- * @returns {T | undefined} The value found (typed) or undefined if not present.
93
- */
94
- static get(key) {
95
- const store = this.storage.getStore();
96
- return store?.[key];
97
- }
98
- /**
99
- * Sets a value in the current context store by symbol key.
100
- *
101
- * @typeParam T - The value type to set.
102
- * @param {symbol} key - Unique symbol key.
103
- * @param {T} value - Value to set in context.
104
- * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
105
- */
106
- static set(key, value) {
107
- const store = this.storage.getStore();
108
- if (!store) {
109
- throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);
110
- }
111
- store[key] = value;
112
- }
113
- /**
114
- * Retrieves the entire context store object for the current async context.
115
- *
116
- * @returns {Store | undefined} The current store object or undefined if called outside a context.
117
- */
118
- static getAll() {
119
- return this.storage.getStore();
120
- }
121
- /**
122
- * Initializes a new async context and executes a callback within it.
123
- * This must be called at the beginning of a request or logical async flow.
124
- *
125
- * @typeParam T - The callback's return type.
126
- * @param {Store} store - The initial key-value store object.
127
- * @param {() => T} callback - The function to run within the new context.
128
- * @returns {T} The result of the callback function.
129
- */
130
- static run(store, callback) {
131
- return this.storage.run(store, callback);
132
- }
133
- /**
134
- * Checks if a key exists in the current context store.
135
- *
136
- * @param {symbol} key - The symbol key to check.
137
- * @returns {boolean} True if the key exists, false otherwise.
138
- */
139
- static has(key) {
140
- const store = this.storage.getStore();
141
- return store !== undefined && key in store;
142
- }
143
- /**
144
- * Removes a value from the current context store by symbol key.
145
- *
146
- * @param {symbol} key - The symbol key to delete.
147
- * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
148
- * @throws {Error} If called outside an active context.
149
- */
150
- static delete(key) {
151
- const store = this.storage.getStore();
152
- if (!store) {
153
- throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
154
- }
155
- return delete store[key];
156
- }
157
- /**
158
- * Updates multiple values in the current context store at once.
159
- *
160
- * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
161
- * @throws {Error} If called outside an active context.
162
- */
163
- static patch(values) {
164
- const store = this.storage.getStore();
165
- if (!store) {
166
- throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');
167
- }
168
- Object.getOwnPropertySymbols(values).forEach(key => {
169
- store[key] = values[key];
170
- });
171
- }
172
- /**
173
- * Executes a callback with a temporary store value that only exists during execution.
174
- * Original store is restored after callback completes.
175
- *
176
- * @typeParam T - The callback's return type.
177
- * @param {symbol} key - The symbol key to temporarily set.
178
- * @param {unknown} value - The temporary value.
179
- * @param {() => T} callback - The function to execute with the temporary value.
180
- * @returns {T} The result of the callback function.
181
- * @throws {Error} If called outside an active context.
182
- */
183
- static withValue(key, value, callback) {
184
- const store = this.storage.getStore();
185
- if (!store) {
186
- throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
187
- }
188
- // Save original value
189
- const hasOriginal = key in store;
190
- const originalValue = store[key];
191
- // Set temporary value
192
- store[key] = value;
193
- try {
194
- // Run callback
195
- return callback();
196
- }
197
- finally {
198
- // Restore original value
199
- if (hasOriginal) {
200
- store[key] = originalValue;
201
- }
202
- else {
203
- delete store[key];
204
- }
205
- }
206
- }
207
- /**
208
- * Creates a new context that inherits values from the current context.
209
- *
210
- * @typeParam T - The callback's return type.
211
- * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
212
- * @param {() => T} callback - The function to execute in the new context.
213
- * @returns {T} The result of the callback function.
214
- */
215
- static extend(newValues, callback) {
216
- const currentStore = this.storage.getStore() || {};
217
- // Create new store with current values plus new ones
218
- const newStore = { ...currentStore };
219
- // Add new values
220
- Object.getOwnPropertySymbols(newValues).forEach(key => {
221
- newStore[key] = newValues[key];
222
- });
223
- // Run with extended store
224
- return this.storage.run(newStore, callback);
225
- }
226
- /**
227
- * Creates Express middleware that initializes a context for each request.
228
- *
229
- * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
230
- * @returns Express middleware function.
231
- */
232
- static createExpressMiddleware(initialValuesFactory = () => ({})) {
233
- return (req, res, next) => {
234
- const initialValues = initialValuesFactory(req);
235
- ContextStore.run(initialValues, next);
236
- };
237
- }
238
- }
239
- /**
240
- * Type-safe wrapper for accessing and modifying context values with specific types.
241
- *
242
- * @typeParam T - The value type.
243
- */
244
- export class TypedContextKey {
245
- symbol;
246
- defaultValue;
247
- /**
248
- * Creates a new typed context key.
249
- *
250
- * @param symbol - The unique symbol for this key
251
- * @param defaultValue - Optional default value if key is not found
252
- */
253
- constructor(symbol, defaultValue) {
254
- this.symbol = symbol;
255
- this.defaultValue = defaultValue;
256
- }
257
- /**
258
- * Gets the current value for this key.
259
- *
260
- * @returns The value or defaultValue if not found
261
- */
262
- get() {
263
- const value = ContextStore.get(this.symbol);
264
- return value !== undefined ? value : this.defaultValue;
265
- }
266
- /**
267
- * Sets the value for this key.
268
- *
269
- * @param value The value to set
270
- */
271
- set(value) {
272
- ContextStore.set(this.symbol, value);
273
- }
274
- /**
275
- * Checks if this key exists in the context.
276
- *
277
- * @returns True if the key exists
278
- */
279
- exists() {
280
- return ContextStore.has(this.symbol);
281
- }
282
- /**
283
- * Deletes this key from the context.
284
- *
285
- * @returns True if the key was deleted
286
- */
287
- delete() {
288
- return ContextStore.delete(this.symbol);
289
- }
290
- }
@@ -1,159 +0,0 @@
1
- import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
2
- export type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
3
- /**
4
- * Generates an HMAC digest using the specified algorithm and secret key.
5
- *
6
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
7
- * @param {string} input - The string to hash.
8
- * @param {string} secret - The secret key for HMAC.
9
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
10
- * @returns {string} HMAC digest as a string.
11
- */
12
- export declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
13
- /**
14
- * Generates a hash digest using the specified algorithm.
15
- *
16
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
17
- * @param {string} input - The string to hash.
18
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
19
- * @returns {string} Hash digest as a string.
20
- */
21
- export declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
22
- /**
23
- * Generates an HMAC-SHA256 digest.
24
- *
25
- * @param {string} input - The string to hash.
26
- * @param {string} secret - The secret key.
27
- * @returns {string} SHA-256 HMAC digest as a string.
28
- */
29
- export declare function sha256Hmac(input: string, secret: string): string;
30
- /**
31
- * Generates a SHA1 hash digest.
32
- *
33
- * @param {string} input - The string to hash.
34
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
35
- * @returns {string} SHA-1 hash as a string.
36
- */
37
- export declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
38
- /**
39
- * Generates a SHA256 hash digest.
40
- *
41
- * @param {string} input - The string to hash.
42
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
43
- * @returns {string} SHA-256 hash as a string.
44
- */
45
- export declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
46
- /**
47
- * Generates an MD5 hash digest.
48
- *
49
- * @param {string} input - The string to hash.
50
- * @returns {string} MD5 hash as a string.
51
- */
52
- export declare function md5(input: string): string;
53
- /**
54
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
55
- *
56
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
57
- */
58
- export declare function randomString(): string;
59
- /**
60
- * Generates a secure random buffer of specified byte length.
61
- *
62
- * @param {number} [byteLength=32] - Number of random bytes to generate.
63
- * @returns {Buffer} Buffer containing random bytes.
64
- */
65
- export declare function generateRandomBytes(byteLength?: number): Buffer;
66
- /**
67
- * Generates a secure random string of specified byte length with specified encoding.
68
- *
69
- * @param {number} [byteLength=32] - Number of random bytes to generate.
70
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
71
- * @returns {string} Random string in specified encoding.
72
- */
73
- export declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
74
- /**
75
- * Generates a secure API key with a specified format.
76
- *
77
- * @param {string} [prefix=''] - Optional prefix for the key.
78
- * @param {number} [byteLength=24] - Number of random bytes to generate.
79
- * @returns {string} Formatted API key.
80
- */
81
- export declare function generateApiKey(prefix?: string, byteLength?: number): string;
82
- /**
83
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
84
- *
85
- * @param {string | Buffer | Uint8Array} a - First value to compare
86
- * @param {string | Buffer | Uint8Array} b - Second value to compare
87
- * @returns {boolean} True if values are equal
88
- */
89
- export declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
90
- /**
91
- * Interface for encryption options
92
- */
93
- export interface EncryptionOptions {
94
- /** Algorithm to use (default: aes-256-gcm) */
95
- algorithm?: CipherGCMTypes;
96
- /** Input encoding for plaintext if string (default: utf8) */
97
- inputEncoding?: BufferEncoding;
98
- /** Output encoding for ciphertext (default: hex) */
99
- outputEncoding?: BinaryToTextEncoding;
100
- }
101
- /**
102
- * Interface for decryption options
103
- */
104
- export interface DecryptionOptions {
105
- /** Algorithm to use (default: aes-256-gcm) */
106
- algorithm?: CipherGCMTypes;
107
- /** Input encoding for ciphertext if string (default: hex) */
108
- inputEncoding?: BinaryToTextEncoding;
109
- /** Output encoding for plaintext (default: utf8) */
110
- outputEncoding?: BufferEncoding;
111
- }
112
- /**
113
- * Result of encryption operation including all data needed for decryption
114
- */
115
- export interface EncryptionResult {
116
- /** Encrypted data (string or Buffer based on options) */
117
- ciphertext: string | Buffer;
118
- /** Initialization vector */
119
- iv: Buffer;
120
- /** Authentication tag (for GCM mode) */
121
- authTag?: Buffer;
122
- /** Algorithm used */
123
- algorithm: string;
124
- }
125
- /**
126
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
127
- *
128
- * @param {string | Buffer} data - Data to encrypt
129
- * @param {string | Buffer} key - Encryption key or passphrase
130
- * @param {EncryptionOptions} [options] - Encryption options
131
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
132
- */
133
- export declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
134
- /**
135
- * Decrypts data that was encrypted with the encrypt function.
136
- *
137
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
138
- * @param {string | Buffer} key - Decryption key or passphrase
139
- * @param {DecryptionOptions} [options] - Decryption options
140
- * @returns {Promise<string | Buffer>} Decrypted data
141
- */
142
- export declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
143
- /**
144
- * Creates a signed token with an expiration time and payload.
145
- *
146
- * @param {object} payload - Data to include in the token
147
- * @param {string} secret - Secret key for signing
148
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
149
- * @returns {string} Signed token string
150
- */
151
- export declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
152
- /**
153
- * Verifies and decodes a signed token.
154
- *
155
- * @param {string} token - The token to verify
156
- * @param {string} secret - Secret key for verification
157
- * @returns {object | null} Decoded payload if valid, null if invalid
158
- */
159
- export declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;