@d0paminedriven/fs 0.1.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.
@@ -0,0 +1,44 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+
31
+ // ../../node_modules/tsup/assets/esm_shims.js
32
+ var init_esm_shims = __esm({
33
+ "../../node_modules/tsup/assets/esm_shims.js"() {
34
+ "use strict";
35
+ }
36
+ });
37
+
38
+ export {
39
+ __name,
40
+ __commonJS,
41
+ __toESM,
42
+ init_esm_shims
43
+ };
44
+ //# sourceMappingURL=chunk-I6PDZOED.js.map
@@ -0,0 +1,531 @@
1
+ import {
2
+ __commonJS,
3
+ __name,
4
+ __toESM,
5
+ init_esm_shims
6
+ } from "./chunk-I6PDZOED.js";
7
+
8
+ // ../../node_modules/dotenv-expand/lib/main.js
9
+ var require_main = __commonJS({
10
+ "../../node_modules/dotenv-expand/lib/main.js"(exports, module) {
11
+ "use strict";
12
+ init_esm_shims();
13
+ function _resolveEscapeSequences(value) {
14
+ return value.replace(/\\\$/g, "$");
15
+ }
16
+ __name(_resolveEscapeSequences, "_resolveEscapeSequences");
17
+ function expandValue(value, processEnv, runningParsed) {
18
+ const env = { ...runningParsed, ...processEnv };
19
+ const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
20
+ let result = value;
21
+ let match;
22
+ const seen = /* @__PURE__ */ new Set();
23
+ while ((match = regex.exec(result)) !== null) {
24
+ seen.add(result);
25
+ const [template, bracedExpression, unbracedExpression] = match;
26
+ const expression = bracedExpression || unbracedExpression;
27
+ const opRegex = /(:\+|\+|:-|-)/;
28
+ const opMatch = expression.match(opRegex);
29
+ const splitter = opMatch ? opMatch[0] : null;
30
+ const r = expression.split(splitter);
31
+ let defaultValue;
32
+ let value2;
33
+ const key = r.shift();
34
+ if ([":+", "+"].includes(splitter)) {
35
+ defaultValue = env[key] ? r.join(splitter) : "";
36
+ value2 = null;
37
+ } else {
38
+ defaultValue = r.join(splitter);
39
+ value2 = env[key];
40
+ }
41
+ if (value2) {
42
+ if (seen.has(value2)) {
43
+ result = result.replace(template, defaultValue);
44
+ } else {
45
+ result = result.replace(template, value2);
46
+ }
47
+ } else {
48
+ result = result.replace(template, defaultValue);
49
+ }
50
+ if (result === runningParsed[key]) {
51
+ break;
52
+ }
53
+ regex.lastIndex = 0;
54
+ }
55
+ return result;
56
+ }
57
+ __name(expandValue, "expandValue");
58
+ function expand2(options) {
59
+ const runningParsed = {};
60
+ let processEnv = process.env;
61
+ if (options && options.processEnv != null) {
62
+ processEnv = options.processEnv;
63
+ }
64
+ for (const key in options.parsed) {
65
+ let value = options.parsed[key];
66
+ if (processEnv[key] && processEnv[key] !== value) {
67
+ value = processEnv[key];
68
+ } else {
69
+ value = expandValue(value, processEnv, runningParsed);
70
+ }
71
+ options.parsed[key] = _resolveEscapeSequences(value);
72
+ runningParsed[key] = _resolveEscapeSequences(value);
73
+ }
74
+ for (const processKey in options.parsed) {
75
+ processEnv[processKey] = options.parsed[processKey];
76
+ }
77
+ return options;
78
+ }
79
+ __name(expand2, "expand");
80
+ module.exports.expand = expand2;
81
+ }
82
+ });
83
+
84
+ // src/fs/index.ts
85
+ init_esm_shims();
86
+ var import_dotenv_expand = __toESM(require_main(), 1);
87
+ import { execSync } from "child_process";
88
+ import fsSync from "fs";
89
+ import fsAsync from "fs/promises";
90
+ import { relative } from "path";
91
+ import * as dotenv from "dotenv";
92
+ dotenv.config();
93
+ var Fs = class {
94
+ constructor(cwd) {
95
+ this.cwd = cwd;
96
+ }
97
+ static {
98
+ __name(this, "Fs");
99
+ }
100
+ extractTuple(obj, props) {
101
+ return [props, obj[props]];
102
+ }
103
+ sort(obj, order) {
104
+ return Object.fromEntries(
105
+ Object.entries(obj).sort(
106
+ ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
107
+ )
108
+ );
109
+ }
110
+ excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
111
+ const resolve = Object.fromEntries(
112
+ Object.entries(obj).map(([key, val]) => {
113
+ if (props.includes(key)) {
114
+ return ["omit", "omit"];
115
+ } else return [key, val];
116
+ }).filter(([t, _v]) => /omit/.test(t) === false)
117
+ );
118
+ return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
119
+ }, "excludeTargeted");
120
+ includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
121
+ const resolve = Object.fromEntries(
122
+ props.map((val) => this.extractTuple(obj, val))
123
+ );
124
+ return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
125
+ }, "includeTargeted");
126
+ get myEnv() {
127
+ return dotenv.config({ processEnv: {} });
128
+ }
129
+ parseDotEnv() {
130
+ return import_dotenv_expand.default.expand(this.myEnv);
131
+ }
132
+ omitFields(target, keys) {
133
+ let obj = target;
134
+ keys.forEach((t) => {
135
+ if (t in obj) {
136
+ delete obj[t];
137
+ return obj;
138
+ } else {
139
+ return obj;
140
+ }
141
+ });
142
+ return obj;
143
+ }
144
+ omitTargetedFields(targ, keys) {
145
+ return { ...this.omitFields(targ, keys) };
146
+ }
147
+ exists(target) {
148
+ return fsSync.existsSync(relative(this.cwd ?? process.cwd(), target));
149
+ }
150
+ arrToArrOfArrs = /* @__PURE__ */ __name(({
151
+ arrToFragment = Array.of(),
152
+ arrOfArrsAggregator = Array.of(),
153
+ interval
154
+ }) => new Promise(
155
+ (resolve, _reject) => resolve(
156
+ ((interval2) => {
157
+ for (let i = 0; i <= arrToFragment.length; i++) {
158
+ if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
159
+ let segment = arrToFragment.slice(i, i + interval2);
160
+ arrOfArrsAggregator.push(segment);
161
+ }
162
+ }
163
+ })(interval)
164
+ )
165
+ ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
166
+ wait(ms) {
167
+ return new Promise((resolve) => setTimeout(resolve, ms));
168
+ }
169
+ countsSorter = /* @__PURE__ */ __name(({
170
+ counter,
171
+ keySort,
172
+ valSort
173
+ }) => Object.fromEntries(
174
+ Object.entries(counter).sort(
175
+ ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
176
+ ).sort(
177
+ ([_aStr, aNum], [_bStr, bNum]) => valSort === "ASC" ? aNum - bNum : bNum - aNum
178
+ )
179
+ ), "countsSorter");
180
+ handleBuffStrArrUnion(arr) {
181
+ return arr.map(
182
+ (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
183
+ );
184
+ }
185
+ readDir(path, options) {
186
+ return this.handleBuffStrArrUnion(
187
+ fsSync.readdirSync(
188
+ relative(this.cwd ??= process.cwd(), path),
189
+ options
190
+ )
191
+ );
192
+ }
193
+ executeCommand = /* @__PURE__ */ __name(({
194
+ command,
195
+ ...options
196
+ }) => Buffer.from(
197
+ Buffer.from(execSync(command, { ...options }).toJSON().data)
198
+ ).toString("utf-8"), "executeCommand");
199
+ fileGenTimestamp(d) {
200
+ const date = d.toISOString();
201
+ return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
202
+ }
203
+ configFileGenTimestamp(d) {
204
+ return this.fileGenTimestamp(d).replace("/*", "#").replace("*/", "");
205
+ }
206
+ mdFileGenTimestamp(d) {
207
+ return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
208
+ }
209
+ existsSync(path) {
210
+ return fsSync.existsSync(relative(this.cwd ?? process.cwd(), path));
211
+ }
212
+ pathHandler(path) {
213
+ return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
214
+ }
215
+ mkdirSync(path, options) {
216
+ return fsSync.mkdirSync(relative(this.cwd ?? process.cwd(), path), options);
217
+ }
218
+ fileSizeMb(path) {
219
+ return fsSync.statSync(relative(this.cwd ?? process.cwd(), path)).size / (1024 * 1024);
220
+ }
221
+ generateDirIfDNE(path, options) {
222
+ const doesExist = this.existsSync(path);
223
+ if (doesExist === true) return;
224
+ else {
225
+ return this.mkdirSync(path, options);
226
+ }
227
+ }
228
+ withWs(path, data, options) {
229
+ try {
230
+ if (/\//g.test(path) === true) {
231
+ return this.generateDirIfDNE(this.pathHandler(path), {
232
+ recursive: true
233
+ });
234
+ } else return path;
235
+ } catch (error) {
236
+ console.error(
237
+ `[withWs error]: `.concat(
238
+ typeof error === "string" ? error : JSON.stringify(error, null, 2)
239
+ )
240
+ );
241
+ } finally {
242
+ return fsSync.createWriteStream(
243
+ relative(this.cwd ?? process.cwd(), path),
244
+ typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
245
+ ).write(Buffer.from(Buffer.from(data).toJSON().data));
246
+ }
247
+ }
248
+ writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
249
+ try {
250
+ if (/\//g.test(path) === true)
251
+ return this.generateDirIfDNE(this.pathHandler(path), {
252
+ recursive: true
253
+ });
254
+ else return path;
255
+ } catch (error) {
256
+ console.error(
257
+ `[writeFileAsync error]: `.concat(
258
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
259
+ )
260
+ );
261
+ } finally {
262
+ return await fsAsync.writeFile(
263
+ relative(this.cwd ?? process.cwd(), path),
264
+ Buffer.from(
265
+ Buffer.from(data).toJSON().data
266
+ ),
267
+ options
268
+ );
269
+ }
270
+ }, "writeFileAsync");
271
+ fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
272
+ Buffer.from(
273
+ fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
274
+ )
275
+ ), "fileToBuffer");
276
+ dirContainsDir(readDir, targetDir, options) {
277
+ return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
278
+ }
279
+ parseJsonBuffer(p) {
280
+ return JSON.parse(
281
+ Buffer.from(Buffer.from(p).toJSON().data).toString("utf-8")
282
+ );
283
+ }
284
+ /* begin url */
285
+ isServerSide() {
286
+ return typeof window === "undefined";
287
+ }
288
+ isBase64(str) {
289
+ if (!str) {
290
+ return false;
291
+ }
292
+ return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?\n?$/.test(
293
+ str.replace(/\n/g, "")
294
+ );
295
+ }
296
+ previewRegex = /\/preview(\/\w|\?)/;
297
+ isPreviewPath(uri) {
298
+ if (typeof uri === "string") {
299
+ return this.previewRegex.test(uri);
300
+ }
301
+ return false;
302
+ }
303
+ // eslint-disable-next-line @typescript-eslint/class-literal-property-style
304
+ get URL_REGEX() {
305
+ return /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
306
+ }
307
+ parseUrl(url) {
308
+ const parsed = this.URL_REGEX.exec(url);
309
+ return {
310
+ href: parsed[0],
311
+ protocol: parsed[1] ?? "",
312
+ baseUrl: `${parsed[1]}${parsed[3]}`,
313
+ host: parsed[4] ?? "",
314
+ pathname: parsed[5] ?? "",
315
+ search: parsed[6] ?? "",
316
+ hash: parsed[8] ?? ""
317
+ };
318
+ }
319
+ /* end url */
320
+ get gzVal() {
321
+ return ["application/x-gzip", "application/gzip"].reduce(
322
+ (vals) => vals
323
+ );
324
+ }
325
+ get zipVal() {
326
+ return ["application/zip", "application/x-zip-compressed"].reduce((vals) => vals);
327
+ }
328
+ get mimeTypeObj() {
329
+ return {
330
+ aac: "audio/aac",
331
+ abw: "application/x-abiword",
332
+ apng: "image/apng",
333
+ arc: "application/x-freearc",
334
+ avif: "image/avif",
335
+ avi: "video/x-msvideo",
336
+ azw: "application/vnd.amazon.ebook",
337
+ bin: "application/octet-stream",
338
+ bmp: "image/bmp",
339
+ bz: "application/x-bzip",
340
+ bz2: "application/x-bzip2",
341
+ cda: "application/x-cdf",
342
+ cjs: "application/javascript",
343
+ csh: "application/x-csh",
344
+ css: "text/css",
345
+ csv: "text/csv",
346
+ doc: "application/msword",
347
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
348
+ eot: "application/vnd.ms-fontobject",
349
+ epub: "application/epub+zip",
350
+ gif: "image/gif",
351
+ gz: this.gzVal,
352
+ htm: "text/html",
353
+ html: "text/html",
354
+ ico: "image/vnd.microsoft.icon",
355
+ ics: "text/calendar",
356
+ jar: "application/java-archive",
357
+ jpeg: "image/jpeg",
358
+ jpg: "image/jpeg",
359
+ js: "text/javascript",
360
+ json: "application/json",
361
+ jsonld: "application/ld+json",
362
+ m3u8: "application/vnd.apple.mpegurl",
363
+ md: "text/markdown",
364
+ mdx: "application/x-mdx",
365
+ mid: "audio/midi",
366
+ midi: "audio/x-midi",
367
+ mjs: "text/javascript",
368
+ mp3: "audio/mpeg",
369
+ mp4: "video/mp4",
370
+ mpeg: "video/mpeg",
371
+ mpkg: "application/vnd.apple.installer+xml",
372
+ ndjson: "application/x-ndjson",
373
+ odp: "application/vnd.oasis.opendocument.presentation",
374
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
375
+ odt: "application/vnd.oasis.opendocument.text",
376
+ oga: "audio/ogg",
377
+ ogv: "video/ogg",
378
+ ogx: "application/ogg",
379
+ opus: "audio/ogg",
380
+ otf: "font/otf",
381
+ png: "image/png",
382
+ pdf: "application/pdf",
383
+ php: "application/x-httpd-php",
384
+ pkpass: "application/vnd.apple.pkpass",
385
+ ppt: "application/vnd.ms-powerpoint",
386
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
387
+ rar: "application/vnd.rar",
388
+ rtf: "application/rtf",
389
+ sh: "application/x-sh",
390
+ svg: "image/svg+xml",
391
+ tar: "application/x-tar",
392
+ tif: "image/tiff",
393
+ tiff: "image/tiff",
394
+ ts: "video/mp2t",
395
+ ttf: "font/ttf",
396
+ txt: "text/plain",
397
+ vsd: "application/vnd.visio",
398
+ wav: "audio/wav",
399
+ weba: "video/webm",
400
+ webp: "image/webp",
401
+ woff: "font/woff",
402
+ woff2: "font/woff2",
403
+ xhtml: "application/xhtml+xml",
404
+ xls: "application/vnd.ms-excel",
405
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
406
+ xml: "application/xml",
407
+ xul: "application/vnd.mozilla.xul+xml",
408
+ zip: this.zipVal,
409
+ "3gp": "video/3gpp",
410
+ "3g2": "video/3gpp2",
411
+ "7z": "application/x-7z-compressed"
412
+ };
413
+ }
414
+ assetType(url) {
415
+ return this.parseUrl(url).pathname?.split(/([.])/gim)?.reverse()?.[0];
416
+ }
417
+ getMime(input) {
418
+ return this.mimeTypeObj[input];
419
+ }
420
+ async assetToBuffer(path) {
421
+ const [fetcher] = await Promise.all([
422
+ fetch(path).then((t) => t.arrayBuffer())
423
+ ]);
424
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
425
+ Buffer.from(fetcher).toJSON().data
426
+ ).toString("base64")}`;
427
+ const extension = this.assetType(path);
428
+ return {
429
+ b64encodedData,
430
+ extension
431
+ };
432
+ }
433
+ async assetToBufferView(path) {
434
+ const [fetcher] = await Promise.all([
435
+ fetch(path).then((t) => t.arrayBuffer())
436
+ ]);
437
+ const reader = new ReadableStream({
438
+ type: "bytes",
439
+ async pull(controller) {
440
+ const byobRequest = controller.byobRequest;
441
+ byobRequest?.respond(byobRequest?.view?.byteLength ?? 0);
442
+ }
443
+ });
444
+ const readerByob = new ReadableStreamBYOBReader(reader);
445
+ const readableByteStream = fetcher;
446
+ const data = await readerByob.read(Buffer.from(readableByteStream));
447
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
448
+ Buffer.from(data.value ?? Buffer.alloc(0)).toJSON().data
449
+ ).toString("base64")}`;
450
+ const extension = this.assetType(path);
451
+ return {
452
+ b64encodedData,
453
+ extension
454
+ };
455
+ }
456
+ formatHelper(f) {
457
+ if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
458
+ const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
459
+ return formatting;
460
+ } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
461
+ }
462
+ range(from, to) {
463
+ const values = [];
464
+ for (let i = from; i < to; i++) {
465
+ values.push(i);
466
+ }
467
+ return values;
468
+ }
469
+ isPrimeNumber = /* @__PURE__ */ __name((n) => {
470
+ for (let i = 2; n > i; i++) {
471
+ if (n % i === 0) {
472
+ return false;
473
+ }
474
+ }
475
+ return n > 1;
476
+ }, "isPrimeNumber");
477
+ acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
478
+ chunkArray(arr, maxChunkLength) {
479
+ const chunks = Array.of();
480
+ let currentChunkLength = 0;
481
+ let currentChunk = Array.of();
482
+ for (const [index, val] of arr.entries()) {
483
+ if (val.length + currentChunkLength >= maxChunkLength) {
484
+ if (currentChunk.length) {
485
+ chunks.push(currentChunk);
486
+ }
487
+ currentChunkLength = val.length;
488
+ currentChunk = [val];
489
+ } else {
490
+ currentChunk.push(val);
491
+ currentChunkLength += val.length + 1;
492
+ }
493
+ if (arr.length === index + 1) {
494
+ chunks.push(currentChunk);
495
+ }
496
+ }
497
+ return chunks.length ? chunks : [arr];
498
+ }
499
+ b64ToBlob(b64Data) {
500
+ {
501
+ const sliceSize = 512;
502
+ const typeMatch = b64Data.match(
503
+ /^data:(image|application|video|text|font)\/[A-Za-z0-9+-.]+;base64,/
504
+ );
505
+ const type = typeMatch?.[1];
506
+ console.log(type ?? "");
507
+ if (!typeMatch) {
508
+ throw new Error(`${b64Data} is not a valid data Url`);
509
+ }
510
+ const byteCharacters = Buffer.from(b64Data, "base64").toString("utf-8");
511
+ const byteArrays = Array.of();
512
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
513
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
514
+ const byteNumbers = Array.of();
515
+ byteNumbers.push(slice.length);
516
+ for (let i = 0; i < slice.length; i++) {
517
+ byteNumbers[i] = slice.charCodeAt(i);
518
+ }
519
+ const byteArray = new Uint8Array(byteNumbers);
520
+ byteArrays.push(byteArray);
521
+ }
522
+ const blob = new Blob(byteArrays, { type });
523
+ return blob;
524
+ }
525
+ }
526
+ };
527
+
528
+ export {
529
+ Fs
530
+ };
531
+ //# sourceMappingURL=chunk-K45COKAJ.js.map