@catbee/utils 2.0.0-next.0 → 2.0.0-next.1

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 (97) hide show
  1. package/README.md +52 -16
  2. package/array/index.cjs +180 -71
  3. package/array/index.d.ts +293 -1
  4. package/array/index.mjs +171 -72
  5. package/async/index.cjs +92 -36
  6. package/async/index.d.ts +275 -1
  7. package/async/index.mjs +92 -36
  8. package/cache/index.cjs +1 -1
  9. package/cache/index.d.ts +155 -1
  10. package/cache/index.mjs +2 -2
  11. package/config/index.cjs +78 -64
  12. package/config/index.d.ts +64 -2
  13. package/config/index.mjs +76 -64
  14. package/context-store/index.d.ts +192 -1
  15. package/crypto/index.d.ts +163 -1
  16. package/date/index.cjs +46 -1
  17. package/date/index.d.ts +190 -1
  18. package/date/index.mjs +45 -2
  19. package/decorators/index.cjs +1156 -18
  20. package/decorators/index.d.ts +684 -1
  21. package/decorators/index.mjs +1156 -18
  22. package/dir/index.cjs +4 -3
  23. package/dir/index.d.ts +195 -1
  24. package/dir/index.mjs +4 -3
  25. package/env/index.cjs +10 -26
  26. package/env/index.d.ts +379 -1
  27. package/env/index.mjs +10 -26
  28. package/exception/index.d.ts +232 -1
  29. package/fs/index.cjs +70 -36
  30. package/fs/index.d.ts +205 -1
  31. package/fs/index.mjs +64 -34
  32. package/http-status-codes/index.d.ts +267 -1
  33. package/id/index.d.ts +37 -1
  34. package/index.cjs +3 -3
  35. package/index.d.ts +1 -1
  36. package/index.mjs +1 -1
  37. package/logger/index.cjs +11 -11
  38. package/logger/index.d.ts +189 -1
  39. package/logger/index.mjs +12 -12
  40. package/middleware/index.d.ts +103 -1
  41. package/obj/index.cjs +150 -162
  42. package/obj/index.d.ts +136 -1
  43. package/obj/index.mjs +150 -162
  44. package/package.json +11 -11
  45. package/performance/index.cjs +2 -2
  46. package/performance/index.d.ts +138 -1
  47. package/performance/index.mjs +2 -2
  48. package/request/index.cjs +1 -1
  49. package/request/index.d.ts +241 -2
  50. package/request/index.mjs +1 -1
  51. package/response/index.d.ts +318 -2
  52. package/server/index.cjs +27 -23
  53. package/server/index.d.ts +785 -4
  54. package/server/index.mjs +28 -23
  55. package/stream/index.d.ts +90 -1
  56. package/string/index.d.ts +102 -1
  57. package/type/index.cjs +1 -1
  58. package/type/index.d.ts +107 -1
  59. package/type/index.mjs +1 -1
  60. package/types/index.d.ts +774 -4
  61. package/url/index.cjs +2 -4
  62. package/url/index.d.ts +142 -1
  63. package/url/index.mjs +2 -4
  64. package/{validate → validation}/index.cjs +89 -42
  65. package/{validate/validate.utils.d.ts → validation/index.d.ts} +32 -23
  66. package/{validate → validation}/index.mjs +85 -42
  67. package/array/array.utils.d.ts +0 -191
  68. package/async/async.utils.d.ts +0 -296
  69. package/cache/cache.utils.d.ts +0 -176
  70. package/config/config.d.ts +0 -57
  71. package/context-store/context-store.utils.d.ts +0 -212
  72. package/crypto/crypto.utils.d.ts +0 -183
  73. package/date/date.utils.d.ts +0 -190
  74. package/decorators/decorators.utils.d.ts +0 -705
  75. package/dir/dir.utils.d.ts +0 -216
  76. package/env/env.utils.d.ts +0 -400
  77. package/exception/exception.utils.d.ts +0 -253
  78. package/fs/fs.utils.d.ts +0 -196
  79. package/http-status-codes/http-status-codes.d.ts +0 -289
  80. package/id/id.utils.d.ts +0 -59
  81. package/logger/logger.utils.d.ts +0 -210
  82. package/middleware/middleware.utils.d.ts +0 -123
  83. package/obj/obj.utils.d.ts +0 -156
  84. package/performance/performance.utils.d.ts +0 -159
  85. package/request/request.utils.d.ts +0 -109
  86. package/response/response.utils.d.ts +0 -186
  87. package/server/server.builder.d.ts +0 -531
  88. package/server/server.d.ts +0 -303
  89. package/stream/stream.utils.d.ts +0 -111
  90. package/string/string.utils.d.ts +0 -124
  91. package/type/type.utils.d.ts +0 -129
  92. package/types/api-response.d.ts +0 -175
  93. package/types/common.d.ts +0 -148
  94. package/types/config.d.ts +0 -88
  95. package/types/server.d.ts +0 -291
  96. package/url/url.utils.d.ts +0 -164
  97. package/validate/index.d.ts +0 -25
