@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,278 +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 { createHmac, createHash, randomBytes, createCipheriv, createDecipheriv, scrypt, timingSafeEqual } from 'crypto';
25
- import { promisify } from 'util';
26
- import { uuid } from './id.utils';
27
- /**
28
- * Generates an HMAC digest using the specified algorithm and secret key.
29
- *
30
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
31
- * @param {string} input - The string to hash.
32
- * @param {string} secret - The secret key for HMAC.
33
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
34
- * @returns {string} HMAC digest as a string.
35
- */
36
- export function hmac(algorithm, input, secret, encoding = 'hex') {
37
- return createHmac(algorithm, secret).update(input).digest(encoding);
38
- }
39
- /**
40
- * Generates a hash digest using the specified algorithm.
41
- *
42
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
43
- * @param {string} input - The string to hash.
44
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
45
- * @returns {string} Hash digest as a string.
46
- */
47
- export function hash(algorithm, input, encoding = 'hex') {
48
- return createHash(algorithm).update(input).digest(encoding);
49
- }
50
- /**
51
- * Generates an HMAC-SHA256 digest.
52
- *
53
- * @param {string} input - The string to hash.
54
- * @param {string} secret - The secret key.
55
- * @returns {string} SHA-256 HMAC digest as a string.
56
- */
57
- export function sha256Hmac(input, secret) {
58
- return hmac('sha256', input, secret);
59
- }
60
- /**
61
- * Generates a SHA1 hash digest.
62
- *
63
- * @param {string} input - The string to hash.
64
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
65
- * @returns {string} SHA-1 hash as a string.
66
- */
67
- export function sha1(input, encoding = 'hex') {
68
- return hash('sha1', input, encoding);
69
- }
70
- /**
71
- * Generates a SHA256 hash digest.
72
- *
73
- * @param {string} input - The string to hash.
74
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
75
- * @returns {string} SHA-256 hash as a string.
76
- */
77
- export function sha256(input, encoding = 'hex') {
78
- return hash('sha256', input, encoding);
79
- }
80
- /**
81
- * Generates an MD5 hash digest.
82
- *
83
- * @param {string} input - The string to hash.
84
- * @returns {string} MD5 hash as a string.
85
- */
86
- export function md5(input) {
87
- return hash('md5', input);
88
- }
89
- /**
90
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
91
- *
92
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
93
- */
94
- export function randomString() {
95
- return sha256(uuid());
96
- }
97
- /**
98
- * Generates a secure random buffer of specified byte length.
99
- *
100
- * @param {number} [byteLength=32] - Number of random bytes to generate.
101
- * @returns {Buffer} Buffer containing random bytes.
102
- */
103
- export function generateRandomBytes(byteLength = 32) {
104
- return randomBytes(byteLength);
105
- }
106
- /**
107
- * Generates a secure random string of specified byte length with specified encoding.
108
- *
109
- * @param {number} [byteLength=32] - Number of random bytes to generate.
110
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
111
- * @returns {string} Random string in specified encoding.
112
- */
113
- export function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
114
- return randomBytes(byteLength).toString(encoding);
115
- }
116
- /**
117
- * Generates a secure API key with a specified format.
118
- *
119
- * @param {string} [prefix=''] - Optional prefix for the key.
120
- * @param {number} [byteLength=24] - Number of random bytes to generate.
121
- * @returns {string} Formatted API key.
122
- */
123
- export function generateApiKey(prefix = '', byteLength = 24) {
124
- const randomString = generateRandomBytesAsString(byteLength, 'base64');
125
- const key = randomString
126
- .replace(/[+/=]/g, '') // Remove non-URL-safe characters
127
- .substring(0, 32); // Limit length
128
- return prefix ? `${prefix}_${key}` : key;
129
- }
130
- /**
131
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
132
- *
133
- * @param {string | Buffer | Uint8Array} a - First value to compare
134
- * @param {string | Buffer | Uint8Array} b - Second value to compare
135
- * @returns {boolean} True if values are equal
136
- */
137
- export function safeCompare(a, b) {
138
- if (typeof a === 'string' && typeof b === 'string') {
139
- // Convert strings to buffers
140
- const bufA = Buffer.from(a);
141
- const bufB = Buffer.from(b);
142
- // Compare lengths first (not constant time, but prevents timing attack on contents)
143
- if (bufA.length !== bufB.length)
144
- return false;
145
- return timingSafeEqual(bufA, bufB);
146
- }
147
- else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
148
- // Compare lengths first
149
- if (a.length !== b.length)
150
- return false;
151
- return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
152
- }
153
- throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
154
- }
155
- // Promisified version of scrypt for key derivation
156
- const scryptAsync = promisify(scrypt);
157
- /**
158
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
159
- *
160
- * @param {string | Buffer} data - Data to encrypt
161
- * @param {string | Buffer} key - Encryption key or passphrase
162
- * @param {EncryptionOptions} [options] - Encryption options
163
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
164
- */
165
- export async function encrypt(data, key, options = {}) {
166
- const algorithm = options.algorithm || 'aes-256-gcm';
167
- const inputEncoding = options.inputEncoding || 'utf8';
168
- const outputEncoding = options.outputEncoding || 'hex';
169
- // Generate a random IV
170
- const iv = randomBytes(16);
171
- // Derive key using scrypt if key is a string (passphrase)
172
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
173
- // Create cipher
174
- const cipher = createCipheriv(algorithm, derivedKey, iv);
175
- // Encrypt the data
176
- let ciphertext;
177
- if (typeof data === 'string') {
178
- ciphertext = cipher.update(data, inputEncoding, outputEncoding);
179
- ciphertext += cipher.final(outputEncoding);
180
- }
181
- else {
182
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
183
- ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
184
- }
185
- // Get authentication tag if using GCM mode
186
- const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
187
- return {
188
- ciphertext,
189
- iv,
190
- authTag,
191
- algorithm
192
- };
193
- }
194
- /**
195
- * Decrypts data that was encrypted with the encrypt function.
196
- *
197
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
198
- * @param {string | Buffer} key - Decryption key or passphrase
199
- * @param {DecryptionOptions} [options] - Decryption options
200
- * @returns {Promise<string | Buffer>} Decrypted data
201
- */
202
- export async function decrypt(encryptedData, key, options = {}) {
203
- const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
204
- const inputEncoding = options.inputEncoding || 'hex';
205
- const outputEncoding = options.outputEncoding || 'utf8';
206
- // Derive key using scrypt if key is a string (passphrase)
207
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
208
- // Create decipher
209
- const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);
210
- // Set auth tag if using GCM mode
211
- if (encryptedData.authTag && algorithm.includes('gcm')) {
212
- decipher.setAuthTag(encryptedData.authTag);
213
- }
214
- // Decrypt the data
215
- let decrypted;
216
- if (typeof encryptedData.ciphertext === 'string') {
217
- decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
218
- decrypted += decipher.final(outputEncoding);
219
- }
220
- else {
221
- const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
222
- decrypted = outputEncoding ? result.toString(outputEncoding) : result;
223
- }
224
- return decrypted;
225
- }
226
- /**
227
- * Creates a signed token with an expiration time and payload.
228
- *
229
- * @param {object} payload - Data to include in the token
230
- * @param {string} secret - Secret key for signing
231
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
232
- * @returns {string} Signed token string
233
- */
234
- export function createSignedToken(payload, secret, expiresInSeconds = 3600) {
235
- // Create payload with expiration
236
- const tokenPayload = {
237
- ...payload,
238
- exp: Math.floor(Date.now() / 1000) + expiresInSeconds
239
- };
240
- // Convert to string
241
- const payloadStr = JSON.stringify(tokenPayload);
242
- // Base64 encode the payload
243
- const base64Payload = Buffer.from(payloadStr).toString('base64url');
244
- // Create signature
245
- const signature = hmac('sha256', base64Payload, secret, 'base64url');
246
- // Combine payload and signature
247
- return `${base64Payload}.${signature}`;
248
- }
249
- /**
250
- * Verifies and decodes a signed token.
251
- *
252
- * @param {string} token - The token to verify
253
- * @param {string} secret - Secret key for verification
254
- * @returns {object | null} Decoded payload if valid, null if invalid
255
- */
256
- export function verifySignedToken(token, secret) {
257
- try {
258
- // Split token into parts
259
- const [payloadB64, signature] = token.split('.');
260
- if (!payloadB64 || !signature)
261
- return null;
262
- // Verify signature
263
- const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
264
- if (!safeCompare(signature, expectedSignature))
265
- return null;
266
- // Decode payload
267
- const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
268
- const payload = JSON.parse(payloadStr);
269
- // Check expiration
270
- if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
271
- return null;
272
- }
273
- return payload;
274
- }
275
- catch {
276
- return null;
277
- }
278
- }
@@ -1,158 +0,0 @@
1
- /**
2
- * Format options for the formatDate function
3
- */
4
- export interface DateFormatOptions {
5
- /** Date format pattern (default: 'yyyy-MM-dd') */
6
- format?: string;
7
- /** Locale to use for formatting (default: system locale) */
8
- locale?: string | string[];
9
- /** Time zone to use (default: system time zone) */
10
- timeZone?: string;
11
- }
12
- /**
13
- * Format a date according to the specified format pattern.
14
- *
15
- * @param date - Date to format
16
- * @param options - Formatting options
17
- * @returns Formatted date string
18
- *
19
- * @example
20
- * ```typescript
21
- * // Format as ISO date
22
- * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
23
- *
24
- * // Format with time
25
- * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
26
- *
27
- * // Format with locale
28
- * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
29
- * ```
30
- */
31
- export declare function formatDate(date: Date | number, options?: DateFormatOptions): string;
32
- /**
33
- * Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
34
- *
35
- * @param date - Date to format
36
- * @param now - Reference date (default: current time)
37
- * @param locale - Locale to use for formatting
38
- * @returns Formatted relative time string
39
- */
40
- export declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string;
41
- /**
42
- * Parse a date string or timestamp into a Date object.
43
- *
44
- * @param input - Date string or timestamp to parse
45
- * @param fallback - Fallback date if parsing fails
46
- * @returns Parsed Date object or fallback
47
- *
48
- * @example
49
- * ```typescript
50
- * parseDate('2023-05-15'); // Date object for May 15, 2023
51
- * parseDate('invalid', new Date()); // Returns current date as fallback
52
- * ```
53
- */
54
- export declare function parseDate(input: string | number, fallback?: Date): Date | null;
55
- /**
56
- * Calculate the difference between two dates in the specified unit.
57
- *
58
- * @param date1 - First date
59
- * @param date2 - Second date (default: current time)
60
- * @param unit - Unit of time for the difference
61
- * @returns Difference in the specified unit
62
- *
63
- * @example
64
- * ```typescript
65
- * // Get difference in days
66
- * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
67
- *
68
- * // Get difference in hours
69
- * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
70
- * ```
71
- */
72
- export declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number;
73
- /**
74
- * Add a specified amount of time to a date.
75
- *
76
- * @param date - Base date
77
- * @param amount - Amount to add (can be negative)
78
- * @param unit - Unit of time to add
79
- * @returns New date with the addition
80
- *
81
- * @example
82
- * ```typescript
83
- * // Add 5 days
84
- * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
85
- *
86
- * // Subtract 2 hours
87
- * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
88
- * ```
89
- */
90
- export declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date;
91
- /**
92
- * Get the start of a time period containing the specified date.
93
- *
94
- * @param date - Date to get the start from
95
- * @param unit - Time unit
96
- * @returns Date object representing the start of the time unit
97
- *
98
- * @example
99
- * ```typescript
100
- * // Get start of day (midnight)
101
- * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
102
- *
103
- * // Get start of month
104
- * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
105
- * ```
106
- */
107
- export declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
108
- /**
109
- * Get the end of a time period containing the specified date.
110
- *
111
- * @param date - Date to get the end from
112
- * @param unit - Time unit
113
- * @returns Date object representing the end of the time unit
114
- *
115
- * @example
116
- * ```typescript
117
- * // Get end of day (23:59:59.999)
118
- * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
119
- *
120
- * // Get end of month
121
- * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
122
- * ```
123
- */
124
- export declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
125
- /**
126
- * Check if a date is between two other dates.
127
- *
128
- * @param date - Date to check
129
- * @param start - Start date of the range
130
- * @param end - End date of the range
131
- * @param inclusive - Whether the comparison should be inclusive of start/end
132
- * @returns True if the date is within the range
133
- *
134
- * @example
135
- * ```typescript
136
- * const date = new Date('2023-05-15');
137
- * const start = new Date('2023-05-10');
138
- * const end = new Date('2023-05-20');
139
- *
140
- * isBetween(date, start, end); // true
141
- * ```
142
- */
143
- export declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean;
144
- /**
145
- * Check if a year is a leap year.
146
- *
147
- * @param year - Year to check (or date object)
148
- * @returns True if the year is a leap year
149
- */
150
- export declare function isLeapYear(year: number | Date): boolean;
151
- /**
152
- * Get the number of days in a month.
153
- *
154
- * @param year - Year
155
- * @param month - Month (0-11)
156
- * @returns Number of days in the month
157
- */
158
- export declare function daysInMonth(year: number | Date, month?: number): number;