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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/README.md +25 -1
  2. package/build/esm/config.d.ts +0 -1
  3. package/build/esm/config.js +6 -7
  4. package/build/esm/index.d.ts +0 -1
  5. package/build/esm/index.js +0 -1
  6. package/build/esm/servers/server.builder.d.ts +0 -1
  7. package/build/esm/servers/server.builder.js +99 -147
  8. package/build/esm/servers/server.d.ts +0 -1
  9. package/build/esm/servers/server.js +591 -876
  10. package/build/esm/types/api-response.d.ts +0 -1
  11. package/build/esm/types/api-response.js +0 -1
  12. package/build/esm/types/index.d.ts +0 -1
  13. package/build/esm/types/index.js +0 -1
  14. package/build/esm/types/server.d.ts +0 -1
  15. package/build/esm/types/server.js +0 -1
  16. package/build/esm/utils/array.utils.d.ts +0 -1
  17. package/build/esm/utils/array.utils.js +48 -86
  18. package/build/esm/utils/async.utils.d.ts +0 -1
  19. package/build/esm/utils/async.utils.js +247 -524
  20. package/build/esm/utils/cache.utils.d.ts +0 -1
  21. package/build/esm/utils/cache.utils.js +96 -301
  22. package/build/esm/utils/context-store.utils.d.ts +0 -1
  23. package/build/esm/utils/context-store.utils.js +62 -79
  24. package/build/esm/utils/crypto.utils.d.ts +0 -1
  25. package/build/esm/utils/crypto.utils.js +78 -175
  26. package/build/esm/utils/date.utils.d.ts +0 -1
  27. package/build/esm/utils/date.utils.js +47 -53
  28. package/build/esm/utils/decorators.utils.d.ts +201 -5
  29. package/build/esm/utils/decorators.utils.js +632 -285
  30. package/build/esm/utils/dir.utils.d.ts +0 -1
  31. package/build/esm/utils/dir.utils.js +264 -786
  32. package/build/esm/utils/env.utils.d.ts +0 -1
  33. package/build/esm/utils/env.utils.js +180 -271
  34. package/build/esm/utils/exception.utils.d.ts +0 -1
  35. package/build/esm/utils/exception.utils.js +112 -289
  36. package/build/esm/utils/fs.utils.d.ts +0 -1
  37. package/build/esm/utils/fs.utils.js +169 -401
  38. package/build/esm/utils/http-status-codes.d.ts +0 -1
  39. package/build/esm/utils/http-status-codes.js +0 -1
  40. package/build/esm/utils/id.utils.d.ts +0 -1
  41. package/build/esm/utils/id.utils.js +5 -9
  42. package/build/esm/utils/logger.utils.d.ts +0 -1
  43. package/build/esm/utils/logger.utils.js +34 -71
  44. package/build/esm/utils/middleware.utils.d.ts +0 -1
  45. package/build/esm/utils/middleware.utils.js +65 -155
  46. package/build/esm/utils/obj.utils.d.ts +0 -1
  47. package/build/esm/utils/obj.utils.js +69 -176
  48. package/build/esm/utils/performance.utils.d.ts +0 -1
  49. package/build/esm/utils/performance.utils.js +92 -195
  50. package/build/esm/utils/request.utils.d.ts +0 -1
  51. package/build/esm/utils/request.utils.js +41 -74
  52. package/build/esm/utils/response.utils.d.ts +0 -1
  53. package/build/esm/utils/response.utils.js +84 -107
  54. package/build/esm/utils/stream.utils.d.ts +0 -1
  55. package/build/esm/utils/stream.utils.js +38 -113
  56. package/build/esm/utils/string.utils.d.ts +0 -1
  57. package/build/esm/utils/string.utils.js +6 -11
  58. package/build/esm/utils/type.utils.d.ts +0 -1
  59. package/build/esm/utils/type.utils.js +8 -12
  60. package/build/esm/utils/url.utils.d.ts +0 -1
  61. package/build/esm/utils/url.utils.js +49 -127
  62. package/build/esm/utils/validate.utils.d.ts +0 -1
  63. package/build/esm/utils/validate.utils.js +23 -40
  64. package/package.json +3 -33
  65. package/build/esm/config.js.map +0 -1
  66. package/build/esm/index.js.map +0 -1
  67. package/build/esm/servers/server.builder.js.map +0 -1
  68. package/build/esm/servers/server.js.map +0 -1
  69. package/build/esm/types/api-response.js.map +0 -1
  70. package/build/esm/types/index.js.map +0 -1
  71. package/build/esm/types/server.js.map +0 -1
  72. package/build/esm/utils/array.utils.js.map +0 -1
  73. package/build/esm/utils/async.utils.js.map +0 -1
  74. package/build/esm/utils/cache.utils.js.map +0 -1
  75. package/build/esm/utils/context-store.utils.js.map +0 -1
  76. package/build/esm/utils/crypto.utils.js.map +0 -1
  77. package/build/esm/utils/date.utils.js.map +0 -1
  78. package/build/esm/utils/decorators.utils.js.map +0 -1
  79. package/build/esm/utils/dir.utils.js.map +0 -1
  80. package/build/esm/utils/env.utils.js.map +0 -1
  81. package/build/esm/utils/exception.utils.js.map +0 -1
  82. package/build/esm/utils/fs.utils.js.map +0 -1
  83. package/build/esm/utils/http-status-codes.js.map +0 -1
  84. package/build/esm/utils/id.utils.js.map +0 -1
  85. package/build/esm/utils/logger.utils.js.map +0 -1
  86. package/build/esm/utils/middleware.utils.js.map +0 -1
  87. package/build/esm/utils/obj.utils.js.map +0 -1
  88. package/build/esm/utils/performance.utils.js.map +0 -1
  89. package/build/esm/utils/request.utils.js.map +0 -1
  90. package/build/esm/utils/response.utils.js.map +0 -1
  91. package/build/esm/utils/stream.utils.js.map +0 -1
  92. package/build/esm/utils/string.utils.js.map +0 -1
  93. package/build/esm/utils/type.utils.js.map +0 -1
  94. package/build/esm/utils/url.utils.js.map +0 -1
  95. package/build/esm/utils/validate.utils.js.map +0 -1
  96. package/build/esnext/config.d.ts +0 -122
  97. package/build/esnext/config.js +0 -133
  98. package/build/esnext/config.js.map +0 -1
  99. package/build/esnext/index.d.ts +0 -27
  100. package/build/esnext/index.js +0 -50
  101. package/build/esnext/index.js.map +0 -1
  102. package/build/esnext/servers/server.builder.d.ts +0 -508
  103. package/build/esnext/servers/server.builder.js +0 -657
  104. package/build/esnext/servers/server.builder.js.map +0 -1
  105. package/build/esnext/servers/server.d.ts +0 -256
  106. package/build/esnext/servers/server.js +0 -955
  107. package/build/esnext/servers/server.js.map +0 -1
  108. package/build/esnext/types/api-response.d.ts +0 -152
  109. package/build/esnext/types/api-response.js +0 -34
  110. package/build/esnext/types/api-response.js.map +0 -1
  111. package/build/esnext/types/index.d.ts +0 -125
  112. package/build/esnext/types/index.js +0 -25
  113. package/build/esnext/types/index.js.map +0 -1
  114. package/build/esnext/types/server.d.ts +0 -268
  115. package/build/esnext/types/server.js +0 -25
  116. package/build/esnext/types/server.js.map +0 -1
  117. package/build/esnext/utils/array.utils.d.ts +0 -168
  118. package/build/esnext/utils/array.utils.js +0 -345
  119. package/build/esnext/utils/array.utils.js.map +0 -1
  120. package/build/esnext/utils/async.utils.d.ts +0 -265
  121. package/build/esnext/utils/async.utils.js +0 -620
  122. package/build/esnext/utils/async.utils.js.map +0 -1
  123. package/build/esnext/utils/cache.utils.d.ts +0 -153
  124. package/build/esnext/utils/cache.utils.js +0 -293
  125. package/build/esnext/utils/cache.utils.js.map +0 -1
  126. package/build/esnext/utils/context-store.utils.d.ts +0 -189
  127. package/build/esnext/utils/context-store.utils.js +0 -289
  128. package/build/esnext/utils/context-store.utils.js.map +0 -1
  129. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  130. package/build/esnext/utils/crypto.utils.js +0 -276
  131. package/build/esnext/utils/crypto.utils.js.map +0 -1
  132. package/build/esnext/utils/date.utils.d.ts +0 -159
  133. package/build/esnext/utils/date.utils.js +0 -384
  134. package/build/esnext/utils/date.utils.js.map +0 -1
  135. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  136. package/build/esnext/utils/decorators.utils.js +0 -504
  137. package/build/esnext/utils/decorators.utils.js.map +0 -1
  138. package/build/esnext/utils/dir.utils.d.ts +0 -196
  139. package/build/esnext/utils/dir.utils.js +0 -477
  140. package/build/esnext/utils/dir.utils.js.map +0 -1
  141. package/build/esnext/utils/env.utils.d.ts +0 -377
  142. package/build/esnext/utils/env.utils.js +0 -785
  143. package/build/esnext/utils/env.utils.js.map +0 -1
  144. package/build/esnext/utils/exception.utils.d.ts +0 -230
  145. package/build/esnext/utils/exception.utils.js +0 -381
  146. package/build/esnext/utils/exception.utils.js.map +0 -1
  147. package/build/esnext/utils/fs.utils.d.ts +0 -164
  148. package/build/esnext/utils/fs.utils.js +0 -349
  149. package/build/esnext/utils/fs.utils.js.map +0 -1
  150. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  151. package/build/esnext/utils/http-status-codes.js +0 -295
  152. package/build/esnext/utils/http-status-codes.js.map +0 -1
  153. package/build/esnext/utils/id.utils.d.ts +0 -36
  154. package/build/esnext/utils/id.utils.js +0 -84
  155. package/build/esnext/utils/id.utils.js.map +0 -1
  156. package/build/esnext/utils/logger.utils.d.ts +0 -160
  157. package/build/esnext/utils/logger.utils.js +0 -300
  158. package/build/esnext/utils/logger.utils.js.map +0 -1
  159. package/build/esnext/utils/middleware.utils.d.ts +0 -100
  160. package/build/esnext/utils/middleware.utils.js +0 -236
  161. package/build/esnext/utils/middleware.utils.js.map +0 -1
  162. package/build/esnext/utils/obj.utils.d.ts +0 -124
  163. package/build/esnext/utils/obj.utils.js +0 -413
  164. package/build/esnext/utils/obj.utils.js.map +0 -1
  165. package/build/esnext/utils/performance.utils.d.ts +0 -136
  166. package/build/esnext/utils/performance.utils.js +0 -271
  167. package/build/esnext/utils/performance.utils.js.map +0 -1
  168. package/build/esnext/utils/request.utils.d.ts +0 -86
  169. package/build/esnext/utils/request.utils.js +0 -186
  170. package/build/esnext/utils/request.utils.js.map +0 -1
  171. package/build/esnext/utils/response.utils.d.ts +0 -163
  172. package/build/esnext/utils/response.utils.js +0 -247
  173. package/build/esnext/utils/response.utils.js.map +0 -1
  174. package/build/esnext/utils/stream.utils.d.ts +0 -88
  175. package/build/esnext/utils/stream.utils.js +0 -210
  176. package/build/esnext/utils/stream.utils.js.map +0 -1
  177. package/build/esnext/utils/string.utils.d.ts +0 -93
  178. package/build/esnext/utils/string.utils.js +0 -165
  179. package/build/esnext/utils/string.utils.js.map +0 -1
  180. package/build/esnext/utils/type.utils.d.ts +0 -90
  181. package/build/esnext/utils/type.utils.js +0 -187
  182. package/build/esnext/utils/type.utils.js.map +0 -1
  183. package/build/esnext/utils/url.utils.d.ts +0 -141
  184. package/build/esnext/utils/url.utils.js +0 -304
  185. package/build/esnext/utils/url.utils.js.map +0 -1
  186. package/build/esnext/utils/validate.utils.d.ts +0 -177
  187. package/build/esnext/utils/validate.utils.js +0 -320
  188. package/build/esnext/utils/validate.utils.js.map +0 -1
  189. package/build/src/config.d.ts +0 -122
  190. package/build/src/config.js +0 -138
  191. package/build/src/config.js.map +0 -1
  192. package/build/src/index.d.ts +0 -27
  193. package/build/src/index.js +0 -69
  194. package/build/src/index.js.map +0 -1
  195. package/build/src/servers/server.builder.d.ts +0 -508
  196. package/build/src/servers/server.builder.js +0 -661
  197. package/build/src/servers/server.builder.js.map +0 -1
  198. package/build/src/servers/server.d.ts +0 -256
  199. package/build/src/servers/server.js +0 -962
  200. package/build/src/servers/server.js.map +0 -1
  201. package/build/src/types/api-response.d.ts +0 -152
  202. package/build/src/types/api-response.js +0 -37
  203. package/build/src/types/api-response.js.map +0 -1
  204. package/build/src/types/index.d.ts +0 -125
  205. package/build/src/types/index.js +0 -26
  206. package/build/src/types/index.js.map +0 -1
  207. package/build/src/types/server.d.ts +0 -268
  208. package/build/src/types/server.js +0 -26
  209. package/build/src/types/server.js.map +0 -1
  210. package/build/src/utils/array.utils.d.ts +0 -168
  211. package/build/src/utils/array.utils.js +0 -364
  212. package/build/src/utils/array.utils.js.map +0 -1
  213. package/build/src/utils/async.utils.d.ts +0 -265
  214. package/build/src/utils/async.utils.js +0 -641
  215. package/build/src/utils/async.utils.js.map +0 -1
  216. package/build/src/utils/cache.utils.d.ts +0 -153
  217. package/build/src/utils/cache.utils.js +0 -297
  218. package/build/src/utils/cache.utils.js.map +0 -1
  219. package/build/src/utils/context-store.utils.d.ts +0 -189
  220. package/build/src/utils/context-store.utils.js +0 -296
  221. package/build/src/utils/context-store.utils.js.map +0 -1
  222. package/build/src/utils/crypto.utils.d.ts +0 -160
  223. package/build/src/utils/crypto.utils.js +0 -293
  224. package/build/src/utils/crypto.utils.js.map +0 -1
  225. package/build/src/utils/date.utils.d.ts +0 -159
  226. package/build/src/utils/date.utils.js +0 -396
  227. package/build/src/utils/date.utils.js.map +0 -1
  228. package/build/src/utils/decorators.utils.d.ts +0 -315
  229. package/build/src/utils/decorators.utils.js +0 -516
  230. package/build/src/utils/decorators.utils.js.map +0 -1
  231. package/build/src/utils/dir.utils.d.ts +0 -196
  232. package/build/src/utils/dir.utils.js +0 -501
  233. package/build/src/utils/dir.utils.js.map +0 -1
  234. package/build/src/utils/env.utils.d.ts +0 -377
  235. package/build/src/utils/env.utils.js +0 -789
  236. package/build/src/utils/env.utils.js.map +0 -1
  237. package/build/src/utils/exception.utils.d.ts +0 -230
  238. package/build/src/utils/exception.utils.js +0 -407
  239. package/build/src/utils/exception.utils.js.map +0 -1
  240. package/build/src/utils/fs.utils.d.ts +0 -164
  241. package/build/src/utils/fs.utils.js +0 -372
  242. package/build/src/utils/fs.utils.js.map +0 -1
  243. package/build/src/utils/http-status-codes.d.ts +0 -266
  244. package/build/src/utils/http-status-codes.js +0 -298
  245. package/build/src/utils/http-status-codes.js.map +0 -1
  246. package/build/src/utils/id.utils.d.ts +0 -36
  247. package/build/src/utils/id.utils.js +0 -91
  248. package/build/src/utils/id.utils.js.map +0 -1
  249. package/build/src/utils/logger.utils.d.ts +0 -160
  250. package/build/src/utils/logger.utils.js +0 -346
  251. package/build/src/utils/logger.utils.js.map +0 -1
  252. package/build/src/utils/middleware.utils.d.ts +0 -100
  253. package/build/src/utils/middleware.utils.js +0 -244
  254. package/build/src/utils/middleware.utils.js.map +0 -1
  255. package/build/src/utils/obj.utils.d.ts +0 -124
  256. package/build/src/utils/obj.utils.js +0 -429
  257. package/build/src/utils/obj.utils.js.map +0 -1
  258. package/build/src/utils/performance.utils.d.ts +0 -136
  259. package/build/src/utils/performance.utils.js +0 -278
  260. package/build/src/utils/performance.utils.js.map +0 -1
  261. package/build/src/utils/request.utils.d.ts +0 -86
  262. package/build/src/utils/request.utils.js +0 -195
  263. package/build/src/utils/request.utils.js.map +0 -1
  264. package/build/src/utils/response.utils.d.ts +0 -163
  265. package/build/src/utils/response.utils.js +0 -260
  266. package/build/src/utils/response.utils.js.map +0 -1
  267. package/build/src/utils/stream.utils.d.ts +0 -88
  268. package/build/src/utils/stream.utils.js +0 -218
  269. package/build/src/utils/stream.utils.js.map +0 -1
  270. package/build/src/utils/string.utils.d.ts +0 -93
  271. package/build/src/utils/string.utils.js +0 -179
  272. package/build/src/utils/string.utils.js.map +0 -1
  273. package/build/src/utils/type.utils.d.ts +0 -90
  274. package/build/src/utils/type.utils.js +0 -196
  275. package/build/src/utils/type.utils.js.map +0 -1
  276. package/build/src/utils/url.utils.d.ts +0 -141
  277. package/build/src/utils/url.utils.js +0 -317
  278. package/build/src/utils/url.utils.js.map +0 -1
  279. package/build/src/utils/validate.utils.d.ts +0 -177
  280. package/build/src/utils/validate.utils.js +0 -345
  281. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,163 +0,0 @@
