@d0paminedriven/fs 4.1.0 → 6.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.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @d0paminedriven/fs
2
+
3
+ > *“Don’t sweat the small stuff; just write your damn files.”*
4
+
5
+ Let's be real, you likely already have a project manager breathing down your neck for updates on the hour, JIRA ticket blues bringing you down, Teams/Slack notification pings plaguing your dreams, the "hey, got five minutes?" guy breaking your flow state on the daily, and nth other pressing issues on your mind mid-development.
6
+
7
+ These situations are all annoying af, which is why this package seamlessly ensures that targeted output paths exist for you (if they don't exist yet, they will before your file is written). Whether you're using `writeFileAsync`, `fetchRemoteWriteLocalLargeFiles`, or `withWs`, this package has you covered no matter how deep your targeted output paths go. Unfortunately, this package *can't* help with that pesky PM or that flow-breaking co-worker (yet--PRs welcome).
8
+
9
+ Want to grab some remote files? Throw any file size its way — no problemo — just use the `fetchRemoteWriteLocalLargeFiles` method. (Proceed with caution in the >=gigabyte range. If your setup can handle it, then by all means.)
10
+
11
+ ---
12
+
13
+ ## 🚀 Quickstart
14
+
15
+ ```ts
16
+ import { Fs } from "@d0paminedriven/fs";
17
+
18
+ // Set your cwd (project root recommended)
19
+ const fs = new Fs(process.cwd());
20
+
21
+ /** Write to a nested file path (no mkdirp needed) */
22
+ await fs.writeFileAsync("public/assets/images/foo/bar.jpg", myImageBuffer);
23
+ // No error, no “does this folder exist?”, no drama
24
+
25
+ /** Fetch and save a massive remote asset */
26
+ await fs.fetchRemoteWriteLocalLargeFiles(
27
+ "https://cdn.example.com/big-model.glb",
28
+ "public/models/my-big-model"
29
+ );
30
+ // Handles directories, streams file to disk, and never blows up your RAM
31
+
32
+ /** Read every file in a directory */
33
+ const files = fs.readDir("public/assets/images", { recursive: true });
34
+
35
+ /** Unlink a file (with existence check) */
36
+ await fs.unlink("public/assets/old/unused.txt");
37
+
38
+ /** Need a wait utility for your script? */
39
+ await fs.wait(2000); // waits 2 seconds
40
+
41
+ /** Get the MIME type for any file by extension */
42
+ const mime = fs.getMimeTypeForPath("foo.png"); // "image/png"
43
+ ```
44
+
45
+ ---
46
+
47
+ ## 🍳 Recipes / Real-World Scripts
48
+
49
+ Need to audit or analyze files, generate a TypeScript object from your assets, or automate asset metadata?
50
+ Here’s a dead-simple pattern to iterate off of:
51
+
52
+ ```ts
53
+
54
+ const files = fs.readDir("public/assets/images", { recursive: true });
55
+
56
+ /** Map those files to a typescript object with file names as keys + corresponding file sizes as values */
57
+ const arr = Array.of<[string, number]>();
58
+
59
+ function generateTsObjOfFileSizes(withExtensions = true) {
60
+ try {
61
+ files.forEach(function (file) {
62
+ const size = fs.fileSizeMb(`public/assets/images/${file}`);
63
+ if (withExtensions === false) {
64
+ arr.push([file.split(/\./g)[0] ?? file, size]);
65
+ } else {
66
+ arr.push([file, size]);
67
+ }
68
+ });
69
+ } catch (err) {
70
+ if (err instanceof Error) throw new Error(err.message);
71
+ else console.error(`generateTsFileOfFileSizes`, err);
72
+ } finally {
73
+ const tupleArrToObj = Object.fromEntries(arr);
74
+ fs.withWs(
75
+ `src/utils/file-sizes.ts`,
76
+ `export const publicAssetsImagesFileSizesMb = ${JSON.stringify(tupleArrToObj, null, 2)} as const;`
77
+ );
78
+ }
79
+ }
80
+
81
+ generateTsObjOfFileSizes();
82
+
83
+ ```
84
+
85
+ *This outputs a TypeScript object you can use for dashboards, asset analytics, or CI/CD checks:*
86
+
87
+ ```ts
88
+ export const fileSizesInMb = {
89
+ "chess-atb.png": 1.1277456283569336,
90
+ "elegant-stone-tiles-albedo.png": 53.93040370941162,
91
+ "port-40.avif": 1.7613801956176758,
92
+ "saeukkang.usdz": 3.6647157669067383
93
+ } as const;
94
+ ```
95
+ <small>ⓘ assets used were pooled from repos across github via the `fetchRemoteWriteLocalLargeFiles` method</small>
96
+
97
+ <br>
98
+
99
+ ---
100
+
101
+ |npm |downloads| github|
102
+ |:----:|:----:|:------:|
103
+ | [![npm](https://img.shields.io/npm/v/@d0paminedriven/fs?color=blue)](https://www.npmjs.com/package/@d0paminedriven/fs) | [![npm](https://img.shields.io/npm/dm/@d0paminedriven/fs)](https://www.npmjs.com/package/@d0paminedriven/fs) | <a style="fill:white;" href="https://github.com/DopamineDriven/d0paminedriven/tree/master/packages/fs"><svg height="24" aria-hidden="true" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"><path d="M12 1C5.9225 1 1 5.9225 1 12C1 16.8675 4.14875 20.9787 8.52125 22.4362C9.07125 22.5325 9.2775 22.2025 9.2775 21.9137C9.2775 21.6525 9.26375 20.7862 9.26375 19.865C6.5 20.3737 5.785 19.1912 5.565 18.5725C5.44125 18.2562 4.905 17.28 4.4375 17.0187C4.0525 16.8125 3.5025 16.3037 4.42375 16.29C5.29 16.2762 5.90875 17.0875 6.115 17.4175C7.105 19.0812 8.68625 18.6137 9.31875 18.325C9.415 17.61 9.70375 17.1287 10.02 16.8537C7.5725 16.5787 5.015 15.63 5.015 11.4225C5.015 10.2262 5.44125 9.23625 6.1425 8.46625C6.0325 8.19125 5.6475 7.06375 6.2525 5.55125C6.2525 5.55125 7.17375 5.2625 9.2775 6.67875C10.1575 6.43125 11.0925 6.3075 12.0275 6.3075C12.9625 6.3075 13.8975 6.43125 14.7775 6.67875C16.8813 5.24875 17.8025 5.55125 17.8025 5.55125C18.4075 7.06375 18.0225 8.19125 17.9125 8.46625C18.6138 9.23625 19.04 10.2125 19.04 11.4225C19.04 15.6437 16.4688 16.5787 14.0213 16.8537C14.42 17.1975 14.7638 17.8575 14.7638 18.8887C14.7638 20.36 14.75 21.5425 14.75 21.9137C14.75 22.2025 14.9563 22.5462 15.5063 22.4362C19.8513 20.9787 23 16.8537 23 12C23 5.9225 18.0775 1 12 1Z"></path></svg></a>
104
+
105
+ ---
@@ -0,0 +1,7 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ export {
5
+ __name
6
+ };
7
+ //# sourceMappingURL=chunk-7QVYU63E.js.map
@@ -0,0 +1,161 @@
1
+ import {
2
+ UrlService
3
+ } from "./chunk-XHN56MDK.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/mime/index.ts
9
+ var extMimeMap = {
10
+ aac: ["audio/aac"],
11
+ abw: ["application/x-abiword"],
12
+ aces: ["image/aces"],
13
+ apng: ["image/apng"],
14
+ arc: ["application/x-freearc"],
15
+ avci: ["image/avci"],
16
+ avif: ["image/avif"],
17
+ avi: ["video/x-msvideo"],
18
+ azw: ["application/vnd.amazon.ebook"],
19
+ bin: ["application/octet-stream"],
20
+ bmp: ["image/bmp"],
21
+ bz: ["application/x-bzip"],
22
+ bz2: ["application/x-bzip2"],
23
+ cda: ["application/x-cdf"],
24
+ cjs: ["application/node", "text/javascript"],
25
+ csh: ["application/x-csh"],
26
+ css: ["text/css"],
27
+ csv: ["text/csv"],
28
+ doc: ["application/msword"],
29
+ docx: [
30
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
31
+ ],
32
+ dpx: ["image/dpx"],
33
+ emf: ["image/emf"],
34
+ eot: ["application/vnd.ms-fontobject"],
35
+ epub: ["application/epub+zip"],
36
+ gif: ["image/gif"],
37
+ glb: ["model/gltf-binary"],
38
+ gltf: ["model/gltf+json"],
39
+ gz: ["application/x-gzip", "application/gzip"],
40
+ hjif: ["haptics/hjif"],
41
+ hmpg: ["haptics/hmpg"],
42
+ htm: ["text/html"],
43
+ html: ["text/html"],
44
+ ico: ["image/vnd.microsoft.icon"],
45
+ ics: ["text/calendar"],
46
+ ivs: ["haptics/ivs"],
47
+ jar: ["application/java-archive"],
48
+ jpeg: ["image/jpeg"],
49
+ jpg: ["image/jpeg"],
50
+ js: ["application/node", "text/javascript"],
51
+ json: ["application/json"],
52
+ jsonld: ["application/ld+json"],
53
+ ktx: ["image/ktx"],
54
+ ktx2: ["image/ktx2"],
55
+ m3u8: ["application/vnd.apple.mpegurl"],
56
+ m4a: ["audio/mp4"],
57
+ m4v: ["video/mp4"],
58
+ md: ["text/markdown"],
59
+ mdx: ["application/x-mdx"],
60
+ mid: ["audio/midi"],
61
+ midi: ["audio/x-midi"],
62
+ mjs: ["text/javascript"],
63
+ mp3: ["audio/mpeg"],
64
+ mp4: ["video/mp4"],
65
+ mpeg: ["video/mpeg"],
66
+ mpkg: ["application/vnd.apple.installer+xml"],
67
+ ndjson: ["application/x-ndjson"],
68
+ obj: ["application/octet-stream", "text/plain", "model/obj"],
69
+ odp: ["application/vnd.oasis.opendocument.presentation"],
70
+ ods: ["application/vnd.oasis.opendocument.spreadsheet"],
71
+ odt: ["application/vnd.oasis.opendocument.text"],
72
+ oga: ["audio/ogg"],
73
+ ogg: ["audio/ogg"],
74
+ ogv: ["video/ogg"],
75
+ ogx: ["application/ogg"],
76
+ opus: ["audio/ogg"],
77
+ otf: ["font/otf"],
78
+ png: ["image/png"],
79
+ pdf: ["application/pdf"],
80
+ php: ["application/x-httpd-php"],
81
+ pkpass: ["application/vnd.apple.pkpass"],
82
+ ppt: ["application/vnd.ms-powerpoint"],
83
+ pptx: [
84
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
85
+ ],
86
+ py: ["text/x-python"],
87
+ pyc: ["application/x-python-code"],
88
+ rar: ["application/vnd.rar"],
89
+ rtf: ["application/rtf"],
90
+ sh: ["application/x-sh"],
91
+ sql: ["application/sql"],
92
+ svg: ["image/svg+xml"],
93
+ tar: ["application/x-tar"],
94
+ tif: ["image/tiff"],
95
+ tiff: ["image/tiff"],
96
+ toml: ["application/toml"],
97
+ ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
98
+ ttf: ["application/font-sfnt", "font/ttf"],
99
+ txt: ["text/plain"],
100
+ usdz: ["model/vnd.usdz+zip"],
101
+ vsd: ["application/vnd.visio"],
102
+ vtt: ["text/vtt"],
103
+ wasm: ["application/wasm"],
104
+ wav: ["audio/wav"],
105
+ weba: ["video/webm"],
106
+ webp: ["image/webp"],
107
+ woff: ["font/woff"],
108
+ woff2: ["font/woff2"],
109
+ xhtml: ["application/xhtml+xml"],
110
+ xls: ["application/vnd.ms-excel"],
111
+ xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
112
+ xml: ["application/xml"],
113
+ xul: ["application/vnd.mozilla.xul+xml"],
114
+ yaml: ["application/yaml"],
115
+ yml: ["application/yaml"],
116
+ zip: ["application/zip", "application/x-zip-compressed"],
117
+ "3gp": ["video/3gpp"],
118
+ "3g2": ["video/3gpp2"],
119
+ "7z": ["application/x-7z-compressed"]
120
+ };
121
+ var MimeService = class extends UrlService {
122
+ static {
123
+ __name(this, "MimeService");
124
+ }
125
+ constructor() {
126
+ super();
127
+ }
128
+ mimeTypeObj = extMimeMap;
129
+ assetType(url) {
130
+ const parsed = this.parseUrl(url);
131
+ if (!parsed) return void 0;
132
+ const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
133
+ return ext && ext in this.mimeTypeObj ? ext : void 0;
134
+ }
135
+ getMimes(ext) {
136
+ return this.mimeTypeObj[ext];
137
+ }
138
+ getMimeFor(ext, opts) {
139
+ const mimes = this.getMimes(ext);
140
+ if (mimes.length === 1) return mimes[0];
141
+ if (opts?.type) {
142
+ const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
143
+ return found ?? mimes[0];
144
+ }
145
+ return mimes[0];
146
+ }
147
+ isMimeFor(ext, mime) {
148
+ return this.getMimes(ext).find((s) => s === mime);
149
+ }
150
+ getMimeTypeForPath(path, opts) {
151
+ const ext = this.assetType(path);
152
+ if (!ext) return "application/octet-stream";
153
+ return this.getMimeFor(ext, opts);
154
+ }
155
+ };
156
+
157
+ export {
158
+ extMimeMap,
159
+ MimeService
160
+ };
161
+ //# sourceMappingURL=chunk-EHOBCDHE.js.map
@@ -0,0 +1,328 @@
1
+ import {
2
+ MimeService
3
+ } from "./chunk-EHOBCDHE.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs/index.ts
9
+ import { execSync } from "child_process";
10
+ import fsSync from "fs";
11
+ import fsAsync from "fs/promises";
12
+ import { join, relative, resolve } from "path";
13
+ import * as dotenv from "dotenv";
14
+ import expand from "dotenv-expand";
15
+ import sharp from "sharp";
16
+ dotenv.config();
17
+ var Fs = class extends MimeService {
18
+ constructor(cwd) {
19
+ super();
20
+ this.cwd = cwd;
21
+ }
22
+ static {
23
+ __name(this, "Fs");
24
+ }
25
+ get myEnv() {
26
+ return dotenv.config({ processEnv: {} });
27
+ }
28
+ parseDotEnv() {
29
+ return expand.expand(this.myEnv);
30
+ }
31
+ exists(target) {
32
+ if (!/\//gm.test(target))
33
+ return fsSync.existsSync(resolve(join(this.cwd, target)));
34
+ return fsSync.existsSync(relative(this.cwd ?? process.cwd(), target));
35
+ }
36
+ wait(ms) {
37
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
38
+ }
39
+ handleBuffStrArrUnion(arr) {
40
+ return arr.map(
41
+ (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
42
+ );
43
+ }
44
+ isRootPathTargeted(path) {
45
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
46
+ return true;
47
+ } else return false;
48
+ }
49
+ readDir(path, options) {
50
+ if (this.isRootPathTargeted(path)) {
51
+ return this.handleBuffStrArrUnion(
52
+ fsSync.readdirSync(resolve(join(this.cwd, "./")), options)
53
+ );
54
+ } else {
55
+ return this.handleBuffStrArrUnion(
56
+ fsSync.readdirSync(
57
+ relative(this.cwd ??= process.cwd(), path),
58
+ options
59
+ )
60
+ );
61
+ }
62
+ }
63
+ executeCommand = /* @__PURE__ */ __name(({
64
+ command,
65
+ ...options
66
+ }) => Buffer.from(execSync(command, { ...options }).toJSON().data).toString(
67
+ "utf-8"
68
+ ), "executeCommand");
69
+ existsSync(path) {
70
+ if (!/\//gm.test(path))
71
+ return fsSync.existsSync(resolve(join(this.cwd, path)));
72
+ return fsSync.existsSync(relative(this.cwd, path));
73
+ }
74
+ pathHandler(path) {
75
+ return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
76
+ }
77
+ mkdirSync(path, options) {
78
+ return fsSync.mkdirSync(relative(this.cwd, path), options);
79
+ }
80
+ fileSizeMb(path) {
81
+ return fsSync.statSync(relative(this.cwd, path)).size / (1024 * 1024);
82
+ }
83
+ generateDirIfDNE(path, options) {
84
+ const doesExist = this.existsSync(path);
85
+ if (doesExist === true) return;
86
+ else {
87
+ return this.mkdirSync(path, options);
88
+ }
89
+ }
90
+ withWs(path, data, options) {
91
+ try {
92
+ if (/\//g.test(path) === true) {
93
+ return this.generateDirIfDNE(this.pathHandler(path), {
94
+ recursive: true
95
+ });
96
+ } else return path;
97
+ } catch (error) {
98
+ console.error(
99
+ `[withWs error]: `.concat(
100
+ typeof error === "string" ? error : JSON.stringify(error, null, 2)
101
+ )
102
+ );
103
+ } finally {
104
+ return fsSync.createWriteStream(
105
+ relative(this.cwd ?? process.cwd(), path),
106
+ typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
107
+ ).write(Buffer.from(Buffer.from(data).toJSON().data));
108
+ }
109
+ }
110
+ writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
111
+ try {
112
+ if (/\//g.test(path) === true)
113
+ return this.generateDirIfDNE(this.pathHandler(path), {
114
+ recursive: true
115
+ });
116
+ else return path;
117
+ } catch (error) {
118
+ console.error(
119
+ `[writeFileAsync error]: `.concat(
120
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
121
+ )
122
+ );
123
+ } finally {
124
+ return await fsAsync.writeFile(
125
+ relative(this.cwd ?? process.cwd(), path),
126
+ Buffer.from(Buffer.from(data).toJSON().data),
127
+ options
128
+ );
129
+ }
130
+ }, "writeFileAsync");
131
+ dirExists(dir) {
132
+ const resolved = relative(this.cwd, dir);
133
+ try {
134
+ return fsSync.statSync(resolved).isDirectory();
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+ async unlink(path) {
140
+ if (this.existsSync(path)) {
141
+ return await fsAsync.unlink(relative(this.cwd, path));
142
+ } else {
143
+ throw new Error(`input path ${path} does not exist`);
144
+ }
145
+ }
146
+ rmFile(filePath) {
147
+ if (this.existsSync(filePath)) {
148
+ if (this.isRootPathTargeted(filePath)) {
149
+ fsSync.rmSync(resolve(join(this.cwd, filePath)));
150
+ } else fsSync.rmSync(resolve(this.cwd, filePath));
151
+ } else return;
152
+ }
153
+ async rmdir(dir, options) {
154
+ const resolved = relative(this.cwd, dir);
155
+ if (this.dirExists(dir)) {
156
+ return fsAsync.rmdir(relative(this.cwd, dir), options);
157
+ } else {
158
+ throw new Error(`directory ${resolved} does not exist`);
159
+ }
160
+ }
161
+ rmDirSync(dir) {
162
+ const resolved = resolve(this.cwd, dir);
163
+ if (this.dirExists(dir)) {
164
+ return fsSync.rm(resolved, { force: true, recursive: true }, (err) => {
165
+ if (err?.message) {
166
+ console.error(err?.message);
167
+ }
168
+ });
169
+ } else {
170
+ throw new Error(`directory ${resolved} does not exist`);
171
+ }
172
+ }
173
+ fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
174
+ fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
175
+ ), "fileToBuffer");
176
+ dirContainsDir(readDir, targetDir, options) {
177
+ return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
178
+ }
179
+ async assetToBuffer(path) {
180
+ const [fetcher] = await Promise.all([
181
+ fetch(path).then((t) => t.arrayBuffer())
182
+ ]);
183
+ const mime = this.getMimeTypeForPath(path);
184
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
185
+ const extension = this.assetType(path) ?? "txt";
186
+ return {
187
+ b64encodedData,
188
+ extension
189
+ };
190
+ }
191
+ async assetToBufferView(path) {
192
+ const response = await fetch(path);
193
+ if (!response.ok) {
194
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
195
+ }
196
+ const reader = response.body?.getReader();
197
+ if (reader) {
198
+ const chunks = Array.of();
199
+ while (true) {
200
+ const { done, value } = await reader.read();
201
+ if (done) break;
202
+ if (value) chunks.push(value);
203
+ }
204
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
205
+ const completeBuffer = new Uint8Array(totalLength);
206
+ let offset = 0;
207
+ for (const chunk of chunks) {
208
+ completeBuffer.set(chunk, offset);
209
+ offset += chunk.length;
210
+ }
211
+ const mime = this.getMimeTypeForPath(path);
212
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
213
+ const extension = this.assetType(path);
214
+ return { b64encodedData, extension };
215
+ } else {
216
+ const arrayBuffer = await response.arrayBuffer();
217
+ const mime = this.getMimeTypeForPath(path);
218
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
219
+ const extension = this.assetType(path);
220
+ return { b64encodedData, extension };
221
+ }
222
+ }
223
+ formatHelper(f) {
224
+ if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
225
+ const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
226
+ return formatting;
227
+ } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
228
+ }
229
+ cleanDataUrl(props) {
230
+ return props.replace(
231
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
232
+ ""
233
+ );
234
+ }
235
+ /**
236
+ *
237
+ * @param inputUrl remote url to fetch data from
238
+ * @param outputPath desired output path relative to the cwd
239
+ * @param useDetectedExtension optional, defaults to true
240
+ *
241
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
242
+ *
243
+ * 🚫 'public/assets/image-1'
244
+ *
245
+ * ✅ 'public/assets/image-1.png'
246
+ */
247
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
248
+ try {
249
+ const result = await this.assetToBufferView(inputUrl);
250
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
251
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
252
+ if (/\./g.test(formattedPath) === false) {
253
+ throw new Error(
254
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
255
+ );
256
+ }
257
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
258
+ } catch (err) {
259
+ return console.error(err);
260
+ }
261
+ }
262
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
263
+ const MAX_SAFE_IN_MEMORY_MB = 100;
264
+ try {
265
+ const head = await fetch(inputUrl, { method: "HEAD" });
266
+ const contentLength = head.headers.get("content-length");
267
+ const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
268
+ const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
269
+ this.generateDirIfDNE(this.pathHandler(formattedPath), {
270
+ recursive: true
271
+ });
272
+ if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
273
+ const res = await fetch(inputUrl);
274
+ if (!res.ok || !res.body) {
275
+ throw new Error(`Failed to fetch asset: ${res.statusText}`);
276
+ }
277
+ const writeStream = fsSync.createWriteStream(
278
+ relative(this.cwd ?? process.cwd(), formattedPath)
279
+ );
280
+ const reader = res.body.getReader();
281
+ const pump = /* @__PURE__ */ __name(async () => {
282
+ while (true) {
283
+ const { done, value } = await reader.read();
284
+ if (done) break;
285
+ writeStream.write(value);
286
+ }
287
+ writeStream.end();
288
+ }, "pump");
289
+ await pump();
290
+ return;
291
+ }
292
+ const result = await this.assetToBufferView(inputUrl);
293
+ const cleanedData = this.cleanDataUrl(result.b64encodedData);
294
+ this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
295
+ } catch (err) {
296
+ console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
297
+ }
298
+ }
299
+ /**
300
+ *
301
+ * @access package-private
302
+ *
303
+ * work in progress, for internal package maintainer use only
304
+ */
305
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
306
+ // https://www.npmjs.com/package/fluent-ffmpeg
307
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
308
+ async imageTransform({
309
+ format,
310
+ target,
311
+ quality = 80,
312
+ tint,
313
+ resize
314
+ }) {
315
+ if (tint && !resize) {
316
+ return await sharp(target).toFormat(format, { quality }).tint(tint).toBuffer();
317
+ } else if (!tint && resize) {
318
+ return await sharp(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
319
+ } else if (tint && resize) {
320
+ return await sharp(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
321
+ } else return await sharp(target).toFormat(format, { quality }).toBuffer();
322
+ }
323
+ };
324
+
325
+ export {
326
+ Fs
327
+ };
328
+ //# sourceMappingURL=chunk-KZWE4E4I.js.map