@catbee/utils 0.0.5 → 0.0.7

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 (246) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +51 -888
  3. package/build/esm/config.d.ts +84 -7
  4. package/build/esm/config.js +89 -5
  5. package/build/esm/config.js.map +1 -1
  6. package/build/esm/index.d.ts +4 -0
  7. package/build/esm/index.js +27 -0
  8. package/build/esm/index.js.map +1 -1
  9. package/build/esm/servers/server.builder.d.ts +508 -0
  10. package/build/esm/servers/server.builder.js +702 -0
  11. package/build/esm/servers/server.builder.js.map +1 -0
  12. package/build/esm/servers/server.d.ts +256 -0
  13. package/build/esm/servers/server.js +1201 -0
  14. package/build/esm/servers/server.js.map +1 -0
  15. package/build/esm/types/api-response.d.ts +33 -7
  16. package/build/esm/types/api-response.js +33 -1
  17. package/build/esm/types/api-response.js.map +1 -1
  18. package/build/esm/types/index.d.ts +125 -0
  19. package/build/esm/types/index.js +25 -0
  20. package/build/esm/types/index.js.map +1 -0
  21. package/build/esm/types/server.d.ts +268 -0
  22. package/build/esm/types/server.js +25 -0
  23. package/build/esm/types/server.js.map +1 -0
  24. package/build/esm/utils/array.utils.js +23 -0
  25. package/build/esm/utils/array.utils.js.map +1 -1
  26. package/build/esm/utils/async.utils.d.ts +91 -0
  27. package/build/esm/utils/async.utils.js +267 -0
  28. package/build/esm/utils/async.utils.js.map +1 -1
  29. package/build/esm/utils/cache.utils.js +23 -0
  30. package/build/esm/utils/cache.utils.js.map +1 -1
  31. package/build/esm/utils/context-store.utils.d.ts +3 -0
  32. package/build/esm/utils/context-store.utils.js +32 -6
  33. package/build/esm/utils/context-store.utils.js.map +1 -1
  34. package/build/esm/utils/crypto.utils.js +23 -0
  35. package/build/esm/utils/crypto.utils.js.map +1 -1
  36. package/build/esm/utils/date.utils.d.ts +159 -0
  37. package/build/esm/utils/date.utils.js +389 -0
  38. package/build/esm/utils/date.utils.js.map +1 -0
  39. package/build/esm/utils/decorators.utils.js +23 -1
  40. package/build/esm/utils/decorators.utils.js.map +1 -1
  41. package/build/esm/utils/dir.utils.js +23 -0
  42. package/build/esm/utils/dir.utils.js.map +1 -1
  43. package/build/esm/utils/env.utils.js +23 -0
  44. package/build/esm/utils/env.utils.js.map +1 -1
  45. package/build/esm/utils/exception.utils.js +31 -8
  46. package/build/esm/utils/exception.utils.js.map +1 -1
  47. package/build/esm/utils/fs.utils.js +23 -0
  48. package/build/esm/utils/fs.utils.js.map +1 -1
  49. package/build/esm/utils/http-status-codes.js +23 -0
  50. package/build/esm/utils/http-status-codes.js.map +1 -1
  51. package/build/esm/utils/id.utils.js +23 -0
  52. package/build/esm/utils/id.utils.js.map +1 -1
  53. package/build/esm/utils/logger.utils.d.ts +5 -0
  54. package/build/esm/utils/logger.utils.js +40 -3
  55. package/build/esm/utils/logger.utils.js.map +1 -1
  56. package/build/esm/utils/middleware.utils.d.ts +2 -0
  57. package/build/esm/utils/middleware.utils.js +61 -50
  58. package/build/esm/utils/middleware.utils.js.map +1 -1
  59. package/build/esm/utils/obj.utils.d.ts +10 -3
  60. package/build/esm/utils/obj.utils.js +225 -15
  61. package/build/esm/utils/obj.utils.js.map +1 -1
  62. package/build/esm/utils/performance.utils.d.ts +136 -0
  63. package/build/esm/utils/performance.utils.js +376 -0
  64. package/build/esm/utils/performance.utils.js.map +1 -0
  65. package/build/esm/utils/request.utils.d.ts +9 -0
  66. package/build/esm/utils/request.utils.js +55 -5
  67. package/build/esm/utils/request.utils.js.map +1 -1
  68. package/build/esm/utils/response.utils.d.ts +15 -1
  69. package/build/esm/utils/response.utils.js +51 -0
  70. package/build/esm/utils/response.utils.js.map +1 -1
  71. package/build/esm/utils/stream.utils.d.ts +88 -0
  72. package/build/esm/utils/stream.utils.js +284 -0
  73. package/build/esm/utils/stream.utils.js.map +1 -0
  74. package/build/esm/utils/string.utils.js +23 -0
  75. package/build/esm/utils/string.utils.js.map +1 -1
  76. package/build/esm/utils/type.utils.d.ts +90 -0
  77. package/build/esm/utils/type.utils.js +190 -0
  78. package/build/esm/utils/type.utils.js.map +1 -0
  79. package/build/esm/utils/url.utils.js +23 -0
  80. package/build/esm/utils/url.utils.js.map +1 -1
  81. package/build/esm/utils/validate.utils.d.ts +7 -0
  82. package/build/esm/utils/validate.utils.js +35 -2
  83. package/build/esm/utils/validate.utils.js.map +1 -1
  84. package/build/esnext/config.d.ts +84 -7
  85. package/build/esnext/config.js +89 -5
  86. package/build/esnext/config.js.map +1 -1
  87. package/build/esnext/index.d.ts +4 -0
  88. package/build/esnext/index.js +27 -0
  89. package/build/esnext/index.js.map +1 -1
  90. package/build/esnext/servers/server.builder.d.ts +508 -0
  91. package/build/esnext/servers/server.builder.js +657 -0
  92. package/build/esnext/servers/server.builder.js.map +1 -0
  93. package/build/esnext/servers/server.d.ts +256 -0
  94. package/build/esnext/servers/server.js +908 -0
  95. package/build/esnext/servers/server.js.map +1 -0
  96. package/build/esnext/types/api-response.d.ts +33 -7
  97. package/build/esnext/types/api-response.js +33 -1
  98. package/build/esnext/types/api-response.js.map +1 -1
  99. package/build/esnext/types/index.d.ts +125 -0
  100. package/build/esnext/types/index.js +25 -0
  101. package/build/esnext/types/index.js.map +1 -0
  102. package/build/esnext/types/server.d.ts +268 -0
  103. package/build/esnext/types/server.js +25 -0
  104. package/build/esnext/types/server.js.map +1 -0
  105. package/build/esnext/utils/array.utils.js +23 -0
  106. package/build/esnext/utils/array.utils.js.map +1 -1
  107. package/build/esnext/utils/async.utils.d.ts +91 -0
  108. package/build/esnext/utils/async.utils.js +213 -0
  109. package/build/esnext/utils/async.utils.js.map +1 -1
  110. package/build/esnext/utils/cache.utils.js +23 -0
  111. package/build/esnext/utils/cache.utils.js.map +1 -1
  112. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  113. package/build/esnext/utils/context-store.utils.js +32 -6
  114. package/build/esnext/utils/context-store.utils.js.map +1 -1
  115. package/build/esnext/utils/crypto.utils.js +23 -0
  116. package/build/esnext/utils/crypto.utils.js.map +1 -1
  117. package/build/esnext/utils/date.utils.d.ts +159 -0
  118. package/build/esnext/utils/date.utils.js +384 -0
  119. package/build/esnext/utils/date.utils.js.map +1 -0
  120. package/build/esnext/utils/decorators.utils.js +23 -1
  121. package/build/esnext/utils/decorators.utils.js.map +1 -1
  122. package/build/esnext/utils/dir.utils.js +23 -0
  123. package/build/esnext/utils/dir.utils.js.map +1 -1
  124. package/build/esnext/utils/env.utils.js +23 -0
  125. package/build/esnext/utils/env.utils.js.map +1 -1
  126. package/build/esnext/utils/exception.utils.js +30 -7
  127. package/build/esnext/utils/exception.utils.js.map +1 -1
  128. package/build/esnext/utils/fs.utils.js +23 -0
  129. package/build/esnext/utils/fs.utils.js.map +1 -1
  130. package/build/esnext/utils/http-status-codes.js +23 -0
  131. package/build/esnext/utils/http-status-codes.js.map +1 -1
  132. package/build/esnext/utils/id.utils.js +23 -0
  133. package/build/esnext/utils/id.utils.js.map +1 -1
  134. package/build/esnext/utils/logger.utils.d.ts +5 -0
  135. package/build/esnext/utils/logger.utils.js +40 -3
  136. package/build/esnext/utils/logger.utils.js.map +1 -1
  137. package/build/esnext/utils/middleware.utils.d.ts +2 -0
  138. package/build/esnext/utils/middleware.utils.js +57 -50
  139. package/build/esnext/utils/middleware.utils.js.map +1 -1
  140. package/build/esnext/utils/obj.utils.d.ts +10 -3
  141. package/build/esnext/utils/obj.utils.js +176 -12
  142. package/build/esnext/utils/obj.utils.js.map +1 -1
  143. package/build/esnext/utils/performance.utils.d.ts +136 -0
  144. package/build/esnext/utils/performance.utils.js +271 -0
  145. package/build/esnext/utils/performance.utils.js.map +1 -0
  146. package/build/esnext/utils/request.utils.d.ts +9 -0
  147. package/build/esnext/utils/request.utils.js +46 -5
  148. package/build/esnext/utils/request.utils.js.map +1 -1
  149. package/build/esnext/utils/response.utils.d.ts +15 -1
  150. package/build/esnext/utils/response.utils.js +51 -0
  151. package/build/esnext/utils/response.utils.js.map +1 -1
  152. package/build/esnext/utils/stream.utils.d.ts +88 -0
  153. package/build/esnext/utils/stream.utils.js +210 -0
  154. package/build/esnext/utils/stream.utils.js.map +1 -0
  155. package/build/esnext/utils/string.utils.js +23 -0
  156. package/build/esnext/utils/string.utils.js.map +1 -1
  157. package/build/esnext/utils/type.utils.d.ts +90 -0
  158. package/build/esnext/utils/type.utils.js +187 -0
  159. package/build/esnext/utils/type.utils.js.map +1 -0
  160. package/build/esnext/utils/url.utils.js +23 -0
  161. package/build/esnext/utils/url.utils.js.map +1 -1
  162. package/build/esnext/utils/validate.utils.d.ts +7 -0
  163. package/build/esnext/utils/validate.utils.js +33 -0
  164. package/build/esnext/utils/validate.utils.js.map +1 -1
  165. package/build/src/config.d.ts +84 -7
  166. package/build/src/config.js +90 -6
  167. package/build/src/config.js.map +1 -1
  168. package/build/src/index.d.ts +4 -0
  169. package/build/src/index.js +27 -0
  170. package/build/src/index.js.map +1 -1
  171. package/build/src/servers/server.builder.d.ts +508 -0
  172. package/build/src/servers/server.builder.js +661 -0
  173. package/build/src/servers/server.builder.js.map +1 -0
  174. package/build/src/servers/server.d.ts +256 -0
  175. package/build/src/servers/server.js +948 -0
  176. package/build/src/servers/server.js.map +1 -0
  177. package/build/src/types/api-response.d.ts +33 -7
  178. package/build/src/types/api-response.js +34 -0
  179. package/build/src/types/api-response.js.map +1 -1
  180. package/build/src/types/index.d.ts +125 -0
  181. package/build/src/types/index.js +26 -0
  182. package/build/src/types/index.js.map +1 -0
  183. package/build/src/types/server.d.ts +268 -0
  184. package/build/src/types/server.js +26 -0
  185. package/build/src/types/server.js.map +1 -0
  186. package/build/src/utils/array.utils.js +23 -0
  187. package/build/src/utils/array.utils.js.map +1 -1
  188. package/build/src/utils/async.utils.d.ts +91 -0
  189. package/build/src/utils/async.utils.js +217 -0
  190. package/build/src/utils/async.utils.js.map +1 -1
  191. package/build/src/utils/cache.utils.js +23 -0
  192. package/build/src/utils/cache.utils.js.map +1 -1
  193. package/build/src/utils/context-store.utils.d.ts +3 -0
  194. package/build/src/utils/context-store.utils.js +32 -6
  195. package/build/src/utils/context-store.utils.js.map +1 -1
  196. package/build/src/utils/crypto.utils.js +23 -0
  197. package/build/src/utils/crypto.utils.js.map +1 -1
  198. package/build/src/utils/date.utils.d.ts +159 -0
  199. package/build/src/utils/date.utils.js +396 -0
  200. package/build/src/utils/date.utils.js.map +1 -0
  201. package/build/src/utils/decorators.utils.js +23 -1
  202. package/build/src/utils/decorators.utils.js.map +1 -1
  203. package/build/src/utils/dir.utils.js +23 -0
  204. package/build/src/utils/dir.utils.js.map +1 -1
  205. package/build/src/utils/env.utils.js +23 -0
  206. package/build/src/utils/env.utils.js.map +1 -1
  207. package/build/src/utils/exception.utils.js +30 -7
  208. package/build/src/utils/exception.utils.js.map +1 -1
  209. package/build/src/utils/fs.utils.js +23 -0
  210. package/build/src/utils/fs.utils.js.map +1 -1
  211. package/build/src/utils/http-status-codes.js +23 -0
  212. package/build/src/utils/http-status-codes.js.map +1 -1
  213. package/build/src/utils/id.utils.js +23 -0
  214. package/build/src/utils/id.utils.js.map +1 -1
  215. package/build/src/utils/logger.utils.d.ts +5 -0
  216. package/build/src/utils/logger.utils.js +41 -4
  217. package/build/src/utils/logger.utils.js.map +1 -1
  218. package/build/src/utils/middleware.utils.d.ts +2 -0
  219. package/build/src/utils/middleware.utils.js +56 -49
  220. package/build/src/utils/middleware.utils.js.map +1 -1
  221. package/build/src/utils/obj.utils.d.ts +10 -3
  222. package/build/src/utils/obj.utils.js +177 -12
  223. package/build/src/utils/obj.utils.js.map +1 -1
  224. package/build/src/utils/performance.utils.d.ts +136 -0
  225. package/build/src/utils/performance.utils.js +278 -0
  226. package/build/src/utils/performance.utils.js.map +1 -0
  227. package/build/src/utils/request.utils.d.ts +9 -0
  228. package/build/src/utils/request.utils.js +48 -5
  229. package/build/src/utils/request.utils.js.map +1 -1
  230. package/build/src/utils/response.utils.d.ts +15 -1
  231. package/build/src/utils/response.utils.js +52 -0
  232. package/build/src/utils/response.utils.js.map +1 -1
  233. package/build/src/utils/stream.utils.d.ts +88 -0
  234. package/build/src/utils/stream.utils.js +218 -0
  235. package/build/src/utils/stream.utils.js.map +1 -0
  236. package/build/src/utils/string.utils.js +23 -0
  237. package/build/src/utils/string.utils.js.map +1 -1
  238. package/build/src/utils/type.utils.d.ts +90 -0
  239. package/build/src/utils/type.utils.js +196 -0
  240. package/build/src/utils/type.utils.js.map +1 -0
  241. package/build/src/utils/url.utils.js +23 -0
  242. package/build/src/utils/url.utils.js.map +1 -1
  243. package/build/src/utils/validate.utils.d.ts +7 -0
  244. package/build/src/utils/validate.utils.js +36 -2
  245. package/build/src/utils/validate.utils.js.map +1 -1
  246. package/package.json +39 -9
