@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
@@ -0,0 +1,88 @@
1
+ import { Readable, Transform } from 'stream';
2
+ import { BufferEncoding } from './crypto.utils';
3
+ /**
4
+ * Convert a buffer or string to a readable stream.
5
+ *
6
+ * @param data - Buffer or string to convert
7
+ * @returns Readable stream containing the data
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const stream = bufferToStream(Buffer.from('Hello world'));
12
+ * // or
13
+ * const stream = bufferToStream('Hello world');
14
+ * ```
15
+ */
16
+ export declare function bufferToStream(data: Buffer | string): Readable;
17
+ /**
18
+ * Convert a readable stream to a buffer.
19
+ *
20
+ * @param stream - Readable stream to convert
21
+ * @returns Promise resolving to a buffer containing all stream data
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
26
+ * console.log(buffer.toString()); // Contents of file.txt
27
+ * ```
28
+ */
29
+ export declare function streamToBuffer(stream: Readable): Promise<Buffer>;
30
+ /**
31
+ * Convert a readable stream to a string.
32
+ *
33
+ * @param stream - Readable stream to convert
34
+ * @param encoding - Character encoding (default: 'utf8')
35
+ * @returns Promise resolving to a string containing all stream data
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const content = await streamToString(fs.createReadStream('file.txt'));
40
+ * console.log(content); // Contents of file.txt as string
41
+ * ```
42
+ */
43
+ export declare function streamToString(stream: Readable, encoding?: BufferEncoding): Promise<string>;
44
+ /**
45
+ * Create a transform stream that limits the rate of data flow.
46
+ *
47
+ * @param bytesPerSecond - Maximum bytes per second
48
+ * @returns Transform stream that throttles data flow
49
+ */
50
+ export declare function createThrottleStream(bytesPerSecond: number): Transform;
51
+ /**
52
+ * Create a transform stream that batches data into chunks of specified size.
53
+ *
54
+ * @param size - Size of each batch (items for object mode, bytes for binary mode)
55
+ * @param options - Stream options
56
+ * @returns Transform stream that batches data
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // Batch lines from a file into arrays of 100 lines each
61
+ * createReadStream('large-file.txt')
62
+ * .pipe(createLineStream())
63
+ * .pipe(createBatchStream(100))
64
+ * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
65
+ * ```
66
+ */
67
+ export declare function createBatchStream(size: number, options?: {
68
+ objectMode?: boolean;
69
+ }): Transform;
70
+ /**
71
+ * Create a transform stream that splits text data by newlines.
72
+ *
73
+ * @param options - Options for the line stream
74
+ * @returns Transform stream that emits lines
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * // Process a file line by line
79
+ * createReadStream('file.txt')
80
+ * .pipe(createLineStream())
81
+ * .on('data', line => console.log(`Line: ${line}`));
82
+ * ```
83
+ */
84
+ export declare function createLineStream(options?: {
85
+ encoding?: BufferEncoding;
86
+ includeNewlines?: boolean;
87
+ }): Transform;
88
+ //# sourceMappingURL=stream.utils.d.ts.map
@@ -0,0 +1,210 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
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 { Readable, Transform } from 'stream';
25
+ /**
26
+ * Convert a buffer or string to a readable stream.
27
+ *
28
+ * @param data - Buffer or string to convert
29
+ * @returns Readable stream containing the data
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const stream = bufferToStream(Buffer.from('Hello world'));
34
+ * // or
35
+ * const stream = bufferToStream('Hello world');
36
+ * ```
37
+ */
38
+ export function bufferToStream(data) {
39
+ const readable = new Readable();
40
+ readable.push(data);
41
+ readable.push(null); // End of stream
42
+ return readable;
43
+ }
44
+ /**
45
+ * Convert a readable stream to a buffer.
46
+ *
47
+ * @param stream - Readable stream to convert
48
+ * @returns Promise resolving to a buffer containing all stream data
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
53
+ * console.log(buffer.toString()); // Contents of file.txt
54
+ * ```
55
+ */
56
+ export async function streamToBuffer(stream) {
57
+ return new Promise((resolve, reject) => {
58
+ const chunks = [];
59
+ stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
60
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
61
+ stream.on('error', reject);
62
+ });
63
+ }
64
+ /**
65
+ * Convert a readable stream to a string.
66
+ *
67
+ * @param stream - Readable stream to convert
68
+ * @param encoding - Character encoding (default: 'utf8')
69
+ * @returns Promise resolving to a string containing all stream data
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * const content = await streamToString(fs.createReadStream('file.txt'));
74
+ * console.log(content); // Contents of file.txt as string
75
+ * ```
76
+ */
77
+ export async function streamToString(stream, encoding = 'utf8') {
78
+ const buffer = await streamToBuffer(stream);
79
+ return buffer.toString(encoding);
80
+ }
81
+ /**
82
+ * Create a transform stream that limits the rate of data flow.
83
+ *
84
+ * @param bytesPerSecond - Maximum bytes per second
85
+ * @returns Transform stream that throttles data flow
86
+ */
87
+ export function createThrottleStream(bytesPerSecond) {
88
+ let bytesSent = 0;
89
+ let startTime = Date.now();
90
+ return new Transform({
91
+ transform(chunk, _encoding, callback) {
92
+ const elapsedSeconds = (Date.now() - startTime) / 1000;
93
+ const targetBytes = bytesPerSecond * elapsedSeconds;
94
+ const chunkSize = chunk.length;
95
+ // If we've sent fewer bytes than our target, just send the chunk
96
+ if (bytesSent + chunkSize <= targetBytes) {
97
+ bytesSent += chunkSize;
98
+ callback(null, chunk);
99
+ return;
100
+ }
101
+ // Otherwise we need to throttle
102
+ const delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;
103
+ setTimeout(() => {
104
+ bytesSent += chunkSize;
105
+ callback(null, chunk);
106
+ }, delay);
107
+ }
108
+ });
109
+ }
110
+ /**
111
+ * Create a transform stream that batches data into chunks of specified size.
112
+ *
113
+ * @param size - Size of each batch (items for object mode, bytes for binary mode)
114
+ * @param options - Stream options
115
+ * @returns Transform stream that batches data
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * // Batch lines from a file into arrays of 100 lines each
120
+ * createReadStream('large-file.txt')
121
+ * .pipe(createLineStream())
122
+ * .pipe(createBatchStream(100))
123
+ * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
124
+ * ```
125
+ */
126
+ export function createBatchStream(size, options = {}) {
127
+ const objectMode = options.objectMode !== false;
128
+ let batch = [];
129
+ let buffers = [];
130
+ let bufferSize = 0;
131
+ return new Transform({
132
+ objectMode,
133
+ transform(chunk, _encoding, callback) {
134
+ if (objectMode) {
135
+ batch.push(chunk);
136
+ if (batch.length >= size) {
137
+ this.push(batch);
138
+ batch = [];
139
+ }
140
+ }
141
+ else {
142
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
143
+ buffers.push(buffer);
144
+ bufferSize += buffer.length;
145
+ // Emit batches of exact size
146
+ let combined = Buffer.concat(buffers, bufferSize);
147
+ while (combined.length >= size) {
148
+ this.push(combined.slice(0, size));
149
+ combined = combined.slice(size);
150
+ }
151
+ buffers = combined.length > 0 ? [combined] : [];
152
+ bufferSize = combined.length;
153
+ }
154
+ callback();
155
+ },
156
+ flush(callback) {
157
+ if (objectMode && batch.length > 0) {
158
+ this.push(batch);
159
+ }
160
+ else if (!objectMode && buffers.length > 0 && bufferSize > 0) {
161
+ let combined = Buffer.concat(buffers, bufferSize);
162
+ while (combined.length >= size) {
163
+ this.push(combined.slice(0, size));
164
+ combined = combined.slice(size);
165
+ }
166
+ if (combined.length > 0) {
167
+ this.push(combined);
168
+ }
169
+ }
170
+ callback();
171
+ }
172
+ });
173
+ }
174
+ /**
175
+ * Create a transform stream that splits text data by newlines.
176
+ *
177
+ * @param options - Options for the line stream
178
+ * @returns Transform stream that emits lines
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * // Process a file line by line
183
+ * createReadStream('file.txt')
184
+ * .pipe(createLineStream())
185
+ * .on('data', line => console.log(`Line: ${line}`));
186
+ * ```
187
+ */
188
+ export function createLineStream(options = {}) {
189
+ const { encoding = 'utf8', includeNewlines = false } = options;
190
+ let buffer = '';
191
+ return new Transform({
192
+ objectMode: true,
193
+ transform(chunk, _encoding, callback) {
194
+ const str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);
195
+ const lines = str.split(/\r?\n/);
196
+ buffer = lines.pop() || '';
197
+ for (const line of lines) {
198
+ this.push(includeNewlines ? line + '\n' : line);
199
+ }
200
+ callback();
201
+ },
202
+ flush(callback) {
203
+ if (buffer) {
204
+ this.push(buffer);
205
+ }
206
+ callback();
207
+ }
208
+ });
209
+ }
210
+ //# sourceMappingURL=stream.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.utils.js","sourceRoot":"","sources":["../../../src/utils/stream.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAqB,MAAM,QAAQ,CAAC;AAGhE;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,cAAc,CAAC,IAAqB;IAClD,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAC;IAChC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB;IACrC,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,MAAgB;IACnD,OAAO,IAAI,OAAO,CAAS,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC7C,MAAM,MAAM,GAAa,EAAE,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7F,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,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,KAAK,CAAC,CAAC;YACjF,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACjC,MAAM,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;YAE3B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;gBACzB,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAClD,CAAC;YAED,QAAQ,EAAE,CAAC;QACb,CAAC;QAED,KAAK,CAAC,QAAQ;YACZ,IAAI,MAAM,EAAE,CAAC;gBACX,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACpB,CAAC;YACD,QAAQ,EAAE,CAAC;QACb,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Readable, Transform, TransformCallback } from 'stream';\nimport { BufferEncoding } from './crypto.utils';\n\n/**\n * Convert a buffer or string to a readable stream.\n *\n * @param data - Buffer or string to convert\n * @returns Readable stream containing the data\n *\n * @example\n * ```typescript\n * const stream = bufferToStream(Buffer.from('Hello world'));\n * // or\n * const stream = bufferToStream('Hello world');\n * ```\n */\nexport function bufferToStream(data: Buffer | string): Readable {\n const readable = new Readable();\n readable.push(data);\n readable.push(null); // End of stream\n return readable;\n}\n\n/**\n * Convert a readable stream to a buffer.\n *\n * @param stream - Readable stream to convert\n * @returns Promise resolving to a buffer containing all stream data\n *\n * @example\n * ```typescript\n * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));\n * console.log(buffer.toString()); // Contents of file.txt\n * ```\n */\nexport async function streamToBuffer(stream: Readable): Promise<Buffer> {\n return new Promise<Buffer>((resolve, reject) => {\n const chunks: Buffer[] = [];\n stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));\n stream.on('end', () => resolve(Buffer.concat(chunks)));\n stream.on('error', reject);\n });\n}\n\n/**\n * Convert a readable stream to a string.\n *\n * @param stream - Readable stream to convert\n * @param encoding - Character encoding (default: 'utf8')\n * @returns Promise resolving to a string containing all stream data\n *\n * @example\n * ```typescript\n * const content = await streamToString(fs.createReadStream('file.txt'));\n * console.log(content); // Contents of file.txt as string\n * ```\n */\nexport async function streamToString(stream: Readable, encoding: BufferEncoding = 'utf8'): Promise<string> {\n const buffer = await streamToBuffer(stream);\n return buffer.toString(encoding);\n}\n\n/**\n * Create a transform stream that limits the rate of data flow.\n *\n * @param bytesPerSecond - Maximum bytes per second\n * @returns Transform stream that throttles data flow\n */\nexport function createThrottleStream(bytesPerSecond: number): Transform {\n let bytesSent = 0;\n let startTime = Date.now();\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n const elapsedSeconds = (Date.now() - startTime) / 1000;\n const targetBytes = bytesPerSecond * elapsedSeconds;\n const chunkSize = chunk.length;\n\n // If we've sent fewer bytes than our target, just send the chunk\n if (bytesSent + chunkSize <= targetBytes) {\n bytesSent += chunkSize;\n callback(null, chunk);\n return;\n }\n\n // Otherwise we need to throttle\n const delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;\n\n setTimeout(() => {\n bytesSent += chunkSize;\n callback(null, chunk);\n }, delay);\n }\n });\n}\n\n/**\n * Create a transform stream that batches data into chunks of specified size.\n *\n * @param size - Size of each batch (items for object mode, bytes for binary mode)\n * @param options - Stream options\n * @returns Transform stream that batches data\n *\n * @example\n * ```typescript\n * // Batch lines from a file into arrays of 100 lines each\n * createReadStream('large-file.txt')\n * .pipe(createLineStream())\n * .pipe(createBatchStream(100))\n * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));\n * ```\n */\nexport function createBatchStream(size: number, options: { objectMode?: boolean } = {}): Transform {\n const objectMode = options.objectMode !== false;\n let batch: any[] = [];\n let buffers: Buffer[] = [];\n let bufferSize = 0;\n\n return new Transform({\n objectMode,\n transform(chunk, _encoding, callback) {\n if (objectMode) {\n batch.push(chunk);\n if (batch.length >= size) {\n this.push(batch);\n batch = [];\n }\n } else {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n buffers.push(buffer);\n bufferSize += buffer.length;\n\n // Emit batches of exact size\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n buffers = combined.length > 0 ? [combined] : [];\n bufferSize = combined.length;\n }\n\n callback();\n },\n\n flush(callback) {\n if (objectMode && batch.length > 0) {\n this.push(batch);\n } else if (!objectMode && buffers.length > 0 && bufferSize > 0) {\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n if (combined.length > 0) {\n this.push(combined);\n }\n }\n callback();\n }\n });\n}\n\n/**\n * Create a transform stream that splits text data by newlines.\n *\n * @param options - Options for the line stream\n * @returns Transform stream that emits lines\n *\n * @example\n * ```typescript\n * // Process a file line by line\n * createReadStream('file.txt')\n * .pipe(createLineStream())\n * .on('data', line => console.log(`Line: ${line}`));\n * ```\n */\nexport function createLineStream(\n options: {\n encoding?: BufferEncoding;\n includeNewlines?: boolean;\n } = {}\n): Transform {\n const { encoding = 'utf8', includeNewlines = false } = options;\n let buffer = '';\n\n return new Transform({\n objectMode: true,\n transform(chunk, _encoding, callback) {\n const str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);\n const lines = str.split(/\\r?\\n/);\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n this.push(includeNewlines ? line + '\\n' : line);\n }\n\n callback();\n },\n\n flush(callback) {\n if (buffer) {\n this.push(buffer);\n }\n callback();\n }\n });\n}\n"]}
@@ -1,3 +1,26 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
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
+ */
1
24
  /**
2
25
  * Capitalizes the first character of a string.
3
26
  *
@@ -1 +1 @@
1
- {"version":3,"file":"string.utils.js","sourceRoot":"","sources":["../../../src/utils/string.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG;SACP,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC,0BAA0B;SAC9D,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,iBAAiB;SACtC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,sBAAsB;SAC1C,WAAW,EAAE,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACpE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,OAAO,GAAG;SACP,WAAW,EAAE;SACb,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,kBAAkB;SAC3C,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,iBAAiB;SACtC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,yBAAyB;SAC7C,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,+BAA+B;AAC7D,CAAC;AA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AY,GAAG,UAAU,CAAC,CAAC,CAAC;IAEpF,OAAO,KAAK,GAAG,MAAM,GAAG,GAAG,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,OAAO,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AACrC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,CAAS,EAAE,CAAS;IACnD,OAAO,CAAC,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AAC7C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,OAAO,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,SAAiB,EAAE,gBAAyB,IAAI;IAC5F,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACxB,SAAS,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;IACtC,CAAC;IAED,OAAO,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Capitalizes the first character of a string.\n *\n * @param {string} str - The input string.\n * @returns {string} The string with the first character in uppercase.\n */\nexport function capitalize(str: string): string {\n return str.length === 0 ? '' : str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts a string to kebab-case (e.g., \"FooBar test\" → \"foo-bar-test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The kebab-cased string.\n */\nexport function toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/_+/g, '-') // underscores to dash\n .toLowerCase();\n}\n\n/**\n * Converts a kebab-case or snake_case string to camelCase.\n *\n * @param {string} str - The input string.\n * @returns {string} The camelCased string.\n */\nexport function toCamelCase(str: string): string {\n return str.replace(/[-_](.)/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Converts a string to a URL-friendly slug (lowercase, dashes, alphanumeric).\n *\n * @param {string} str - The input string.\n * @returns {string} The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // remove non-word\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/-+/g, '-') // multiple dashes to one\n .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes\n}\n\n/**\n * Truncates a string to a specific length, appending '...' if truncated.\n *\n * @param {string} str - The input string.\n * @param {number} len - The maximum length.\n * @returns {string} The truncated string.\n */\nexport function truncate(str: string, len: number): string {\n return str.length > len ? str.slice(0, len) + '...' : str;\n}\n\n/**\n * Converts a string to PascalCase (e.g., \"foo-bar\" → \"FooBar\").\n *\n * @param {string} str - The input string.\n * @returns {string} The PascalCased string.\n */\nexport function toPascalCase(str: string): string {\n return capitalize(toCamelCase(str));\n}\n\n/**\n * Converts a string to snake_case (e.g., \"FooBar test\" → \"foo_bar_test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The snake_cased string.\n */\nexport function toSnakeCase(str: string): string {\n return str\n .trim()\n .replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase -> camel_Case\n .replace(/\\s+/g, '_') // spaces to underscore\n .replace(/-+/g, '_') // dashes to underscore\n .toLowerCase();\n}\n\n/**\n * Masks a string by replacing characters with a mask character.\n * Useful for hiding sensitive information like credit cards or passwords.\n *\n * @param {string} str - The string to mask.\n * @param {number} [visibleStart=0] - Number of characters to show at start.\n * @param {number} [visibleEnd=0] - Number of characters to show at end.\n * @param {string} [maskChar=\"*\"] - Character to use for masking.\n * @returns {string} The masked string.\n */\nexport function mask(str: string, visibleStart: number = 0, visibleEnd: number = 0, maskChar: string = '*'): string {\n if (!str || str.length === 0) return '';\n if (visibleStart >= str.length) return str;\n\n const start = str.slice(0, visibleStart);\n const end = visibleEnd > 0 ? str.slice(-visibleEnd) : '';\n const masked = maskChar.repeat(Math.max(0, str.length - visibleStart - visibleEnd));\n\n return start + masked + end;\n}\n\n/**\n * Removes all HTML tags from a string.\n *\n * @param {string} str - The HTML string to process.\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, '');\n}\n\n/**\n * Performs case-insensitive string comparison.\n *\n * @param {string} a - First string.\n * @param {string} b - Second string.\n * @returns {boolean} True if the strings are equal ignoring case.\n */\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Reverses a string.\n *\n * @param {string} str - The string to reverse.\n * @returns {string} The reversed string.\n */\nexport function reverse(str: string): string {\n return str.split('').reverse().join('');\n}\n\n/**\n * Counts occurrences of a substring within a string.\n *\n * @param {string} str - The source string.\n * @param {string} substring - The substring to count.\n * @param {boolean} [caseSensitive=true] - Whether to perform case-sensitive counting.\n * @returns {number} Number of occurrences.\n */\nexport function countOccurrences(str: string, substring: string, caseSensitive: boolean = true): number {\n if (!caseSensitive) {\n str = str.toLowerCase();\n substring = substring.toLowerCase();\n }\n\n return str.split(substring).length - 1;\n}\n"]}
1
+ {"version":3,"file":"string.utils.js","sourceRoot":"","sources":["../../../src/utils/string.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;GAK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,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,SAAiB,EAAE,gBAAyB,IAAI;IAC5F,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACxB,SAAS,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;IACtC,CAAC;IAED,OAAO,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AACzC,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Capitalizes the first character of a string.\n *\n * @param {string} str - The input string.\n * @returns {string} The string with the first character in uppercase.\n */\nexport function capitalize(str: string): string {\n return str.length === 0 ? '' : str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts a string to kebab-case (e.g., \"FooBar test\" → \"foo-bar-test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The kebab-cased string.\n */\nexport function toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/_+/g, '-') // underscores to dash\n .toLowerCase();\n}\n\n/**\n * Converts a kebab-case or snake_case string to camelCase.\n *\n * @param {string} str - The input string.\n * @returns {string} The camelCased string.\n */\nexport function toCamelCase(str: string): string {\n return str.replace(/[-_](.)/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Converts a string to a URL-friendly slug (lowercase, dashes, alphanumeric).\n *\n * @param {string} str - The input string.\n * @returns {string} The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // remove non-word\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/-+/g, '-') // multiple dashes to one\n .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes\n}\n\n/**\n * Truncates a string to a specific length, appending '...' if truncated.\n *\n * @param {string} str - The input string.\n * @param {number} len - The maximum length.\n * @returns {string} The truncated string.\n */\nexport function truncate(str: string, len: number): string {\n return str.length > len ? str.slice(0, len) + '...' : str;\n}\n\n/**\n * Converts a string to PascalCase (e.g., \"foo-bar\" → \"FooBar\").\n *\n * @param {string} str - The input string.\n * @returns {string} The PascalCased string.\n */\nexport function toPascalCase(str: string): string {\n return capitalize(toCamelCase(str));\n}\n\n/**\n * Converts a string to snake_case (e.g., \"FooBar test\" → \"foo_bar_test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The snake_cased string.\n */\nexport function toSnakeCase(str: string): string {\n return str\n .trim()\n .replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase -> camel_Case\n .replace(/\\s+/g, '_') // spaces to underscore\n .replace(/-+/g, '_') // dashes to underscore\n .toLowerCase();\n}\n\n/**\n * Masks a string by replacing characters with a mask character.\n * Useful for hiding sensitive information like credit cards or passwords.\n *\n * @param {string} str - The string to mask.\n * @param {number} [visibleStart=0] - Number of characters to show at start.\n * @param {number} [visibleEnd=0] - Number of characters to show at end.\n * @param {string} [maskChar=\"*\"] - Character to use for masking.\n * @returns {string} The masked string.\n */\nexport function mask(str: string, visibleStart: number = 0, visibleEnd: number = 0, maskChar: string = '*'): string {\n if (!str || str.length === 0) return '';\n if (visibleStart >= str.length) return str;\n\n const start = str.slice(0, visibleStart);\n const end = visibleEnd > 0 ? str.slice(-visibleEnd) : '';\n const masked = maskChar.repeat(Math.max(0, str.length - visibleStart - visibleEnd));\n\n return start + masked + end;\n}\n\n/**\n * Removes all HTML tags from a string.\n *\n * @param {string} str - The HTML string to process.\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, '');\n}\n\n/**\n * Performs case-insensitive string comparison.\n *\n * @param {string} a - First string.\n * @param {string} b - Second string.\n * @returns {boolean} True if the strings are equal ignoring case.\n */\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Reverses a string.\n *\n * @param {string} str - The string to reverse.\n * @returns {string} The reversed string.\n */\nexport function reverse(str: string): string {\n return str.split('').reverse().join('');\n}\n\n/**\n * Counts occurrences of a substring within a string.\n *\n * @param {string} str - The source string.\n * @param {string} substring - The substring to count.\n * @param {boolean} [caseSensitive=true] - Whether to perform case-sensitive counting.\n * @returns {number} Number of occurrences.\n */\nexport function countOccurrences(str: string, substring: string, caseSensitive: boolean = true): number {\n if (!caseSensitive) {\n str = str.toLowerCase();\n substring = substring.toLowerCase();\n }\n\n return str.split(substring).length - 1;\n}\n"]}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Check if a value is of a specific primitive type.
3
+ *
4
+ * @param value - Value to check
5
+ * @param type - Type to check against
6
+ * @returns Whether the value is of the specified type
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * isPrimitiveType('hello', 'string'); // true
11
+ * isPrimitiveType(42, 'number'); // true
12
+ * isPrimitiveType(true, 'boolean'); // true
13
+ * isPrimitiveType(null, 'null'); // true
14
+ * isPrimitiveType(undefined, 'undefined'); // true
15
+ * isPrimitiveType({}, 'object'); // true
16
+ * isPrimitiveType([], 'array'); // true
17
+ * ```
18
+ */
19
+ export declare function isPrimitiveType(value: unknown, type: 'string' | 'number' | 'boolean' | 'symbol' | 'bigint' | 'function' | 'object' | 'array' | 'null' | 'undefined'): boolean;
20
+ /**
21
+ * Get the primitive type of a value as a string.
22
+ *
23
+ * @param value - Value to get the type of
24
+ * @returns String representing the type
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * getTypeOf('hello'); // 'string'
29
+ * getTypeOf(42); // 'number'
30
+ * getTypeOf([]); // 'array'
31
+ * getTypeOf(null); // 'null'
32
+ * ```
33
+ */
34
+ export declare function getTypeOf(value: unknown): string;
35
+ /**
36
+ * Type guard for checking if a value is an array of a specific type.
37
+ *
38
+ * @param value - Value to check
39
+ * @param itemTypeGuard - Function that checks if items are of the expected type
40
+ * @returns True if the value is an array with items of the expected type
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
45
+ * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
46
+ * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
47
+ * ```
48
+ */
49
+ export declare function isArrayOf<T>(value: unknown, itemTypeGuard: (item: unknown) => item is T): value is T[];
50
+ /**
51
+ * Convert a value to a string.
52
+ *
53
+ * @param value - Value to convert
54
+ * @param defaultValue - Default value if conversion fails
55
+ * @returns String representation of the value
56
+ */
57
+ export declare function toStr(value: unknown, defaultValue?: string): string;
58
+ /**
59
+ * Convert a value to a number.
60
+ *
61
+ * @param value - Value to convert
62
+ * @param defaultValue - Default value if conversion fails
63
+ * @returns Numeric representation of the value
64
+ */
65
+ export declare function toNum(value: unknown, defaultValue?: number): number;
66
+ /**
67
+ * Convert a value to a boolean.
68
+ *
69
+ * @param value - Value to convert
70
+ * @param defaultValue - Default value if conversion fails
71
+ * @returns Boolean representation of the value
72
+ */
73
+ export declare function toBool(value: unknown, defaultValue?: boolean): boolean;
74
+ /**
75
+ * Ensure a value matches the expected type, or provide a default.
76
+ *
77
+ * @param value - Value to check
78
+ * @param expectedType - Expected primitive type
79
+ * @param defaultValue - Default value to use if type doesn't match
80
+ * @returns The value if it matches the type, otherwise the default
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * ensureType(42, 'number', 0); // 42
85
+ * ensureType('42', 'number', 0); // 0
86
+ * ensureType(undefined, 'string', 'default'); // 'default'
87
+ * ```
88
+ */
89
+ export declare function ensureType<T>(value: unknown, expectedType: string, defaultValue: T): T;
90
+ //# sourceMappingURL=type.utils.d.ts.map
@@ -0,0 +1,187 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
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
+ /**
25
+ * Check if a value is of a specific primitive type.
26
+ *
27
+ * @param value - Value to check
28
+ * @param type - Type to check against
29
+ * @returns Whether the value is of the specified type
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * isPrimitiveType('hello', 'string'); // true
34
+ * isPrimitiveType(42, 'number'); // true
35
+ * isPrimitiveType(true, 'boolean'); // true
36
+ * isPrimitiveType(null, 'null'); // true
37
+ * isPrimitiveType(undefined, 'undefined'); // true
38
+ * isPrimitiveType({}, 'object'); // true
39
+ * isPrimitiveType([], 'array'); // true
40
+ * ```
41
+ */
42
+ export function isPrimitiveType(value, type) {
43
+ if (type === 'array') {
44
+ return Array.isArray(value);
45
+ }
46
+ if (type === 'null') {
47
+ return value === null;
48
+ }
49
+ if (type === 'undefined') {
50
+ return value === undefined;
51
+ }
52
+ if (type === 'object') {
53
+ // Only plain objects, not arrays or null
54
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
55
+ }
56
+ return typeof value === type;
57
+ }
58
+ /**
59
+ * Get the primitive type of a value as a string.
60
+ *
61
+ * @param value - Value to get the type of
62
+ * @returns String representing the type
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * getTypeOf('hello'); // 'string'
67
+ * getTypeOf(42); // 'number'
68
+ * getTypeOf([]); // 'array'
69
+ * getTypeOf(null); // 'null'
70
+ * ```
71
+ */
72
+ export function getTypeOf(value) {
73
+ if (value === null)
74
+ return 'null';
75
+ if (value === undefined)
76
+ return 'undefined';
77
+ if (Array.isArray(value))
78
+ return 'array';
79
+ return typeof value;
80
+ }
81
+ /**
82
+ * Type guard for checking if a value is an array of a specific type.
83
+ *
84
+ * @param value - Value to check
85
+ * @param itemTypeGuard - Function that checks if items are of the expected type
86
+ * @returns True if the value is an array with items of the expected type
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
91
+ * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
92
+ * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
93
+ * ```
94
+ */
95
+ export function isArrayOf(value, itemTypeGuard) {
96
+ if (!Array.isArray(value))
97
+ return false;
98
+ return value.every(item => itemTypeGuard(item));
99
+ }
100
+ /**
101
+ * Convert a value to a string.
102
+ *
103
+ * @param value - Value to convert
104
+ * @param defaultValue - Default value if conversion fails
105
+ * @returns String representation of the value
106
+ */
107
+ export function toStr(value, defaultValue = '') {
108
+ if (value === null || value === undefined)
109
+ return defaultValue;
110
+ try {
111
+ if (typeof value === 'object') {
112
+ return JSON.stringify(value);
113
+ }
114
+ return String(value);
115
+ }
116
+ catch (_a) {
117
+ return defaultValue;
118
+ }
119
+ }
120
+ /**
121
+ * Convert a value to a number.
122
+ *
123
+ * @param value - Value to convert
124
+ * @param defaultValue - Default value if conversion fails
125
+ * @returns Numeric representation of the value
126
+ */
127
+ export function toNum(value, defaultValue = 0) {
128
+ if (value === null || value === undefined)
129
+ return defaultValue;
130
+ if (typeof value === 'number')
131
+ return value;
132
+ try {
133
+ const num = Number(value);
134
+ return isNaN(num) ? defaultValue : num;
135
+ }
136
+ catch (_a) {
137
+ return defaultValue;
138
+ }
139
+ }
140
+ /**
141
+ * Convert a value to a boolean.
142
+ *
143
+ * @param value - Value to convert
144
+ * @param defaultValue - Default value if conversion fails
145
+ * @returns Boolean representation of the value
146
+ */
147
+ export function toBool(value, defaultValue = false) {
148
+ if (value === null || value === undefined)
149
+ return defaultValue;
150
+ if (typeof value === 'boolean')
151
+ return value;
152
+ if (typeof value === 'string') {
153
+ const lowercased = value.toLowerCase();
154
+ if (lowercased === 'true' || lowercased === 'yes' || lowercased === 'y' || lowercased === '1') {
155
+ return true;
156
+ }
157
+ if (lowercased === 'false' || lowercased === 'no' || lowercased === 'n' || lowercased === '0') {
158
+ return false;
159
+ }
160
+ }
161
+ if (typeof value === 'number') {
162
+ return value !== 0;
163
+ }
164
+ return defaultValue;
165
+ }
166
+ /**
167
+ * Ensure a value matches the expected type, or provide a default.
168
+ *
169
+ * @param value - Value to check
170
+ * @param expectedType - Expected primitive type
171
+ * @param defaultValue - Default value to use if type doesn't match
172
+ * @returns The value if it matches the type, otherwise the default
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * ensureType(42, 'number', 0); // 42
177
+ * ensureType('42', 'number', 0); // 0
178
+ * ensureType(undefined, 'string', 'default'); // 'default'
179
+ * ```
180
+ */
181
+ export function ensureType(value, expectedType, defaultValue) {
182
+ if (getTypeOf(value) === expectedType) {
183
+ return value;
184
+ }
185
+ return defaultValue;
186
+ }
187
+ //# sourceMappingURL=type.utils.js.map