@d0paminedriven/fs 10.1.0 → 12.0.0

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 (60) hide show
  1. package/dist/docs/index.d.ts +151 -0
  2. package/dist/docs/index.js +1163 -0
  3. package/dist/extract/client.d.ts +56 -0
  4. package/dist/extract/client.js +116 -0
  5. package/dist/extract/index.d.ts +66 -0
  6. package/dist/extract/index.js +620 -0
  7. package/dist/fs/index.d.ts +18 -58
  8. package/dist/fs/index.js +89 -19
  9. package/dist/fs-atomic/index.d.ts +25 -39
  10. package/dist/fs-atomic/index.js +94 -13
  11. package/dist/fs-base/index.d.ts +105 -113
  12. package/dist/fs-base/index.js +197 -12
  13. package/dist/fs-core/index.d.ts +18 -26
  14. package/dist/fs-core/index.js +43 -16
  15. package/dist/fs-fetch/index.d.ts +48 -65
  16. package/dist/fs-fetch/index.js +183 -18
  17. package/dist/fs-size/index.d.ts +15 -31
  18. package/dist/fs-size/index.js +63 -15
  19. package/dist/fs-tmp/index.d.ts +178 -195
  20. package/dist/fs-tmp/index.js +320 -17
  21. package/dist/images/index.d.ts +443 -0
  22. package/dist/images/index.js +893 -0
  23. package/dist/images/workup.d.ts +26 -0
  24. package/dist/images/workup.js +316 -0
  25. package/dist/index.d.ts +48 -22
  26. package/dist/index.js +19 -64
  27. package/dist/ld/index.d.ts +14 -16
  28. package/dist/ld/index.js +54 -6
  29. package/dist/mime/index.d.ts +301 -296
  30. package/dist/mime/index.js +348 -13
  31. package/dist/mixins/index.d.ts +30 -0
  32. package/dist/mixins/index.js +54 -0
  33. package/dist/types/index.d.ts +339 -260
  34. package/dist/types/index.js +10 -6
  35. package/dist/types/stream.d.ts +7 -9
  36. package/dist/types/stream.js +1 -1
  37. package/dist/url/index.d.ts +18 -25
  38. package/dist/url/index.js +19 -8
  39. package/dist/utils/index.d.ts +18 -26
  40. package/dist/utils/index.js +80 -7
  41. package/package.json +42 -22
  42. package/dist/chunk-4D2YBCI6.js +0 -163
  43. package/dist/chunk-5CACVZVF.js +0 -386
  44. package/dist/chunk-5H6GE5AO.js +0 -14
  45. package/dist/chunk-7QVYU63E.js +0 -7
  46. package/dist/chunk-DNR5ZI2T.js +0 -75
  47. package/dist/chunk-JZ6JNZZ6.js +0 -77
  48. package/dist/chunk-L2QMQOEJ.js +0 -366
  49. package/dist/chunk-NJHN5OE3.js +0 -33
  50. package/dist/chunk-OHKRQJZH.js +0 -82
  51. package/dist/chunk-OT5JEQKW.js +0 -139
  52. package/dist/chunk-PATMSIQK.js +0 -367
  53. package/dist/chunk-PB5A7ZFD.js +0 -79
  54. package/dist/chunk-VDKUXJE7.js +0 -240
  55. package/dist/chunk-Y5QWE4EG.js +0 -1335
  56. package/dist/chunk-YRCJWFZD.js +0 -107
  57. package/dist/image/index.d.ts +0 -182
  58. package/dist/image/index.js +0 -13
  59. package/dist/image/workup.d.ts +0 -40
  60. package/dist/image/workup.js +0 -12
