react-smart-copy 1.19.0 → 1.20.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/files.cjs ADDED
@@ -0,0 +1,948 @@
1
+
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
4
+ //#region src/files/detect.ts
5
+ /** How many leading bytes {@link detectFileType} reads: enough for every signature and a text sniff. */
6
+ const FILE_SNIFF_BYTES = 8192;
7
+ const type = (mime, family, extensions, parent = null) => Object.freeze({
8
+ mime,
9
+ family,
10
+ extensions: Object.freeze(extensions),
11
+ parent
12
+ });
13
+ const ZIP = "application/zip";
14
+ const TEXT = "text/plain";
15
+ /** Every type this module recognises, by MIME type. */
16
+ const FILE_TYPES = {
17
+ pdf: type("application/pdf", "document", ["pdf"]),
18
+ png: type("image/png", "image", ["png", "apng"]),
19
+ jpeg: type("image/jpeg", "image", [
20
+ "jpg",
21
+ "jpeg",
22
+ "jpe",
23
+ "jfif"
24
+ ]),
25
+ gif: type("image/gif", "image", ["gif"]),
26
+ webp: type("image/webp", "image", ["webp"]),
27
+ avif: type("image/avif", "image", ["avif"]),
28
+ heic: type("image/heic", "image", ["heic", "heif"]),
29
+ bmp: type("image/bmp", "image", ["bmp", "dib"]),
30
+ ico: type("image/x-icon", "image", ["ico", "cur"]),
31
+ tiff: type("image/tiff", "image", [
32
+ "tif",
33
+ "tiff",
34
+ "dng",
35
+ "cr2",
36
+ "nef",
37
+ "arw"
38
+ ]),
39
+ psd: type("image/vnd.adobe.photoshop", "image", ["psd"]),
40
+ svg: type("image/svg+xml", "image", ["svg", "svgz"], TEXT),
41
+ mp3: type("audio/mpeg", "audio", ["mp3"]),
42
+ wav: type("audio/wav", "audio", ["wav"]),
43
+ flac: type("audio/flac", "audio", ["flac"]),
44
+ ogg: type("audio/ogg", "audio", [
45
+ "ogg",
46
+ "oga",
47
+ "ogv",
48
+ "opus",
49
+ "spx"
50
+ ]),
51
+ m4a: type("audio/mp4", "audio", ["m4a", "m4b"], "video/mp4"),
52
+ mp4: type("video/mp4", "video", [
53
+ "mp4",
54
+ "m4v",
55
+ "m4a",
56
+ "mov"
57
+ ]),
58
+ mov: type("video/quicktime", "video", ["mov", "qt"], "video/mp4"),
59
+ threegp: type("video/3gpp", "video", ["3gp", "3g2"], "video/mp4"),
60
+ webm: type("video/webm", "video", ["webm", "weba"]),
61
+ mkv: type("video/x-matroska", "video", [
62
+ "mkv",
63
+ "mka",
64
+ "webm"
65
+ ]),
66
+ avi: type("video/x-msvideo", "video", ["avi"]),
67
+ zip: type(ZIP, "archive", ["zip"]),
68
+ docx: type("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document", [
69
+ "docx",
70
+ "docm",
71
+ "dotx",
72
+ "dotm"
73
+ ], ZIP),
74
+ xlsx: type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "document", [
75
+ "xlsx",
76
+ "xlsm",
77
+ "xltx",
78
+ "xltm"
79
+ ], ZIP),
80
+ pptx: type("application/vnd.openxmlformats-officedocument.presentationml.presentation", "document", [
81
+ "pptx",
82
+ "pptm",
83
+ "potx",
84
+ "potm",
85
+ "ppsx",
86
+ "ppsm"
87
+ ], ZIP),
88
+ odt: type("application/vnd.oasis.opendocument.text", "document", ["odt"], ZIP),
89
+ ods: type("application/vnd.oasis.opendocument.spreadsheet", "document", ["ods"], ZIP),
90
+ odp: type("application/vnd.oasis.opendocument.presentation", "document", ["odp"], ZIP),
91
+ epub: type("application/epub+zip", "document", ["epub"], ZIP),
92
+ jar: type("application/java-archive", "executable", [
93
+ "jar",
94
+ "war",
95
+ "ear"
96
+ ], ZIP),
97
+ apk: type("application/vnd.android.package-archive", "executable", ["apk", "aab"], ZIP),
98
+ ole: type("application/x-ole-storage", "document", [
99
+ "doc",
100
+ "xls",
101
+ "ppt",
102
+ "msg",
103
+ "msi",
104
+ "dot",
105
+ "xlt",
106
+ "pps"
107
+ ]),
108
+ rtf: type("application/rtf", "document", ["rtf"], TEXT),
109
+ gzip: type("application/gzip", "archive", ["gz", "tgz"]),
110
+ bzip2: type("application/x-bzip2", "archive", ["bz2", "tbz2"]),
111
+ xz: type("application/x-xz", "archive", ["xz", "txz"]),
112
+ zstd: type("application/zstd", "archive", ["zst"]),
113
+ sevenZip: type("application/x-7z-compressed", "archive", ["7z"]),
114
+ rar: type("application/vnd.rar", "archive", ["rar"]),
115
+ tar: type("application/x-tar", "archive", ["tar"]),
116
+ sqlite: type("application/vnd.sqlite3", "data", ["sqlite", "sqlite3"]),
117
+ woff: type("font/woff", "font", ["woff"]),
118
+ woff2: type("font/woff2", "font", ["woff2"]),
119
+ otf: type("font/otf", "font", ["otf"]),
120
+ ttf: type("font/ttf", "font", ["ttf", "ttc"]),
121
+ exe: type("application/vnd.microsoft.portable-executable", "executable", [
122
+ "exe",
123
+ "dll",
124
+ "sys",
125
+ "scr",
126
+ "com",
127
+ "cpl",
128
+ "ocx",
129
+ "efi"
130
+ ]),
131
+ elf: type("application/x-elf", "executable", [
132
+ "so",
133
+ "run",
134
+ "elf"
135
+ ]),
136
+ macho: type("application/x-mach-binary", "executable", ["dylib", "bundle"]),
137
+ wasm: type("application/wasm", "executable", ["wasm"]),
138
+ shortcut: type("application/x-ms-shortcut", "executable", ["lnk"]),
139
+ script: type("text/x-shellscript", "executable", [
140
+ "sh",
141
+ "bash",
142
+ "zsh",
143
+ "command",
144
+ "py",
145
+ "pl",
146
+ "rb"
147
+ ], TEXT),
148
+ html: type("text/html", "text", [
149
+ "html",
150
+ "htm",
151
+ "xhtml",
152
+ "xht",
153
+ "shtml",
154
+ "mht",
155
+ "mhtml"
156
+ ], TEXT),
157
+ xml: type("application/xml", "text", [
158
+ "xml",
159
+ "xsl",
160
+ "xslt",
161
+ "rss",
162
+ "atom",
163
+ "kml",
164
+ "gpx"
165
+ ], TEXT),
166
+ json: type("application/json", "text", [
167
+ "json",
168
+ "geojson",
169
+ "jsonld",
170
+ "webmanifest",
171
+ "map"
172
+ ], TEXT),
173
+ text: type(TEXT, "text", ["txt"])
174
+ };
175
+ /** Bounds-checked reads: past the end is never a match. */
176
+ var Head = class {
177
+ constructor(bytes) {
178
+ this.bytes = bytes;
179
+ }
180
+ at(index) {
181
+ return index < this.bytes.length ? this.bytes[index] : -1;
182
+ }
183
+ is(offset, ...values) {
184
+ return values.every((value, index) => this.at(offset + index) === value);
185
+ }
186
+ ascii(offset, length) {
187
+ let out = "";
188
+ for (let index = offset; index < offset + length && index < this.bytes.length; index += 1) out += String.fromCharCode(this.bytes[index]);
189
+ return out;
190
+ }
191
+ u16le(offset) {
192
+ return this.at(offset) + (this.at(offset + 1) << 8);
193
+ }
194
+ u32le(offset) {
195
+ return (this.at(offset) | this.at(offset + 1) << 8 | this.at(offset + 2) << 16 | this.at(offset + 3) << 24) >>> 0;
196
+ }
197
+ };
198
+ /** ISO base media (MP4, MOV, HEIC, AVIF, 3GP): `ftyp` with its major brand. */
199
+ function isoMedia(head) {
200
+ if (head.ascii(4, 4) !== "ftyp") return null;
201
+ const brand = head.ascii(8, 4);
202
+ if (brand === "avif" || brand === "avis") return FILE_TYPES.avif;
203
+ if ([
204
+ "heic",
205
+ "heix",
206
+ "heim",
207
+ "heis",
208
+ "hevc",
209
+ "hevx",
210
+ "mif1",
211
+ "msf1"
212
+ ].includes(brand)) return FILE_TYPES.heic;
213
+ if (brand === "qt ") return FILE_TYPES.mov;
214
+ if (brand.startsWith("M4A") || brand.startsWith("M4B")) return FILE_TYPES.m4a;
215
+ if (brand.startsWith("3g")) return FILE_TYPES.threegp;
216
+ return FILE_TYPES.mp4;
217
+ }
218
+ /** RIFF containers: WebP, WAV, AVI. */
219
+ function riff(head) {
220
+ if (head.ascii(0, 4) !== "RIFF") return null;
221
+ const form = head.ascii(8, 4);
222
+ if (form === "WEBP") return FILE_TYPES.webp;
223
+ if (form === "WAVE") return FILE_TYPES.wav;
224
+ if (form === "AVI ") return FILE_TYPES.avi;
225
+ return null;
226
+ }
227
+ /** A ZIP, and what it packages: Office, OpenDocument, EPUB, Java and Android archives. */
228
+ function zip(head) {
229
+ if (!head.is(0, 80, 75) || !(head.is(2, 3, 4) || head.is(2, 5, 6) || head.is(2, 7, 8))) return null;
230
+ if (head.ascii(30, 8) === "mimetype") {
231
+ const declared = head.ascii(38, head.u32le(18) > 0 && head.u32le(18) < 100 ? head.u32le(18) : 80);
232
+ for (const candidate of [
233
+ FILE_TYPES.epub,
234
+ FILE_TYPES.odt,
235
+ FILE_TYPES.ods,
236
+ FILE_TYPES.odp
237
+ ]) if (declared.startsWith(candidate.mime)) return {
238
+ type: candidate,
239
+ macros: false
240
+ };
241
+ }
242
+ const names = head.ascii(0, head.bytes.length);
243
+ const macros = names.includes("vbaProject.bin");
244
+ if (names.includes("AndroidManifest.xml") || names.includes("classes.dex")) return {
245
+ type: FILE_TYPES.apk,
246
+ macros
247
+ };
248
+ if (names.includes("META-INF/MANIFEST.MF")) return {
249
+ type: FILE_TYPES.jar,
250
+ macros
251
+ };
252
+ if (names.includes("word/")) return {
253
+ type: FILE_TYPES.docx,
254
+ macros
255
+ };
256
+ if (names.includes("xl/")) return {
257
+ type: FILE_TYPES.xlsx,
258
+ macros
259
+ };
260
+ if (names.includes("ppt/")) return {
261
+ type: FILE_TYPES.pptx,
262
+ macros
263
+ };
264
+ return {
265
+ type: FILE_TYPES.zip,
266
+ macros
267
+ };
268
+ }
269
+ /** Binary formats, recognised by their signatures. */
270
+ function binary(head) {
271
+ if (head.ascii(0, 5) === "%PDF-") return FILE_TYPES.pdf;
272
+ if (head.is(0, 137, 80, 78, 71, 13, 10, 26, 10)) return FILE_TYPES.png;
273
+ if (head.is(0, 255, 216, 255)) return FILE_TYPES.jpeg;
274
+ if (head.ascii(0, 6) === "GIF87a" || head.ascii(0, 6) === "GIF89a") return FILE_TYPES.gif;
275
+ if (head.ascii(0, 2) === "BM" && [
276
+ 12,
277
+ 40,
278
+ 52,
279
+ 56,
280
+ 64,
281
+ 108,
282
+ 124
283
+ ].includes(head.u32le(14))) return FILE_TYPES.bmp;
284
+ if (head.is(0, 0, 0, 1, 0) || head.is(0, 0, 0, 2, 0)) {
285
+ const count = head.u16le(4);
286
+ if (count > 0 && count <= 256 && head.at(9) === 0) return FILE_TYPES.ico;
287
+ }
288
+ if (head.is(0, 73, 73, 42, 0) || head.is(0, 77, 77, 0, 42)) return FILE_TYPES.tiff;
289
+ if (head.ascii(0, 4) === "8BPS") return FILE_TYPES.psd;
290
+ const media = isoMedia(head) ?? riff(head);
291
+ if (media) return media;
292
+ if (head.ascii(0, 3) === "ID3" || head.at(0) === 255 && [
293
+ 251,
294
+ 243,
295
+ 242
296
+ ].includes(head.at(1))) return FILE_TYPES.mp3;
297
+ if (head.ascii(0, 4) === "fLaC") return FILE_TYPES.flac;
298
+ if (head.ascii(0, 4) === "OggS") return FILE_TYPES.ogg;
299
+ if (head.is(0, 26, 69, 223, 163)) return head.ascii(0, 64).includes("webm") ? FILE_TYPES.webm : FILE_TYPES.mkv;
300
+ if (head.is(0, 31, 139)) return FILE_TYPES.gzip;
301
+ if (head.ascii(0, 3) === "BZh") return FILE_TYPES.bzip2;
302
+ if (head.is(0, 253, 55, 122, 88, 90, 0)) return FILE_TYPES.xz;
303
+ if (head.is(0, 40, 181, 47, 253)) return FILE_TYPES.zstd;
304
+ if (head.is(0, 55, 122, 188, 175, 39, 28)) return FILE_TYPES.sevenZip;
305
+ if (head.is(0, 82, 97, 114, 33, 26, 7)) return FILE_TYPES.rar;
306
+ if (head.ascii(257, 5) === "ustar") return FILE_TYPES.tar;
307
+ if (head.is(0, 208, 207, 17, 224, 161, 177, 26, 225)) return FILE_TYPES.ole;
308
+ if (head.ascii(0, 5) === "{\\rtf") return FILE_TYPES.rtf;
309
+ if (head.ascii(0, 15) === "SQLite format 3" && head.at(15) === 0) return FILE_TYPES.sqlite;
310
+ if (head.ascii(0, 4) === "wOFF") return FILE_TYPES.woff;
311
+ if (head.ascii(0, 4) === "wOF2") return FILE_TYPES.woff2;
312
+ if (head.ascii(0, 4) === "OTTO") return FILE_TYPES.otf;
313
+ if (head.is(0, 0, 1, 0, 0, 0) || head.ascii(0, 4) === "true" || head.ascii(0, 4) === "ttcf") return FILE_TYPES.ttf;
314
+ if (head.ascii(0, 2) === "MZ") return FILE_TYPES.exe;
315
+ if (head.is(0, 127, 69, 76, 70)) return FILE_TYPES.elf;
316
+ if ([
317
+ 4277009102,
318
+ 4277009103,
319
+ 3472551422,
320
+ 3489328638,
321
+ 3405691582,
322
+ 3199925962
323
+ ].includes(head.u32le(0))) return FILE_TYPES.macho;
324
+ if (head.is(0, 0, 97, 115, 109)) return FILE_TYPES.wasm;
325
+ if (head.is(0, 76, 0, 0, 0, 1, 20, 2, 0)) return FILE_TYPES.shortcut;
326
+ return null;
327
+ }
328
+ /** UTF-8 (valid, with no NUL), or UTF-16 with its byte order mark: the bytes are text. */
329
+ function decodeText(bytes, complete) {
330
+ if (bytes.length >= 2 && (bytes[0] === 255 && bytes[1] === 254 || bytes[0] === 254 && bytes[1] === 255)) return new TextDecoder(bytes[0] === 255 ? "utf-16le" : "utf-16be").decode(bytes.subarray(2));
331
+ if (bytes.includes(0)) return null;
332
+ try {
333
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: !complete });
334
+ } catch {
335
+ return null;
336
+ }
337
+ }
338
+ /** Elements that start an HTML document. Case-insensitive, though it is given lowercase text. */
339
+ const HTML_START = /^<(?:!doctype\s+html|html|head|body|script|iframe|frame|object|embed|meta|title|link|style|base|form|div|p|a|img|table)[\s/>]/i;
340
+ /** Text formats, recognised from their start. */
341
+ function textType(text, complete) {
342
+ const start = text.replace(/^\uFEFF/, "").trimStart();
343
+ const lower = start.slice(0, 1024).toLowerCase();
344
+ if (start.startsWith("#!")) return FILE_TYPES.script;
345
+ if (lower.startsWith("{\\rtf")) return FILE_TYPES.rtf;
346
+ if (lower.startsWith("<")) {
347
+ const body = lower.replace(/^(?:<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype\s+(?!html)[^>]*>|\s+)*/, "");
348
+ if (body.startsWith("<svg")) return FILE_TYPES.svg;
349
+ if (HTML_START.test(body)) return FILE_TYPES.html;
350
+ return lower.startsWith("<?xml") || /^<[a-z_][\w.:-]*[\s/>]/.test(body) ? FILE_TYPES.xml : FILE_TYPES.text;
351
+ }
352
+ if (complete && (start.startsWith("{") || start.startsWith("["))) try {
353
+ JSON.parse(start);
354
+ return FILE_TYPES.json;
355
+ } catch {
356
+ return FILE_TYPES.text;
357
+ }
358
+ return FILE_TYPES.text;
359
+ }
360
+ const ACTIVE_XML = /<script|<\?xml-stylesheet|xmlns(?::[\w.-]+)?\s*=\s*["']http:\/\/www\.w3\.org\/1999\/xhtml/i;
361
+ /**
362
+ * What `bytes` (the start of a file, {@link FILE_SNIFF_BYTES} or all of it) are.
363
+ * `complete` says whether they are the whole file, which some text formats need (JSON).
364
+ */
365
+ function detect(bytes, complete) {
366
+ const head = new Head(bytes);
367
+ const packaged = zip(head);
368
+ if (packaged) return {
369
+ type: packaged.type,
370
+ macros: packaged.macros,
371
+ active: false
372
+ };
373
+ const found = binary(head);
374
+ if (found) return {
375
+ type: found,
376
+ macros: false,
377
+ active: false
378
+ };
379
+ const text = bytes.length === 0 ? null : decodeText(bytes, complete);
380
+ if (text === null) return {
381
+ type: null,
382
+ macros: false,
383
+ active: false
384
+ };
385
+ const kind = textType(text, complete);
386
+ return {
387
+ type: kind,
388
+ macros: false,
389
+ active: kind === FILE_TYPES.html || kind === FILE_TYPES.svg || kind === FILE_TYPES.xml && ACTIVE_XML.test(text)
390
+ };
391
+ }
392
+ /**
393
+ * The type of a file's content, from its leading bytes: never from its name or claimed type.
394
+ * Reads at most {@link FILE_SNIFF_BYTES}. `null` when the content is not a recognised type.
395
+ */
396
+ function detectFileType(bytes, options = {}) {
397
+ return detect(bytes.subarray(0, FILE_SNIFF_BYTES), options.complete ?? bytes.length <= 8192).type;
398
+ }
399
+ //#endregion
400
+ //#region src/files/name.ts
401
+ /** File names: making them safe to show and store, and what they say about the file. */
402
+ /**
403
+ * Extensions the operating system runs, or mounts, when the file is opened: Windows, macOS
404
+ * and Linux programs, scripts and installers, shortcuts, and disk images (which can carry
405
+ * programs past download warnings).
406
+ */
407
+ const EXECUTABLE_EXTENSIONS = /* @__PURE__ */ new Set("exe com scr pif bat cmd ps1 ps1xml ps2 psc1 psm1 psd1 vb vbs vbe js jse mjs cjs ws wsf wsc wsh hta msi msp mst msc dll ocx sys cpl drv efi lnk url scf inf reg appref-ms application gadget xbap jar war ear class apk aab xapk ipa app command tool sh bash zsh csh ksh fish run py pyc pyw pl rb php elf so dylib bundle deb rpm pkg mpkg dmg iso img vhd vhdx appx appxbundle msix msixbundle wasm settingcontent-ms library-ms search-ms chm hlp".split(" "));
408
+ /** Extensions of documents, images and media: the decoy in front of an executable one (`invoice.pdf.exe`). */
409
+ const DECOY_EXTENSIONS = /* @__PURE__ */ new Set("pdf doc docx xls xlsx ppt pptx odt ods odp rtf txt csv md jpg jpeg png gif webp heic bmp tif tiff svg mp3 mp4 mov avi wav m4a zip rar 7z html htm eml msg".split(" "));
410
+ /** Extensions of Office files that can hold macros. */
411
+ const MACRO_EXTENSIONS = /* @__PURE__ */ new Set([
412
+ "docm",
413
+ "dotm",
414
+ "xlsm",
415
+ "xltm",
416
+ "xlam",
417
+ "pptm",
418
+ "potm",
419
+ "ppsm",
420
+ "ppam",
421
+ "sldm"
422
+ ]);
423
+ /** Extensions of active content: it runs script when a browser opens it from your origin. */
424
+ const ACTIVE_EXTENSIONS = /* @__PURE__ */ new Set([
425
+ "html",
426
+ "htm",
427
+ "xhtml",
428
+ "xht",
429
+ "shtml",
430
+ "mht",
431
+ "mhtml",
432
+ "svg",
433
+ "svgz"
434
+ ]);
435
+ /**
436
+ * Bidirectional controls, invisible and control characters, and other characters that make
437
+ * a name display as something else, or break where it is stored.
438
+ */
439
+ const HIDDEN_SOURCE = String.raw`[\u0000-\u001f\u007f-\u009f\u00AD\u061C\u115F\u1160\u17B4\u17B5\u180B-\u180F\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF0-\uFFFB]|[\u{e0000}-\u{e0fff}]`;
440
+ const HIDDEN = /* @__PURE__ */ new RegExp(HIDDEN_SOURCE, "u");
441
+ const HIDDEN_ALL = /* @__PURE__ */ new RegExp(HIDDEN_SOURCE, "gu");
442
+ /** Whether `name` holds characters that hide or reorder what it shows. */
443
+ function hasHiddenCharacters(name) {
444
+ return HIDDEN.test(name);
445
+ }
446
+ /** The last extension of `name`, lowercase, without the dot; `null` for none (`README`, `.env`). */
447
+ function extensionOf(name) {
448
+ const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1).replace(/[\s.]+$/u, "");
449
+ const dot = base.lastIndexOf(".");
450
+ if (dot <= 0) return null;
451
+ return base.slice(dot + 1).trim().toLowerCase();
452
+ }
453
+ /**
454
+ * A document or image extension followed by an executable one, as in `invoice.pdf.exe`, or
455
+ * an executable extension pushed out of view by a run of spaces (`invoice.pdf .exe`).
456
+ */
457
+ function hasDoubleExtension(name) {
458
+ const cleaned = name.replace(HIDDEN_ALL, "");
459
+ const last = extensionOf(cleaned);
460
+ if (last === null || !EXECUTABLE_EXTENSIONS.has(last)) return false;
461
+ const rest = cleaned.slice(0, cleaned.toLowerCase().lastIndexOf(`.${last}`));
462
+ if (/\s{3,}$/u.test(rest)) return true;
463
+ const previous = extensionOf(rest);
464
+ return previous !== null && DECOY_EXTENSIONS.has(previous);
465
+ }
466
+ const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[0-9\u00B9\u00B2\u00B3]|lpt[0-9\u00B9\u00B2\u00B3]|conin\$|conout\$)$/i;
467
+ const encoder = /* @__PURE__ */ new TextEncoder();
468
+ /** Cuts `text` to at most `bytes` UTF-8 bytes, never inside a character. */
469
+ function cutToBytes(text, bytes) {
470
+ let out = "";
471
+ let used = 0;
472
+ for (const char of text) {
473
+ const size = encoder.encode(char).length;
474
+ if (used + size > bytes) break;
475
+ out += char;
476
+ used += size;
477
+ }
478
+ return out;
479
+ }
480
+ /** A replacement that can itself be in a file name (up to 4 characters), or `_`. */
481
+ const safeReplacement = (value) => /^[^<>:"/\\|?*\s.]{0,4}$/u.test(value) && !hasHiddenCharacters(value) ? value : "_";
482
+ /**
483
+ * `name` made safe to show and to store on any operating system:
484
+ *
485
+ * - only the last path segment is kept, so `../../etc/passwd` becomes `passwd`;
486
+ * - bidirectional controls, invisible and control characters are removed (tabs and line breaks become spaces);
487
+ * - characters Windows, macOS or Linux reject (`<>:"/\|?*`) become `replacement`;
488
+ * - runs of whitespace become one space, and leading dots and spaces and trailing dots and
489
+ * spaces are removed (no hidden files, nothing Windows would change);
490
+ * - Windows device names (`CON`, `NUL`, `COM1`, ...) are prefixed with `replacement`;
491
+ * - the result is at most `maxBytes` long in UTF-8, keeping the extension; Unicode is NFC.
492
+ *
493
+ * Never empty: `fallback` is used when nothing is left. Idempotent.
494
+ */
495
+ function safeFileName(name, options = {}) {
496
+ const replacement = safeReplacement(options.replacement ?? "_");
497
+ const fallback = options.fallback ?? "file";
498
+ const maxBytes = Math.max(16, Math.floor(options.maxBytes ?? 255));
499
+ let safe = name.replace(/[\t\n\v\f\r]/gu, " ").replace(HIDDEN_ALL, "").normalize("NFC");
500
+ safe = safe.slice(Math.max(safe.lastIndexOf("/"), safe.lastIndexOf("\\")) + 1);
501
+ safe = safe.replace(/[<>:"|?*]/gu, replacement).replace(/\s+/gu, " ").replace(/^[\s.]+/u, "").replace(/[\s.]+$/u, "");
502
+ if (safe === "") return fallback;
503
+ const prefix = replacement === "" ? "_" : replacement;
504
+ const reserved = (text) => WINDOWS_RESERVED.test((text.includes(".") ? text.slice(0, text.indexOf(".")) : text).trim());
505
+ if (reserved(safe)) safe = `${prefix}${safe}`;
506
+ if (encoder.encode(safe).length <= maxBytes) return safe;
507
+ const extension = extensionOf(safe);
508
+ const kept = extension === null ? "" : `.${extension}`;
509
+ const suffix = kept !== "" && encoder.encode(kept).length <= Math.min(17, maxBytes - 8) ? kept : "";
510
+ const budget = maxBytes - encoder.encode(suffix).length;
511
+ const cut = (bytes) => cutToBytes(safe.slice(0, safe.length - suffix.length), bytes).replace(/[\s.]+$/u, "");
512
+ const result = `${cut(budget)}${suffix}`;
513
+ return reserved(result) ? `${prefix}${cut(budget - encoder.encode(prefix).length)}${suffix}` : result;
514
+ }
515
+ //#endregion
516
+ //#region src/files/types.ts
517
+ /** Every risk, in a stable order. */
518
+ const FILE_RISKS = Object.freeze([
519
+ "executable",
520
+ "active-content",
521
+ "macros",
522
+ "type-mismatch",
523
+ "double-extension",
524
+ "hidden-characters",
525
+ "empty"
526
+ ]);
527
+ //#endregion
528
+ //#region src/files/inspect.ts
529
+ /** Content types that any text extension may hold (`.csv`, `.md`, `.log`, ...). */
530
+ const PLAIN_TEXT = /* @__PURE__ */ new Set([
531
+ FILE_TYPES.text.mime,
532
+ FILE_TYPES.json.mime,
533
+ FILE_TYPES.xml.mime
534
+ ]);
535
+ /** Extensions of text formats this module doesn't tell apart: any plain text content fits them. */
536
+ const TEXT_EXTENSIONS = /* @__PURE__ */ new Set("txt text csv tsv md markdown mdx rst adoc org tex bib log ini cfg conf toml yaml yml env properties ics vcf vcard sql srt vtt sub css scss sass less js mjs cjs jsx ts tsx mts cts vue svelte astro py rb pl php go rs java kt kts c h cc cpp hpp cs swift m sh bash zsh bat cmd ps1 r lua dart scala clj ex exs erl hs ml fs diff patch gitignore editorconfig".split(" "));
537
+ /** MIME types of text formats known by their extension, for `accept` lists such as `text/csv`. */
538
+ const TEXT_MIME_BY_EXTENSION = {
539
+ csv: ["text/csv"],
540
+ tsv: ["text/tab-separated-values"],
541
+ md: ["text/markdown"],
542
+ markdown: ["text/markdown"],
543
+ yaml: ["application/yaml", "text/yaml"],
544
+ yml: ["application/yaml", "text/yaml"],
545
+ ics: ["text/calendar"],
546
+ vcf: ["text/vcard"],
547
+ css: ["text/css"],
548
+ js: ["text/javascript"],
549
+ mjs: ["text/javascript"],
550
+ vtt: ["text/vtt"],
551
+ srt: ["application/x-subrip"],
552
+ json: ["application/json"],
553
+ xml: ["application/xml", "text/xml"]
554
+ };
555
+ let byExtension = null;
556
+ /** Every type saved with `extension`. Built on first use. */
557
+ function typesFor(extension) {
558
+ if (byExtension === null) {
559
+ const map = /* @__PURE__ */ new Map();
560
+ for (const type of Object.values(FILE_TYPES)) for (const ext of type.extensions) map.set(ext, [...map.get(ext) ?? [], type]);
561
+ byExtension = map;
562
+ }
563
+ return byExtension.get(extension) ?? [];
564
+ }
565
+ /** Whether `extension` is saved for text: a known text format, or a type that is text inside. */
566
+ function isTextExtension(extension) {
567
+ return TEXT_EXTENSIONS.has(extension) || typesFor(extension).some((type) => type.parent === FILE_TYPES.text.mime || type === FILE_TYPES.text);
568
+ }
569
+ /**
570
+ * Whether the content contradicts the extension. An unknown extension never does; a known one
571
+ * does when the content is another type (a container and what it packages are the same family:
572
+ * `.zip` and a Word document), or is not recognised at all.
573
+ */
574
+ function contradicts(extension, detected) {
575
+ if (extension === null) return false;
576
+ const expected = typesFor(extension);
577
+ const text = isTextExtension(extension);
578
+ if (expected.length === 0 && !text) return false;
579
+ if (detected === null) return true;
580
+ const related = (child, parent) => child.parent === parent.mime && parent !== FILE_TYPES.text;
581
+ if (expected.some((type) => type.mime === detected.mime || related(detected, type) || related(type, detected))) return false;
582
+ return !(text && PLAIN_TEXT.has(detected.mime));
583
+ }
584
+ /** The type to store a file as: the detected one, made precise by the extension for plain text (`text/csv`). */
585
+ function typeOf(detected, extension, mismatch) {
586
+ if (detected === null) return "application/octet-stream";
587
+ const named = extension === null || mismatch ? void 0 : TEXT_MIME_BY_EXTENSION[extension]?.[0];
588
+ return named !== void 0 && PLAIN_TEXT.has(detected.mime) ? named : detected.mime;
589
+ }
590
+ /** An inspection of `bytes`, the start of a file (all of it when `complete`). */
591
+ function inspectBytes(bytes, name, declaredType, size, complete, names = {}) {
592
+ const extension = extensionOf(name);
593
+ const detection = detect(bytes, complete);
594
+ const detected = detection.type;
595
+ const mismatch = size > 0 && contradicts(extension, detected);
596
+ const found = /* @__PURE__ */ new Set();
597
+ if (detected?.family === "executable" || extension !== null && EXECUTABLE_EXTENSIONS.has(extension)) found.add("executable");
598
+ if (detection.active || extension !== null && ACTIVE_EXTENSIONS.has(extension)) found.add("active-content");
599
+ if (detection.macros || extension !== null && MACRO_EXTENSIONS.has(extension)) found.add("macros");
600
+ if (mismatch) found.add("type-mismatch");
601
+ if (hasDoubleExtension(name)) found.add("double-extension");
602
+ if (hasHiddenCharacters(name)) found.add("hidden-characters");
603
+ if (size === 0) found.add("empty");
604
+ return {
605
+ name,
606
+ safeName: safeFileName(name, names),
607
+ extension,
608
+ size,
609
+ declaredType,
610
+ detected,
611
+ type: typeOf(detected, extension, mismatch),
612
+ mismatch,
613
+ risks: FILE_RISKS.filter((risk) => found.has(risk))
614
+ };
615
+ }
616
+ /** Reads the first `bytes` of `blob`. */
617
+ async function readHead(blob, bytes) {
618
+ const candidate = blob;
619
+ if (typeof candidate !== "object" || candidate === null || typeof candidate.slice !== "function") throw require_errors.copyFailure("invalid-payload", "Expected a Blob or File.");
620
+ return new Uint8Array(await blob.slice(0, bytes).arrayBuffer());
621
+ }
622
+ /**
623
+ * What a file really is, and why it may be unsafe to accept: its type from its content (never
624
+ * its name or claimed type), whether that contradicts its extension, and its risks.
625
+ * Reads only the first {@link FILE_SNIFF_BYTES} bytes, so it is fast for any size. Server-safe.
626
+ *
627
+ * @throws {CopyFailure} `invalid-payload` when `file` is not a Blob.
628
+ */
629
+ async function inspectFile(file, options = {}) {
630
+ return inspectBytes(await readHead(file, FILE_SNIFF_BYTES), options.name ?? file.name ?? "", options.declaredType ?? file.type, file.size, file.size <= FILE_SNIFF_BYTES, options.names);
631
+ }
632
+ //#endregion
633
+ //#region src/files/accept.ts
634
+ /** The tokens of an `accept` list, as in `<input type="file" accept>`: `.pdf`, `image/*`, `text/csv`. Lowercase. */
635
+ function parseAccept(accept) {
636
+ return (typeof accept === "string" ? accept.split(",") : accept).map((token) => token.trim().toLowerCase()).filter((token) => /^(?:\.[^\s,/\\]+|\*|\*\/\*|[a-z0-9!#$&^_.+-]+\/(?:\*|[a-z0-9!#$&^_.+-]+))$/.test(token));
637
+ }
638
+ /**
639
+ * Whether a file fits an `accept` list, judged by its content. An extension token (`.pdf`)
640
+ * matches the name, when the content does not contradict it. A MIME token (`application/pdf`,
641
+ * `image/*`) matches the detected type or its container; plain text also matches the type its
642
+ * extension names (`text/csv` for `data.csv`). The claimed type is never used. An empty list
643
+ * accepts everything.
644
+ */
645
+ function matchesAccept(inspection, accept) {
646
+ const tokens = parseAccept(accept);
647
+ if (tokens.length === 0) return true;
648
+ const name = inspection.name.toLowerCase();
649
+ const types = [inspection.type];
650
+ if (inspection.detected?.parent) types.push(inspection.detected.parent);
651
+ if (inspection.detected?.family === "text" && !inspection.mismatch && inspection.extension !== null) types.push(...TEXT_MIME_BY_EXTENSION[inspection.extension] ?? []);
652
+ return tokens.some((token) => {
653
+ if (token === "*" || token === "*/*") return true;
654
+ if (token.startsWith(".")) return name.endsWith(token) && !inspection.mismatch;
655
+ if (token.endsWith("/*")) return inspection.detected !== null && types.some((type) => type.startsWith(token.slice(0, -1)));
656
+ return types.includes(token);
657
+ });
658
+ }
659
+ //#endregion
660
+ //#region src/files/collect.ts
661
+ const DEFAULT_MAX_FILES = 100;
662
+ const DEFAULT_MAX_FILE_BYTES = 104857600;
663
+ const DEFAULT_MAX_TOTAL_BYTES = 1073741824;
664
+ const DEFAULT_MAX_FOLDER_DEPTH = 8;
665
+ function readEntries(directory) {
666
+ const reader = directory.createReader();
667
+ return (async function* batches() {
668
+ for (;;) {
669
+ const batch = await new Promise((resolve, reject) => {
670
+ reader.readEntries(resolve, reject);
671
+ });
672
+ if (batch.length === 0) return;
673
+ yield* batch;
674
+ }
675
+ })();
676
+ }
677
+ const entryFile = (entry) => new Promise((resolve, reject) => {
678
+ entry.file(resolve, reject);
679
+ });
680
+ function isDataTransfer(value) {
681
+ return "files" in value && "types" in value;
682
+ }
683
+ /**
684
+ * The dropped items, read at once: a `DataTransfer` is emptied when its event ends, so this
685
+ * runs before anything is awaited. Dropped files are taken as files (`getAsFile`), which every
686
+ * engine gives; entries are used only to walk folders.
687
+ */
688
+ function roots(source, folders) {
689
+ const candidate = source;
690
+ const transfer = isDataTransfer(source) ? source : candidate.dataTransfer ?? candidate.clipboardData;
691
+ if (transfer === void 0) {
692
+ const list = source;
693
+ return Array.from(Symbol.iterator in Object(list) ? list : list, (file) => ({ file }));
694
+ }
695
+ if (transfer === null) return [];
696
+ const found = [];
697
+ for (const item of Array.from(transfer.items ?? [])) {
698
+ if (item.kind !== "file") continue;
699
+ const getEntry = item.webkitGetAsEntry;
700
+ const entry = folders && getEntry ? getEntry.call(item) : null;
701
+ if (entry?.isDirectory) {
702
+ found.push({ entry });
703
+ continue;
704
+ }
705
+ const file = item.getAsFile();
706
+ if (file) found.push({ file });
707
+ }
708
+ return found.length > 0 ? found : Array.from(transfer.files, (file) => ({ file }));
709
+ }
710
+ async function* walk(roots, maxDepth, names) {
711
+ const safe = (name, fallback) => safeFileName(name, {
712
+ ...names,
713
+ fallback
714
+ });
715
+ async function* visit(entry, parent, depth) {
716
+ const name = safe(entry.name, entry.isDirectory ? "folder" : "file");
717
+ const path = parent === "" ? name : `${parent}/${name}`;
718
+ if (entry.isFile) {
719
+ try {
720
+ yield {
721
+ kind: "file",
722
+ file: await entryFile(entry),
723
+ path,
724
+ name
725
+ };
726
+ } catch {
727
+ yield {
728
+ kind: "skipped",
729
+ reason: "unreadable",
730
+ path,
731
+ name
732
+ };
733
+ }
734
+ return;
735
+ }
736
+ if (!entry.isDirectory) return;
737
+ if (depth >= maxDepth) {
738
+ yield {
739
+ kind: "skipped",
740
+ reason: "too-deep",
741
+ path,
742
+ name
743
+ };
744
+ return;
745
+ }
746
+ try {
747
+ for await (const child of readEntries(entry)) yield* visit(child, path, depth + 1);
748
+ } catch {
749
+ yield {
750
+ kind: "skipped",
751
+ reason: "unreadable",
752
+ path,
753
+ name
754
+ };
755
+ }
756
+ }
757
+ for (const root of roots) if ("entry" in root) yield* visit(root.entry, "", 0);
758
+ else {
759
+ const name = safe(root.file.name ?? "", "file");
760
+ yield {
761
+ kind: "file",
762
+ file: root.file,
763
+ path: name,
764
+ name
765
+ };
766
+ }
767
+ }
768
+ const UNITS = [
769
+ "bytes",
770
+ "KB",
771
+ "MB",
772
+ "GB",
773
+ "TB"
774
+ ];
775
+ /** `1048576` as `1 MB`. */
776
+ function formatBytes(bytes) {
777
+ let value = bytes;
778
+ let unit = 0;
779
+ while (value >= 1024 && unit < UNITS.length - 1) {
780
+ value /= 1024;
781
+ unit += 1;
782
+ }
783
+ return `${String(unit === 0 ? value : Math.round(value * 10) / 10)} ${UNITS[unit]}`;
784
+ }
785
+ const RISK_MESSAGES = {
786
+ executable: (name) => `${name} is a program or script, which can't be added.`,
787
+ "active-content": (name) => `${name} is a web page or SVG that can run scripts, so it can't be added.`,
788
+ macros: (name) => `${name} can contain macros, so it can't be added.`,
789
+ "type-mismatch": (name) => `${name} is not the type of file its name says.`,
790
+ "double-extension": (name) => `${name} hides its real type behind a second extension.`,
791
+ "hidden-characters": (name) => `${name} has hidden characters in its name.`,
792
+ empty: (name) => `${name} is empty.`
793
+ };
794
+ async function sha256(blob) {
795
+ const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
796
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
797
+ }
798
+ function positive(value, fallback, name) {
799
+ if (value === void 0) return fallback;
800
+ if (!(value >= 0)) throw require_errors.copyFailure("invalid-payload", `${name} must be a number of at least 0.`);
801
+ return value;
802
+ }
803
+ /**
804
+ * Takes the files from a paste, a drop (folders included), a file input or a list, and
805
+ * decides for each whether it is safe and wanted: its type is read from its content, its
806
+ * name made safe, and the limits applied. Nothing is uploaded or read whole (except with
807
+ * `digest`): only each file's first 8 KiB.
808
+ *
809
+ * Call it from the event handler, before anything is awaited: a `DataTransfer` is emptied
810
+ * when its event ends. Folders are read through `webkitGetAsEntry` (every current browser).
811
+ *
812
+ * ```ts
813
+ * onDrop={(event) => {
814
+ * event.preventDefault();
815
+ * void acceptFiles(event, { accept: '.pdf,image/*', maxFileBytes: 20e6 }).then(({ accepted, rejected }) => { ... });
816
+ * }}
817
+ * ```
818
+ *
819
+ * @throws {CopyFailure} `aborted` when `signal` aborts; `unsupported` for `digest` without Web Crypto;
820
+ * `invalid-payload` for a negative limit.
821
+ */
822
+ async function acceptFiles(source, options = {}) {
823
+ const found = roots(source, options.folders ?? true);
824
+ const maxFiles = positive(options.maxFiles, 100, "maxFiles");
825
+ const maxFileBytes = positive(options.maxFileBytes, DEFAULT_MAX_FILE_BYTES, "maxFileBytes");
826
+ const maxTotalBytes = positive(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES, "maxTotalBytes");
827
+ const maxDepth = positive(options.maxDepth, 8, "maxDepth");
828
+ const block = new Set(options.block ?? FILE_RISKS);
829
+ const digest = options.digest === true;
830
+ if (digest && (typeof crypto === "undefined" || typeof crypto.subtle === "undefined")) throw require_errors.copyFailure("unsupported", "digest needs Web Crypto (crypto.subtle): a secure page, or Node.js 20+ (on 18, set globalThis.crypto to webcrypto from node:crypto).");
831
+ const signal = options.signal;
832
+ const checkAborted = () => {
833
+ if (signal?.aborted) throw require_errors.copyFailure("aborted", "Adding files was aborted.", signal.reason);
834
+ };
835
+ checkAborted();
836
+ const accepted = [];
837
+ const rejected = [];
838
+ const seen = /* @__PURE__ */ new Map();
839
+ let totalBytes = 0;
840
+ let count = 0;
841
+ let truncated = false;
842
+ const reject = (file, name, path, reason, message, risks = []) => {
843
+ rejected.push({
844
+ file,
845
+ name,
846
+ path,
847
+ reason,
848
+ risks,
849
+ message
850
+ });
851
+ };
852
+ for await (const item of walk(found, maxDepth, options.names ?? {})) {
853
+ checkAborted();
854
+ if (item.kind === "skipped") {
855
+ reject(null, item.name, item.path, item.reason, item.reason === "too-deep" ? `${item.path} was not read: it is more than ${String(maxDepth)} folders deep.` : `${item.path} could not be read.`);
856
+ continue;
857
+ }
858
+ const { file, name, path } = item;
859
+ count += 1;
860
+ if (count > maxFiles) {
861
+ truncated = true;
862
+ reject(file, name, path, "too-many", `${name} and any files after it were not added: at most ${String(maxFiles)} files can be added at once.`);
863
+ break;
864
+ }
865
+ if (file.size > maxFileBytes) {
866
+ reject(file, name, path, "too-large", `${name} is larger than ${formatBytes(maxFileBytes)}.`);
867
+ continue;
868
+ }
869
+ let inspection;
870
+ try {
871
+ inspection = inspectBytes(await readHead(file, FILE_SNIFF_BYTES), file.name ?? "", file.type, file.size, file.size <= FILE_SNIFF_BYTES, options.names);
872
+ } catch {
873
+ checkAborted();
874
+ reject(file, name, path, "unreadable", `${name} could not be read.`);
875
+ continue;
876
+ }
877
+ checkAborted();
878
+ const blocked = inspection.risks.find((risk) => block.has(risk));
879
+ if (blocked !== void 0) {
880
+ reject(file, name, path, "blocked", RISK_MESSAGES[blocked](name), inspection.risks);
881
+ continue;
882
+ }
883
+ if (options.accept !== void 0 && !matchesAccept(inspection, options.accept)) {
884
+ reject(file, name, path, "not-accepted", `${name} is not a type of file that can be added here.`, inspection.risks);
885
+ continue;
886
+ }
887
+ if (totalBytes + file.size > maxTotalBytes) {
888
+ reject(file, name, path, "total-too-large", `${name} was not added: the files together would be larger than ${formatBytes(maxTotalBytes)}.`, inspection.risks);
889
+ continue;
890
+ }
891
+ let hash = null;
892
+ if (digest) {
893
+ try {
894
+ hash = await sha256(file);
895
+ } catch {
896
+ checkAborted();
897
+ reject(file, name, path, "unreadable", `${name} could not be read.`, inspection.risks);
898
+ continue;
899
+ }
900
+ checkAborted();
901
+ const original = seen.get(hash);
902
+ if (original !== void 0) {
903
+ reject(file, name, path, "duplicate", `${name} is the same file as ${original}.`, inspection.risks);
904
+ continue;
905
+ }
906
+ seen.set(hash, path);
907
+ }
908
+ totalBytes += file.size;
909
+ accepted.push({
910
+ file,
911
+ upload: typeof File === "function" ? new File([file], name, {
912
+ type: inspection.type,
913
+ lastModified: file.lastModified ?? Date.now()
914
+ }) : new Blob([file], { type: inspection.type }),
915
+ name,
916
+ path,
917
+ size: file.size,
918
+ type: inspection.type,
919
+ inspection,
920
+ sha256: hash
921
+ });
922
+ }
923
+ return {
924
+ accepted,
925
+ rejected,
926
+ totalBytes,
927
+ truncated
928
+ };
929
+ }
930
+ //#endregion
931
+ exports.DEFAULT_MAX_FILES = DEFAULT_MAX_FILES;
932
+ exports.DEFAULT_MAX_FILE_BYTES = DEFAULT_MAX_FILE_BYTES;
933
+ exports.DEFAULT_MAX_FOLDER_DEPTH = DEFAULT_MAX_FOLDER_DEPTH;
934
+ exports.DEFAULT_MAX_TOTAL_BYTES = DEFAULT_MAX_TOTAL_BYTES;
935
+ exports.EXECUTABLE_EXTENSIONS = EXECUTABLE_EXTENSIONS;
936
+ exports.FILE_RISKS = FILE_RISKS;
937
+ exports.FILE_SNIFF_BYTES = FILE_SNIFF_BYTES;
938
+ exports.FILE_TYPES = FILE_TYPES;
939
+ exports.acceptFiles = acceptFiles;
940
+ exports.detectFileType = detectFileType;
941
+ exports.extensionOf = extensionOf;
942
+ exports.formatBytes = formatBytes;
943
+ exports.inspectFile = inspectFile;
944
+ exports.matchesAccept = matchesAccept;
945
+ exports.parseAccept = parseAccept;
946
+ exports.safeFileName = safeFileName;
947
+
948
+ //# sourceMappingURL=files.cjs.map