-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlittle-export.core.js
More file actions
2548 lines (2232 loc) · 81.1 KB
/
little-export.core.js
File metadata and controls
2548 lines (2232 loc) · 81.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
const TYPE = { OPFS: 1, IDB: 2, LS: 4, SS: 8, COOKIE: 16, CACHE: 32 };
const DECISION = { SKIP: 0, PROCESS: 1, TRUST: 2, ABORT: 3 };
let blobIdCounter = 0;
function createYielder(threshold = 100) {
// Testing has shown that Chromium's performance.now() is worst-case slower than all other browsers (but can still be called millions of times per second). Date.now() Browsers like Firefox actually have performance.now() over 10x faster than Date.now(), upwards of hundreds of millions of checks per second. However, this shouldn't really matter too much here as yielding is not checked often enough for this to add up significantly.
let lastYield = 0;
let inflight = null;
const channel = new MessageChannel();
const resolvers = [];
channel.port1.onmessage = () => resolvers.shift()?.();
async function doYield() {
if ("scheduler" in window && "yield" in scheduler) {
await scheduler.yield();
} else {
await new Promise((res) => {
resolvers.push(res);
channel.port2.postMessage(null);
});
}
lastYield = Date.now();
inflight = null;
}
return function (force = false) {
const now = Date.now();
if (!force && now - lastYield <= threshold) return null;
if (!inflight) inflight = doYield();
return inflight;
};
}
const CHUNK_SIZE = 4194304;
const TAR_BUFFER_SIZE = 65536;
const ENC = new TextEncoder();
const DEC = new TextDecoder("utf-8", { fatal: false });
async function deriveKey(password, salt) {
const km = await crypto.subtle.importKey(
"raw",
ENC.encode(password),
{ name: "PBKDF2" },
false,
["deriveKey"],
);
return crypto.subtle.deriveKey(
{ name: "PBKDF2", salt, iterations: 600000, hash: "SHA-256" },
km,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
// Simple mode filter, supports functions and arrays
function checkSimpleFilter(category, pathStr, config) {
const { include, exclude } = config;
// Check exclude first (blacklist)
if (exclude && exclude[category]) {
const filter = exclude[category];
if (typeof filter === "function") {
if (filter(pathStr)) return false;
} else if (Array.isArray(filter)) {
// Either exact match or directory prefix match
if (filter.some((t) => pathStr === t || pathStr.startsWith(t + "/")))
return false;
}
}
// Check include (whitelist), only if specified
if (include && include[category]) {
const filter = include[category];
if (typeof filter === "function") {
return filter(pathStr);
} else if (Array.isArray(filter) && filter.length > 0) {
return filter.some((t) => pathStr === t || pathStr.startsWith(t + "/"));
}
}
return true;
}
// All access of this function will be from LittleExport.prepForCBOR to allow for customization.
function prepForCBOR(
item,
externalBlobs,
seen = new WeakMap(),
blobMap = new Map(),
) {
if (!item || typeof item !== "object") return item;
if (
item instanceof ArrayBuffer ||
ArrayBuffer.isView(item) ||
item instanceof Date
) {
return item;
}
if (seen.has(item)) return seen.get(item);
if (item instanceof Blob) {
if (blobMap.has(item)) {
return blobMap.get(item);
}
const id = (blobIdCounter++).toString(16);
externalBlobs.push({ uuid: id, blob: item });
const ref = { __le_blob_ref: id, type: item.type, size: item.size };
blobMap.set(item, ref);
return ref;
}
let res;
if (Array.isArray(item)) {
const keys = Object.keys(item);
const isSparse = keys.length < item.length || keys.some((k) => isNaN(k));
if (isSparse) {
res = { __le_sparse: true, length: item.length, data: {} };
seen.set(item, res);
for (const k of keys) {
res.data[k] = LittleExport.prepForCBOR(
item[k],
externalBlobs,
seen,
blobMap,
);
}
} else {
res = new Array(item.length);
seen.set(item, res);
for (let i = 0; i < item.length; i++) {
res[i] = LittleExport.prepForCBOR(
item[i],
externalBlobs,
seen,
blobMap,
);
}
}
} else {
res = {};
seen.set(item, res);
for (const k in item) {
if (Object.prototype.hasOwnProperty.call(item, k)) {
res[k] = LittleExport.prepForCBOR(
item[k],
externalBlobs,
seen,
blobMap,
);
}
}
}
return res;
}
async function restoreFromCBOR(item, tempBlobDir) {
if (!item || typeof item !== "object") return item;
if (item.__le_blob_ref) {
if (!tempBlobDir) return null;
try {
const fh = await tempBlobDir.getFileHandle(item.__le_blob_ref);
const file = await fh.getFile();
return file.slice(0, file.size, item.type);
} catch (err) {
return null; // Blob not found, gracefully return null
}
}
if (item.__le_sparse) {
const arr = new Array(item.length);
for (const k in item.data) {
arr[k] = await restoreFromCBOR(item.data[k], tempBlobDir);
}
return arr;
}
if (Array.isArray(item)) {
const res = new Array(item.length);
for (let i = 0; i < item.length; i++) {
res[i] = await LittleExport.restoreFromCBOR(item[i], tempBlobDir);
}
return res;
}
if (item.constructor === Object) {
const n = {};
for (const k in item) {
n[k] = await LittleExport.restoreFromCBOR(item[k], tempBlobDir);
}
return n;
}
return item;
}
const TAR_CONSTANTS = {
USTAR_MAGIC: new Uint8Array([117, 115, 116, 97, 114, 0]),
USTAR_VER: new Uint8Array([48, 48]),
EMPTY_SPACE: new Uint8Array(8).fill(32),
};
const HEADER_TEMPLATE = new Uint8Array(512);
(function initTemplate() {
const w = (str, off) => ENC.encodeInto(str, HEADER_TEMPLATE.subarray(off));
w("000644 \0", 100);
w("000000 \0", 108);
w("000000 \0", 116);
HEADER_TEMPLATE.set(TAR_CONSTANTS.EMPTY_SPACE, 148);
HEADER_TEMPLATE[156] = 48;
HEADER_TEMPLATE.set(TAR_CONSTANTS.USTAR_MAGIC, 257);
HEADER_TEMPLATE.set(TAR_CONSTANTS.USTAR_VER, 263);
})();
function createPaxData(path, size) {
const encoder = new TextEncoder();
let content = new Uint8Array(0);
const addRecord = (keyword, value) => {
if (value == null) return;
const strVal = String(value);
// Format: "length keyword=value\n"
const suffix = ` ${keyword}=${strVal}\n`;
const suffixBytes = encoder.encode(suffix);
// Calculate total length (bytes of length string + space + bytes of suffix)
let total = suffixBytes.length;
let lenStr = String(total);
// Adjust length until it stabilizes (since going from length 9 to 10 adds a digit)
while (true) {
const newTotal = suffixBytes.length + lenStr.length;
if (newTotal === total) break;
total = newTotal;
lenStr = String(total);
}
const line = encoder.encode(`${lenStr}${suffix}`);
const newContent = new Uint8Array(content.length + line.length);
newContent.set(content);
newContent.set(line, content.length);
content = newContent;
};
addRecord("path", path);
if (size > 8589934591) {
addRecord("size", size);
}
return content;
}
function createTarHeader(filename, size, time, type = "0", mode = "000644") {
const safeSize = size > 8589934591 ? 0 : size;
const buffer = HEADER_TEMPLATE.slice(0);
// 0=file, 5=dir, x=pax
buffer[156] = type.charCodeAt(0);
// Write filename
const nameBytes = ENC.encode(filename);
const copyLen = Math.min(nameBytes.length, 100);
buffer.set(nameBytes.subarray(0, copyLen), 0);
if (mode) {
ENC.encodeInto(mode.padEnd(7, "\0"), buffer.subarray(100, 108));
}
const writeOctal = (num, offset, len) => {
const str = Math.floor(num)
.toString(8)
.padStart(len - 1, "0");
if (str.length >= len) {
LittleExport.warn(
"PAX attempted to write octal that was too long (due to either sizes or timestamp).",
);
return;
}
ENC.encodeInto(str, buffer.subarray(offset, offset + len - 1));
buffer[offset + len - 1] = 0; // Space/null termination
};
writeOctal(safeSize, 124, 12);
writeOctal(time, 136, 12);
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += buffer[i];
}
const cksumStr = sum.toString(8).padStart(6, "0");
ENC.encodeInto(cksumStr, buffer.subarray(148));
buffer[154] = 0;
buffer[155] = 32;
return buffer;
}
class TarWriter {
constructor(writableStream, yielder) {
this.writer = writableStream.getWriter();
this.yielder = yielder;
this.pos = 0;
this.time = Math.floor(Date.now() / 1000);
this.buffer = new Uint8Array(TAR_BUFFER_SIZE);
this.bufferOffset = 0;
}
async writeEntry(path, data) {
const bytes = typeof data === "string" ? ENC.encode(data) : data;
const size = bytes.byteLength;
if (this.onFileProgress) this.onFileProgress(0, size);
await this.smartWrite(path, size, async () => {
await this.write(bytes);
});
if (this.onFileProgress) this.onFileProgress(size, size);
}
async writeStream(path, size, readableStream) {
let contentWritten = 0;
await this.flush();
await this.smartWrite(path, size, async () => {
const reader = readableStream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
const remaining = size - contentWritten;
if (remaining <= 0) {
continue;
}
const toWrite =
value.byteLength > remaining
? value.subarray(0, remaining)
: value;
await this.write(toWrite);
contentWritten += toWrite.byteLength;
if (this.onFileProgress)
this.onFileProgress(contentWritten, size);
}
const p = this.yielder();
if (p) await p;
}
if (contentWritten < size) {
const missing = size - contentWritten;
const zeros = new Uint8Array(missing);
await this.write(zeros);
}
} finally {
reader.releaseLock();
}
});
}
async smartWrite(path, size, contentFn) {
const pathBytes = ENC.encode(path);
const needsPax = pathBytes.length > 100 || size > 8589934591;
if (needsPax) {
const paxData = createPaxData(path, size); // Already handles encoding internally
const safePaxName =
"PaxHeaders/" + (path.length > 50 ? path.slice(0, 50) : path);
await this.write(
createTarHeader(safePaxName, paxData.length, this.time, "x"),
);
await this.write(paxData);
await this.pad();
}
await this.write(
createTarHeader(
path,
size,
this.time,
size === 0 && path.endsWith("/") ? "5" : "0",
),
);
if (contentFn) await contentFn();
await this.pad();
}
async writeDir(path) {
// Ensure path ends with /
if (!path.endsWith("/")) path += "/";
// Inline PAX logic
const pathBytes = ENC.encode(path);
const needsPax = pathBytes.length > 100;
if (needsPax) {
const paxData = createPaxData(path, 0);
const safePaxName =
"PaxHeaders/" + (path.length > 50 ? path.slice(0, 50) : path);
await this.write(
createTarHeader(safePaxName, paxData.length, this.time, "x"),
);
await this.write(paxData);
await this.pad();
}
const header = createTarHeader(path, 0, this.time, "5", "000755");
await this.write(header);
}
async write(chunk) {
const len = chunk.byteLength;
if (len >= TAR_BUFFER_SIZE) {
await this.flush();
await this.writer.write(chunk);
} else if (this.bufferOffset + len > TAR_BUFFER_SIZE) {
await this.flush();
this.buffer.set(chunk, 0);
this.bufferOffset = len;
} else {
this.buffer.set(chunk, this.bufferOffset);
this.bufferOffset += len;
}
this.pos += len;
}
async pad() {
const padding = (512 - (this.pos % 512)) % 512;
if (padding > 0) await this.write(new Uint8Array(padding));
}
async flush() {
if (this.bufferOffset > 0) {
await this.writer.write(this.buffer.slice(0, this.bufferOffset));
this.bufferOffset = 0;
}
}
async close() {
await this.write(new Uint8Array(1024)); // EOF
await this.flush();
await this.writer.close();
}
}
class EncryptionTransformer {
constructor(password, salt) {
this.salt = salt;
this.keyPromise = deriveKey(password, salt);
this.chunks = [];
this.currentSize = 0;
}
async start(controller) {
controller.enqueue(ENC.encode("LE_ENC"));
controller.enqueue(this.salt);
await this.encryptAndPush(
new Uint8Array(0),
controller,
await this.keyPromise,
);
}
async transform(chunk, controller) {
this.chunks.push(chunk);
this.currentSize += chunk.byteLength;
if (this.currentSize >= CHUNK_SIZE) {
const fullBuffer = new Uint8Array(this.currentSize);
let offset = 0;
for (const c of this.chunks) {
fullBuffer.set(c, offset);
offset += c.byteLength;
}
const key = await this.keyPromise;
let pos = 0;
while (pos + CHUNK_SIZE <= fullBuffer.length) {
await this.encryptAndPush(
fullBuffer.subarray(pos, pos + CHUNK_SIZE),
controller,
key,
);
pos += CHUNK_SIZE;
}
const remainder = fullBuffer.subarray(pos);
this.chunks = remainder.length > 0 ? [remainder] : [];
this.currentSize = remainder.length;
}
}
async flush(controller) {
if (this.currentSize > 0) {
const finalBuffer = new Uint8Array(this.currentSize);
let offset = 0;
for (const c of this.chunks) {
finalBuffer.set(c, offset);
offset += c.byteLength;
}
await this.encryptAndPush(
finalBuffer,
controller,
await this.keyPromise,
);
}
}
async encryptAndPush(data, controller, key) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
data,
);
const lenParams = new DataView(new ArrayBuffer(4));
lenParams.setUint32(0, ciphertext.byteLength, true);
controller.enqueue(iv);
controller.enqueue(new Uint8Array(lenParams.buffer));
controller.enqueue(new Uint8Array(ciphertext));
}
}
class ChunkBuffer {
constructor() {
this.chunks = [];
this.totalSize = 0;
this.offset = 0; // Pointer to start of valid data in chunks[0]
}
push(chunk) {
if (!chunk || chunk.byteLength === 0) return;
this.chunks.push(chunk);
this.totalSize += chunk.byteLength;
}
has(n) {
return this.totalSize >= n;
}
_internalConsume(n, callback) {
let consumed = 0;
while (consumed < n && this.chunks.length > 0) {
const chunk = this.chunks[0];
const availableInChunk = chunk.byteLength - this.offset;
const remainingNeeded = n - consumed;
const toTake = Math.min(availableInChunk, remainingNeeded);
callback(chunk.subarray(this.offset, this.offset + toTake));
this.offset += toTake;
if (this.offset >= chunk.byteLength) {
this.chunks.shift();
this.offset = 0;
}
this.totalSize -= toTake;
consumed += toTake;
}
}
read(n) {
if (n === 0) return new Uint8Array(0);
if (this.totalSize < n) throw new Error("Insufficient chunk data.");
// Fast path: data is fully contained in the first chunk
if (
this.chunks.length > 0 &&
this.chunks[0].byteLength - this.offset >= n
) {
const res = this.chunks[0].subarray(this.offset, this.offset + n);
this.offset += n;
if (this.offset >= this.chunks[0].byteLength) {
this.chunks.shift();
this.offset = 0;
}
this.totalSize -= n;
return res;
}
const result = new Uint8Array(n);
let offset = 0;
this._internalConsume(n, (seg) => {
result.set(seg, offset);
offset += seg.byteLength;
});
return result;
}
async consume(n, callback) {
let remaining = n;
while (remaining > 0 && this.chunks.length > 0) {
const chunk = this.chunks[0];
const availableInChunk = chunk.byteLength - this.offset;
const toProcess = Math.min(availableInChunk, remaining);
await callback(chunk.subarray(this.offset, this.offset + toProcess));
this.offset += toProcess;
if (this.offset >= chunk.byteLength) {
this.chunks.shift();
this.offset = 0;
}
this.totalSize -= toProcess;
remaining -= toProcess;
}
}
}
class DecryptionSource {
constructor(readableStream, password, yielder) {
this.stream = readableStream;
this.password = password;
this.yielder = yielder;
this.buffer = new ChunkBuffer();
}
readable() {
const self = this;
let reader;
async function ensure(n) {
while (!self.buffer.has(n)) {
const { value, done } = await reader.read();
if (done) return false;
self.buffer.push(value);
}
return true;
}
return new ReadableStream({
async start(controller) {
reader = self.stream.getReader();
try {
if (!(await ensure(22)))
throw new Error("Not an encrypted archive.");
const sig = DEC.decode(self.buffer.read(6));
if (sig !== "LE_ENC") throw new Error("Not an encrypted archive.");
const salt = self.buffer.read(16);
const key = await deriveKey(self.password, salt);
if (!(await ensure(16))) throw new Error("Corrupt header.");
const initIV = self.buffer.read(12);
const initLenRaw = self.buffer.read(4);
const initLen = new DataView(
initLenRaw.buffer,
initLenRaw.byteOffset,
initLenRaw.byteLength,
).getUint32(0, true);
if (initLen !== 16 || !(await ensure(initLen)))
throw new Error("Corrupt header.");
const initCipher = self.buffer.read(initLen);
try {
await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: initIV },
key,
initCipher,
);
} catch (err) {
throw new Error("Incorrect password or corrupt file.");
}
while (true) {
const p = self.yielder();
if (p) await p;
if (!self.buffer.has(16)) {
const { value, done } = await reader.read();
if (done) {
if (self.buffer.totalSize === 0) break;
throw new Error("Truncated encrypted stream.");
}
self.buffer.push(value);
continue;
}
const iv = self.buffer.read(12);
const lenRaw = self.buffer.read(4);
const lenVal = new DataView(
lenRaw.buffer,
lenRaw.byteOffset,
lenRaw.byteLength,
).getUint32(0, true);
while (!self.buffer.has(lenVal)) {
const { value, done } = await reader.read();
if (done) throw new Error("Unexpected EOF in ciphertext.");
self.buffer.push(value);
const p2 = self.yielder();
if (p2) await p2;
}
const cipher = self.buffer.read(lenVal);
const plain = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
key,
cipher,
);
const pForce = self.yielder(true);
if (pForce) await pForce;
controller.enqueue(new Uint8Array(plain));
}
controller.close();
} catch (err) {
controller.error(err);
} finally {
reader.releaseLock();
}
},
});
}
}
function verifyChecksum(header) {
const claimedStr = DEC.decode(header.slice(148, 156))
.replace(/\0/g, "")
.trim();
const claimed = parseInt(claimedStr, 8);
if (isNaN(claimed)) return false;
let sum = 0;
for (let i = 0; i < 512; i++) {
// The 8 bytes at 148 must be treated as spaces (ASCII 32)
if (i >= 148 && i < 156) sum += 32;
else sum += header[i];
}
return sum === claimed;
}
async function exportData(config = {}) {
blobIdCounter = 0;
const CBOR = window.CBOR;
// Check the LittleExport docs on all the options.
const opts = {
fileName: "archive",
logSpeed: 100,
customItems: [],
include: {}, // logic handled with checkSimpleFilter
exclude: {},
cborExtensionName: "cbor",
...config,
};
const encoder =
opts.encoder ||
new CBOR.Encoder({
structuredClone: true, // Circular references may cause errors/problems if disabled.
copyBuffers: false, // Free optimization of preventing copying of buffers (less memory use).
bundleStrings: true, // Optimization for strings at the cost of inconsistency with the formal CBOR spec (and lack of explicit documentation in cbor-x to parse). See the LittleExport README for more information.
...opts.cborOptions,
});
const cborExtensionName = opts.cborExtensionName;
const logger = opts.logger || (() => {});
const yielder = createYielder(opts.logSpeed);
const graceful = opts.graceful !== false;
const useOnVisit = typeof opts.onVisit === "function";
const onVisit = opts.onVisit;
let aborted = false;
function getDecision(type, path, meta) {
if (!useOnVisit) return DECISION.PROCESS;
return onVisit(type, path, meta);
}
async function tryGraceful(fn, context) {
try {
return await fn();
} catch (err) {
if (opts.onerror) opts.onerror(err);
if (graceful) {
logger(`Error: ${context} - ${err.message}`);
return null;
}
throw err;
}
}
const status = { category: "", detail: "" };
let outputStream,
chunks = [];
let fileName = opts.fileName.includes(".")
? opts.fileName
: opts.password
? `${opts.fileName}.enc`
: `${opts.fileName}.tar.gz`;
if (window.showSaveFilePicker && opts.download !== false) {
try {
const name = fileName;
const handle = await window.showSaveFilePicker({ suggestedName: name });
outputStream = await handle.createWritable();
} catch (err) {
if (err.name === "AbortError") {
logger("Export cancelled.");
return;
}
LittleExport.warn("FileSystem picker failed, falling back.");
}
}
if (!outputStream) {
outputStream = new WritableStream({
write(c) {
chunks.push(c);
},
close() {},
});
}
let outputBytesWritten = 0;
const countingStream = new TransformStream({
async transform(chunk, controller) {
outputBytesWritten += chunk.byteLength;
const p = yielder();
if (p) {
if (status.category) {
if (status.category === "Finishing") {
logger("Finishing...");
} else {
let msg = `Exporting ${status.category}: ${(outputBytesWritten / 1e6).toFixed(2)} MB`;
if (currentFileProgress.total > 1e6) {
msg += ` (${status.detail}: ${(currentFileProgress.written / 1e6).toFixed(1)}/${(currentFileProgress.total / 1e6).toFixed(1)} MB)`;
} else {
msg += ` (${status.detail})`;
}
logger(msg);
}
}
await p;
}
controller.enqueue(chunk);
},
});
const gzip = new CompressionStream("gzip");
let pipeline = gzip.readable;
if (opts.password) {
status.category = "Setup";
status.detail = "Encrypting...";
const salt = crypto.getRandomValues(new Uint8Array(16));
pipeline = pipeline.pipeThrough(
new TransformStream(new EncryptionTransformer(opts.password, salt)),
);
}
let currentFileProgress = { written: 0, total: 0 };
const exportFinishedPromise = pipeline
.pipeThrough(countingStream)
.pipeTo(outputStream);
const tar = new TarWriter(gzip.writable, yielder);
tar.onFileProgress = (written, total) => {
currentFileProgress.written = written;
currentFileProgress.total = total;
};
try {
// Custom items (always processed)
for (const item of opts.customItems) {
if (aborted) break;
status.category = "custom";
status.detail = item.path;
const path = `data/custom/${item.path}`;
if (item.data instanceof Blob) {
await tar.writeStream(path, item.data.size, item.data.stream());
} else {
await tar.writeEntry(
path,
typeof item.data === "string"
? item.data
: JSON.stringify(item.data),
);
}
}
// OPFS
if (!aborted && opts.opfs !== false && navigator.storage) {
let categoryDecision = getDecision(TYPE.OPFS);
if (categoryDecision && typeof categoryDecision.then === "function")
categoryDecision = await categoryDecision;
if (categoryDecision === DECISION.ABORT) aborted = true;
if (!aborted && categoryDecision !== DECISION.SKIP) {
status.category = "OPFS";
const root = await navigator.storage.getDirectory();
const trustAll = categoryDecision === DECISION.TRUST;
async function walkOpfs(dir, pathArray, inherited) {
try {
for await (const entry of dir.values()) {
if (aborted) return;
currentFileProgress.written = 0;
currentFileProgress.total = 0;
const currentPath = [...pathArray, entry.name];
const pathStr = currentPath.join("/");
let decision = inherited;
status.detail = pathStr;
if (!inherited) {
if (useOnVisit) {
let raw = getDecision(TYPE.OPFS, currentPath, {
kind: entry.kind,
handle: entry,
});
if (raw && typeof raw.then === "function") raw = await raw;
decision = raw;
if (decision === DECISION.ABORT) {
aborted = true;
return;
}
if (decision === DECISION.SKIP) continue;
} else {
if (!checkSimpleFilter("opfs", pathStr, opts)) continue;
decision = DECISION.PROCESS;
}
}
const trustChildren = decision === DECISION.TRUST;
if (entry.kind === "file") {
await tryGraceful(async () => {
const f = await entry.getFile();
await tar.writeStream(
`opfs/${pathStr}`,
f.size,
f.stream(),
);
}, `OPFS file ${pathStr}`);
} else {
// Write and recurse
await tar.writeDir(`opfs/${pathStr}`);
await walkOpfs(
entry,
currentPath,
trustChildren ? DECISION.TRUST : false,
);
}
const p = yielder();
if (p) await p;
}
} catch (err) {
// Log error but allow other folders to continue processing
logger(
`Error: accessing OPFS folder /${pathArray.join("/")} failed (${err.message})`,
);
if (opts.onerror) opts.onerror(err);
if (!graceful) throw err;
}
}
await walkOpfs(root, [], trustAll ? DECISION.TRUST : false);
}
currentFileProgress.written = 0;
currentFileProgress.total = 0;
}
// IndexedDB
if (!aborted && opts.idb !== false && window.indexedDB && CBOR) {
let categoryDecision = getDecision(TYPE.IDB);
if (categoryDecision && typeof categoryDecision.then === "function")
categoryDecision = await categoryDecision;
if (categoryDecision === DECISION.ABORT) aborted = true;
if (!aborted && categoryDecision !== DECISION.SKIP) {
status.category = "IndexedDB";
const trustAllDbs = categoryDecision === DECISION.TRUST;
const dbs = await window.indexedDB.databases();
for (const { name, version } of dbs) {
if (aborted) break;
currentFileProgress.written = 0;
currentFileProgress.total = 0;
status.detail = name;
const safeName = encodeURIComponent(name);