@catbee/utils 0.0.8-rc.2 → 0.0.8-rc.3
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.
- package/build/cjs/config.d.ts +121 -0
- package/build/cjs/config.js +137 -0
- package/build/cjs/index.d.ts +26 -0
- package/build/cjs/index.js +68 -0
- package/build/cjs/servers/server.builder.d.ts +507 -0
- package/build/cjs/servers/server.builder.js +658 -0
- package/build/cjs/servers/server.d.ts +255 -0
- package/build/cjs/servers/server.js +970 -0
- package/build/cjs/types/api-response.d.ts +151 -0
- package/build/cjs/types/api-response.js +36 -0
- package/build/cjs/types/index.d.ts +124 -0
- package/build/cjs/types/index.js +25 -0
- package/build/cjs/types/server.d.ts +267 -0
- package/build/cjs/types/server.js +25 -0
- package/build/cjs/utils/array.utils.d.ts +167 -0
- package/build/cjs/utils/array.utils.js +363 -0
- package/build/cjs/utils/async.utils.d.ts +264 -0
- package/build/cjs/utils/async.utils.js +640 -0
- package/build/cjs/utils/cache.utils.d.ts +152 -0
- package/build/cjs/utils/cache.utils.js +298 -0
- package/build/cjs/utils/context-store.utils.d.ts +188 -0
- package/build/cjs/utils/context-store.utils.js +297 -0
- package/build/cjs/utils/crypto.utils.d.ts +159 -0
- package/build/cjs/utils/crypto.utils.js +295 -0
- package/build/cjs/utils/date.utils.d.ts +158 -0
- package/build/cjs/utils/date.utils.js +395 -0
- package/build/cjs/utils/decorators.utils.d.ts +511 -0
- package/build/cjs/utils/decorators.utils.js +1035 -0
- package/build/cjs/utils/dir.utils.d.ts +195 -0
- package/build/cjs/utils/dir.utils.js +500 -0
- package/build/cjs/utils/env.utils.d.ts +376 -0
- package/build/cjs/utils/env.utils.js +786 -0
- package/build/cjs/utils/exception.utils.d.ts +229 -0
- package/build/cjs/utils/exception.utils.js +408 -0
- package/build/cjs/utils/fs.utils.d.ts +163 -0
- package/build/cjs/utils/fs.utils.js +371 -0
- package/build/cjs/utils/http-status-codes.d.ts +265 -0
- package/build/cjs/utils/http-status-codes.js +297 -0
- package/build/cjs/utils/id.utils.d.ts +35 -0
- package/build/cjs/utils/id.utils.js +90 -0
- package/build/cjs/utils/logger.utils.d.ts +159 -0
- package/build/cjs/utils/logger.utils.js +350 -0
- package/build/cjs/utils/middleware.utils.d.ts +99 -0
- package/build/cjs/utils/middleware.utils.js +243 -0
- package/build/cjs/utils/obj.utils.d.ts +123 -0
- package/build/cjs/utils/obj.utils.js +428 -0
- package/build/cjs/utils/performance.utils.d.ts +135 -0
- package/build/cjs/utils/performance.utils.js +280 -0
- package/build/cjs/utils/request.utils.d.ts +85 -0
- package/build/cjs/utils/request.utils.js +199 -0
- package/build/cjs/utils/response.utils.d.ts +162 -0
- package/build/cjs/utils/response.utils.js +274 -0
- package/build/cjs/utils/stream.utils.d.ts +87 -0
- package/build/cjs/utils/stream.utils.js +217 -0
- package/build/cjs/utils/string.utils.d.ts +92 -0
- package/build/cjs/utils/string.utils.js +178 -0
- package/build/cjs/utils/type.utils.d.ts +89 -0
- package/build/cjs/utils/type.utils.js +195 -0
- package/build/cjs/utils/url.utils.d.ts +140 -0
- package/build/cjs/utils/url.utils.js +316 -0
- package/build/cjs/utils/validate.utils.d.ts +176 -0
- package/build/cjs/utils/validate.utils.js +344 -0
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +1 -1
- package/build/esm/utils/decorators.utils.js +1 -1
- package/package.json +287 -32
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
/**
|
|
3
|
+
* Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
|
|
4
|
+
*
|
|
5
|
+
* @param {string} dirPath - The directory path to ensure.
|
|
6
|
+
* @returns {Promise<void>} Resolves when the directory exists.
|
|
7
|
+
* @throws {Error} If directory cannot be created.
|
|
8
|
+
*/
|
|
9
|
+
export declare function ensureDir(dirPath: string): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Recursively lists all files in a directory.
|
|
12
|
+
*
|
|
13
|
+
* @param {string} dirPath - The base directory.
|
|
14
|
+
* @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
|
|
15
|
+
* @returns {Promise<string[]>} Array of absolute file paths.
|
|
16
|
+
* @throws {Error} If the directory cannot be read.
|
|
17
|
+
*/
|
|
18
|
+
export declare function listFiles(dirPath: string, recursive?: boolean): Promise<string[]>;
|
|
19
|
+
/**
|
|
20
|
+
* Deletes a directory and all its contents recursively (like `rm -rf`).
|
|
21
|
+
*
|
|
22
|
+
* @param {string} dirPath - Directory to delete.
|
|
23
|
+
* @returns {Promise<void>} Resolves when deletion is complete.
|
|
24
|
+
* @throws {Error} If deletion fails.
|
|
25
|
+
*/
|
|
26
|
+
export declare function deleteDirRecursive(dirPath: string): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Checks whether a given path is a directory.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} pathStr - Path to check.
|
|
31
|
+
* @returns {Promise<boolean>} True if the path is a directory, else false.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isDirectory(pathStr: string): Promise<boolean>;
|
|
34
|
+
/**
|
|
35
|
+
* Recursively copies a directory and all its contents to a destination.
|
|
36
|
+
*
|
|
37
|
+
* @param {string} src - Source directory path.
|
|
38
|
+
* @param {string} dest - Destination directory path.
|
|
39
|
+
* @returns {Promise<void>} Resolves when copy is complete.
|
|
40
|
+
* @throws {Error} If source does not exist or copy fails.
|
|
41
|
+
*/
|
|
42
|
+
export declare function copyDir(src: string, dest: string): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Moves a directory to a new location by copying and deleting the original.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} src - Source directory path.
|
|
47
|
+
* @param {string} dest - Destination directory path.
|
|
48
|
+
* @returns {Promise<void>} Resolves when move is complete.
|
|
49
|
+
* @throws {Error} If copy or deletion fails.
|
|
50
|
+
*/
|
|
51
|
+
export declare function moveDir(src: string, dest: string): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Empties a directory by deleting all files and subdirectories inside it.
|
|
54
|
+
*
|
|
55
|
+
* @param {string} dirPath - Path to the directory to empty.
|
|
56
|
+
* @returns {Promise<void>} Resolves when the directory has been emptied.
|
|
57
|
+
* @throws {Error} If files or subdirectories cannot be removed.
|
|
58
|
+
*/
|
|
59
|
+
export declare function emptyDir(dirPath: string): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Calculates the total size (in bytes) of all files in a directory (recursive).
|
|
62
|
+
*
|
|
63
|
+
* @param {string} dirPath - Path to the directory.
|
|
64
|
+
* @returns {Promise<number>} Total size in bytes.
|
|
65
|
+
* @throws {Error} If any file stats cannot be read.
|
|
66
|
+
*/
|
|
67
|
+
export declare function getDirSize(dirPath: string): Promise<number>;
|
|
68
|
+
/**
|
|
69
|
+
* Watches a directory for file changes and calls a callback on each event.
|
|
70
|
+
*
|
|
71
|
+
* @param {string} dirPath - Directory path to watch.
|
|
72
|
+
* @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
|
|
73
|
+
* @returns {() => void} A function to stop watching the directory.
|
|
74
|
+
*/
|
|
75
|
+
export declare function watchDir(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string | null) => void): () => void;
|
|
76
|
+
/**
|
|
77
|
+
* Finds files matching a glob pattern.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} pattern - Glob pattern to match files.
|
|
80
|
+
* @param {object} [options] - Options for glob pattern matching.
|
|
81
|
+
* @param {string} [options.cwd] - Current working directory for relative patterns.
|
|
82
|
+
* @param {boolean} [options.dot=false] - Include dotfiles in matches.
|
|
83
|
+
* @param {boolean} [options.nodir=true] - Only match files, not directories.
|
|
84
|
+
* @returns {Promise<string[]>} Array of matched file paths.
|
|
85
|
+
* @throws {Error} If pattern matching fails.
|
|
86
|
+
*/
|
|
87
|
+
export declare function findFilesByPattern(pattern: string, options?: {
|
|
88
|
+
cwd?: string;
|
|
89
|
+
dot?: boolean;
|
|
90
|
+
nodir?: boolean;
|
|
91
|
+
}): Promise<string[]>;
|
|
92
|
+
/**
|
|
93
|
+
* Gets all subdirectories in a directory.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} dirPath - The directory to search in.
|
|
96
|
+
* @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
|
|
97
|
+
* @returns {Promise<string[]>} Array of absolute subdirectory paths.
|
|
98
|
+
* @throws {Error} If directory cannot be read.
|
|
99
|
+
*/
|
|
100
|
+
export declare function getSubdirectories(dirPath: string, recursive?: boolean): Promise<string[]>;
|
|
101
|
+
/**
|
|
102
|
+
* Ensures a directory exists and is empty.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} dirPath - Path to the directory.
|
|
105
|
+
* @returns {Promise<void>} Resolves when the directory exists and is empty.
|
|
106
|
+
* @throws {Error} If directory cannot be created or emptied.
|
|
107
|
+
*/
|
|
108
|
+
export declare function ensureEmptyDir(dirPath: string): Promise<void>;
|
|
109
|
+
/**
|
|
110
|
+
* Creates a temporary directory with optional auto-cleanup.
|
|
111
|
+
*
|
|
112
|
+
* @param {object} [options] - Options for the temporary directory.
|
|
113
|
+
* @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
|
|
114
|
+
* @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
|
|
115
|
+
* @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
|
|
116
|
+
* @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
|
|
117
|
+
* @throws {Error} If directory cannot be created.
|
|
118
|
+
*/
|
|
119
|
+
export declare function createTempDir(options?: {
|
|
120
|
+
prefix?: string;
|
|
121
|
+
parentDir?: string;
|
|
122
|
+
cleanup?: boolean;
|
|
123
|
+
}): Promise<{
|
|
124
|
+
path: string;
|
|
125
|
+
cleanup: () => Promise<void>;
|
|
126
|
+
}>;
|
|
127
|
+
/**
|
|
128
|
+
* Finds the newest file in a directory.
|
|
129
|
+
*
|
|
130
|
+
* @param {string} dirPath - Directory to search.
|
|
131
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
132
|
+
* @returns {Promise<string | null>} Path to the newest file or null if no files.
|
|
133
|
+
* @throws {Error} If directory cannot be read.
|
|
134
|
+
*/
|
|
135
|
+
export declare function findNewestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
|
|
136
|
+
/**
|
|
137
|
+
* Finds the oldest file in a directory.
|
|
138
|
+
*
|
|
139
|
+
* @param {string} dirPath - Directory to search.
|
|
140
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
141
|
+
* @returns {Promise<string | null>} Path to the oldest file or null if no files.
|
|
142
|
+
* @throws {Error} If directory cannot be read.
|
|
143
|
+
*/
|
|
144
|
+
export declare function findOldestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
|
|
145
|
+
/**
|
|
146
|
+
* Finds files or directories in a directory matching a predicate function.
|
|
147
|
+
*
|
|
148
|
+
* @param {string} dirPath - Directory to search.
|
|
149
|
+
* @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
|
|
150
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
151
|
+
* @returns {Promise<string[]>} Array of matching paths.
|
|
152
|
+
* @throws {Error} If directory cannot be read.
|
|
153
|
+
*/
|
|
154
|
+
export declare function findInDir(dirPath: string, predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>, recursive?: boolean): Promise<string[]>;
|
|
155
|
+
/**
|
|
156
|
+
* Watches a directory recursively for file changes.
|
|
157
|
+
*
|
|
158
|
+
* @param {string} dirPath - Base directory path to watch.
|
|
159
|
+
* @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
|
|
160
|
+
* @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
|
|
161
|
+
* @returns {Promise<() => void>} A function to stop watching the directory.
|
|
162
|
+
* @throws {Error} If directory cannot be watched.
|
|
163
|
+
*/
|
|
164
|
+
export declare function watchDirRecursive(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string) => void, includeSubdirs?: boolean): Promise<() => void>;
|
|
165
|
+
/**
|
|
166
|
+
* Gets detailed directory statistics including file count, directory count, and size.
|
|
167
|
+
*
|
|
168
|
+
* @param {string} dirPath - Path to the directory.
|
|
169
|
+
* @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
|
|
170
|
+
* @throws {Error} If directory cannot be read.
|
|
171
|
+
*/
|
|
172
|
+
export declare function getDirStats(dirPath: string): Promise<{
|
|
173
|
+
fileCount: number;
|
|
174
|
+
dirCount: number;
|
|
175
|
+
totalSize: number;
|
|
176
|
+
}>;
|
|
177
|
+
/**
|
|
178
|
+
* Walks through a directory hierarchy, calling a visitor function for each entry.
|
|
179
|
+
*
|
|
180
|
+
* @param {string} dirPath - Starting directory path.
|
|
181
|
+
* @param {object} options - Options for walking the directory.
|
|
182
|
+
* @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
|
|
183
|
+
* Function called for each file/directory. Return false to skip a directory.
|
|
184
|
+
* @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
|
|
185
|
+
* @throws {Error} If directory cannot be read.
|
|
186
|
+
*/
|
|
187
|
+
export declare function walkDir(dirPath: string, options: {
|
|
188
|
+
visitorFn: (entry: {
|
|
189
|
+
path: string;
|
|
190
|
+
name: string;
|
|
191
|
+
isDirectory: boolean;
|
|
192
|
+
stats: fs.Stats;
|
|
193
|
+
}) => boolean | void | Promise<boolean | void>;
|
|
194
|
+
traversalOrder?: 'pre' | 'post';
|
|
195
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,500 @@
|
|
|
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
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.ensureDir = ensureDir;
|
|
30
|
+
exports.listFiles = listFiles;
|
|
31
|
+
exports.deleteDirRecursive = deleteDirRecursive;
|
|
32
|
+
exports.isDirectory = isDirectory;
|
|
33
|
+
exports.copyDir = copyDir;
|
|
34
|
+
exports.moveDir = moveDir;
|
|
35
|
+
exports.emptyDir = emptyDir;
|
|
36
|
+
exports.getDirSize = getDirSize;
|
|
37
|
+
exports.watchDir = watchDir;
|
|
38
|
+
exports.findFilesByPattern = findFilesByPattern;
|
|
39
|
+
exports.getSubdirectories = getSubdirectories;
|
|
40
|
+
exports.ensureEmptyDir = ensureEmptyDir;
|
|
41
|
+
exports.createTempDir = createTempDir;
|
|
42
|
+
exports.findNewestFile = findNewestFile;
|
|
43
|
+
exports.findOldestFile = findOldestFile;
|
|
44
|
+
exports.findInDir = findInDir;
|
|
45
|
+
exports.watchDirRecursive = watchDirRecursive;
|
|
46
|
+
exports.getDirStats = getDirStats;
|
|
47
|
+
exports.walkDir = walkDir;
|
|
48
|
+
const os_1 = __importDefault(require("os"));
|
|
49
|
+
const fs_1 = __importDefault(require("fs"));
|
|
50
|
+
const promises_1 = __importDefault(require("fs/promises"));
|
|
51
|
+
const path_1 = __importDefault(require("path"));
|
|
52
|
+
const glob_1 = require("glob");
|
|
53
|
+
const crypto_1 = require("crypto");
|
|
54
|
+
/**
|
|
55
|
+
* Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
|
|
56
|
+
*
|
|
57
|
+
* @param {string} dirPath - The directory path to ensure.
|
|
58
|
+
* @returns {Promise<void>} Resolves when the directory exists.
|
|
59
|
+
* @throws {Error} If directory cannot be created.
|
|
60
|
+
*/
|
|
61
|
+
async function ensureDir(dirPath) {
|
|
62
|
+
await promises_1.default.mkdir(dirPath, { recursive: true });
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Recursively lists all files in a directory.
|
|
66
|
+
*
|
|
67
|
+
* @param {string} dirPath - The base directory.
|
|
68
|
+
* @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
|
|
69
|
+
* @returns {Promise<string[]>} Array of absolute file paths.
|
|
70
|
+
* @throws {Error} If the directory cannot be read.
|
|
71
|
+
*/
|
|
72
|
+
async function listFiles(dirPath, recursive = false) {
|
|
73
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
74
|
+
const files = [];
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
const fullPath = path_1.default.join(dirPath, entry.name);
|
|
77
|
+
if (entry.isFile()) {
|
|
78
|
+
files.push(fullPath);
|
|
79
|
+
}
|
|
80
|
+
else if (recursive && entry.isDirectory()) {
|
|
81
|
+
const nestedFiles = await listFiles(fullPath, true);
|
|
82
|
+
files.push(...nestedFiles);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return files;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Deletes a directory and all its contents recursively (like `rm -rf`).
|
|
89
|
+
*
|
|
90
|
+
* @param {string} dirPath - Directory to delete.
|
|
91
|
+
* @returns {Promise<void>} Resolves when deletion is complete.
|
|
92
|
+
* @throws {Error} If deletion fails.
|
|
93
|
+
*/
|
|
94
|
+
async function deleteDirRecursive(dirPath) {
|
|
95
|
+
await promises_1.default.rm(dirPath, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Checks whether a given path is a directory.
|
|
99
|
+
*
|
|
100
|
+
* @param {string} pathStr - Path to check.
|
|
101
|
+
* @returns {Promise<boolean>} True if the path is a directory, else false.
|
|
102
|
+
*/
|
|
103
|
+
async function isDirectory(pathStr) {
|
|
104
|
+
try {
|
|
105
|
+
const stat = await promises_1.default.stat(pathStr);
|
|
106
|
+
return stat.isDirectory();
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Recursively copies a directory and all its contents to a destination.
|
|
114
|
+
*
|
|
115
|
+
* @param {string} src - Source directory path.
|
|
116
|
+
* @param {string} dest - Destination directory path.
|
|
117
|
+
* @returns {Promise<void>} Resolves when copy is complete.
|
|
118
|
+
* @throws {Error} If source does not exist or copy fails.
|
|
119
|
+
*/
|
|
120
|
+
async function copyDir(src, dest) {
|
|
121
|
+
await ensureDir(dest);
|
|
122
|
+
const entries = await promises_1.default.readdir(src, { withFileTypes: true });
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
const srcPath = path_1.default.join(src, entry.name);
|
|
125
|
+
const destPath = path_1.default.join(dest, entry.name);
|
|
126
|
+
if (entry.isDirectory()) {
|
|
127
|
+
await copyDir(srcPath, destPath);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
await promises_1.default.copyFile(srcPath, destPath);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Moves a directory to a new location by copying and deleting the original.
|
|
136
|
+
*
|
|
137
|
+
* @param {string} src - Source directory path.
|
|
138
|
+
* @param {string} dest - Destination directory path.
|
|
139
|
+
* @returns {Promise<void>} Resolves when move is complete.
|
|
140
|
+
* @throws {Error} If copy or deletion fails.
|
|
141
|
+
*/
|
|
142
|
+
async function moveDir(src, dest) {
|
|
143
|
+
await copyDir(src, dest);
|
|
144
|
+
await deleteDirRecursive(src);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Empties a directory by deleting all files and subdirectories inside it.
|
|
148
|
+
*
|
|
149
|
+
* @param {string} dirPath - Path to the directory to empty.
|
|
150
|
+
* @returns {Promise<void>} Resolves when the directory has been emptied.
|
|
151
|
+
* @throws {Error} If files or subdirectories cannot be removed.
|
|
152
|
+
*/
|
|
153
|
+
async function emptyDir(dirPath) {
|
|
154
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
155
|
+
for (const entry of entries) {
|
|
156
|
+
const entryPath = path_1.default.join(dirPath, entry.name);
|
|
157
|
+
if (entry.isDirectory()) {
|
|
158
|
+
await promises_1.default.rm(entryPath, { recursive: true, force: true });
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
await promises_1.default.unlink(entryPath);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Calculates the total size (in bytes) of all files in a directory (recursive).
|
|
167
|
+
*
|
|
168
|
+
* @param {string} dirPath - Path to the directory.
|
|
169
|
+
* @returns {Promise<number>} Total size in bytes.
|
|
170
|
+
* @throws {Error} If any file stats cannot be read.
|
|
171
|
+
*/
|
|
172
|
+
async function getDirSize(dirPath) {
|
|
173
|
+
let total = 0;
|
|
174
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
175
|
+
for (const entry of entries) {
|
|
176
|
+
const entryPath = path_1.default.join(dirPath, entry.name);
|
|
177
|
+
if (entry.isDirectory()) {
|
|
178
|
+
total += await getDirSize(entryPath);
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const stat = await promises_1.default.stat(entryPath);
|
|
182
|
+
total += stat.size;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return total;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Watches a directory for file changes and calls a callback on each event.
|
|
189
|
+
*
|
|
190
|
+
* @param {string} dirPath - Directory path to watch.
|
|
191
|
+
* @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
|
|
192
|
+
* @returns {() => void} A function to stop watching the directory.
|
|
193
|
+
*/
|
|
194
|
+
function watchDir(dirPath, callback) {
|
|
195
|
+
const watcher = fs_1.default.watch(dirPath, (eventType, filename) => {
|
|
196
|
+
callback(eventType, filename);
|
|
197
|
+
});
|
|
198
|
+
return () => watcher.close();
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Finds files matching a glob pattern.
|
|
202
|
+
*
|
|
203
|
+
* @param {string} pattern - Glob pattern to match files.
|
|
204
|
+
* @param {object} [options] - Options for glob pattern matching.
|
|
205
|
+
* @param {string} [options.cwd] - Current working directory for relative patterns.
|
|
206
|
+
* @param {boolean} [options.dot=false] - Include dotfiles in matches.
|
|
207
|
+
* @param {boolean} [options.nodir=true] - Only match files, not directories.
|
|
208
|
+
* @returns {Promise<string[]>} Array of matched file paths.
|
|
209
|
+
* @throws {Error} If pattern matching fails.
|
|
210
|
+
*/
|
|
211
|
+
async function findFilesByPattern(pattern, options = {}) {
|
|
212
|
+
const defaultOptions = { nodir: true, ...options };
|
|
213
|
+
return (0, glob_1.glob)(pattern, defaultOptions);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Gets all subdirectories in a directory.
|
|
217
|
+
*
|
|
218
|
+
* @param {string} dirPath - The directory to search in.
|
|
219
|
+
* @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
|
|
220
|
+
* @returns {Promise<string[]>} Array of absolute subdirectory paths.
|
|
221
|
+
* @throws {Error} If directory cannot be read.
|
|
222
|
+
*/
|
|
223
|
+
async function getSubdirectories(dirPath, recursive = false) {
|
|
224
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
225
|
+
const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path_1.default.join(dirPath, entry.name));
|
|
226
|
+
if (recursive && dirs.length > 0) {
|
|
227
|
+
const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));
|
|
228
|
+
return [...dirs, ...nestedDirs.flat()];
|
|
229
|
+
}
|
|
230
|
+
return dirs;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Ensures a directory exists and is empty.
|
|
234
|
+
*
|
|
235
|
+
* @param {string} dirPath - Path to the directory.
|
|
236
|
+
* @returns {Promise<void>} Resolves when the directory exists and is empty.
|
|
237
|
+
* @throws {Error} If directory cannot be created or emptied.
|
|
238
|
+
*/
|
|
239
|
+
async function ensureEmptyDir(dirPath) {
|
|
240
|
+
if (await isDirectory(dirPath)) {
|
|
241
|
+
await emptyDir(dirPath);
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
try {
|
|
245
|
+
await promises_1.default.unlink(dirPath);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
// Ignore if file doesn't exist
|
|
249
|
+
if (error.code !== 'ENOENT') {
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
await ensureDir(dirPath);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Creates a temporary directory with optional auto-cleanup.
|
|
258
|
+
*
|
|
259
|
+
* @param {object} [options] - Options for the temporary directory.
|
|
260
|
+
* @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
|
|
261
|
+
* @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
|
|
262
|
+
* @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
|
|
263
|
+
* @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
|
|
264
|
+
* @throws {Error} If directory cannot be created.
|
|
265
|
+
*/
|
|
266
|
+
async function createTempDir(options = {}) {
|
|
267
|
+
const prefix = options.prefix || 'tmp-';
|
|
268
|
+
const parentDir = options.parentDir || os_1.default.tmpdir();
|
|
269
|
+
const dirName = `${prefix}${(0, crypto_1.randomBytes)(6).toString('hex')}`;
|
|
270
|
+
const tempDirPath = path_1.default.join(parentDir, dirName);
|
|
271
|
+
await ensureDir(tempDirPath);
|
|
272
|
+
const cleanup = async () => {
|
|
273
|
+
try {
|
|
274
|
+
await deleteDirRecursive(tempDirPath);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
// Ignore cleanup errors
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
if (options.cleanup) {
|
|
281
|
+
process.once('exit', () => {
|
|
282
|
+
try {
|
|
283
|
+
fs_1.default.rmSync(tempDirPath, { recursive: true, force: true });
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
// Ignore cleanup errors on exit
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
// Handle signals for better cleanup
|
|
290
|
+
['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {
|
|
291
|
+
process.once(signal, () => {
|
|
292
|
+
cleanup().then(() => process.exit());
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return { path: tempDirPath, cleanup };
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Finds the newest file in a directory.
|
|
300
|
+
*
|
|
301
|
+
* @param {string} dirPath - Directory to search.
|
|
302
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
303
|
+
* @returns {Promise<string | null>} Path to the newest file or null if no files.
|
|
304
|
+
* @throws {Error} If directory cannot be read.
|
|
305
|
+
*/
|
|
306
|
+
async function findNewestFile(dirPath, recursive = false) {
|
|
307
|
+
const files = await listFiles(dirPath, recursive);
|
|
308
|
+
if (files.length === 0)
|
|
309
|
+
return null;
|
|
310
|
+
const stats = await Promise.all(files.map(async (file) => ({
|
|
311
|
+
path: file,
|
|
312
|
+
mtime: (await promises_1.default.stat(file)).mtime
|
|
313
|
+
})));
|
|
314
|
+
return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Finds the oldest file in a directory.
|
|
318
|
+
*
|
|
319
|
+
* @param {string} dirPath - Directory to search.
|
|
320
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
321
|
+
* @returns {Promise<string | null>} Path to the oldest file or null if no files.
|
|
322
|
+
* @throws {Error} If directory cannot be read.
|
|
323
|
+
*/
|
|
324
|
+
async function findOldestFile(dirPath, recursive = false) {
|
|
325
|
+
const files = await listFiles(dirPath, recursive);
|
|
326
|
+
if (files.length === 0)
|
|
327
|
+
return null;
|
|
328
|
+
const stats = await Promise.all(files.map(async (file) => ({
|
|
329
|
+
path: file,
|
|
330
|
+
mtime: (await promises_1.default.stat(file)).mtime
|
|
331
|
+
})));
|
|
332
|
+
return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Finds files or directories in a directory matching a predicate function.
|
|
336
|
+
*
|
|
337
|
+
* @param {string} dirPath - Directory to search.
|
|
338
|
+
* @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
|
|
339
|
+
* @param {boolean} [recursive=false] - Whether to search subdirectories.
|
|
340
|
+
* @returns {Promise<string[]>} Array of matching paths.
|
|
341
|
+
* @throws {Error} If directory cannot be read.
|
|
342
|
+
*/
|
|
343
|
+
async function findInDir(dirPath, predicate, recursive = false) {
|
|
344
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
345
|
+
const results = [];
|
|
346
|
+
for (const entry of entries) {
|
|
347
|
+
const entryPath = path_1.default.join(dirPath, entry.name);
|
|
348
|
+
const stat = await promises_1.default.stat(entryPath);
|
|
349
|
+
if (await predicate(entryPath, stat)) {
|
|
350
|
+
results.push(entryPath);
|
|
351
|
+
}
|
|
352
|
+
if (recursive && entry.isDirectory()) {
|
|
353
|
+
const nestedResults = await findInDir(entryPath, predicate, true);
|
|
354
|
+
results.push(...nestedResults);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return results;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Watches a directory recursively for file changes.
|
|
361
|
+
*
|
|
362
|
+
* @param {string} dirPath - Base directory path to watch.
|
|
363
|
+
* @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
|
|
364
|
+
* @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
|
|
365
|
+
* @returns {Promise<() => void>} A function to stop watching the directory.
|
|
366
|
+
* @throws {Error} If directory cannot be watched.
|
|
367
|
+
*/
|
|
368
|
+
async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
|
|
369
|
+
// Normalize the path to ensure consistent path separators
|
|
370
|
+
const normalizedBasePath = path_1.default.normalize(dirPath);
|
|
371
|
+
// Create watchers for the base dir and all subdirectories
|
|
372
|
+
const watchers = [];
|
|
373
|
+
// Helper function to add a watcher for a directory
|
|
374
|
+
const addWatcher = (dir) => {
|
|
375
|
+
try {
|
|
376
|
+
const watcher = fs_1.default.watch(dir, (eventType, filename) => {
|
|
377
|
+
if (!filename)
|
|
378
|
+
return;
|
|
379
|
+
const fullPath = path_1.default.join(dir, filename);
|
|
380
|
+
// Make the path relative to the base directory
|
|
381
|
+
const relativePath = path_1.default.relative(normalizedBasePath, fullPath);
|
|
382
|
+
callback(eventType, relativePath);
|
|
383
|
+
// If a new directory is created, we should watch it
|
|
384
|
+
if (eventType === 'rename' && includeSubdirs) {
|
|
385
|
+
setTimeout(async () => {
|
|
386
|
+
try {
|
|
387
|
+
if (await isDirectory(fullPath)) {
|
|
388
|
+
addWatcher(fullPath);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
// Ignore errors checking newly created items
|
|
393
|
+
}
|
|
394
|
+
}, 100);
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
watchers.push(watcher);
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
// Silently ignore directories we can't watch
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
// Add watcher for the base directory
|
|
404
|
+
addWatcher(normalizedBasePath);
|
|
405
|
+
// If watching subdirectories, add watchers for all existing subdirectories
|
|
406
|
+
if (includeSubdirs) {
|
|
407
|
+
const subdirs = await getSubdirectories(normalizedBasePath, true);
|
|
408
|
+
for (const subdir of subdirs) {
|
|
409
|
+
addWatcher(subdir);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
// Return a function to close all watchers
|
|
413
|
+
return () => {
|
|
414
|
+
watchers.forEach(watcher => watcher.close());
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Gets detailed directory statistics including file count, directory count, and size.
|
|
419
|
+
*
|
|
420
|
+
* @param {string} dirPath - Path to the directory.
|
|
421
|
+
* @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
|
|
422
|
+
* @throws {Error} If directory cannot be read.
|
|
423
|
+
*/
|
|
424
|
+
async function getDirStats(dirPath) {
|
|
425
|
+
let fileCount = 0;
|
|
426
|
+
let dirCount = 0;
|
|
427
|
+
let totalSize = 0;
|
|
428
|
+
async function processDir(currentPath) {
|
|
429
|
+
const entries = await promises_1.default.readdir(currentPath, { withFileTypes: true });
|
|
430
|
+
for (const entry of entries) {
|
|
431
|
+
const entryPath = path_1.default.join(currentPath, entry.name);
|
|
432
|
+
if (entry.isDirectory()) {
|
|
433
|
+
dirCount++;
|
|
434
|
+
await processDir(entryPath);
|
|
435
|
+
}
|
|
436
|
+
else if (entry.isFile()) {
|
|
437
|
+
fileCount++;
|
|
438
|
+
const stat = await promises_1.default.stat(entryPath);
|
|
439
|
+
totalSize += stat.size;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
await processDir(dirPath);
|
|
444
|
+
return { fileCount, dirCount, totalSize };
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Walks through a directory hierarchy, calling a visitor function for each entry.
|
|
448
|
+
*
|
|
449
|
+
* @param {string} dirPath - Starting directory path.
|
|
450
|
+
* @param {object} options - Options for walking the directory.
|
|
451
|
+
* @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
|
|
452
|
+
* Function called for each file/directory. Return false to skip a directory.
|
|
453
|
+
* @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
|
|
454
|
+
* @throws {Error} If directory cannot be read.
|
|
455
|
+
*/
|
|
456
|
+
async function walkDir(dirPath, options) {
|
|
457
|
+
const traversalOrder = options.traversalOrder || 'pre';
|
|
458
|
+
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
459
|
+
for (const entry of entries) {
|
|
460
|
+
const entryPath = path_1.default.join(dirPath, entry.name);
|
|
461
|
+
const stats = await promises_1.default.stat(entryPath);
|
|
462
|
+
const entryInfo = {
|
|
463
|
+
path: entryPath,
|
|
464
|
+
name: entry.name,
|
|
465
|
+
isDirectory: entry.isDirectory(),
|
|
466
|
+
stats
|
|
467
|
+
};
|
|
468
|
+
if (entry.isDirectory()) {
|
|
469
|
+
// Pre-order: visit directory before its contents
|
|
470
|
+
if (traversalOrder === 'pre') {
|
|
471
|
+
const shouldContinue = await options.visitorFn(entryInfo);
|
|
472
|
+
// If the visitor returns false, don't recurse into this directory
|
|
473
|
+
if (shouldContinue !== false) {
|
|
474
|
+
await walkDir(entryPath, options);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
else {
|
|
478
|
+
// Post-order: visit directory after its contents
|
|
479
|
+
await walkDir(entryPath, options);
|
|
480
|
+
await options.visitorFn(entryInfo);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
// Files are always visited when encountered
|
|
485
|
+
await options.visitorFn(entryInfo);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
if (traversalOrder === 'post') {
|
|
489
|
+
// Only visit the root if this is the top-level call (not for subdirectories)
|
|
490
|
+
// But since this function is always called recursively, always visit after children
|
|
491
|
+
const stats = await promises_1.default.stat(dirPath);
|
|
492
|
+
const entryInfo = {
|
|
493
|
+
path: dirPath,
|
|
494
|
+
name: path_1.default.basename(dirPath),
|
|
495
|
+
isDirectory: true,
|
|
496
|
+
stats
|
|
497
|
+
};
|
|
498
|
+
await options.visitorFn(entryInfo);
|
|
499
|
+
}
|
|
500
|
+
}
|