1
- import { Request } from 'express';
2
- import { ApiErrorResponse, ApiResponse } from '../types/api-response';
3
- /**
4
- * Standard HTTP response wrapper for successful responses.
5
- * Implements the `ApiResponse<T>` interface and sets default values.
6
- *
7
- * @typeParam T - The shape of the data returned in the response.
8
- */
9
- export declare class SuccessResponse<T> implements ApiResponse<T> {
10
- /** Message describing the result of the operation. */
11
- message: string;
12
- /** Whether the response is an error. Always false in success responses. */
13
- error: boolean;
14
- /** The payload returned from the API. */
15
- data: T | null;
16
- /** Timestamp when the response was generated, in ISO format. */
17
- timestamp: string;
18
- /** Unique identifier for this response, useful for request tracing. */
19
- requestId: string;
20
- /**
21
- * Constructs a new success response.
22
- *
23
- * @param {string} message - Optional message to override the default.
24
- * @param {T} [data] - Optional data payload.
25
- */
26
- constructor(message: string, data?: T);
27
- }
28
- /**
29
- * Wrapper for error responses that extends the native `Error` object.
30
- * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
31
- */
32
- export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {
33
- /** HTTP status code associated with the error (e.g., 404, 500). */
34
- status: number;
35
- /** Indicates that this is an error. Always true. */
36
- error: boolean;
37
- /** Timestamp when the error occurred, in ISO format. */
38
- timestamp: string;
39
- /** Unique identifier for this error instance. */
40
- requestId: string;
41
- /**
42
- * Constructs a new error response.
43
- *
44
- * @param {string} message - The error message to display or log.
45
- * @param {number} [status=500] - Optional HTTP status code (defaults to 500).
46
- */
47
- constructor(message: string, status?: number);
48
- }
49
- /**
50
- * Response with paginated data extending the standard success response.
51
- * Useful for APIs that return large collections of data.
52
- *
53
- * @typeParam T - The shape of each item in the paginated collection.
54
- */
55
- export declare class PaginatedResponse<T> extends SuccessResponse<T[]> {
56
- /** Total number of items across all pages */
57
- total: number;
58
- /** Current page number (1-based) */
59
- page: number;
60
- /** Number of items per page */
61
- pageSize: number;
62
- /** Total number of pages */
63
- totalPages: number;
64
- /** Whether there's a next page available */
65
- hasNext: boolean;
66
- /** Whether there's a previous page available */
67
- hasPrevious: boolean;
68
- /**
69
- * Constructs a new paginated response.
70
- *
71
- * @param {T[]} items - The current page of items.
72
- * @param {Object} pagination - Pagination information.
73
- * @param {number} pagination.total - Total number of items across all pages.
74
- * @param {number} pagination.page - Current page number (1-based).
75
- * @param {number} pagination.pageSize - Number of items per page.
76
- * @param {string} [message="Success"] - Optional custom message.
77
- */
78
- constructor(items: T[], pagination: {
79
- total: number;
80
- page: number;
81
- pageSize: number;
82
- }, message?: string);
83
- }
84
- /**
85
- * Specialized response for operations that don't return data (HTTP 204).
86
- */
87
- export declare class NoContentResponse extends SuccessResponse<null> {
88
- /**
89
- * Constructs a new no-content response.
90
- *
91
- * @param {string} [message="Operation completed successfully"] - Optional custom message.
92
- */
93
- constructor(message?: string);
94
- }
95
- /**
96
- * Specialized response for redirects.
97
- */
98
- export declare class RedirectResponse {
99
- /** The URL to redirect to */
100
- redirectUrl: string;
101
- /** HTTP status code for the redirect (301, 302, 303, 307, 308) */
102
- statusCode: number;
103
- /** Whether the response is a redirect */
104
- isRedirect: boolean;
105
- /** Unique identifier for this response */
106
- requestId: string;
107
- /**
108
- * Constructs a new redirect response.
109
- *
110
- * @param {string} url - The URL to redirect to.
111
- * @param {number} [statusCode=302] - HTTP status code for the redirect.
112
- */
113
- constructor(url: string, statusCode?: number);
114
- }
115
- /**
116
- * Creates a standard success response.
117
- *
118
- * @typeParam T - The shape of the data returned in the response.
119
- * @param {T} data - The data to include in the response.
120
- * @param {string} [message="Success"] - Optional custom message.
121
- * @returns {SuccessResponse<T>} A properly formatted success response.
122
- */
123
- export declare function createSuccessResponse<T>(data: T, message?: string): SuccessResponse<T>;
124
- /**
125
- * Creates a standard error response.
126
- *
127
- * @param {string} message - The error message.
128
- * @param {number} [statusCode=500] - HTTP status code for the error.
129
- * @returns {ErrorResponse} A properly formatted error response.
130
- */
131
- export declare function createErrorResponse(message: string, statusCode?: number): ErrorResponse;
132
- /**
133
- * Creates a final error response with request information.
134
- *
135
- * @param req - The original request object.
136
- * @param status - The HTTP status code.
137
- * @param message - The error message.
138
- * @param error - The original error object (optional).
139
- * @param options - Additional options for the response (optional).
140
- * @returns A properly formatted final error response.
141
- */
142
- export declare function createFinalErrorResponse(req: Request, status: number, message: string, error?: any, options?: {
143
- includeDetails?: boolean;
144
- }): ApiErrorResponse;
145
- /**
146
- * Creates a paginated response from array data.
147
- *
148
- * @typeParam T - The shape of each item in the collection.
149
- * @param {T[]} allItems - The complete array of items to paginate.
150
- * @param {number} page - The requested page (1-based).
151
- * @param {number} pageSize - The number of items per page.
152
- * @param {string} [message="Success"] - Optional custom message.
153
- * @returns {PaginatedResponse<T>} A properly formatted paginated response.
154
- */
155
- export declare function createPaginatedResponse<T>(allItems: T[], page: number, pageSize: number, message?: string): PaginatedResponse<T>;
156
- /**
157
- * Adapter to convert API responses to Express.js response format.
158
- *
159
- * @param {any} res - Express response object.
160
- * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.
161
- */
162
- export declare function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void;
163
- //# sourceMappingURL=response.utils.d.ts.map
@@ -1,260 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.RedirectResponse = exports.NoContentResponse = exports.PaginatedResponse = exports.ErrorResponse = exports.SuccessResponse = void 0;
27
- exports.createSuccessResponse = createSuccessResponse;
28
- exports.createErrorResponse = createErrorResponse;
29
- exports.createFinalErrorResponse = createFinalErrorResponse;
30
- exports.createPaginatedResponse = createPaginatedResponse;
31
- exports.sendResponse = sendResponse;
32
- const context_store_utils_1 = require("./context-store.utils");
33
- const env_utils_1 = require("./env.utils");
34
- const id_utils_1 = require("./id.utils");
35
- /**
36
- * Standard HTTP response wrapper for successful responses.
37
- * Implements the `ApiResponse<T>` interface and sets default values.
38
- *
39
- * @typeParam T - The shape of the data returned in the response.
40
- */
41
- class SuccessResponse {
42
- /**
43
- * Constructs a new success response.
44
- *
45
- * @param {string} message - Optional message to override the default.
46
- * @param {T} [data] - Optional data payload.
47
- */
48
- constructor(message, data) {
49
- var _a;
50
- /** Message describing the result of the operation. */
51
- this.message = 'Success';
52
- /** Whether the response is an error. Always false in success responses. */
53
- this.error = false;
54
- /** The payload returned from the API. */
55
- this.data = null;
56
- /** Timestamp when the response was generated, in ISO format. */
57
- this.timestamp = new Date().toISOString();
58
- /** Unique identifier for this response, useful for request tracing. */
59
- this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
60
- if (message)
61
- this.message = message;
62
- this.data = data !== null && data !== void 0 ? data : null;
63
- }
64
- }
65
- exports.SuccessResponse = SuccessResponse;
66
- /**
67
- * Wrapper for error responses that extends the native `Error` object.
68
- * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
69
- */
70
- class ErrorResponse extends Error {
71
- /**
72
- * Constructs a new error response.
73
- *
74
- * @param {string} message - The error message to display or log.
75
- * @param {number} [status=500] - Optional HTTP status code (defaults to 500).
76
- */
77
- constructor(message, status = 500) {
78
- var _a;
79
- super(message);
80
- /** Indicates that this is an error. Always true. */
81
- this.error = true;
82
- /** Timestamp when the error occurred, in ISO format. */
83
- this.timestamp = new Date().toISOString();
84
- /** Unique identifier for this error instance. */
85
- this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
86
- this.status = status;
87
- this.name = this.constructor.name;
88
- Error.captureStackTrace(this, this.constructor);
89
- }
90
- }
91
- exports.ErrorResponse = ErrorResponse;
92
- /**
93
- * Response with paginated data extending the standard success response.
94
- * Useful for APIs that return large collections of data.
95
- *
96
- * @typeParam T - The shape of each item in the paginated collection.
97
- */
98
- class PaginatedResponse extends SuccessResponse {
99
- /**
100
- * Constructs a new paginated response.
101
- *
102
- * @param {T[]} items - The current page of items.
103
- * @param {Object} pagination - Pagination information.
104
- * @param {number} pagination.total - Total number of items across all pages.
105
- * @param {number} pagination.page - Current page number (1-based).
106
- * @param {number} pagination.pageSize - Number of items per page.
107
- * @param {string} [message="Success"] - Optional custom message.
108
- */
109
- constructor(items, pagination, message = 'Success') {
110
- super(message, items);
111
- this.total = pagination.total;
112
- this.page = pagination.page;
113
- this.pageSize = pagination.pageSize;
114
- this.totalPages = Math.ceil(this.total / this.pageSize);
115
- this.hasNext = this.page < this.totalPages;
116
- this.hasPrevious = this.page > 1;
117
- }
118
- }
119
- exports.PaginatedResponse = PaginatedResponse;
120
- /**
121
- * Specialized response for operations that don't return data (HTTP 204).
122
- */
123
- class NoContentResponse extends SuccessResponse {
124
- /**
125
- * Constructs a new no-content response.
126
- *
127
- * @param {string} [message="Operation completed successfully"] - Optional custom message.
128
- */
129
- constructor(message = 'Operation completed successfully') {
130
- super(message, null);
131
- }
132
- }
133
- exports.NoContentResponse = NoContentResponse;
134
- /**
135
- * Specialized response for redirects.
136
- */
137
- class RedirectResponse {
138
- /**
139
- * Constructs a new redirect response.
140
- *
141
- * @param {string} url - The URL to redirect to.
142
- * @param {number} [statusCode=302] - HTTP status code for the redirect.
143
- */
144
- constructor(url, statusCode = 302) {
145
- var _a;
146
- /** Whether the response is a redirect */
147
- this.isRedirect = true;
148
- /** Unique identifier for this response */
149
- this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
150
- this.redirectUrl = url;
151
- this.statusCode = statusCode;
152
- }
153
- }
154
- exports.RedirectResponse = RedirectResponse;
155
- /**
156
- * Creates a standard success response.
157
- *
158
- * @typeParam T - The shape of the data returned in the response.
159
- * @param {T} data - The data to include in the response.
160
- * @param {string} [message="Success"] - Optional custom message.
161
- * @returns {SuccessResponse<T>} A properly formatted success response.
162
- */
163
- function createSuccessResponse(data, message = 'Success') {
164
- return new SuccessResponse(message, data);
165
- }
166
- /**
167
- * Creates a standard error response.
168
- *
169
- * @param {string} message - The error message.
170
- * @param {number} [statusCode=500] - HTTP status code for the error.
171
- * @returns {ErrorResponse} A properly formatted error response.
172
- */
173
- function createErrorResponse(message, statusCode = 500) {
174
- return new ErrorResponse(message, statusCode);
175
- }
176
- /**
177
- * Creates a final error response with request information.
178
- *
179
- * @param req - The original request object.
180
- * @param status - The HTTP status code.
181
- * @param message - The error message.
182
- * @param error - The original error object (optional).
183
- * @param options - Additional options for the response (optional).
184
- * @returns A properly formatted final error response.
185
- */
186
- function createFinalErrorResponse(req, status, message, error, options) {
187
- const isDev = env_utils_1.Env.isDev();
188
- const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
189
- const response = {
190
- error: true,
191
- message,
192
- timestamp: new Date().toISOString(),
193
- requestId: (error === null || error === void 0 ? void 0 : error.requestId) || (req === null || req === void 0 ? void 0 : req.id) || (0, id_utils_1.uuid)(),
194
- status,
195
- path: req.originalUrl || req.url
196
- };
197
- // Include stack trace in development mode if requested
198
- if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
199
- response.stack = error.stack.split('\n').map((line) => line.trim());
200
- }
201
- return response;
202
- }
203
- /**
204
- * Creates a paginated response from array data.
205
- *
206
- * @typeParam T - The shape of each item in the collection.
207
- * @param {T[]} allItems - The complete array of items to paginate.
208
- * @param {number} page - The requested page (1-based).
209
- * @param {number} pageSize - The number of items per page.
210
- * @param {string} [message="Success"] - Optional custom message.
211
- * @returns {PaginatedResponse<T>} A properly formatted paginated response.
212
- */
213
- function createPaginatedResponse(allItems, page, pageSize, message = 'Success') {
214
- // Ensure valid pagination parameters
215
- const validPage = Math.max(1, page);
216
- const validPageSize = Math.max(1, pageSize);
217
- // Calculate slice indices
218
- const startIndex = (validPage - 1) * validPageSize;
219
- const endIndex = startIndex + validPageSize;
220
- // Get current page items
221
- const pageItems = allItems.slice(startIndex, endIndex);
222
- return new PaginatedResponse(pageItems, {
223
- total: allItems.length,
224
- page: validPage,
225
- pageSize: validPageSize
226
- }, message);
227
- }
228
- /**
229
- * Adapter to convert API responses to Express.js response format.
230
- *
231
- * @param {any} res - Express response object.
232
- * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.
233
- */
234
- function sendResponse(res, apiResponse) {
235
- // Handle redirects
236
- if ('redirectUrl' in apiResponse) {
237
- res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);
238
- return;
239
- }
240
- // Handle errors
241
- if ('error' in apiResponse && apiResponse.error) {
242
- const errorResponse = apiResponse;
243
- res.status(errorResponse.status).json({
244
- error: true,
245
- message: errorResponse.message,
246
- timestamp: errorResponse.timestamp,
247
- requestId: errorResponse.requestId
248
- });
249
- return;
250
- }
251
- // Handle success responses
252
- const successResponse = apiResponse;
253
- // No content (204) shouldn't return a body
254
- if (successResponse instanceof NoContentResponse) {
255
- res.status(204).end();
256
- return;
257
- }
258
- res.status(200).json(successResponse);
259
- }
260
- //# sourceMappingURL=response.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;AA2KH,sDAEC;AASD,kDAEC;AAYD,4DAyBC;AAYD,0DA0BC;AAQD,oCA6BC;AApSD,+DAAqD;AACrD,2CAAkC;AAClC,yCAAkC;AAElC;;;;;GAKG;AACH,MAAa,eAAe;IAgB1B;;;;;OAKG;IACH,YAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAAI,GAAa,IAAI,CAAC;QAEtB,gEAAgE;QAChE,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,uEAAuE;QACvE,cAAS,GAAW,MAAA,IAAA,kCAAY,GAAE,mCAAI,IAAA,eAAI,GAAE,CAAC;QAS3C,IAAI,OAAO;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,aAAJ,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G,mBAAmB;IACnB,IAAI,aAAa,IAAI,WAAW,EAAE,CAAC;QACjC,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC;QAC9D,OAAO;IACT,CAAC;IAED,gBAAgB;IAChB,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,aAAa,GAAG,WAA4B,CAAC;QACnD,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpC,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,SAAS;YAClC,SAAS,EAAE,aAAa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\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 { Request } from 'express';\nimport { ApiErrorResponse, ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\nimport { Env } from './env.utils';\nimport { uuid } from './id.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a final error response with request information.\n *\n * @param req - The original request object.\n * @param status - The HTTP status code.\n * @param message - The error message.\n * @param error - The original error object (optional).\n * @param options - Additional options for the response (optional).\n * @returns A properly formatted final error response.\n */\nexport function createFinalErrorResponse(\n req: Request,\n status: number,\n message: string,\n error?: any,\n options?: { includeDetails?: boolean }\n) {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: ApiErrorResponse = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
@@ -1,88 +0,0 @@
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