@d0paminedriven/fs 1.0.0 → 3.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/dist/fs/index.cjs CHANGED
@@ -130,6 +130,7 @@ var import_promises = __toESM(require("fs/promises"), 1);
130
130
  var import_path = require("path");
131
131
  var dotenv = __toESM(require("dotenv"), 1);
132
132
  var import_dotenv_expand = __toESM(require_main(), 1);
133
+ var import_sharp = __toESM(require("sharp"), 1);
133
134
  dotenv.config();
134
135
  var Fs = class {
135
136
  constructor(cwd) {
@@ -149,20 +150,20 @@ var Fs = class {
149
150
  );
150
151
  }
151
152
  excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
152
- const resolve = Object.fromEntries(
153
+ const resolve2 = Object.fromEntries(
153
154
  Object.entries(obj).map(([key, val]) => {
154
155
  if (props.includes(key)) {
155
156
  return ["omit", "omit"];
156
157
  } else return [key, val];
157
158
  }).filter(([t, _v]) => /omit/.test(t) === false)
158
159
  );
159
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
160
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
160
161
  }, "excludeTargeted");
161
162
  includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
162
- const resolve = Object.fromEntries(
163
+ const resolve2 = Object.fromEntries(
163
164
  props.map((val) => this.extractTuple(obj, val))
164
165
  );
165
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
166
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
166
167
  }, "includeTargeted");