package/README.md CHANGED
@@ -2,16 +2,30 @@
2
2
 
3
3
  ## 🧰 Utility Modules for Node.js
4
4
 
5
- A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
5
+ A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications. All utilities are tree-shakable and can be imported independently.
6
6
 
7
7
  ![build](https://img.shields.io/badge/build-passing-brightgreen) ![coverage](https://codecov.io/gh/catbee-technologies/catbee-utils/graph/badge.svg?token=XAJHK6R1OQ) ![node](https://img.shields.io/node/v/@catbee/utils) ![npm](https://img.shields.io/npm/v/@catbee/utils) ![downloads](https://img.shields.io/npm/dm/@catbee/utils) ![dependencies](https://img.shields.io/librariesio/release/npm/@catbee%2Futils) ![license](https://img.shields.io/npm/l/@catbee/utils)
8
8
 
9
+ ---
10
+
11
+ ## 🚀 Key Features
12
+
13
+ - Modular: Import only what you need
14
+ - TypeScript-first: Full typings and type safety
15
+ - Production-ready: Robust, well-tested utilities
16
+ - Tree-shakable: Zero bloat in your bundle
17
+ - Express-friendly: Designed for scalable server apps
18
+
19
+ ---
20
+
9
21
  ## 📦 Installation
10
22
 
11
23
  ```bash
12
24
  npm i @catbee/utils
13
25
  ```
14
26
 
27
+ ---
28
+
15
29
  ## ⚡ Quick Start
16
30
 
17
31
  ```ts
@@ -33,906 +47,55 @@ console.log(uuid()); // e.g. 2a563ec1-caf6-4fe2-b60c-9cf7fb1bdb7f
33
47
  console.log(isEmail("user@example.com")); // true
34
48
  ```
35
49
 
36
- ## 📦 Modules Overview
37
-
38
- - [**Array Utilities**](#-array-utilities)
39
- - [**Async Utilities**](#-async-utilities)
40
- - [**Cache Utilities**](#-cache-utilities)
41
- - [**Config**](#-config)
42
- - [**Context Store**](#-context-store)
43
- - [**Crypto Utilities**](#-crypto-utilities)
44
- - [**Directory Utilities**](#-directory-utilities)
45
- - [**Environment Utilities**](#-environment-utilities)
46
- - [**Exception Utilities**](#-exception-utilities)
47
- - [**File System Utilities**](#-file-system-utilities)
48
- - [**HTTP Status Codes**](#-http-status-codes)
49
- - [**ID Utilities**](#-id-utilities)
50
- - [**Logger Utilities**](#-logger-utilities)
51
- - [**Middleware Utilities**](#-middleware-utilities)
52
- - [**Object Utilities**](#-object-utilities)
53
- - [**Request Utilities**](#-request-utilities)
54
- - [**Response Utilities**](#-response-utilities)
55
- - [**String Utilities**](#-string-utilities)
56
- - [**URL Utilities**](#-url-utilities)
57
- - [**Validate Utilities**](#-validate-utilities)
58
- - [**Decorators Utilities**](#-decorators-utilities)
59
-
60
50
  ---
61
51
 
62
- ## 📦 Array Utilities
63
-
64
- A collection of functions for handling arrays with type-safety and efficiency.
65
-
66
- - `chunk<T>(array: T[], size: number): T[][]` – Split array into chunks of specified size.
67
- - `unique<T>(array: T[], keyFn?: (item: T) => unknown): T[]` – Remove duplicate items from an array, optionally by key.
68
- - `flattenDeep<T>(array: any[]): T[]` – Deeply flatten a nested array.
69
- - `random<T>(array: T[]): T | undefined` – Get a random element from an array.
70
- - `groupBy<T>(array: T[], keyOrFn: keyof T | ((item: T) => string | number | symbol)): Record<string | number | symbol, T[]>` – Group array items by a key or function.
71
- - `shuffle<T>(array: T[]): T[]` – Shuffle array elements randomly.
72
- - `pluck<T, K extends keyof T>(array: T[], key: K): T[K][]` – Extract values for a given key from an array of objects.
73
- - `difference<T>(a: T[], b: T[]): T[]` – Get elements in array `a` not present in array `b`.
74
- - `intersect<T>(a: T[], b: T[]): T[]` – Get elements common to both arrays.
75
- - `mergeSort<T>(array: T[], key: string | ((item: T) => any), direction?: "asc" | "desc"): T[]` – Sort array by key or function using merge sort.
76
- - `zip<T>(...arrays: T[][]): T[][]` – Combine multiple arrays element-wise.
77
- - `partition<T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): [T[], T[]]` – Split array into two based on predicate.
78
- - `range(start: number, end: number, step?: number): number[]` – Create an array of numbers in a range.
79
- - `take<T>(array: T[], n?: number): T[]` – Take the first `n` elements from an array.
80
- - `takeWhile<T>(array: T[], predicate: (item: T, index: number) => boolean): T[]` – Take elements from array while predicate is true.
81
- - `compact<T>(array: T[]): NonNullable<T>[]` – Remove falsy values from an array.
82
- - `countBy<T>(array: T[], keyFn: (item: T) => string | number | symbol): Record<string, number>` – Count occurrences by key or function.
83
-
84
- **Examples:**
85
-
86
- ```ts
87
- // Group users by their role
88
- const users = [
89
- { id: 1, role: 'admin', name: 'Alice' },
90
- { id: 2, role: 'user', name: 'Bob' },
91
- { id: 3, role: 'user', name: 'Charlie' }
92
- ];
93
- const groupedByRole = groupBy(users, 'role');
94
- // { admin: [{ id: 1, ... }], user: [{ id: 2, ... }, { id: 3, ... }] }
95
-
96
- // Partition an array into two groups
97
- const numbers = [1, 2, 3, 4, 5, 6];
98
- const [evens, odds] = partition(numbers, n => n % 2 === 0);
99
- // evens: [2, 4, 6], odds: [1, 3, 5]
100
-
101
- // Complex sorting with mergeSort
102
- const items = [
103
- { nested: { value: 5 } },
104
- { nested: { value: 2 } },
105
- { nested: { value: 8 } }
106
- ];
107
- const sorted = mergeSort(items, (item) => item.nested.value);
108
- // [{ nested: { value: 2 } }, { nested: { value: 5 } }, { nested: { value: 8 } }]
109
- ```
110
-
111
- ## ⏳ Async Utilities
112
-
113
- Functions for handling asynchronous operations with better control flow and error handling.
114
-
115
- - `sleep(ms: number): Promise<void>` – Pause execution for a given number of milliseconds.
116
- - `debounce<T>(fn: T, delay: number): T & { cancel(): void; flush(): void }` – Debounce function calls, only invoking after delay.
117
- - `throttle<T>(fn: T, limit: number, opts?): (...args: Parameters<T>) => void` – Throttle function calls to a maximum rate.
118
- - `retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?): Promise<T>` – Retry a promise-returning function with optional backoff.
119
- - `withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>` – Reject promise if it takes longer than specified time.
120
- - `runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>` – Run async tasks in batches with concurrency limit.
121
- - `singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>` – Ensure only one instance of an async function runs at a time.
122
- - `settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>` – Run all tasks and return their settled results.
123
- - `createTaskQueue(limit: number): TaskQueue` – Create a queue to run tasks with concurrency control.
124
- - `runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>` – Run async tasks one after another.
125
- - `memoizeAsync<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?): (...args: Args) => Promise<T>` – Memoize async function results.
126
- - `abortable<T>(promise: Promise<T>, signal: AbortSignal, abortValue?: any): Promise<T>` – Make a promise abortable via AbortSignal.
127
- - `createDeferred<T>(): [Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void]` – Create a deferred promise with resolve/reject.
128
- - `waterfall<T>(fns: Array<(input: any) => Promise<any>>): (initialValue: any) => Promise<T>` – Run async functions in sequence, passing result to next.
129
- - `rateLimit<T>(fn: (...args: any[]) => Promise<T>, maxCalls: number, interval: number): (...args: any[]) => Promise<T>` – Limit the rate of async function calls.
130
-
131
- **Examples:**
132
-
133
- ```ts
134
- // Retry a flaky API call
135
- const fetchData = async () => {
136
- const response = await fetch('https://api.example.com/data');
137
- if (!response.ok) throw new Error(`HTTP error ${response.status}`);
138
- return await response.json();
139
- };
140
-
141
- const result = await retry(
142
- fetchData,
143
- 3, // retry 3 times
144
- 1000, // wait 1 second between retries
145
- true, // use exponential backoff
146
- (err, attempt) => console.log(`Attempt ${attempt} failed: ${err.message}`)
147
- );
148
-
149
- // Process items in batches to avoid overloading resources
150
- const processItem = async (id) => {
151
- // Process a single item...
152
- return `Processed ${id}`;
153
- };
154
-
155
- const itemIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
156
- const tasks = itemIds.map(id => processItem(id));
157
- const results = await runInBatches(tasks, 3); // Process 3 items concurrently
158
-
159
- // Function waterfall (pipeline)
160
- const pipeline = waterfall([
161
- async (input) => input * 2,
162
- async (input) => input + 10,
163
- async (input) => `Result: ${input}`
164
- ]);
165
-
166
- const finalResult = await pipeline(5); // "Result: 20"
167
- ```
168
-
169
- ## 🗃️ Cache Utilities
170
-
171
- In-memory TTL cache with advanced features for efficient data caching and retrieval.
172
-
173
- - `TTLCache<K, V>(options?: TTLCacheOptions)` – Create a time-to-live in-memory cache with various methods for managing entries.
174
-
175
- **Examples:**
176
- ```ts
177
- const cache = new TTLCache<string, number>({ ttlMs: 3600_000 });
178
- cache.set("foo", 42);
179
- cache.get("foo"); // 42
180
- cache.has("foo"); // true
181
- cache.cleanup(); // cleans expired
182
- ```
183
-
184
- ## ⚙️ Config
185
-
186
- Global configuration settings for the application, including logging, HTTP, and cache settings.
187
-
188
- - `config.logger.level` – Set the logging level (e.g., 'info', 'debug').
189
- - `config.logger.name` – Set the logger name.
190
- - `config.logger.pretty` – Enable pretty print for logs.
191
- - `config.http.timeout` – Set HTTP request timeout in milliseconds.
192
- - `config.cache.defaultTtl` – Set default cache TTL in seconds.
193
- - `setConfig(value: Partial<typeof config>): void` – Update configuration settings.
194
- - `getConfig(): typeof config` – Get the current configuration settings.
195
-
196
- **Example:**
197
- ```ts
198
- import { setConfig } from "@catbee/utils";
199
-
200
- // Configure logging
201
- setConfig({ logger: { pretty: true } });
202
-
203
- console.log(getConfig());
204
- ```
205
-
206
- ## 🧩 Context Store
207
-
208
- Per-request context management using AsyncLocalStorage, allowing for easy sharing of data across async calls.
209
-
210
- - `ContextStore` – Per-request context using AsyncLocalStorage.
211
- - `getInstance(): AsyncLocalStorage<Store>` – Get the AsyncLocalStorage instance.
212
- - `getAll(): Store | undefined` – Get the current context store.
213
- - `run(store: Store, callback: () => void): void` – Run a callback with a specific store context.
214
- - `set(key: symbol, value: unknown): void` – Set a value in the current store.
215
- - `get<T>(key: symbol): T | undefined` – Get a value from the current store.
216
- - `has(key: symbol): boolean` – Check if a key exists in the store.
217
- - `delete(key: symbol): boolean` – Remove a key from the store.
218
- - `patch(values: Partial<Record<symbol, unknown>>): void` – Update multiple values in the store.
219
- - `withValue(key: symbol, value: unknown, callback: () => T): T` – Temporarily set a value for a callback.
220
- - `extend(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T` – Temporarily extend the store for a callback.
221
- - `createExpressMiddleware(initialValuesFactory?): Middleware` – Create Express middleware for context.
222
-
223
- - `StoreKeys` – Common context keys.
224
- - `getRequestId(): string | undefined` – Get the current request ID from context.
225
-
226
- **Example (Express middleware usage):**
227
- ```ts
228
- import { ContextStore, StoreKeys, getLogger } from "@catbee/utils";
229
- import crypto from "crypto";
230
-
231
- export function setupRequestContext(req, res, next) {
232
- const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
233
- ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
234
- const logger = getLogger().child({ requestId });
235
- ContextStore.set(StoreKeys.LOGGER, logger);
236
- logger.info("Request context initialized");
237
- next();
238
- });
239
- }
240
- app.use(setupRequestContext);
241
- ```
242
-
243
- ## 🔐 Crypto Utilities
244
-
245
- Secure cryptographic functions for encryption, hashing, and token generation.
246
-
247
- - `hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string` – Generate an HMAC hash.
248
- - `hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string` – Generate a hash using a specified algorithm.
249
- - `sha256Hmac(input: string, secret: string): string` – Generate a SHA256 HMAC.
250
- - `sha1(input: string, encoding?: BinaryToTextEncoding): string` – Generate a SHA1 hash.
251
- - `sha256(input: string, encoding?: BinaryToTextEncoding): string` – Generate a SHA256 hash.
252
- - `md5(input: string): string` – Generate an MD5 hash.
253
- - `randomString(): string` – Generate a cryptographically secure random string.
254
- - `generateRandomBytes(byteLength?: number): Buffer` – Generate random bytes.
255
- - `generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string` – Generate random bytes as a string.
256
- - `generateApiKey(prefix?: string, byteLength?: number): string` – Generate an API key with optional prefix.
257
- - `safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean` – Timing-safe string comparison.
258
- - `encrypt(data: string | Buffer, key: string | Buffer, options?): Promise<EncryptionResult>` – Encrypt data using AES.
259
- - `decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?): Promise<string | Buffer>` – Decrypt AES encrypted data.
260
- - `createSignedToken(payload: object, secret: string, expiresInSeconds?: number): string` – Create a signed token (JWT-like).
261
- - `verifySignedToken(token: string, secret: string): object | null` – Verify and decode a signed token.
262
-
263
- **Examples:**
264
-
265
- ```ts
266
- // Generate and verify JWT-like tokens
267
- const payload = { userId: 123, permissions: ['read', 'write'] };
268
- const secret = 'secret-key';
269
-
270
- const token = createSignedToken(payload, secret, 3600); // expires in 1 hour
271
-
272
- // Later, verify and decode
273
- const decodedPayload = verifySignedToken(token, secret);
274
- if (decodedPayload) {
275
- console.log(`User ID: ${decodedPayload.userId}`);
276
- }
277
-
278
- // Generate API keys for your service
279
- const apiKey = generateApiKey('usr_', 32);
280
- // usr_8f7d8937a9f27cb6b3f8a0928f5c9c1e
281
- ```
282
-
283
- ## 📂 Directory Utilities
284
-
285
- File and directory manipulation utilities for managing file system interactions.
286
-
287
- - `ensureDir(dirPath: string): Promise<void>` – Ensure a directory exists.
288
- - `listFiles(dirPath: string, recursive?: boolean): Promise<string[]>` – List files in a directory.
289
- - `deleteDirRecursive(dirPath: string): Promise<void>` – Delete a directory and its contents.
290
- - `isDirectory(pathStr: string): Promise<boolean>` – Check if a path is a directory.
291
- - `copyDir(src: string, dest: string): Promise<void>` – Copy a directory recursively.
292
- - `moveDir(src: string, dest: string): Promise<void>` – Move a directory.
293
- - `emptyDir(dirPath: string): Promise<void>` – Remove all contents from a directory.
294
- - `getDirSize(dirPath: string): Promise<number>` – Get the total size of a directory.
295
- - `watchDir(dirPath: string, callback): () => void` – Watch a directory for changes.
296
- - `findFilesByPattern(pattern: string, options?): Promise<string[]>` – Find files matching a pattern.
297
- - `getSubdirectories(dirPath: string, recursive?: boolean): Promise<string[]>` – Get subdirectories of a directory.
298
- - `ensureEmptyDir(dirPath: string): Promise<void>` – Ensure a directory exists and is empty.
299
- - `createTempDir(options?): Promise<{ path: string, cleanup: () => Promise<void> }>` – Create a temporary directory.
300
- - `findNewestFile(dirPath: string, recursive?: boolean): Promise<string | null>` – Find the newest file in a directory.
301
- - `findOldestFile(dirPath: string, recursive?: boolean): Promise<string | null>` – Find the oldest file in a directory.
302
- - `findInDir(dirPath: string, predicate, recursive?: boolean): Promise<string[]>` – Find files in a directory by predicate.
303
- - `watchDirRecursive(dirPath: string, callback, includeSubdirs?: boolean): Promise<() => void>` – Watch a directory and subdirectories for changes.
304
- - `getDirStats(dirPath: string): Promise<{ fileCount: number, dirCount: number, totalSize: number }>` – Get statistics for a directory.
305
- - `walkDir(dirPath: string, options): Promise<void>` – Walk a directory tree with callbacks.
306
-
307
- **Examples:**
308
-
309
- ```ts
310
- // Safely ensure a directory exists and is empty
311
- await ensureEmptyDir('./temp/uploads');
312
-
313
- // Find specific files in a directory structure
314
- const imageFiles = await findInDir('./content',
315
- (path) => path.endsWith('.jpg') || path.endsWith('.png'),
316
- true // recursive search
317
- );
318
-
319
- // Create a temporary directory that cleans itself up
320
- const { path, cleanup } = await createTempDir({
321
- prefix: 'app-',
322
- parentDir: './temp'
323
- });
324
-
325
- try {
326
- // Use the temporary directory...
327
- await writeTextFile(`${path}/data.txt`, 'Hello world');
328
- } finally {
329
- // Clean up when done
330
- await cleanup();
331
- }
332
- ```
333
-
334
- ## 🌱 Environment Utilities
335
-
336
- Environment variable management with powerful type-safe access, validation, and transformation capabilities.
337
-
338
- - `Environment` enum – (`DEVELOPMENT`, `PRODUCTION`, `STAGING`, `TESTING`) – Enum for environment types.
339
- - `Env` class – Environment variable helpers.
340
- - `isDev(): boolean` – Check if running in development environment.
341
- - `isProd(): boolean` – Check if running in production environment.
342
- - `isTest(): boolean` – Check if running in test environment.
343
- - `isStaging(): boolean` – Check if running in staging environment.
344
- - `set(key: string, value: string): void` – Set an environment variable.
345
- - `getAll(): object` – Get all environment variables.
346
- - `get(key: string, defaultValue: string): string` – Get a variable with a default value.
347
- - `getRequired(key: string): string` – Get a required variable, throw if missing.
348
- - `getOrFail(key: string): string` – Alias for getRequired.
349
- - `getNumber(key: string, defaultValue: number): number` – Get a variable as a number.
350
- - `getNumberRequired(key: string): number` – Get a required number variable.
351
- - `getInteger(key: string, defaultValue: number, options?): number` – Get an integer with optional validation.
352
- - `getBoolean(key: string, defaultValue?: boolean): boolean` – Get a variable as a boolean.
353
- - `getBooleanRequired(key: string): boolean` – Get a required boolean variable.
354
- - `getJSON<T>(key: string, defaultValue: T): T` – Parse a variable as JSON.
355
- - `getArray<T = string>(key: string, defaultValue?: T[], splitter?: string, transform?): T[]` – Parse a variable as an array.
356
- - `getNumberArray(key: string, defaultValue?: number[], splitter?: string): number[]` – Parse a variable as an array of numbers.
357
- - `getEnum<T extends string>(key: string, allowedValues: T[], defaultValue: T): T` – Get a variable as an enum value.
358
- - `getNumberEnum(key: string, allowedValues: number[], defaultValue: number): number` – Get a variable as a numeric enum.
359
- - `getUrl(key: string, defaultValue: string, options?): string` – Get and validate a URL variable.
360
- - `getEmail(key: string, defaultValue: string): string` – Get and validate an email variable.
361
- - `getPath(key: string, defaultValue: string, options?): string` – Get and validate a file path variable.
362
- - `getPort(key: string, defaultValue: number): number` – Get and validate a port number.
363
- - `getDate(key: string, defaultValue?: string | Date): Date` – Parse a variable as a date.
364
- - `getDuration(key: string, defaultValue?: string | number): number` – Parse a variable as a duration in ms.
365
- - `getSafeEnv(sensitiveKeys?: string[]): Record<string, string>` – Get environment with sensitive values masked.
366
- - `getWithDefault(key: string, defaultFn: () => string): string` – Get a variable or compute a default.
367
- - `loadFromFile(path: string): Record<string, string>` – Load variables from a .env file.
368
- - `has(key: string): boolean` – Check if a variable exists.
369
- - `delete(key: string): void` – Delete a variable.
370
- - `clearCache(): void` – Clear the internal cache.
371
-
372
- **Examples:**
373
-
374
- ```ts
375
- import { Env, Environment } from "@catbee/utils";
376
-
377
- // Check current environment
378
- if (Env.isDev()) {
379
- console.log("Running in development mode");
380
- }
381
-
382
- // Variable expansion (reference other environment variables)
383
- // If DATABASE_HOST=localhost and DATABASE_NAME=myapp
384
- Env.set('DATABASE_URL', 'postgres://${DATABASE_HOST}:5432/${DATABASE_NAME}');
385
- const dbUrl = Env.get('DATABASE_URL', ''); // "postgres://localhost:5432/myapp"
386
-
387
- // Load from .env file
388
- Env.loadFromFile('.env.local');
389
-
390
- // Number validation with range checks
391
- const port = Env.getInteger('PORT', 3000, { min: 1024, max: 49151 });
392
- const workerCount = Env.getNumber('WORKER_COUNT', 4);
393
-
394
- // URL validation with protocol restrictions
395
- const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {
396
- protocols: ['https'],
397
- requireTld: true,
398
- allowLocalhost: Env.isDev() // allow localhost in development
399
- });
400
-
401
- // Path validation with existence check
402
- const configPath = Env.getPath('CONFIG_PATH', './config.json', {
403
- mustExist: true,
404
- allowedExtensions: ['.json', '.yaml']
405
- });
406
-
407
- // Parse arrays with automatic transformation
408
- const ports = Env.getNumberArray('ALLOWED_PORTS', [80, 443]);
409
- const features = Env.getArray('ENABLED_FEATURES', [], ',');
410
-
411
- // Parse dates and durations
412
- const launchDate = Env.getDate('LAUNCH_DATE');
413
- const cacheTtl = Env.getDuration('CACHE_TTL', '1h'); // in milliseconds
414
-
415
- // Complex configurations from JSON
416
- const serverConfig = Env.getJSON('SERVER_CONFIG', {
417
- maxConnections: 100,
418
- timeout: 30000,
419
- retries: 3
420
- });
421
-
422
- // Safe environment printing (hiding secrets)
423
- console.log(Env.getSafeEnv(['PASSWORD', 'API_KEY', 'SECRET']));
424
-
425
- // Lazy default evaluation (only runs if variable is missing)
426
- const hostname = Env.getWithDefault('HOSTNAME', () => {
427
- console.log('Computing hostname...');
428
- return require('os').hostname();
429
- });
430
- ```
431
-
432
- ## 🚨 Exception Utilities
433
-
434
- - `HttpError` – Base HTTP error class.
435
- - `InternalServerErrorException` – HTTP 500 error.
436
- - `UnauthorizedException` – HTTP 401 error.
437
- - `BadRequestException` – HTTP 400 error.
438
- - `NotFoundException` – HTTP 404 error.
439
- - `ForbiddenException` – HTTP 403 error.
440
- - `ConflictException` – HTTP 409 error.
441
- - `BadGatewayException` – HTTP 502 error.
442
- - `TooManyRequestsException` – HTTP 429 error.
443
- - `ServiceUnavailableException` – HTTP 503 error.
444
- - `GatewayTimeoutException` – HTTP 504 error.
445
- - `UnprocessableEntityException` – HTTP 422 error.
446
- - `MethodNotAllowedException` – HTTP 405 error.
447
- - `NotAcceptableException` – HTTP 406 error.
448
- - `RequestTimeoutException` – HTTP 408 error.
449
- - `UnsupportedMediaTypeException` – HTTP 415 error.
450
- - `PayloadTooLargeException` – HTTP 413 error.
451
- - `InsufficientStorageException` – HTTP 507 error.
452
- - `isHttpError(error: unknown): error is ErrorResponse` – Check if an error is an HTTP error.
453
- - `createHttpError(status: number, message?: string): ErrorResponse` – Create a custom HTTP error.
454
- - `hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string }` – Check if an error has a standard shape.
455
- - `getErrorMessage(error: unknown): string` – Extract a message from any error.
456
- - `withErrorHandling<T extends (...args: any[]) => Promise<any>>(handler: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>` – Wrap an async function with error handling.
457
-
458
- ## 📁 File System Utilities
52
+ ## 📚 Modules Overview
53
+
54
+ | Module | Description |
55
+ | ------ | ----------- |
56
+ | [Express Server](https://catbee-utils.npm.hprasath.com/docs/express-server) | Fast, secure, and scalable server setup |
57
+ | [Array Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/array) | Advanced array manipulation |
58
+ | [Async Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/async) | Promise helpers, concurrency, timing |
59
+ | [Cache Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/cache) | In-memory caching with TTL |
60
+ | [Context Store](https://catbee-utils.npm.hprasath.com/docs/utils/context-store) | Per-request context via AsyncLocalStorage |
61
+ | [Crypto Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/crypto) | Hashing, encryption, tokens |
62
+ | [Date Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/date) | Date/time manipulation |
63
+ | [Decorators Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/decorators) | TypeScript decorators for Express |
64
+ | [Directory Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/directory) | Directory and file system helpers |
65
+ | [Environment Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/environment) | Env variable management |
66
+ | [Exception Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/exception) | HTTP and error handling |
67
+ | [File System Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/file-system) | File operations |
68
+ | [HTTP Status Codes](https://catbee-utils.npm.hprasath.com/docs/utils/http-status-codes) | Typed status codes |
69
+ | [ID Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/id) | UUID and ID generation |
70
+ | [Logger Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/logger) | Structured logging with Pino |
71
+ | [Middleware Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/middleware) | Express middleware collection |
72
+ | [Object Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/object) | Deep merge, flatten, pick/omit, etc. |
73
+ | [Performance Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/performance) | Timing, memoization, memory tracking |
74
+ | [Request Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/request) | HTTP request parameter parsing/validation |
75
+ | [Response Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/response) | Standardized API response formatting |
76
+ | [Stream Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/stream) | Stream conversion, batching, throttling, line splitting |
77
+ | [String Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/string) | Casing, masking, slugifying, formatting |
78
+ | [Type Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/type) | Type checking, conversion, guards |
79
+ | [URL Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/url) | URL parsing, query manipulation, normalization |
80
+ | [Validate Utilities](https://catbee-utils.npm.hprasath.com/docs/utils/validation) | Input validation functions |
459
81
 
460
- - `fileExists(path: string): Promise<boolean>` – Check if a file exists.
461
- - `readJsonFile<T>(path: string): Promise<T | null>` – Read and parse a JSON file.
462
- - `writeJsonFile(path: string, data: any, space?: number): Promise<void>` – Write data to a JSON file.
463
- - `deleteFileIfExists(path: string): Promise<boolean>` – Delete a file if it exists.
464
- - `readTextFile(path: string, encoding?: BufferEncoding): Promise<string | null>` – Read a text file.
465
- - `writeTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>` – Write text to a file.
466
- - `appendTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>` – Append text to a file.
467
- - `copyFile(source: string, destination: string, overwrite?: boolean): Promise<boolean>` – Copy a file.
468
- - `moveFile(oldPath: string, newPath: string): Promise<boolean>` – Move or rename a file.
469
- - `getFileStats(path: string): Promise<fs.Stats | null>` – Get file statistics.
470
- - `createTempFile(options?): Promise<string>` – Create a temporary file.
471
- - `streamFile(source: string, destination: string): Promise<void>` – Stream file contents.
472
- - `readDirectory(dirPath: string, options?): Promise<string[]>` – Read directory contents.
473
- - `createDirectory(dirPath: string, recursive?: boolean): Promise<boolean>` – Create a directory.
474
- - `safeReadJsonFile<T>(path: string): Promise<{ data: T | null; error: Error | null }>` – Safely read a JSON file.
475
- - `isFile(path: string): Promise<boolean>` – Check if a path is a file.
476
- - `getFileSize(path: string): Promise<number>` – Get the size of a file.
477
- - `readFileBuffer(path: string): Promise<Buffer | null>` – Read a file as a buffer.
478
-
479
- **Examples:**
480
- ```ts
481
- import { readFileBuffer } from "@catbee/utils";
482
- const buffer = await readFileBuffer("./file.txt");
483
- ```
484
-
485
- ## 📊 HTTP Status Codes
486
-
487
- A typed enum with all HTTP status codes and their standard messages.
488
-
489
- - `HttpStatusCodes.OK === 200` – HTTP 200 OK.
490
- - `HttpStatusCodes.NOT_FOUND === 404` – HTTP 404 Not Found.
491
- - ...and so on.
492
-
493
- **Example:**
494
- ```ts
495
- import { HttpStatusCodes } from "@catbee/utils";
496
- res.status(HttpStatusCodes.BAD_REQUEST).send("Invalid payload");
497
- ```
498
-
499
- ## 🆔 ID Utilities
500
-
501
- - `uuid(): string` – Generate a UUID v4.
502
- - `nanoId(size?: number): string` – Generate a compact, URL-friendly unique ID.
503
- - `randomHex(byteLength?: number): string` – Generate a random hexadecimal string.
504
- - `randomInt(min: number, max: number): number` – Generate a random integer in a range.
505
- - `randomBase64(byteLength?: number): number` – Generate a random Base64 string.
506
-
507
- **Examples:**
508
- ```ts
509
- import { nanoId } from "@catbee/utils";
510
- const id = nanoId();
511
- ```
512
-
513
- ## 📄 Logger Utilities
514
-
515
- - `getLogger(): Logger` – Get the default logger instance.
516
- - `createChildLogger(bindings: Record<string, any>, parentLogger?: Logger): Logger` – Create a child logger with bindings.
517
- - `createRequestLogger(requestId: string, additionalContext?: Record<string, any>): Logger` – Create a logger for a specific request.
518
- - `logError(error: Error | unknown, message?: string, context?: Record<string, any>): void` – Log an error with optional context.
519
- - `resetLogger(): void` – Reset the logger to its initial state.
520
- - `getRedactCensor(): (value: any, paths: string[]) => any` – Get a censor function for redacting sensitive info.
521
- - `setRedactCensor(censor: (value: any, paths: string[]) => any): void` – Set a custom censor function.
522
- - `addRedactFields(fields: string[]): void` – Add fields to redact.
523
- - `setSensitiveFields(): void` – Set the list of sensitive fields to redact.
524
- - `addSensitiveFields(fields: string[]): void` – Add sensitive fields to redact.
525
- - `LoggerLevels`: Enum for log levels (e.g., INFO, WARN, ERROR).
526
- - `Logger`: Interface for the logger instance.
527
-
528
- **Examples:**
529
- ```ts
530
- import { getLogger } from "@catbee/utils";
531
- const logger = getLogger();
532
- logger.info("App started");
533
- logger.warn("Potential issue detected");
534
- logger.error({ context: "some context" }, "Error occurred");
535
- ```
536
-
537
- ## 🧩 Middleware Utilities
538
-
539
- - `requestId(options?): Middleware` – Generate and attach a unique request ID to each request.
540
- - `responseTime(options?): Middleware` – Measure and log the response time for each request.
541
- - `timeout(timeoutMs?: number): Middleware` – Abort requests that exceed a specified timeout.
542
- - `setupRequestContext(): Middleware` – Set up the request context for each incoming request.
543
- - `errorHandler(options?): Middleware` – Centralized error handling middleware.
544
-
545
- **Example:**
546
- ```ts
547
- import { Env, requestId, responseTime, errorHandler } from "@catbee/utils";
548
- app.use(requestId({ headerName: "X-Request-ID", autoLog: true }));
549
- app.use(responseTime({ addHeaders: true, logOnComplete: true }));
550
- app.use(errorHandler({ logErrors: true, includeDetails: true }));
551
- ```
552
-
553
- ## 🧩 Object Utilities
554
-
555
- A set of helpers for working with JavaScript objects, including deep merging, flattening, picking/omitting keys, and more. These utilities help safely manipulate and inspect objects in a type-safe way.
556
-
557
- - `isObjEmpty(obj: Record<any, any>): boolean` – Check if an object has no own properties.
558
- - `pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>` – Create a new object with only the specified keys.
559
- - `omit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>` – Create a new object without the specified keys.
560
- - `deepObjMerge<T>(target: T, source: Partial<T>): T` – Deeply merge two objects.
561
- - `flattenObject<T>(obj: T, prefix?: string): Record<string, any>` – Flatten a nested object into dot notation.
562
- - `getValueByPath<T>(obj: T, path: string): any` – Get a value from an object by dot path.
563
- - `setValueByPath<T>(obj: T, path: string, value: any): T` – Set a value in an object by dot path.
564
- - `isEqual(a: any, b: any): boolean` – Deeply compare two values for equality.
565
- - `filterObject<T>(obj: T, predicate): Partial<T>` – Filter object properties by predicate.
566
- - `mapObject<T, U>(obj: T, mapFn): Record<keyof T, U>` – Map object values to a new object.
567
- - `deepFreeze<T>(obj: T): Readonly<T>` – Recursively freeze an object.
568
- - `isObject(value: unknown): value is Record<string, any>` – Check if a value is a plain object.
569
- - `getAllPaths(obj: Record<string, any>, parentPath?: string): string[]` – Get all dot paths in an object.
570
-
571
- **Examples:**
572
-
573
- ```ts
574
- // Deep merge configurations
575
- const defaultConfig = {
576
- server: { port: 3000, host: 'localhost' },
577
- logging: { level: 'info', format: 'json' }
578
- };
579
-
580
- const userConfig = {
581
- server: { port: 8080 },
582
- logging: { pretty: true }
583
- };
584
-
585
- const finalConfig = deepObjMerge(defaultConfig, userConfig);
586
- /* Result:
587
- {
588
- server: { port: 8080, host: 'localhost' },
589
- logging: { level: 'info', format: 'json', pretty: true }
590
- }
591
- */
592
-
593
- // Flatten and unflatten nested objects
594
- const user = {
595
- name: 'Alice',
596
- details: {
597
- address: {
598
- city: 'New York',
599
- zip: '10001'
600
- },
601
- preferences: {
602
- theme: 'dark'
603
- }
604
- }
605
- };
606
-
607
- const flat = flattenObject(user);
608
- /* Result:
609
- {
610
- 'name': 'Alice',
611
- 'details.address.city': 'New York',
612
- 'details.address.zip': '10001',
613
- 'details.preferences.theme': 'dark'
614
- }
615
- */
616
-
617
- // Getting and setting values by path
618
- const theme = getValueByPath(user, 'details.preferences.theme'); // 'dark'
619
- const updated = setValueByPath(user, 'details.address.state', 'NY');
620
- ```
621
-
622
- ## 📝 Request Utilities
623
-
624
- Functions for safely parsing, validating, and extracting parameters from HTTP requests.
625
-
626
- - `parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>` – Parse and validate a numeric parameter from a string.
627
- - `parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>` – Parse and validate a boolean parameter from a string.
628
- - `extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): { page: number; limit: number }` – Extract and validate pagination parameters from a query object.
629
- - `extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?): { sortBy: string; sortOrder: 'asc' | 'desc' }` – Extract and validate sorting parameters from a query object.
630
- - `extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>` – Extract filter parameters from a query object based on allowed fields.
631
-
632
- **Types:**
633
- ```ts
634
- interface ValidationOptions {
635
- throwOnError?: boolean;
636
- errorMessage?: string;
637
- defaultValue?: any;
638
- required?: boolean;
639
- }
640
-
641
- interface ValidationResult<T> {
642
- isValid: boolean;
643
- value: T | null;
644
- error?: string;
645
- }
646
- ```
647
-
648
- **Examples:**
649
-
650
- ```ts
651
- import {
652
- parseNumberParam,
653
- parseBooleanParam,
654
- extractPaginationParams,
655
- extractSortParams,
656
- extractFilterParams
657
- } from '@catbee/utils';
658
-
659
- // Parse and validate query parameters
660
- function handleRequest(req, res) {
661
- // Parse numeric parameter with validation
662
- const idResult = parseNumberParam(req.query.id, {
663
- required: true,
664
- throwOnError: false
665
- });
666
-
667
- if (!idResult.isValid) {
668
- return res.status(400).send({ error: idResult.error });
669
- }
670
-
671
- // Parse boolean parameter
672
- const isActiveResult = parseBooleanParam(req.query.isActive, {
673
- defaultValue: false
674
- });
675
-
676
- // Extract standard pagination parameters
677
- const { page, limit } = extractPaginationParams(
678
- req.query,
679
- 1, // default page
680
- 20, // default limit
681
- 100 // max limit
682
- );
683
-
684
- // Extract sorting parameters
685
- const { sortBy, sortOrder } = extractSortParams(
686
- req.query,
687
- ['name', 'createdAt', 'price'], // allowed fields
688
- { sortBy: 'createdAt', sortOrder: 'desc' } // defaults
689
- );
690
-
691
- // Extract filters based on allowed fields
692
- const filters = extractFilterParams(
693
- req.query,
694
- ['category', 'status', 'price']
695
- );
696
-
697
- // Process the request with validated parameters
698
- const items = getItems({
699
- page,
700
- limit,
701
- sortBy,
702
- sortOrder,
703
- filters,
704
- isActive: isActiveResult.value
705
- });
706
-
707
- return res.json(items);
708
- }
709
- ```
710
-
711
- ## 📝 Response Utilities
712
-
713
- Helpers for creating and sending standardized API responses, including success, error, paginated, and redirect responses. Ensures consistent structure and status codes for all API endpoints.
714
-
715
- - `SuccessResponse<T>` – Standard API success wrapper object.
716
- - `ErrorResponse` – Standard API error wrapper object.
717
- - `PaginatedResponse<T>` – Paginated API response object.
718
- - `NoContentResponse` – 204 No Content response object.
719
- - `RedirectResponse` – Redirect response object.
720
- - `createSuccessResponse<T>(data: T, message?: string): SuccessResponse<T>` – Create a success response.
721
- - `createErrorResponse(message: string, statusCode?: number): ErrorResponse` – Create an error response.
722
- - `createPaginatedResponse<T>(allItems: T[], page: number, pageSize: number, message?: string): PaginatedResponse<T>` – Create a paginated response.
723
- - `sendResponse(res, apiResponse): void` – Send an API response using an HTTP response object.
724
- - `isApiResponse(value: any): value is ApiResponse<any>` – Check if a value is an API response.
725
-
726
- **Examples:**
727
-
728
- ```ts
729
- import {
730
- createSuccessResponse,
731
- createErrorResponse,
732
- createPaginatedResponse,
733
- sendResponse
734
- } from "@catbee/utils";
735
- import express from "express";
736
-
737
- const app = express();
738
-
739
- app.get('/api/users', (req, res) => {
740
- try {
741
- const allUsers = [/* ...users from database... */];
742
- const page = parseInt(req.query.page as string) || 1;
743
- const pageSize = parseInt(req.query.limit as string) || 10;
744
-
745
- const response = createPaginatedResponse(
746
- allUsers,
747
- page,
748
- pageSize,
749
- 'Users retrieved successfully'
750
- );
751
-
752
- sendResponse(res, response);
753
- } catch (error) {
754
- const errorResponse = createErrorResponse(
755
- 'Failed to retrieve users',
756
- 500
757
- );
758
- sendResponse(res, errorResponse);
759
- }
760
- });
761
-
762
- app.get('/api/profile', (req, res) => {
763
- const user = { id: 123, name: 'Alice' };
764
- const response = createSuccessResponse(user, 'Profile retrieved');
765
- sendResponse(res, response);
766
-
767
- // This sends:
768
- // {
769
- // success: true,
770
- // data: { id: 123, name: 'Alice' },
771
- // message: 'Profile retrieved'
772
- // }
773
- });
774
- ```
775
-
776
- ## 🧵 String Utilities
777
-
778
- A set of utilities for manipulating, formatting, and transforming strings. Includes helpers for casing, masking, slugifying, truncating, and more.
779
-
780
- - `capitalize(str: string): string` – Capitalize the first letter of a string.
781
- - `toKebabCase(str: string): string` – Convert a string to kebab-case.
782
- - `toCamelCase(str: string): string` – Convert a string to camelCase.
783
- - `slugify(str: string): string` – Convert a string to a URL-friendly slug.
784
- - `truncate(str: string, len: number): string` – Truncate a string to a maximum length.
785
- - `toPascalCase(str: string): string` – Convert a string to PascalCase.
786
- - `toSnakeCase(str: string): string` – Convert a string to snake_case.
787
- - `mask(str: string, visibleStart?: number, visibleEnd?: number, maskChar?: string): string` – Mask part of a string for privacy.
788
- - `stripHtml(str: string): string` – Remove HTML tags from a string.
789
- - `equalsIgnoreCase(a: string, b: string): boolean` – Compare two strings ignoring case.
790
- - `reverse(str: string): string` – Reverse the characters in a string.
791
- - `countOccurrences(str: string, substring: string, caseSensitive?: boolean): number` – Count how many times a substring appears.
792
-
793
- ** Examples **
794
- ```ts
795
- import { capitalize, toCamelCase, slugify, mask } from "@catbee/utils";
796
-
797
- const exampleString = "Hello World";
798
-
799
- console.log(capitalize(exampleString)); // "Hello world"
800
- console.log(toCamelCase(exampleString)); // "helloWorld"
801
- console.log(slugify(exampleString)); // "hello-world"
802
- console.log(mask(exampleString, 2, 5, "*")); // "He***"
803
- ```
804
-
805
- ## 🌐 URL Utilities
82
+ ---
806
83
 
807
- Helpers for parsing, validating, building, and manipulating URLs and query strings. Useful for web, API, and routing logic.
84
+ ## 🏁 Usage
808
85
 
809
- - `appendQueryParams(url: string, params: Record<string, string | number>): string` – Add query parameters to a URL.
810
- - `parseQueryString(query: string): Record<string, string>` – Parse a query string into an object.
811
- - `isValidUrl(url: string, requireHttps?: boolean): boolean` – Check if a string is a valid URL.
812
- - `getDomain(url: string, removeSubdomains?: boolean): string` – Extract the domain from a URL.
813
- - `joinPaths(...segments: string[]): string` – Join multiple URL path segments.
814
- - `normalizeUrl(url: string, base?: string): string` – Normalize a URL, optionally with a base.
815
- - `createUrlBuilder(baseUrl: string): { path(path: string, params?: Record<string, any>): string; query(params: Record<string, any>): string }` – Build URLs with paths and query parameters.
816
- - `extractQueryParams(url: string, paramNames: string[]): Record<string, string>` – Extract specific query parameters from a URL.
817
- - `removeQueryParams(url: string, paramsToRemove: string[]): string` – Remove specific query parameters from a URL.
818
- - `getExtension(url: string): string` – Get the file extension from a URL.
819
- - `parseTypedQueryParams<T>(url: string, converters?: Record<keyof T, (val: string) => any>): Partial<T>` – Parse and convert query parameters to typed values.
86
+ Import only what you need:
820
87
 
821
- **Example:**
822
88
  ```ts
823
- const url = appendQueryParams('https://example.com', { page: 1, limit: 10 });
824
- // → 'https://example.com/?page=1&limit=10'
89
+ import { chunk, sleep, TTLCache, getLogger } from "@catbee/utils";
825
90
  ```
826
91
 
827
- ## ✅ Validate Utilities
828
-
829
- A comprehensive suite of validators for checking strings, numbers, objects, arrays, and common formats such as email, UUID, IP, and more. Useful for input validation and API parameter checks.
830
-
831
- - `isEmail(str: string): boolean` – Check if a string is a valid email address.
832
- - `isUUID(str: string): boolean` – Check if a string is a valid UUID.
833
- - `isURL(str: string): boolean` – Check if a string is a valid URL.
834
- - `isPhone(str: string): boolean` – Check if a string is a valid phone number.
835
- - `isAlphanumeric(str: string): boolean` – Check if a string contains only letters and numbers.
836
- - `isNumeric(value: string | number): boolean` – Check if a value is numeric.
837
- - `isHexColor(str: string): boolean` – Check if a string is a valid hex color code.
838
- - `isISODate(str: string): boolean` – Check if a string is a valid ISO date.
839
- - `isLengthBetween(str: string, min: number, max: number): boolean` – Check if a string's length is within a range.
840
- - `isNumberBetween(value: number, min: number, max: number): boolean` – Check if a number is within a range.
841
- - `isAlpha(str: string): boolean` – Check if a string contains only letters.
842
- - `isStrongPassword(str: string): boolean` – Check if a string is a strong password.
843
- - `isIPv4(str: string): boolean` – Check if a string is a valid IPv4 address.
844
- - `isIPv6(str: string): boolean` – Check if a string is a valid IPv6 address.
845
- - `isCreditCard(str: string): boolean` – Check if a string is a valid credit card number.
846
- - `isValidJSON(str: string): boolean` – Check if a string is valid JSON.
847
- - `isArray<T = unknown>(value: unknown, itemGuard?: (item: unknown) => item is T): value is T[]` – Check if a value is an array (optionally with type guard).
848
- - `isObject(value: unknown): value is Record<string, unknown>` – Check if a value is a plain object.
849
- - `hasRequiredProps(obj: Record<string, unknown>, requiredProps: string[]): boolean` – Check if an object has all required properties.
850
- - `isDateInRange(date: Date, minDate?: Date, maxDate?: Date): boolean` – Check if a date is within a range.
851
- - `matchesPattern(str: string, pattern: RegExp): boolean` – Check if a string matches a regular expression.
852
- - `validateAll(value: unknown, validators: Array<(value: unknown) => boolean>): boolean` – Check if all validators pass for a value.
853
-
854
92
  ---
855
93
 
856
- # 📧 Decorators Utilities
857
-
858
- ## Available Decorators
859
-
860
- - `@Controller(basePath: string)` – Class decorator to set the base route.
861
- - `@Get(path)`, `@Post(path)`, `@Put(path)`, `@Patch(path)`, `@Delete(path)`, `@Options(path)`, `@Head(path)`, `@Trace(path)`, `@Connect(path)` – Method decorators for HTTP verbs.
862
- - `@Use(...middlewares)` – Attach Express-style middleware to a route handler.
863
- - `@Query(key?)`, `@Param(key?)`, `@Body(key?)`, `@Req()`, `@Res()` – Parameter decorators for extracting request data.
864
- - `@HttpCode(status)` – Set custom HTTP status code for the response.
865
- - `@Header(name, value)` – Set custom response headers.
866
- - `@Before(fn)`, `@After(fn)` – Register before/after hooks for a route handler.
867
- - `@Redirect({ url?: string, statusCode: number })` – Redirect to a different URL.
868
- - `@Roles(...roles: string[])` – Restrict access to certain roles - req.user.roles[] should include at least one of the specified roles.
94
+ ## 📖 Documentation
869
95
 
870
- ## Example Usage
96
+ - [Full API Docs & Examples](https://catbee-utils.npm.hprasath.com)
871
97
 
872
- ```typescript
873
- import {
874
- Controller, Get, Post, Use, Query, Param, Body, Req, Res,
875
- HttpCode, Header, Before, After, Roles, registerControllers
876
- } from './src/utils/decorators.utils';
877
-
878
- // Example middleware
879
- function logMiddleware(req: Request, res: Response, next: NextFunction) {
880
- console.log('Request:', req.method, req.url);
881
- next();
882
- }
883
-
884
- // Example before/after hooks
885
- function beforeHook(req: Request, res: Response) {
886
- console.log('Before handler');
887
- }
888
- function afterHook(req: Request, res: Response, result: any) {
889
- console.log('After handler', result);
890
- }
891
-
892
- @Controller('/api')
893
- class ExampleController {
894
- @Get('/items/:id')
895
- @Use(logMiddleware)
896
- @HttpCode(200)
897
- @Header('X-Example', 'yes')
898
- @Before(beforeHook)
899
- @After(afterHook)
900
- @Roles('admin', 'moderator')
901
- @Redirect('/https://example.com')
902
- getItem(
903
- @Query('q') q: string,
904
- @Param('id') id: string,
905
- @Body('name') name: string,
906
- @Req() req: Request,
907
- @Res() res: Response
908
- ) {
909
- return { q, id, name };
910
- }
911
-
912
- @Post('/items')
913
- createItem(@Body() body: any) {
914
- return { created: true, ...body };
915
- }
916
- }
917
-
918
- // Register controllers with your router (Express-like)
919
- const router = /* your router instance */;
920
- registerControllers(router, [ExampleController]);
921
- ```
922
-
923
- ## Notes
924
-
925
- - Decorated methods **must** use standard method syntax, not arrow functions or property initializers.
926
- - All parameter decorators (`@Query`, `@Param`, etc.) are optional and can be used in any order.
927
- - `registerControllers(router, controllers)` will register all routes and apply middlewares, hooks, status codes, and headers as defined.
928
-
929
- ## 🏁 Usage
930
-
931
- Import only what you need:
932
-
933
- ```ts
934
- import { chunk, sleep, TTLCache, getLogger } from "@catbee/utils";
935
- ```
98
+ ---
936
99
 
937
100
  ## 📜 License
938
101