@@ -22,4 +22,235 @@
22
22
  * SOFTWARE.
23
23
  */
24
24
 
25
- export * from './exception.utils';
25
+ import { ErrorResponse } from '@catbee/utils/response';
26
+
27
+ /**
28
+ * Generic HTTP error class used for custom exceptions with any status code.
29
+ * Inherit this when you need to throw errors dynamically at runtime.
30
+ */
31
+ declare class HttpError extends ErrorResponse {
32
+ /**
33
+ * Creates a new HTTP error instance.
34
+ * @param status - A valid HTTP status code (e.g., 400, 500).
35
+ * @param message - The error message to return to the client.
36
+ */
37
+ constructor(status: number, message: string);
38
+ }
39
+ /**
40
+ * Represents a 500 Internal Server Error.
41
+ * Use this for unexpected backend errors that are not caused by the client.
42
+ */
43
+ declare class InternalServerErrorException extends ErrorResponse {
44
+ /**
45
+ * @param message - Optional custom message. Defaults to "Internal server error".
46
+ */
47
+ constructor(message?: string);
48
+ }
49
+ /**
50
+ * Represents a 401 Unauthorized Error.
51
+ * Indicates that authentication is required and has failed or not been provided.
52
+ */
53
+ declare class UnauthorizedException extends ErrorResponse {
54
+ /**
55
+ * @param message - Optional custom message. Defaults to "Unauthorized".
56
+ */
57
+ constructor(message?: string);
58
+ }
59
+ /**
60
+ * Represents a 400 Bad Request Error.
61
+ * Indicates that the client has sent invalid data (e.g., malformed request body).
62
+ */
63
+ declare class BadRequestException extends ErrorResponse {
64
+ /**
65
+ * @param message - Optional custom message. Defaults to "Bad request".
66
+ */
67
+ constructor(message?: string);
68
+ }
69
+ /**
70
+ * Represents a 404 Not Found Error.
71
+ * Used when a requested resource (e.g., user, file) could not be located.
72
+ */
73
+ declare class NotFoundException extends ErrorResponse {
74
+ /**
75
+ * @param message - Optional custom message. Defaults to "Resource not found".
76
+ */
77
+ constructor(message?: string);
78
+ }
79
+ /**
80
+ * Represents a 403 Forbidden Error.
81
+ * Indicates that the client is authenticated but not allowed to access the resource.
82
+ */
83
+ declare class ForbiddenException extends ErrorResponse {
84
+ /**
85
+ * @param message - Optional custom message. Defaults to "Forbidden".
86
+ */
87
+ constructor(message?: string);
88
+ }
89
+ /**
90
+ * Represents a 409 Conflict Error.
91
+ * Commonly used when a resource already exists or a versioning conflict occurs.
92
+ */
93
+ declare class ConflictException extends ErrorResponse {
94
+ /**
95
+ * @param message - Optional custom message. Defaults to "Conflict".
96
+ */
97
+ constructor(message?: string);
98
+ }
99
+ /**
100
+ * Represents a 502 Bad Gateway Error.
101
+ * Used when the server receives an invalid response from an upstream server.
102
+ */
103
+ declare class BadGatewayException extends ErrorResponse {
104
+ /**
105
+ * @param message - Optional custom message. Defaults to "Bad Gateway".
106
+ */
107
+ constructor(message?: string);
108
+ }
109
+ /**
110
+ * Represents a 429 Too Many Requests Error.
111
+ * Returned when the client has hit a rate limit.
112
+ */
113
+ declare class TooManyRequestsException extends ErrorResponse {
114
+ /**
115
+ * @param message - Optional custom message. Defaults to "Too many requests".
116
+ */
117
+ constructor(message?: string);
118
+ }
119
+ /**
120
+ * Represents a 503 Service Unavailable Error.
121
+ * Indicates that the server is temporarily unavailable (e.g., for maintenance).
122
+ */
123
+ declare class ServiceUnavailableException extends ErrorResponse {
124
+ /**
125
+ * @param message - Optional custom message. Defaults to "Service Unavailable".
126
+ */
127
+ constructor(message?: string);
128
+ }
129
+ /**
130
+ * Represents a 504 Gateway Timeout Error.
131
+ * Returned when the server acting as a gateway times out waiting for a response.
132
+ */
133
+ declare class GatewayTimeoutException extends ErrorResponse {
134
+ /**
135
+ * @param message - Optional custom message. Defaults to "Gateway Timeout".
136
+ */
137
+ constructor(message?: string);
138
+ }
139
+ /**
140
+ * Represents a 422 Unprocessable Entity Error.
141
+ * Used when the server understands the content type but cannot process the contained instructions.
142
+ */
143
+ declare class UnprocessableEntityException extends ErrorResponse {
144
+ details?: Record<string, any> | undefined;
145
+ /**
146
+ * @param message - Optional custom message. Defaults to "Unprocessable Entity".
147
+ * @param details - Optional validation details or additional error context.
148
+ */
149
+ constructor(message?: string, details?: Record<string, any> | undefined);
150
+ }
151
+ /**
152
+ * Represents a 405 Method Not Allowed Error.
153
+ * Used when the request method is not supported for the requested resource.
154
+ */
155
+ declare class MethodNotAllowedException extends ErrorResponse {
156
+ allowedMethods?: string[] | undefined;
157
+ /**
158
+ * @param message - Optional custom message. Defaults to "Method Not Allowed".
159
+ * @param allowedMethods - Optional array of allowed HTTP methods.
160
+ */
161
+ constructor(message?: string, allowedMethods?: string[] | undefined);
162
+ }
163
+ /**
164
+ * Represents a 406 Not Acceptable Error.
165
+ * Used when the server cannot produce a response matching the client's accepted content types.
166
+ */
167
+ declare class NotAcceptableException extends ErrorResponse {
168
+ /**
169
+ * @param message - Optional custom message. Defaults to "Not Acceptable".
170
+ */
171
+ constructor(message?: string);
172
+ }
173
+ /**
174
+ * Represents a 408 Request Timeout Error.
175
+ * Used when the server times out waiting for the client to send a request.
176
+ */
177
+ declare class RequestTimeoutException extends ErrorResponse {
178
+ /**
179
+ * @param message - Optional custom message. Defaults to "Request Timeout".
180
+ */
181
+ constructor(message?: string);
182
+ }
183
+ /**
184
+ * Represents a 415 Unsupported Media Type Error.
185
+ * Used when the request's Content-Type is not supported.
186
+ */
187
+ declare class UnsupportedMediaTypeException extends ErrorResponse {
188
+ /**
189
+ * @param message - Optional custom message. Defaults to "Unsupported Media Type".
190
+ */
191
+ constructor(message?: string);
192
+ }
193
+ /**
194
+ * Represents a 413 Payload Too Large Error.
195
+ * Used when the request body exceeds server limits.
196
+ */
197
+ declare class PayloadTooLargeException extends ErrorResponse {
198
+ /**
199
+ * @param message - Optional custom message. Defaults to "Payload Too Large".
200
+ */
201
+ constructor(message?: string);
202
+ }
203
+ /**
204
+ * Represents a 507 Insufficient Storage Error.
205
+ * Used when the server has insufficient storage to complete the request.
206
+ */
207
+ declare class InsufficientStorageException extends ErrorResponse {
208
+ /**
209
+ * @param message - Optional custom message. Defaults to "Insufficient Storage".
210
+ */
211
+ constructor(message?: string);
212
+ }
213
+ /**
214
+ * Checks if an error is an instance of HttpError or its subclasses.
215
+ *
216
+ * @param error - The error to check.
217
+ * @returns True if the error is an HttpError, false otherwise.
218
+ */
219
+ declare function isHttpError(error: unknown): error is ErrorResponse;
220
+ /**
221
+ * Creates an HTTP error with the specified status code and message.
222
+ * Factory function for creating appropriate HTTP error instances.
223
+ *
224
+ * @param status - HTTP status code.
225
+ * @param message - Optional custom error message.
226
+ * @returns An instance of the appropriate HTTP error class.
227
+ */
228
+ declare function createHttpError(status: number, message?: string): ErrorResponse;
229
+ /**
230
+ * Type guard to check if an object has specific error properties.
231
+ *
232
+ * @param error - The object to check.
233
+ * @returns True if object has error-like structure.
234
+ */
235
+ declare function hasErrorShape(error: unknown): error is {
236
+ message: string;
237
+ status?: number;
238
+ code?: string;
239
+ };
240
+ /**
241
+ * Safely extracts message from any error type.
242
+ *
243
+ * @param error - Any error object or value.
244
+ * @returns A string error message.
245
+ */
246
+ declare function getErrorMessage(error: unknown): string;
247
+ /**
248
+ * Wraps a function and transforms any errors into HTTP errors.
249
+ * Useful for API handlers to ensure consistent error responses.
250
+ *
251
+ * @param handler - The async function to wrap.
252
+ * @returns A function that always returns or throws an HTTP error.
253
+ */
254
+ declare function withErrorHandling<T extends (...args: any[]) => Promise<any>>(handler: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;
255
+
256
+ export { BadGatewayException, BadRequestException, ConflictException, ForbiddenException, GatewayTimeoutException, HttpError, InsufficientStorageException, InternalServerErrorException, MethodNotAllowedException, NotAcceptableException, NotFoundException, PayloadTooLargeException, RequestTimeoutException, ServiceUnavailableException, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, createHttpError, getErrorMessage, hasErrorShape, isHttpError, withErrorHandling };
package/fs/index.cjs CHANGED
@@ -24,8 +24,8 @@
24
24
 
25
25
  'use strict';
26
26
 
27
- var fs$1 = require('fs');
28
- var fs = require('fs/promises');
27
+ var fs = require('fs');
28
+ var fsp = require('fs/promises');
29
29
  var os = require('os');
30
30
  var path = require('path');
31
31
  var promises = require('stream/promises');
@@ -34,13 +34,14 @@ var crypto = require('crypto');
34
34
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
35
35
 
36
36
  var fs__default = /*#__PURE__*/_interopDefault(fs);
37
+ var fsp__default = /*#__PURE__*/_interopDefault(fsp);
37
38
  var path__default = /*#__PURE__*/_interopDefault(path);
38
39
 
39
40
  var __defProp = Object.defineProperty;
40
41
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
41
42
  async function fileExists(path2) {
42
43
  try {
43
- await fs__default.default.access(path2);
44
+ await fsp__default.default.access(path2);
44
45
  return true;
45
46
  } catch {
46
47
  return false;
@@ -49,7 +50,7 @@ async function fileExists(path2) {
49
50
  __name(fileExists, "fileExists");
50
51
  async function readJsonFile(path2) {
51
52
  try {
52
- const data = await fs__default.default.readFile(path2, "utf-8");
53
+ const data = await fsp__default.default.readFile(path2, "utf-8");
53
54
  return JSON.parse(data);
54
55
  } catch {
55
56
  return null;
@@ -63,12 +64,12 @@ async function readJsonOrDefault(path2, defaultValue) {
63
64
  __name(readJsonOrDefault, "readJsonOrDefault");
64
65
  async function writeJsonFile(path2, data, space = 2) {
65
66
  const json = JSON.stringify(data, null, space);
66
- await fs__default.default.writeFile(path2, json, "utf-8");
67
+ await fsp__default.default.writeFile(path2, json, "utf-8");
67
68
  }
68
69
  __name(writeJsonFile, "writeJsonFile");
69
70
  async function deleteFileIfExists(path2) {
70
71
  try {
71
- await fs__default.default.unlink(path2);
72
+ await fsp__default.default.unlink(path2);
72
73
  return true;
73
74
  } catch (err) {
74
75
  if (err.code === "ENOENT") return true;
@@ -76,36 +77,66 @@ async function deleteFileIfExists(path2) {
76
77
  }
77
78
  }
78
79
  __name(deleteFileIfExists, "deleteFileIfExists");
79
- async function readTextFile(path2, encoding = "utf-8") {
80
+ async function readFile(path2, encoding = "utf-8") {
81
+ return await fsp__default.default.readFile(path2, encoding);
82
+ }
83
+ __name(readFile, "readFile");
84
+ function readFileSync(path2, encoding = "utf-8") {
85
+ return fs__default.default.readFileSync(path2, encoding);
86
+ }
87
+ __name(readFileSync, "readFileSync");
88
+ async function safeReadFile(path2, encoding = "utf-8") {
80
89
  try {
81
- return await fs__default.default.readFile(path2, encoding);
82
- } catch {
83
- return null;
90
+ const data = await fsp__default.default.readFile(path2, encoding);
91
+ return {
92
+ data,
93
+ error: null
94
+ };
95
+ } catch (error) {
96
+ return {
97
+ data: null,
98
+ error: new Error(`Failed to read file ${path2}: ${error.message}`)
99
+ };
100
+ }
101
+ }
102
+ __name(safeReadFile, "safeReadFile");
103
+ function safeReadFileSync(path2, encoding = "utf-8") {
104
+ try {
105
+ const data = fs__default.default.readFileSync(path2, encoding);
106
+ return {
107
+ data,
108
+ error: null
109
+ };
110
+ } catch (error) {
111
+ return {
112
+ data: null,
113
+ error: new Error(`Failed to read file ${path2}: ${error.message}`)
114
+ };
84
115
  }
85
116
  }
86
- __name(readTextFile, "readTextFile");
87
- async function writeTextFile(path2, content, encoding = "utf-8") {
117
+ __name(safeReadFileSync, "safeReadFileSync");
118
+ async function writeFile(path2, content, encoding = "utf-8") {
88
119
  try {
89
- await fs__default.default.writeFile(path2, content, encoding);
120
+ await fsp__default.default.writeFile(path2, content, encoding);
90
121
  return true;
91
122
  } catch {
92
123
  return false;
93
124
  }
94
125
  }
95
- __name(writeTextFile, "writeTextFile");
96
- async function appendTextFile(path2, content, encoding = "utf-8") {
126
+ __name(writeFile, "writeFile");
127
+ async function appendFile(path2, content, encoding = "utf-8") {
97
128
  try {
98
- await fs__default.default.appendFile(path2, content, encoding);
129
+ await fsp__default.default.appendFile(path2, content, encoding);
99
130
  return true;
100
131
  } catch {
101
132
  return false;
102
133
  }
103
134
  }
104
- __name(appendTextFile, "appendTextFile");
135
+ __name(appendFile, "appendFile");
105
136
  async function copyFile(source, destination, overwrite = false) {
106
137
  try {
107
- const flags = overwrite ? 0 : fs__default.default.constants.COPYFILE_EXCL;
108
- await fs__default.default.copyFile(source, destination, flags);
138
+ const flags = overwrite ? 0 : fsp__default.default.constants.COPYFILE_EXCL;
139
+ await fsp__default.default.copyFile(source, destination, flags);
109
140
  return true;
110
141
  } catch {
111
142
  return false;
@@ -114,12 +145,12 @@ async function copyFile(source, destination, overwrite = false) {
114
145
  __name(copyFile, "copyFile");
115
146
  async function moveFile(oldPath, newPath) {
116
147
  try {
117
- await fs__default.default.rename(oldPath, newPath);
148
+ await fsp__default.default.rename(oldPath, newPath);
118
149
  return true;
119
150
  } catch {
120
151
  try {
121
- await fs__default.default.copyFile(oldPath, newPath);
122
- await fs__default.default.unlink(oldPath);
152
+ await fsp__default.default.copyFile(oldPath, newPath);
153
+ await fsp__default.default.unlink(oldPath);
123
154
  return true;
124
155
  } catch {
125
156
  return false;
@@ -129,7 +160,7 @@ async function moveFile(oldPath, newPath) {
129
160
  __name(moveFile, "moveFile");
130
161
  async function getFileStats(path2) {
131
162
  try {
132
- return await fs__default.default.stat(path2);
163
+ return await fsp__default.default.stat(path2);
133
164
  } catch {
134
165
  return null;
135
166
  }
@@ -140,16 +171,16 @@ async function createTempFile({ prefix = "tmp-", extension = "", dir = os.tmpdir
140
171
  const filename = `${prefix}${crypto.randomUUID()}${ext}`;
141
172
  const filepath = path__default.default.join(dir, filename);
142
173
  if (content) {
143
- await fs__default.default.writeFile(filepath, content);
174
+ await fsp__default.default.writeFile(filepath, content);
144
175
  } else {
145
- await fs__default.default.writeFile(filepath, "");
176
+ await fsp__default.default.writeFile(filepath, "");
146
177
  }
147
178
  return filepath;
148
179
  }
149
180
  __name(createTempFile, "createTempFile");
150
181
  async function streamFile(source, destination) {
151
- const readStream = fs$1.createReadStream(source);
152
- const writeStream = fs$1.createWriteStream(destination);
182
+ const readStream = fs__default.default.createReadStream(source);
183
+ const writeStream = fs__default.default.createWriteStream(destination);
153
184
  try {
154
185
  await promises.pipeline(readStream, writeStream);
155
186
  } catch (error) {
@@ -160,7 +191,7 @@ async function streamFile(source, destination) {
160
191
  }
161
192
  __name(streamFile, "streamFile");
162
193
  async function readDirectory(dirPath, options = {}) {
163
- const files = await fs__default.default.readdir(dirPath);
194
+ const files = await fsp__default.default.readdir(dirPath);
164
195
  let result = files;
165
196
  if (options.filter) {
166
197
  result = result.filter((file) => options.filter.test(file));
@@ -173,7 +204,7 @@ async function readDirectory(dirPath, options = {}) {
173
204
  __name(readDirectory, "readDirectory");
174
205
  async function createDirectory(dirPath, recursive = true) {
175
206
  try {
176
- await fs__default.default.mkdir(dirPath, {
207
+ await fsp__default.default.mkdir(dirPath, {
177
208
  recursive
178
209
  });
179
210
  return true;
@@ -184,7 +215,7 @@ async function createDirectory(dirPath, recursive = true) {
184
215
  __name(createDirectory, "createDirectory");
185
216
  async function safeReadJsonFile(path2) {
186
217
  try {
187
- const content = await fs__default.default.readFile(path2, "utf-8");
218
+ const content = await fsp__default.default.readFile(path2, "utf-8");
188
219
  try {
189
220
  const data = JSON.parse(content);
190
221
  return {
@@ -207,7 +238,7 @@ async function safeReadJsonFile(path2) {
207
238
  __name(safeReadJsonFile, "safeReadJsonFile");
208
239
  async function isFile(path2) {
209
240
  try {
210
- const stat = await fs__default.default.stat(path2);
241
+ const stat = await fsp__default.default.stat(path2);
211
242
  return stat.isFile();
212
243
  } catch {
213
244
  return false;
@@ -216,7 +247,7 @@ async function isFile(path2) {
216
247
  __name(isFile, "isFile");
217
248
  async function getFileSize(path2) {
218
249
  try {
219
- const stat = await fs__default.default.stat(path2);
250
+ const stat = await fsp__default.default.stat(path2);
220
251
  return stat.size;
221
252
  } catch {
222
253
  return -1;
@@ -225,14 +256,14 @@ async function getFileSize(path2) {
225
256
  __name(getFileSize, "getFileSize");
226
257
  async function readFileBuffer(path2) {
227
258
  try {
228
- return await fs__default.default.readFile(path2);
259
+ return await fsp__default.default.readFile(path2);
229
260
  } catch {
230
261
  return null;
231
262
  }
232
263
  }
233
264
  __name(readFileBuffer, "readFileBuffer");
234
265
 
235
- exports.appendTextFile = appendTextFile;
266
+ exports.appendFile = appendFile;
236
267
  exports.copyFile = copyFile;
237
268
  exports.createDirectory = createDirectory;
238
269
  exports.createTempFile = createTempFile;
@@ -243,11 +274,14 @@ exports.getFileStats = getFileStats;
243
274
  exports.isFile = isFile;
244
275
  exports.moveFile = moveFile;
245
276
  exports.readDirectory = readDirectory;
277
+ exports.readFile = readFile;
246
278
  exports.readFileBuffer = readFileBuffer;
279
+ exports.readFileSync = readFileSync;
247
280
  exports.readJsonFile = readJsonFile;
248
281
  exports.readJsonOrDefault = readJsonOrDefault;
249
- exports.readTextFile = readTextFile;
282
+ exports.safeReadFile = safeReadFile;
283
+ exports.safeReadFileSync = safeReadFileSync;
250
284
  exports.safeReadJsonFile = safeReadJsonFile;
251
285
  exports.streamFile = streamFile;
286
+ exports.writeFile = writeFile;
252
287
  exports.writeJsonFile = writeJsonFile;
253
- exports.writeTextFile = writeTextFile;
package/fs/index.d.ts CHANGED
@@ -22,4 +22,208 @@
22
22
  * SOFTWARE.
23
23
  */
24
24
 
25
- export * from './fs.utils';
25
+ import { BufferEncoding } from '@catbee/utils/crypto';
26
+ import fs from 'node:fs';
27
+
28
+ /**
29
+ * Checks whether a file or directory exists at the given path.
30
+ *
31
+ * @param {string} path - The file or directory path to check.
32
+ * @returns {Promise<boolean>} Resolves to `true` if the path exists, `false` otherwise.
33
+ */
34
+ declare function fileExists(path: string): Promise<boolean>;
35
+ /**
36
+ * Reads and parses a JSON file from the specified path.
37
+ *
38
+ * @typeParam T - The expected type of the parsed JSON object.
39
+ * @param {string} path - The path to the JSON file.
40
+ * @returns {Promise<T | null>} The parsed object, or `null` if reading or parsing fails.
41
+ */
42
+ declare function readJsonFile<T = any>(path: string): Promise<T | null>;
43
+ /**
44
+ * Read and parse JSON file or return a provided default value on error.
45
+ *
46
+ * @typeParam T
47
+ * @param {string} path - Path to JSON file
48
+ * @param {T} defaultValue - Default value to return when read/parse fails
49
+ * @returns {Promise<T>} Parsed JSON or defaultValue
50
+ */
51
+ declare function readJsonOrDefault<T = any>(path: string, defaultValue: T): Promise<T>;
52
+ /**
53
+ * Writes a JavaScript object to a file as formatted JSON.
54
+ *
55
+ * @param {string} path - The destination file path.
56
+ * @param {any} data - The object to serialize and write.
57
+ * @param {number} [space=2] - Number of spaces for JSON formatting.
58
+ * @returns {Promise<void>} Resolves when writing is complete.
59
+ */
60
+ declare function writeJsonFile(path: string, data: any, space?: number): Promise<void>;
61
+ /**
62
+ * Deletes a file if it exists.
63
+ *
64
+ * @param {string} path - The file path to delete.
65
+ * @returns {Promise<boolean>} Resolves to `true` if the file was deleted or didn't exist, `false` if deletion failed.
66
+ */
67
+ declare function deleteFileIfExists(path: string): Promise<boolean>;
68
+ /**
69
+ * Reads a file from the specified path.
70
+ *
71
+ * @param {string} path - The path to the file.
72
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
73
+ * @returns {Promise<string | null>} The file contents, or `null` if reading fails.
74
+ */
75
+ declare function readFile(path: string, encoding?: BufferEncoding): Promise<string>;
76
+ /**
77
+ * Reads a file from the specified path synchronously.
78
+ *
79
+ * @param {string} path - The path to the file.
80
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
81
+ * @returns {string | null} The file contents, or `null` if reading fails.
82
+ */
83
+ declare function readFileSync(path: string, encoding?: BufferEncoding): string;
84
+ /**
85
+ * Safely reads a file and returns its content along with any error encountered.
86
+ *
87
+ * @param {string} path - The path to the file.
88
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
89
+ * @returns {Promise<{ data: string | null; error: Error | null }>} Object with data and error properties.
90
+ */
91
+ declare function safeReadFile(path: string, encoding?: BufferEncoding): Promise<{
92
+ data: string | null;
93
+ error: Error | null;
94
+ }>;
95
+ /**
96
+ * Safely reads a file synchronously and returns its content along with any error encountered.
97
+ *
98
+ * @param {string} path - The path to the file.
99
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
100
+ * @returns {{ data: string | null; error: Error | null }} Object with data and error properties.
101
+ */
102
+ declare function safeReadFileSync(path: string, encoding?: BufferEncoding): {
103
+ data: string | null;
104
+ error: Error | null;
105
+ };
106
+ /**
107
+ * Writes content to a file.
108
+ *
109
+ * @param {string} path - The destination file path.
110
+ * @param {string} content - The text content to write.
111
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
112
+ * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
113
+ */
114
+ declare function writeFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>;
115
+ /**
116
+ * Appends text content to a file.
117
+ *
118
+ * @param {string} path - The file path to append to.
119
+ * @param {string} content - The text content to append.
120
+ * @param {BufferEncoding} [encoding="utf-8"] - The encoding to use.
121
+ * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
122
+ */
123
+ declare function appendFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>;
124
+ /**
125
+ * Copies a file from source to destination.
126
+ *
127
+ * @param {string} source - Source file path.
128
+ * @param {string} destination - Destination file path.
129
+ * @param {boolean} [overwrite=false] - Whether to overwrite if destination exists.
130
+ * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
131
+ */
132
+ declare function copyFile(source: string, destination: string, overwrite?: boolean): Promise<boolean>;
133
+ /**
134
+ * Renames/moves a file.
135
+ *
136
+ * @param {string} oldPath - Current file path.
137
+ * @param {string} newPath - New file path.
138
+ * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
139
+ */
140
+ declare function moveFile(oldPath: string, newPath: string): Promise<boolean>;
141
+ /**
142
+ * Gets file stats if the file exists.
143
+ *
144
+ * @param {string} path - Path to the file.
145
+ * @returns {Promise<fsp.Stats | null>} File stats object or null if file doesn't exist.
146
+ */
147
+ declare function getFileStats(path: string): Promise<fs.Stats | null>;
148
+ /**
149
+ * Creates a temporary file with optional content.
150
+ *
151
+ * @param {object} [options] - Options for creating the temp file.
152
+ * @param {string} [options.prefix="tmp-"] - Filename prefix.
153
+ * @param {string} [options.extension=""] - File extension.
154
+ * @param {string} [options.dir] - Directory to create the file in (defaults to OS temp dir).
155
+ * @param {string | Buffer} [options.content] - Optional content to write to the file.
156
+ * @returns {Promise<string>} Path to the created temporary file.
157
+ */
158
+ declare function createTempFile({ prefix, extension, dir, content }?: {
159
+ prefix?: string;
160
+ extension?: string;
161
+ dir?: string;
162
+ content?: string | Buffer;
163
+ }): Promise<string>;
164
+ /**
165
+ * Streams a file from source to destination.
166
+ * Useful for large files to avoid loading the entire file into memory.
167
+ *
168
+ * @param {string} source - Source file path.
169
+ * @param {string} destination - Destination file path.
170
+ * @returns {Promise<void>} Resolves when streaming completes.
171
+ * @throws {Error} If streaming fails.
172
+ */
173
+ declare function streamFile(source: string, destination: string): Promise<void>;
174
+ /**
175
+ * Reads a directory and returns file names.
176
+ *
177
+ * @param {string} dirPath - Path to the directory.
178
+ * @param {object} [options] - Options for reading the directory.
179
+ * @param {boolean} [options.fullPaths=false] - Whether to return full paths.
180
+ * @param {RegExp} [options.filter] - Optional regex to filter files.
181
+ * @returns {Promise<string[]>} Array of file names or paths.
182
+ * @throws {Error} If directory cannot be read.
183
+ */
184
+ declare function readDirectory(dirPath: string, options?: {
185
+ fullPaths?: boolean;
186
+ filter?: RegExp;
187
+ }): Promise<string[]>;
188
+ /**
189
+ * Creates a directory if it doesn't exist.
190
+ *
191
+ * @param {string} dirPath - Path to the directory.
192
+ * @param {boolean} [recursive=true] - Whether to create parent directories.
193
+ * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.
194
+ */
195
+ declare function createDirectory(dirPath: string, recursive?: boolean): Promise<boolean>;
196
+ /**
197
+ * Safely reads and parses a JSON file with error details.
198
+ *
199
+ * @typeParam T - The expected type of the parsed JSON object.
200
+ * @param {string} path - The path to the JSON file.
201
+ * @returns {Promise<{ data: T | null; error: Error | null }>} Object with data and error properties.
202
+ */
203
+ declare function safeReadJsonFile<T = any>(path: string): Promise<{
204
+ data: T | null;
205
+ error: Error | null;
206
+ }>;
207
+ /**
208
+ * Checks if a path points to a file (not a directory).
209
+ *
210
+ * @param {string} path - Path to check.
211
+ * @returns {Promise<boolean>} True if the path is a file, false otherwise.
212
+ */
213
+ declare function isFile(path: string): Promise<boolean>;
214
+ /**
215
+ * Gets the size of a file in bytes.
216
+ *
217
+ * @param {string} path - Path to the file.
218
+ * @returns {Promise<number>} Size in bytes or -1 if file doesn't exist.
219
+ */
220
+ declare function getFileSize(path: string): Promise<number>;
221
+ /**
222
+ * Reads a file as a Buffer.
223
+ *
224
+ * @param {string} path - Path to the file.
225
+ * @returns {Promise<Buffer | null>} File contents as Buffer or null if reading fails.
226
+ */
227
+ declare function readFileBuffer(path: string): Promise<Buffer | null>;
228
+
229
+ export { appendFile, copyFile, createDirectory, createTempFile, deleteFileIfExists, fileExists, getFileSize, getFileStats, isFile, moveFile, readDirectory, readFile, readFileBuffer, readFileSync, readJsonFile, readJsonOrDefault, safeReadFile, safeReadFileSync, safeReadJsonFile, streamFile, writeFile, writeJsonFile };