@@ -1,19 +1,322 @@
1
- import {
2
- FsTmp
3
- } from "../chunk-PATMSIQK.js";
4
- import "../chunk-OHKRQJZH.js";
5
- import "../chunk-DNR5ZI2T.js";
6
- import "../chunk-5H6GE5AO.js";
7
- import "../chunk-YRCJWFZD.js";
8
- import "../chunk-VDKUXJE7.js";
9
- import "../chunk-Y5QWE4EG.js";
10
- import "../chunk-5CACVZVF.js";
11
- import "../chunk-L2QMQOEJ.js";
12
- import "../chunk-NJHN5OE3.js";
13
- import "../chunk-OT5JEQKW.js";
14
- import "../chunk-PB5A7ZFD.js";
15
- import "../chunk-7QVYU63E.js";
16
- export {
17
- FsTmp
1
+ import fsSync from "fs";
2
+ import fsAsync from "fs/promises";
3
+ import { resolve } from "path";
4
+ import { FsCore } from "../fs-core/index.js";
5
+ // src/fs-tmp/index.ts
6
+ var FsTmp = class extends FsCore {
7
+ cwd;
8
+ constructor(cwd) {
9
+ super(cwd ??= process.cwd());
10
+ this.cwd = cwd;
11
+ }
12
+ /**
13
+ * Write data to a file in the system's tmp directory
14
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
15
+ * @param data The data to write
16
+ * @param options Optional write stream options
17
+ * @returns The full path to the written file
18
+ * @example
19
+ * ```ts
20
+ * const fs = new Fs(process.cwd());
21
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
22
+ * // Or with a subdirectory:
23
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
24
+ * ```
25
+ */
26
+ writeTmp(filename, data, options) {
27
+ const fullPath = resolve(this.tmpDir, filename);
28
+ Promise.resolve(this.withWs(fullPath, data, options));
29
+ }
30
+ async writeTmpAsync(filename, data, options = {}) {
31
+ const fullPath = resolve(this.tmpDir, filename);
32
+ return await this.writeFileAsync(fullPath, data, typeof options === "object" ? {
33
+ ...options,
34
+ mode: 511
35
+ } : options);
36
+ }
37
+ async readTmpAsync(filename) {
38
+ const fullPath = resolve(this.tmpDir, filename);
39
+ if (!this.existsTmp(filename)) throw new Error(`Tmp file not found: ${filename}`);
40
+ return await fsAsync.readFile(fullPath);
41
+ }
42
+ /**
43
+ * Read a file from the tmp directory
44
+ * @param filename The filename to read (can include subdirectories)
45
+ * @returns Buffer containing the file data
46
+ * @example
47
+ * ```ts
48
+ * const fs = new Fs(process.cwd());
49
+ * const data = fs.readTmp("session-data.json");
50
+ * const parsed = JSON.parse(data.toString("utf-8"));
51
+ * ```
52
+ */
53
+ readTmp(filename) {
54
+ const fullPath = resolve(this.tmpDir, filename);
55
+ if (!this.exists(fullPath)) throw new Error(`Tmp file not found: ${filename}`);
56
+ return this.fileToBuffer(fullPath);
57
+ }
58
+ /**
59
+ * Scan the tmp directory for files matching a pattern
60
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
61
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
62
+ * @returns Array of matching file paths relative to tmp directory
63
+ * @example
64
+ * ```ts
65
+ * const fs = new Fs(process.cwd());
66
+ * // Get all img-probe files
67
+ * const imgFiles = fs.scanTmp("img-probe");
68
+ * // Get all files in tmp (non-recursive)
69
+ * const allFiles = fs.scanTmp();
70
+ * ```
71
+ */
72
+ scanTmp(pattern, options = {
73
+ recursive: false,
74
+ withFileTypes: false,
75
+ encoding: "utf-8"
76
+ }) {
77
+ const dirs = resolve(this.tmpDir);
78
+ const tmpContents = this.readDir(dirs, options);
79
+ if (!pattern) return tmpContents;
80
+ if (typeof pattern === "string") return tmpContents.filter((t) => t.includes(pattern));
81
+ return tmpContents.filter((path) => {
82
+ return pattern.test(path);
83
+ });
84
+ }
85
+ /**
86
+ * Extract specific files from tmp directory to a target location
87
+ * @param pattern Pattern to match files (e.g., "img-probe")
88
+ * @param targetDir Target directory to extract files to
89
+ * @param options Options for extraction behavior
90
+ * @returns Array of extracted file paths
91
+ * @example
92
+ * ```ts
93
+ * const fs = new Fs(process.cwd());
94
+ * // Extract all img-probe files to ./output
95
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
96
+ * // Extract with custom behavior
97
+ * fs.extractFromTmp("session-", "./sessions", {
98
+ * preserveStructure: true,
99
+ * cleanupAfter: true
100
+ * });
101
+ * ```
102
+ */
103
+ extractFromTmp(pattern, targetDir, options) {
104
+ const { preserveStructure = false, cleanupAfter = false, overwrite = true } = options ?? {};
105
+ const matchingFiles = this.scanTmp(pattern);
106
+ const extracted = [];
107
+ for (const file of matchingFiles) {
108
+ const sourcePath = resolve(this.tmpDir, file);
109
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
110
+ if (!lastSegment) continue;
111
+ const targetPath = preserveStructure ? resolve(targetDir, file) : resolve(targetDir, lastSegment);
112
+ if (this.exists(targetPath) && !overwrite) {
113
+ console.warn(`Skipping existing file: ${targetPath}`);
114
+ continue;
115
+ }
116
+ const data = this.fileToBuffer(sourcePath);
117
+ this.withWs(targetPath, data);
118
+ extracted.push(targetPath);
119
+ if (cleanupAfter) this.rmFile(sourcePath);
120
+ }
121
+ return extracted;
122
+ }
123
+ /**
124
+ * Clean up tmp files matching a pattern
125
+ * @param pattern Pattern to match files for deletion
126
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
127
+ * @returns Number of files removed
128
+ * @example
129
+ * ```ts
130
+ * const fs = new Fs(process.cwd());
131
+ * // Remove all img-probe files
132
+ * fs.cleanupTmp("img-probe");
133
+ * // Remove session files older than 1 hour
134
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
135
+ * ```
136
+ */
137
+ cleanupTmp(pattern, maxAge) {
138
+ const matchingFiles = this.scanTmp(pattern);
139
+ let removed = 0;
140
+ for (const file of matchingFiles) {
141
+ const fullPath = resolve(this.tmpDir, file);
142
+ try {
143
+ const stats = fsSync.statSync(fullPath);
144
+ if (maxAge) {
145
+ if (Date.now() - stats.mtimeMs < maxAge) continue;
146
+ }
147
+ if (stats.isDirectory()) this.rmDirSync(fullPath);
148
+ else this.rmFile(fullPath);
149
+ removed++;
150
+ } catch (err) {
151
+ console.warn(`Failed to remove tmp file ${file}:`, err);
152
+ }
153
+ }
154
+ return removed;
155
+ }
156
+ /**
157
+ * Generate a unique tmp filename with optional prefix
158
+ * @param prefix Optional prefix for the filename
159
+ * @param extension Optional file extension (without dot)
160
+ * @returns Unique filename
161
+ * @example
162
+ * ```ts
163
+ * const fs = new Fs(process.cwd());
164
+ * const filename = fs.uniqueTmpName("img-probe", "png");
165
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
166
+ * ```
167
+ */
168
+ uniqueTmpName(prefix, extension) {
169
+ const timestamp = Date.now();
170
+ const random = Math.random().toString(36).substring(2, 8);
171
+ const parts = [
172
+ prefix ?? "tmp",
173
+ timestamp,
174
+ random
175
+ ].join("-");
176
+ return extension ? `${parts}.${extension}` : parts;
177
+ }
178
+ /**
179
+ * Async generator for cleaning tmp files with batched removal
180
+ * @param pattern Pattern to match files for deletion
181
+ * @param batchSize Number of files to remove per batch (default 10)
182
+ * @yields Progress information during cleanup
183
+ * @returns Final cleanup summary
184
+ * @example
185
+ * ```ts
186
+ * const fs = new Fs(process.cwd());
187
+ * // Clean up with progress tracking
188
+ * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
189
+ * console.log(progress);
190
+ * }
191
+ * ```
192
+ */
193
+ async *cleanTmpGenerator(pattern, batchSize = 10) {
194
+ const files = this.scanTmp(pattern);
195
+ const batches = this.arrToArrOfArrs(files, batchSize);
196
+ let totalRemoved = 0;
197
+ for (const [index, batch] of batches.entries()) {
198
+ yield {
199
+ action: "removing",
200
+ batch: [...batch],
201
+ batchNumber: index + 1,
202
+ totalBatches: batches.length,
203
+ totalFound: files.length,
204
+ removed: totalRemoved
205
+ };
206
+ for (const file of batch) {
207
+ this.rmTmpFile(file);
208
+ totalRemoved++;
209
+ }
210
+ yield {
211
+ action: "batch-complete",
212
+ batchNumber: index + 1,
213
+ batchSize: batch.length,
214
+ totalRemoved,
215
+ remaining: files.length - totalRemoved
216
+ };
217
+ }
218
+ return {
219
+ action: "complete",
220
+ totalRemoved,
221
+ totalBatches: batches.length,
222
+ pattern: pattern.toString()
223
+ };
224
+ }
225
+ /**
226
+ * Async version of withWs with atomic write support and progress tracking
227
+ * @param path Target file path
228
+ * @param data Streamable data to write
229
+ * @param options Optional atomic write and abort signal
230
+ * @returns Promise with path and bytes written
231
+ * @example
232
+ * ```ts
233
+ * const fs = new Fs(process.cwd());
234
+ * // Simple async write
235
+ * const result = await fs.asyncWithWs("output.txt", "Hello World");
236
+ * console.log(`Wrote ${result.bytes} bytes to ${result.path}`);
237
+ *
238
+ * // Atomic write with temp file
239
+ * const { path, bytes } = await fs.asyncWithWs(
240
+ * "critical-data.json",
241
+ * JSON.stringify(data),
242
+ * { atomic: true }
243
+ * );
244
+ * ```
245
+ */
246
+ async asyncWithWs(path, data, options) {
247
+ const { atomic = false, signal: _signal = AbortSignal } = options ?? {};
248
+ let bytes = 0;
249
+ if (!atomic) try {
250
+ if (/\//g.test(path)) return this.generateDirIfDNETmp(this.pathHandler(path), { recursive: true });
251
+ else return path;
252
+ } catch (error) {
253
+ console.error(`[asyncWithWs non-atomic error]: `.concat(error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)));
254
+ } finally {
255
+ const readable = this.toReadable(data);
256
+ const chunks = [];
257
+ for await (const chunk of readable) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
258
+ const buffer = Buffer.concat(chunks);
259
+ try {
260
+ this.withWs(path, buffer);
261
+ } catch (err) {
262
+ console.error(err);
263
+ } finally {
264
+ return {
265
+ path,
266
+ bytes: buffer.length
267
+ };
268
+ }
269
+ }
270
+ let tmpName;
271
+ try {
272
+ if (/\//g.test(path)) this.generateDirIfDNETmp(this.pathHandler(path), { recursive: true });
273
+ tmpName = this.uniqueTmpName("atomic", "tmp");
274
+ } catch (error) {
275
+ console.error(`[asyncWithWs atomic setup error]: `.concat(error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)));
276
+ if (tmpName) try {
277
+ this.rmTmpFile(tmpName);
278
+ } catch (err) {
279
+ console.error(err);
280
+ }
281
+ } finally {
282
+ if (tmpName) {
283
+ let newPath = null;
284
+ let newBytes = 0;
285
+ const readable = this.toReadable(data);
286
+ const chunks = [];
287
+ for await (const chunk of readable) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
288
+ const buffer = Buffer.concat(chunks);
289
+ bytes = buffer.length;
290
+ try {
291
+ await this.writeTmpAsync(tmpName, buffer.toString());
292
+ const tmpPath = resolve(this.tmpDir, tmpName);
293
+ const finalPath = resolve(this.cwd, path);
294
+ await fsAsync.rename(tmpPath, finalPath);
295
+ newPath = path;
296
+ newBytes = bytes;
297
+ } catch (err) {
298
+ console.error(`[asyncWithWs atomic rename error]:`, err);
299
+ if (this.existsTmp(tmpName)) try {
300
+ this.rmTmpFile(tmpName);
301
+ } catch (err) {
302
+ console.error(err);
303
+ }
304
+ throw err;
305
+ }
306
+ return {
307
+ path,
308
+ bytes,
309
+ newPath,
310
+ newBytes
311
+ };
312
+ }
313
+ }
314
+ return {
315
+ path,
316
+ bytes: 0
317
+ };
318
+ }
18
319
  };
320
+ export { FsTmp };
321
+
19
322
  //# sourceMappingURL=index.js.map