@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,20 +1,185 @@
1
- import {
2
- FsFetch
3
- } from "../chunk-4D2YBCI6.js";
4
- import "../chunk-PATMSIQK.js";
5
- import "../chunk-OHKRQJZH.js";
6
- import "../chunk-DNR5ZI2T.js";
7
- import "../chunk-5H6GE5AO.js";
8
- import "../chunk-YRCJWFZD.js";
9
- import "../chunk-VDKUXJE7.js";
10
- import "../chunk-Y5QWE4EG.js";
11
- import "../chunk-5CACVZVF.js";
12
- import "../chunk-L2QMQOEJ.js";
13
- import "../chunk-NJHN5OE3.js";
14
- import "../chunk-OT5JEQKW.js";
15
- import "../chunk-PB5A7ZFD.js";
16
- import "../chunk-7QVYU63E.js";
17
- export {
18
- FsFetch
1
+ import fsSync from "fs";
2
+ import { open, rename } from "fs/promises";
3
+ import { relative } from "path";
4
+ import { FsTmp } from "../fs-tmp/index.js";
5
+ import { sniffFromRanges } from "@d0paminedriven/mimedown";
6
+ // src/fs-fetch/index.ts
7
+ var FsFetch = class extends FsTmp {
8
+ cwd;
9
+ constructor(cwd) {
10
+ super(cwd ??= process.cwd());
11
+ this.cwd = cwd;
12
+ }
13
+ async assetToBuffer(path) {
14
+ const [fetcher] = await Promise.all([fetch(path).then((t) => t.arrayBuffer())]);
15
+ return {
16
+ b64encodedData: `data:${this.getMimeTypeForPath(path)};base64, ${Buffer.from(fetcher).toString("base64")}`,
17
+ extension: this.assetType(path) ?? "txt"
18
+ };
19
+ }
20
+ async assetToBufferView(path) {
21
+ const response = await fetch(path, { method: "GET" });
22
+ if (!response.ok) throw new Error(`Failed to fetch asset: ${response.statusText}`);
23
+ const reader = response.body?.getReader();
24
+ if (reader) {
25
+ const chunks = Array.of();
26
+ while (true) {
27
+ const { done, value } = await reader.read();
28
+ if (done) break;
29
+ if (value) chunks.push(value);
30
+ }
31
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
32
+ const completeBuffer = new Uint8Array(totalLength);
33
+ let offset = 0;
34
+ for (const chunk of chunks) {
35
+ completeBuffer.set(chunk, offset);
36
+ offset += chunk.length;
37
+ }
38
+ return {
39
+ b64encodedData: `data:${this.getMimeTypeForPath(path)};base64, ${Buffer.from(completeBuffer).toString("base64")}`,
40
+ extension: this.assetType(path)
41
+ };
42
+ } else {
43
+ const arrayBuffer = await response.arrayBuffer();
44
+ return {
45
+ b64encodedData: `data:${this.getMimeTypeForPath(path)};base64, ${Buffer.from(arrayBuffer).toString("base64")}`,
46
+ extension: this.assetType(path)
47
+ };
48
+ }
49
+ }
50
+ /**
51
+ *
52
+ * @param inputUrl remote url to fetch data from
53
+ * @param outputPath desired output path relative to the cwd
54
+ * @param useDetectedExtension optional, defaults to true
55
+ *
56
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
57
+ *
58
+ * 🚫 'public/assets/image-1'
59
+ *
60
+ * ✅ 'public/assets/image-1.png'
61
+ */
62
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
63
+ try {
64
+ const result = await this.assetToBufferView(inputUrl);
65
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
66
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
67
+ if (/\./g.test(formattedPath) === false) throw new Error("either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension");
68
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
69
+ } catch (err) {
70
+ return console.error(err);
71
+ }
72
+ }
73
+ knownToBlockHead(inputUrl) {
74
+ if (inputUrl.startsWith("https://github.com")) return "GET";
75
+ else if (inputUrl.startsWith("https://raw.githubusercontent.com")) return "GET";
76
+ else return "HEAD";
77
+ }
78
+ getUrlExt(url) {
79
+ const pathname = new URL(url).pathname;
80
+ const lastDot = pathname.lastIndexOf(".");
81
+ if (lastDot === -1 || lastDot === pathname.length - 1) return null;
82
+ return pathname.slice(lastDot + 1).toLowerCase();
83
+ }
84
+ fuzzyExtEquality(a, b) {
85
+ const aNorm = a.toLowerCase();
86
+ const bNorm = b.toLowerCase();
87
+ return this.calculateLD(aNorm, bNorm) / (Math.max(aNorm.length, bNorm.length) || 1) <= .34;
88
+ }
89
+ async sniffFile(path) {
90
+ const file = await open(path, "r");
91
+ try {
92
+ const { size } = await file.stat();
93
+ const pieces = Array.of();
94
+ const take = async (offset, length) => {
95
+ const bytes = Buffer.alloc(Math.max(0, Math.min(length, size - offset)));
96
+ const { bytesRead } = await file.read(bytes, 0, bytes.byteLength, offset);
97
+ pieces.push({
98
+ offset,
99
+ bytes: bytes.subarray(0, bytesRead)
100
+ });
101
+ };
102
+ await take(0, 4096);
103
+ let found = sniffFromRanges(pieces, size, { retryOnUnknown: true });
104
+ for (let asked = 0; found.needs !== null && asked < 8; asked++) {
105
+ const { offset, length, fromEnd } = found.needs;
106
+ await take(fromEnd ? Math.max(0, size - offset) : offset, length);
107
+ found = sniffFromRanges(pieces, size, { retryOnUnknown: true });
108
+ }
109
+ return {
110
+ ...found,
111
+ size
112
+ };
113
+ } finally {
114
+ await file.close();
115
+ }
116
+ }
117
+ /**
118
+ *
119
+ * @param inputUrl remote url to fetch data from
120
+ * @param outputPath desired output path relative to the cwd
121
+ * @param useDetectedExtension optional, defaults to true
122
+ *
123
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
124
+ *
125
+ * 🚫 'public/assets/image-1'
126
+ *
127
+ * ✅ 'public/assets/image-1.png'
128
+ *
129
+ * @description
130
+ * This method is designed for all files regardless of size, but especially for
131
+ * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
132
+ * It streams the data directly to disk for files of all sizes instead of loading it all into memory
133
+ */
134
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true, verbose = false) {
135
+ if (!URL.canParse(inputUrl)) throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
136
+ try {
137
+ const res = await fetch(inputUrl);
138
+ if (!res.ok || !res.body) throw new Error(`Failed to fetch asset: ${res.status} ${res.statusText}`);
139
+ const partial = `${outputPathI}.part`;
140
+ this.generateDirIfDNE(this.pathHandler(partial), { recursive: true });
141
+ const writeStream = fsSync.createWriteStream(relative(this.cwd, partial));
142
+ const { promise, reject, resolve } = Promise.withResolvers();
143
+ writeStream.on("finish", () => resolve({}));
144
+ writeStream.on("error", () => reject({}));
145
+ const reader = res.body.getReader();
146
+ const pump = async () => {
147
+ while (true) {
148
+ const { done, value } = await reader.read();
149
+ if (done) break;
150
+ writeStream.write(value);
151
+ }
152
+ writeStream.end();
153
+ };
154
+ await pump();
155
+ await promise.then(() => {});
156
+ const { evidence, ext, mime, parser, retry, topLevel, size } = await this.sniffFile(relative(this.cwd, partial));
157
+ const { unit, value } = this.autoFileSizeRaw(size);
158
+ if (verbose) console.log({
159
+ extension: ext,
160
+ topLevelMime: topLevel,
161
+ mime,
162
+ parser,
163
+ retry,
164
+ evidence,
165
+ size: `${value} ${unit}`
166
+ });
167
+ let formattedPath;
168
+ if (useDetectedExtension) formattedPath = `${outputPathI}.${ext}`;
169
+ else {
170
+ const lastDot = outputPathI.lastIndexOf(".");
171
+ if (lastDot === 1 || lastDot === -1) formattedPath = `${outputPathI}.${ext}`;
172
+ const outputPathExt = outputPathI.slice(outputPathI.lastIndexOf(".") + 1);
173
+ if (this.fuzzyExtEquality(ext, outputPathExt) === true) formattedPath = outputPathI;
174
+ else formattedPath = outputPathI.replace(outputPathExt, ext);
175
+ }
176
+ await rename(relative(this.cwd, partial), relative(this.cwd, formattedPath));
177
+ return;
178
+ } catch (err) {
179
+ console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
180
+ }
181
+ }
19
182
  };