167
168
  get myEnv() {
168
169
  return dotenv.config({ processEnv: {} });
@@ -186,6 +187,7 @@ var Fs = class {
186
187
  return { ...this.omitFields(targ, keys) };
187
188
  }
188
189
  exists(target) {
190
+ if (!/\//gm.test(target)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
189
191
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
190
192
  }
191
193
  arrToArrOfArrs = /* @__PURE__ */ __name(({
@@ -193,7 +195,7 @@ var Fs = class {
193
195
  arrOfArrsAggregator = Array.of(),
194
196
  interval
195
197
  }) => new Promise(
196
- (resolve, _reject) => resolve(
198
+ (resolve2, _reject) => resolve2(
197
199
  ((interval2) => {
198
200
  for (let i = 0; i <= arrToFragment.length; i++) {
199
201
  if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
@@ -205,7 +207,7 @@ var Fs = class {
205
207
  )
206
208
  ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
207
209
  wait(ms) {
208
- return new Promise((resolve) => setTimeout(resolve, ms));
210
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
209
211
  }
210
212
  countsSorter = /* @__PURE__ */ __name(({
211
213
  counter,
@@ -223,8 +225,15 @@ var Fs = class {
223
225
  (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
224
226
  );
225
227
  }
228
+ isRootPathTargeted(path) {
229
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
230
+ return true;
231
+ } else return false;
232
+ }
226
233
  readDir(path, options) {
227
- return this.handleBuffStrArrUnion(
234
+ if (this.isRootPathTargeted(path)) {
235
+ return this.handleBuffStrArrUnion(import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), options));
236
+ } else return this.handleBuffStrArrUnion(
228
237
  import_fs.default.readdirSync(
229
238
  (0, import_path.relative)(this.cwd ??= process.cwd(), path),
230
239
  options
@@ -234,9 +243,7 @@ var Fs = class {
234
243
  executeCommand = /* @__PURE__ */ __name(({
235
244
  command,
236
245
  ...options
237
- }) => Buffer.from(
238
- Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data)
239
- ).toString("utf-8"), "executeCommand");
246
+ }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString("utf-8"), "executeCommand");
240
247
  fileGenTimestamp(d) {
241
248
  const date = d.toISOString();
242
249
  return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
@@ -248,6 +255,7 @@ var Fs = class {
248
255
  return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
249
256
  }
250
257
  existsSync(path) {
258
+ if (!/\//gm.test(path)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, path)));
251
259
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), path));
252
260
  }
253
261
  pathHandler(path) {
@@ -310,18 +318,11 @@ var Fs = class {
310
318
  }
311
319
  }, "writeFileAsync");
312
320
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
313
- Buffer.from(
314
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
315
- )
321
+ import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
316
322
  ), "fileToBuffer");
317
323
  dirContainsDir(readDir, targetDir, options) {
318
324
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
319
325
  }
320
- parseJsonBuffer(p) {
321
- return JSON.parse(
322
- Buffer.from(Buffer.from(p).toJSON().data).toString("utf-8")
323
- );
324
- }
325
326
  /* begin url */
326
327
  isServerSide() {
327
328
  return typeof window === "undefined";
@@ -358,11 +359,21 @@ var Fs = class {
358
359
  };
359
360
  }
360
361
  /* end url */
362
+ get cjsVal() {
363
+ return ["application/node", "text/javascript"].reduce(
364
+ (union) => union
365
+ );
366
+ }
361
367
  get gzVal() {
362
368
  return ["application/x-gzip", "application/gzip"].reduce(
363
369
  (union) => union
364
370
  );
365
371
  }
372
+ get jsVal() {
373
+ return ["application/node", "text/javascript"].reduce(
374
+ (union) => union
375
+ );
376
+ }
366
377
  get objVal() {
367
378
  return ["application/octet-stream", "text/plain", "model/obj"].reduce((union) => union);
368
379
  }
@@ -381,8 +392,10 @@ var Fs = class {
381
392
  return {
382
393
  aac: "audio/aac",
383
394
  abw: "application/x-abiword",
395
+ aces: "image/aces",
384
396
  apng: "image/apng",
385
397
  arc: "application/x-freearc",
398
+ avci: "image/avci",
386
399
  avif: "image/avif",
387
400
  avi: "video/x-msvideo",
388
401
  azw: "application/vnd.amazon.ebook",
@@ -391,26 +404,31 @@ var Fs = class {
391
404
  bz: "application/x-bzip",
392
405
  bz2: "application/x-bzip2",
393
406
  cda: "application/x-cdf",
394
- cjs: "application/javascript",
407
+ cjs: this.cjsVal,
395
408
  csh: "application/x-csh",
396
409
  css: "text/css",
397
410
  csv: "text/csv",
398
411
  doc: "application/msword",
399
412
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
413
+ dpx: "image/dpx",
414
+ emf: "image/emf",
400
415
  eot: "application/vnd.ms-fontobject",
401
416
  epub: "application/epub+zip",
402
417
  gif: "image/gif",
403
418
  glb: "model/gltf-binary",
404
419
  gltf: "model/gltf+json",
405
420
  gz: this.gzVal,
421
+ hjif: "haptics/hjif",
422
+ hmpg: "haptics/hmpg",
406
423
  htm: "text/html",
407
424
  html: "text/html",
408
425
  ico: "image/vnd.microsoft.icon",
409
426
  ics: "text/calendar",
427
+ ivs: "haptics/ivs",
410
428
  jar: "application/java-archive",
411
429
  jpeg: "image/jpeg",
412
430
  jpg: "image/jpeg",
413
- js: "text/javascript",
431
+ js: this.jsVal,
414
432
  json: "application/json",
415
433
  jsonld: "application/ld+json",
416
434
  m3u8: "application/vnd.apple.mpegurl",
@@ -447,13 +465,16 @@ var Fs = class {
447
465
  rar: "application/vnd.rar",
448
466
  rtf: "application/rtf",
449
467
  sh: "application/x-sh",
468
+ sql: "application/sql",
450
469
  svg: "image/svg+xml",
451
470
  tar: "application/x-tar",
452
471
  tif: "image/tiff",
453
472
  tiff: "image/tiff",
473
+ toml: "application/toml",
454
474
  ts: this.tsVal,
455
475
  ttf: this.ttfVal,
456
476
  txt: "text/plain",
477
+ usdz: "model/vnd.usdz+zip",
457
478
  vsd: "application/vnd.visio",
458
479
  vtt: "text/vtt",
459
480
  wasm: "application/wasm",
@@ -467,6 +488,8 @@ var Fs = class {
467
488
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
468
489
  xml: "application/xml",
469
490
  xul: "application/vnd.mozilla.xul+xml",
491
+ yaml: "application/yaml",
492
+ yml: "application/yaml",
470
493
  zip: this.zipVal,
471
494
  "3gp": "video/3gpp",
472
495
  "3g2": "video/3gpp2",
@@ -495,6 +518,12 @@ var Fs = class {
495
518
  };
496
519
  }
497
520
  async assetToBufferView(path) {
521
+ const p = this.parseUrl(path);
522
+ const doesUrlPathContainFileExtension = /\./g.test(
523
+ p.pathname.split(/\//g).reverse()[0] ?? ""
524
+ );
525
+ if (doesUrlPathContainFileExtension === false)
526
+ console.warn(`no file extension detected in input url ${path}, attempting fetch`);
498
527
  const response = await fetch(path);
499
528
  if (!response.ok) {
500
529
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
@@ -571,7 +600,7 @@ var Fs = class {
571
600
  {
572
601
  const sliceSize = 512;
573
602
  const typeMatch = b64Data.match(
574
- /^data:(image|application|video|text|model|font)\/[A-Za-z0-9+-.]+;base64,/
603
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
575
604
  );
576
605
  const type = typeMatch?.[1];
577
606
  if (!typeMatch) {
@@ -595,10 +624,19 @@ var Fs = class {
595
624
  }
596
625
  cleanDataUrl(props) {
597
626
  return props.replace(
598
- /^data:(image|application|video|text|font|model|audio)\/[A-Za-z0-9+-.]+;base64,/,
627
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
628
+ ""
629
+ );
630
+ }
631
+ /**
632
+ * public cleanDataUrl<const C extends string>(props: C) {
633
+ return props.replace(
634
+ /^data:(?:image|application|video|text|font|model|audio|haptics|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
599
635
  ""
600
636
  );
601
637
  }
638
+
639
+ */
602
640
  /**
603
641
  *
604
642
  * @param inputUrl remote url to fetch data from
@@ -618,7 +656,7 @@ var Fs = class {
618
656
  const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
619
657
  if (/\./g.test(formattedPath) === false) {
620
658
  throw new Error(
621
- "either add false as the third argument in `fetchRemoteWriteLocal` [input, output, use-detected-file-extension (defaults to true)]"
659
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
622
660
  );
623
661
  }
624
662
  this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
@@ -626,5 +664,102 @@ var Fs = class {
626
664
  return console.error(err);
627
665
  }
628
666
  }
667
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
668
+ const MAX_SAFE_IN_MEMORY_MB = 100;
669
+ try {
670
+ const head = await fetch(inputUrl, { method: "HEAD" });
671
+ const contentLength = head.headers.get("content-length");
672
+ const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
673
+ const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
674
+ this.generateDirIfDNE(this.pathHandler(formattedPath), {
675
+ recursive: true
676
+ });
677
+ if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
678
+ const res = await fetch(inputUrl);
679
+ if (!res.ok || !res.body) {
680
+ throw new Error(`Failed to fetch asset: ${res.statusText}`);
681
+ }
682
+ const writeStream = import_fs.default.createWriteStream(
683
+ (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
684
+ );
685
+ const reader = res.body.getReader();
686
+ const pump = /* @__PURE__ */ __name(async () => {
687
+ while (true) {
688
+ const { done, value } = await reader.read();
689
+ if (done) break;
690
+ writeStream.write(value);
691
+ }
692
+ writeStream.end();
693
+ }, "pump");
694
+ await pump();
695
+ return;
696
+ }
697
+ const result = await this.assetToBufferView(inputUrl);
698
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
699
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
700
+ } catch (err) {
701
+ console.error(`[fetchRemoteWriteLocal error]:`, err);
702
+ }
703
+ }
704
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
705
+ // https://www.npmjs.com/package/fluent-ffmpeg
706
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
707
+ async imageTransform({
708
+ format,
709
+ target,
710
+ quality = 80,
711
+ tint,
712
+ resize
713
+ }) {
714
+ if (tint && !resize) {
715
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
716
+ } else if (!tint && resize) {
717
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
718
+ } else if (tint && resize) {
719
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
720
+ } else return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
721
+ }
722
+ // public async convertImage<
723
+ // const L extends "local" | "remote",
724
+ // const F extends "webp" | "avif" | "jpg" | "png",
725
+ // const I extends string,
726
+ // const O extends string
727
+ // >(isLocal: L, inputUrl: I, outputPath: O, useDetectedExtension = true) {
728
+ // if (isLocal === "remote") {
729
+ // try {
730
+ // const result = await this.assetToBufferView(inputUrl);
731
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
732
+ // const imageBuffer = Buffer.from(cleanData, "base64");
733
+ // const s = this.imageTransform({format: "webp", target: imageBuffer, quality: 100, resize: {options: {width: 1.2, height: 1.2}}} )
734
+ // const formattedPath = useDetectedExtension
735
+ // ? `${outputPath}.${result.extension}`
736
+ // : outputPath;
737
+ // if (/\./g.test(formattedPath) === false) {
738
+ // throw new Error(
739
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
740
+ // );
741
+ // }
742
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
743
+ // } catch (err) {
744
+ // return console.error(err);
745
+ // }
746
+ // } else {
747
+ // try {
748
+ // const result = await this.assetToBufferView(inputUrl);
749
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
750
+ // const formattedPath = useDetectedExtension
751
+ // ? `${outputPath}.${result.extension}`
752
+ // : outputPath;
753
+ // if (/\./g.test(formattedPath) === false) {
754
+ // throw new Error(
755
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
756
+ // );
757
+ // }
758
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
759
+ // } catch (err) {
760
+ // return console.error(err);
761
+ // }
762
+ // }
763
+ // }
629
764
  };
630
765
  //# sourceMappingURL=index.cjs.map