183
+ export { FsFetch };
184
+
20
185
  //# sourceMappingURL=index.js.map
@@ -1,32 +1,16 @@
1
- import { Unit, SizeOpts } from '../types/index.js';
2
- import { FsAtomic } from '../fs-atomic/index.js';
3
- import 'stream';
4
- import 'fs';
5
- import '../fs-base/index.js';
6
- import 'node:stream';
7
- import 'stream/web';
8
- import 'dotenv-expand';
9
- import '../types/stream.js';
10
- import '../image/index.js';
11
- import '@d0paminedriven/metadata';
12
- import '../image/workup.js';
13
- import '../mime/index.js';
14
- import '../url/index.js';
15
- import '../utils/index.js';
16
- import '../ld/index.js';
17
-
18
- declare class FsSize extends FsAtomic {
19
- cwd: string;
20
- constructor(cwd: string);
21
- private units;
22
- private u;
23
- autoFileSizeRaw(size: number | bigint): {
24
- value: number;
25
- unit: "B" | "KB" | "MB" | "GB" | "TB" | "PB" | undefined;
26
- };
27
- getSize<const S extends Unit | Lowercase<Unit> | "auto">(size: number | bigint, target: S, opts?: SizeOpts): string | number;
28
- fileSizeMb<const T extends string>(path: T): number;
29
- fileSize<const T extends string, const S extends Unit | Lowercase<Unit> | "auto">(path: T, target: S, opts?: SizeOpts): string | number;
1
+ import { SizeOpts, Unit } from "../types/index.js";
2
+ import { FsAtomic } from "../fs-atomic/index.js";
3
+ export declare class FsSize extends FsAtomic {
4
+ cwd: string;
5
+ constructor(cwd: string);
6
+ private units;
7
+ private u;
8
+ autoFileSizeRaw(size: number | bigint): {
9
+ value: number;
10
+ unit: "B" | "KB" | "MB" | "GB" | "TB" | "PB" | undefined;
11
+ };
12
+ getSize<const S extends Unit | Lowercase<Unit> | "auto">(size: number | bigint, target: S, opts?: SizeOpts): string | number;
13
+ fileSizeMb<const T extends string>(path: T): number;
14
+ fileSize<const T extends string, const S extends Unit | Lowercase<Unit> | "auto">(path: T, target: S, opts?: SizeOpts): string | number;
30
15
  }
31
-
32
- export { FsSize };
16
+ //# sourceMappingURL=index.d.ts.map
@@ -1,17 +1,65 @@
1
- import {
2
- FsSize
3
- } from "../chunk-DNR5ZI2T.js";
4
- import "../chunk-5H6GE5AO.js";
5
- import "../chunk-YRCJWFZD.js";
6
- import "../chunk-VDKUXJE7.js";
7
- import "../chunk-Y5QWE4EG.js";
8
- import "../chunk-5CACVZVF.js";
9
- import "../chunk-L2QMQOEJ.js";
10
- import "../chunk-NJHN5OE3.js";
11
- import "../chunk-OT5JEQKW.js";
12
- import "../chunk-PB5A7ZFD.js";
13
- import "../chunk-7QVYU63E.js";
14
- export {
15
- FsSize
1
+ import { statSync } from "fs";
2
+ import { relative } from "path";
3
+ import { FsAtomic } from "../fs-atomic/index.js";
4
+ import { unitsObj } from "../types/index.js";
5
+ // src/fs-size/index.ts
6
+ var FsSize = class extends FsAtomic {
7
+ cwd;
8
+ constructor(cwd) {
9
+ super(cwd ??= process.cwd());
10
+ this.cwd = cwd;
11
+ }
12
+ units = unitsObj;
13
+ u = [
14
+ "B",
15
+ "KB",
16
+ "MB",
17
+ "GB",
18
+ "TB",
19
+ "PB"
20
+ ];
21
+ autoFileSizeRaw(size) {
22
+ let s = typeof size === "bigint" ? Number(size) : size;
23
+ let i = 0;
24
+ while (s >= 1024 && i < this.u.length - 1) {
25
+ s /= 1024;
26
+ i++;
27
+ }
28
+ return {
29
+ value: s,
30
+ unit: this.u[i]
31
+ };
32
+ }
33
+ getSize(size, target, opts = {
34
+ decimals: 4,
35
+ includeUnits: true
36
+ }) {
37
+ const { decimals, includeUnits } = opts;
38
+ if (target === "auto") {
39
+ const { value, unit } = this.autoFileSizeRaw(size);
40
+ const rounded = value.toFixed(decimals);
41
+ return includeUnits ? `${rounded} ${unit}` : Number.parseFloat(rounded);
42
+ }
43
+ const key = target.toUpperCase();
44
+ const exp = this.units[key];
45
+ const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
46
+ let v = 0;
47
+ if (typeof size === "bigint" || typeof divisor === "bigint") {
48
+ if (typeof size === "bigint" && typeof divisor === "bigint") v = Number(size / divisor);
49
+ else if (typeof size !== "bigint" && typeof divisor === "bigint") v = size / Number(divisor);
50
+ else if (typeof size === "bigint" && typeof divisor !== "bigint") v = Number(size) / divisor;
51
+ } else if (typeof size === "number" && typeof divisor === "number") v = size / divisor;
52
+ const rounded = v.toFixed(decimals);
53
+ return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
54
+ }
55
+ fileSizeMb(path) {
56
+ return statSync(relative(this.cwd, path)).size / 1048576;
57
+ }
58
+ fileSize(path, target, opts) {
59
+ if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
60
+ else return this.getSize(statSync(relative(this.cwd, path)).size, target, opts);
61
+ }
16
62
  };
63
+ export { FsSize };
64
+
17
65
  //# sourceMappingURL=index.js.map