-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ZipFS.ts
1522 lines (1177 loc) Β· 49.1 KB
/
ZipFS.ts
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
import {Libzip} from '@yarnpkg/libzip';
import {ReadStream, WriteStream, constants} from 'fs';
import {PassThrough} from 'stream';
import {isDate} from 'util';
import zlib from 'zlib';
import {WatchOptions, WatchCallback, Watcher, Dir, Stats, BigIntStats} from './FakeFS';
import {FakeFS, MkdirOptions, RmdirOptions, WriteFileOptions, OpendirOptions} from './FakeFS';
import {CreateReadStreamOptions, CreateWriteStreamOptions, BasePortableFakeFS, ExtractHintOptions, WatchFileCallback, WatchFileOptions, StatWatcher} from './FakeFS';
import {NodeFS} from './NodeFS';
import {opendir} from './algorithms/opendir';
import {watchFile, unwatchFile, unwatchAllFiles} from './algorithms/watchFile';
import {S_IFLNK, S_IFDIR, S_IFMT, S_IFREG} from './constants';
import * as errors from './errors';
import {FSPath, PortablePath, npath, ppath, Filename} from './path';
import * as statUtils from './statUtils';
export type ZipCompression = `mixed` | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
export const DEFAULT_COMPRESSION_LEVEL: ZipCompression = `mixed`;
export type ZipBufferOptions = {
libzip: Libzip;
readOnly?: boolean;
stats?: Stats;
level?: ZipCompression;
};
export type ZipPathOptions = ZipBufferOptions & {
baseFs?: FakeFS<PortablePath>;
create?: boolean;
};
function toUnixTimestamp(time: Date | string | number) {
if (typeof time === `string` && String(+time) === time)
return +time;
if (Number.isFinite(time)) {
if (time < 0) {
return Date.now() / 1000;
} else {
return time;
}
}
// convert to 123.456 UNIX timestamp
if (isDate(time))
return (time as Date).getTime() / 1000;
throw new Error(`Invalid time`);
}
export function makeEmptyArchive() {
return Buffer.from([
0x50, 0x4B, 0x05, 0x06,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
]);
}
export class ZipFS extends BasePortableFakeFS {
private readonly libzip: Libzip;
private readonly baseFs: FakeFS<PortablePath> | null;
private readonly path: PortablePath | null;
private readonly stats: Stats;
private readonly zip: number;
private readonly lzSource: number | null = null;
private readonly level: ZipCompression;
private readonly listings: Map<PortablePath, Set<Filename>> = new Map();
private readonly entries: Map<PortablePath, number> = new Map();
/**
* A cache of indices mapped to file sources.
* Populated by `setFileSource` calls.
* Required for supporting read after write.
*/
private readonly fileSources: Map<number, Buffer> = new Map();
private symlinkCount: number;
private readonly fds: Map<number, {cursor: number, p: PortablePath}> = new Map();
private nextFd: number = 0;
private ready = false;
private readOnly = false;
constructor(p: PortablePath, opts: ZipPathOptions);
/**
* Create a ZipFS in memory
* @param data If null; an empty zip file will be created
*/
constructor(data: Buffer | null, opts: ZipBufferOptions);
constructor(source: PortablePath | Buffer | null, opts: ZipPathOptions | ZipBufferOptions) {
super();
this.libzip = opts.libzip;
const pathOptions = opts as ZipPathOptions;
this.level = typeof pathOptions.level !== `undefined`
? pathOptions.level
: DEFAULT_COMPRESSION_LEVEL;
source ??= makeEmptyArchive();
if (typeof source === `string`) {
const {baseFs = new NodeFS()} = pathOptions;
this.baseFs = baseFs;
this.path = source;
} else {
this.path = null;
this.baseFs = null;
}
if (opts.stats) {
this.stats = opts.stats;
} else {
if (typeof source === `string`) {
try {
this.stats = this.baseFs!.statSync(source);
} catch (error) {
if (error.code === `ENOENT` && pathOptions.create) {
this.stats = statUtils.makeDefaultStats();
} else {
throw error;
}
}
} else {
this.stats = statUtils.makeDefaultStats();
}
}
const errPtr = this.libzip.malloc(4);
try {
let flags = 0;
if (typeof source === `string` && pathOptions.create)
flags |= this.libzip.ZIP_CREATE | this.libzip.ZIP_TRUNCATE;
if (opts.readOnly) {
flags |= this.libzip.ZIP_RDONLY;
this.readOnly = true;
}
if (typeof source === `string`) {
this.zip = this.libzip.open(npath.fromPortablePath(source), flags, errPtr);
} else {
const lzSource = this.allocateUnattachedSource(source);
try {
this.zip = this.libzip.openFromSource(lzSource, flags, errPtr);
this.lzSource = lzSource;
} catch (error) {
this.libzip.source.free(lzSource);
throw error;
}
}
if (this.zip === 0) {
const error = this.libzip.struct.errorS();
this.libzip.error.initWithCode(error, this.libzip.getValue(errPtr, `i32`));
throw this.makeLibzipError(error);
}
} finally {
this.libzip.free(errPtr);
}
this.listings.set(PortablePath.root, new Set());
const entryCount = this.libzip.getNumEntries(this.zip, 0);
for (let t = 0; t < entryCount; ++t) {
const raw = this.libzip.getName(this.zip, t, 0);
if (ppath.isAbsolute(raw))
continue;
const p = ppath.resolve(PortablePath.root, raw);
this.registerEntry(p, t);
// If the raw path is a directory, register it
// to prevent empty folder being skipped
if (raw.endsWith(`/`)) {
this.registerListing(p);
}
}
this.symlinkCount = this.libzip.ext.countSymlinks(this.zip);
if (this.symlinkCount === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
this.ready = true;
}
makeLibzipError(error: number) {
const errorCode: number = this.libzip.struct.errorCodeZip(error);
const strerror: string = this.libzip.error.strerror(error);
const libzipError = new errors.LibzipError(strerror, this.libzip.errors[errorCode]);
// This error should never come up because of the file source cache
if (errorCode === this.libzip.errors.ZIP_ER_CHANGED)
throw new Error(`Assertion failed: Unexpected libzip error: ${libzipError.message}`);
return libzipError;
}
getExtractHint(hints: ExtractHintOptions) {
for (const fileName of this.entries.keys()) {
const ext = this.pathUtils.extname(fileName);
if (hints.relevantExtensions.has(ext)) {
return true;
}
}
return false;
}
getAllFiles() {
return Array.from(this.entries.keys());
}
getRealPath() {
if (!this.path)
throw new Error(`ZipFS don't have real paths when loaded from a buffer`);
return this.path;
}
getBufferAndClose(): Buffer {
this.prepareClose();
if (!this.lzSource)
throw new Error(`ZipFS was not created from a Buffer`);
try {
// Prevent close from cleaning up the source
this.libzip.source.keep(this.lzSource);
// Close the zip archive
if (this.libzip.close(this.zip) === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
// Open the source for reading
if (this.libzip.source.open(this.lzSource) === -1)
throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
// Move to the end of source
if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_END) === -1)
throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
// Get the size of source
const size: number = this.libzip.source.tell(this.lzSource);
if (size === -1)
throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
// Move to the start of source
if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_SET) === -1)
throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
const buffer = this.libzip.malloc(size);
if (!buffer)
throw new Error(`Couldn't allocate enough memory`);
try {
const rc = this.libzip.source.read(this.lzSource, buffer, size);
if (rc === -1)
throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
else if (rc < size)
throw new Error(`Incomplete read`);
else if (rc > size)
throw new Error(`Overread`);
const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
return Buffer.from(memory);
} finally {
this.libzip.free(buffer);
}
} finally {
this.libzip.source.close(this.lzSource);
this.libzip.source.free(this.lzSource);
this.ready = false;
}
}
private prepareClose() {
if (!this.ready)
throw errors.EBUSY(`archive closed, close`);
unwatchAllFiles(this);
}
saveAndClose() {
if (!this.path || !this.baseFs)
throw new Error(`ZipFS cannot be saved and must be discarded when loaded from a buffer`);
this.prepareClose();
if (this.readOnly) {
this.discardAndClose();
return;
}
const newMode = this.baseFs.existsSync(this.path) || this.stats.mode === statUtils.DEFAULT_MODE
? undefined
: this.stats.mode;
// zip_close doesn't persist empty archives
if (this.entries.size === 0) {
this.discardAndClose();
this.baseFs.writeFileSync(this.path, makeEmptyArchive(), {mode: newMode});
} else {
const rc = this.libzip.close(this.zip);
if (rc === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
if (typeof newMode !== `undefined`) {
this.baseFs.chmodSync(this.path, newMode);
}
}
this.ready = false;
}
discardAndClose() {
this.prepareClose();
this.libzip.discard(this.zip);
this.ready = false;
}
resolve(p: PortablePath) {
return ppath.resolve(PortablePath.root, p);
}
async openPromise(p: PortablePath, flags: string, mode?: number) {
return this.openSync(p, flags, mode);
}
openSync(p: PortablePath, flags: string, mode?: number) {
const fd = this.nextFd++;
this.fds.set(fd, {cursor: 0, p});
return fd;
}
hasOpenFileHandles(): boolean {
return !!this.fds.size;
}
async opendirPromise(p: PortablePath, opts?: OpendirOptions) {
return this.opendirSync(p, opts);
}
opendirSync(p: PortablePath, opts: OpendirOptions = {}): Dir<PortablePath> {
const resolvedP = this.resolveFilename(`opendir '${p}'`, p);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`opendir '${p}'`);
const directoryListing = this.listings.get(resolvedP);
if (!directoryListing)
throw errors.ENOTDIR(`opendir '${p}'`);
const entries = [...directoryListing];
const fd = this.openSync(resolvedP, `r`);
const onClose = () => {
this.closeSync(fd);
};
return opendir(this, resolvedP, entries, {onClose});
}
async readPromise(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number | null) {
return this.readSync(fd, buffer, offset, length, position);
}
readSync(fd: number, buffer: Buffer, offset: number = 0, length: number = buffer.byteLength, position: number | null = -1) {
const entry = this.fds.get(fd);
if (typeof entry === `undefined`)
throw errors.EBADF(`read`);
let realPosition;
if (position === -1 || position === null)
realPosition = entry.cursor;
else
realPosition = position;
const source = this.readFileSync(entry.p);
source.copy(buffer, offset, realPosition, realPosition + length);
const bytesRead = Math.max(0, Math.min(source.length - realPosition, length));
if (position === -1 || position === null)
entry.cursor += bytesRead;
return bytesRead;
}
writePromise(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number): Promise<number>;
writePromise(fd: number, buffer: string, position?: number): Promise<number>;
async writePromise(fd: number, buffer: Buffer | string, offset?: number, length?: number, position?: number): Promise<number> {
if (typeof buffer === `string`) {
return this.writeSync(fd, buffer, position);
} else {
return this.writeSync(fd, buffer, offset, length, position);
}
}
writeSync(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number): number;
writeSync(fd: number, buffer: string, position?: number): number;
writeSync(fd: number, buffer: Buffer | string, offset?: number, length?: number, position?: number): never {
const entry = this.fds.get(fd);
if (typeof entry === `undefined`)
throw errors.EBADF(`read`);
throw new Error(`Unimplemented`);
}
async closePromise(fd: number) {
return this.closeSync(fd);
}
closeSync(fd: number) {
const entry = this.fds.get(fd);
if (typeof entry === `undefined`)
throw errors.EBADF(`read`);
this.fds.delete(fd);
}
createReadStream(p: PortablePath | null, {encoding}: CreateReadStreamOptions = {}): ReadStream {
if (p === null)
throw new Error(`Unimplemented`);
const fd = this.openSync(p, `r`);
const stream = Object.assign(
new PassThrough({
emitClose: true,
autoDestroy: true,
destroy: (error, callback) => {
clearImmediate(immediate);
this.closeSync(fd);
callback(error);
},
}),
{
close() {
stream.destroy();
},
bytesRead: 0,
path: p,
},
);
const immediate = setImmediate(async () => {
try {
const data = await this.readFilePromise(p, encoding);
stream.bytesRead = data.length;
stream.end(data);
} catch (error) {
stream.destroy(error);
}
});
return stream;
}
createWriteStream(p: PortablePath | null, {encoding}: CreateWriteStreamOptions = {}): WriteStream {
if (this.readOnly)
throw errors.EROFS(`open '${p}'`);
if (p === null)
throw new Error(`Unimplemented`);
const chunks: Array<Buffer> = [];
const fd = this.openSync(p, `w`);
const stream = Object.assign(
new PassThrough({
autoDestroy: true,
emitClose: true,
destroy: (error, callback) => {
try {
if (error) {
callback(error);
} else {
this.writeFileSync(p, Buffer.concat(chunks), encoding);
callback(null);
}
} catch (err) {
callback(err);
} finally {
this.closeSync(fd);
}
},
}),
{
bytesWritten: 0,
path: p,
close() {
stream.destroy();
},
},
);
stream.on(`data`, chunk => {
const chunkBuffer = Buffer.from(chunk);
stream.bytesWritten += chunkBuffer.length;
chunks.push(chunkBuffer);
});
return stream;
}
async realpathPromise(p: PortablePath) {
return this.realpathSync(p);
}
realpathSync(p: PortablePath): PortablePath {
const resolvedP = this.resolveFilename(`lstat '${p}'`, p);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`lstat '${p}'`);
return resolvedP;
}
async existsPromise(p: PortablePath) {
return this.existsSync(p);
}
existsSync(p: PortablePath): boolean {
if (!this.ready)
throw errors.EBUSY(`archive closed, existsSync '${p}'`);
if (this.symlinkCount === 0) {
const resolvedP = ppath.resolve(PortablePath.root, p);
return this.entries.has(resolvedP) || this.listings.has(resolvedP);
}
let resolvedP;
try {
resolvedP = this.resolveFilename(`stat '${p}'`, p);
} catch (error) {
return false;
}
return this.entries.has(resolvedP) || this.listings.has(resolvedP);
}
async accessPromise(p: PortablePath, mode?: number) {
return this.accessSync(p, mode);
}
accessSync(p: PortablePath, mode: number = constants.F_OK) {
const resolvedP = this.resolveFilename(`access '${p}'`, p);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`access '${p}'`);
if (this.readOnly && (mode & constants.W_OK)) {
throw errors.EROFS(`access '${p}'`);
}
}
async statPromise(p: PortablePath): Promise<Stats>
async statPromise(p: PortablePath, opts: {bigint: true}): Promise<BigIntStats>
async statPromise(p: PortablePath, opts?: {bigint: boolean}): Promise<BigIntStats | Stats>
async statPromise(p: PortablePath, opts?: {bigint: boolean}) {
return this.statSync(p, opts);
}
statSync(p: PortablePath): Stats
statSync(p: PortablePath, opts: {bigint: true}): BigIntStats
statSync(p: PortablePath, opts?: {bigint: boolean}): BigIntStats | Stats
statSync(p: PortablePath, opts?: {bigint: boolean}) {
const resolvedP = this.resolveFilename(`stat '${p}'`, p);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`stat '${p}'`);
if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
throw errors.ENOTDIR(`stat '${p}'`);
return this.statImpl(`stat '${p}'`, resolvedP, opts);
}
async fstatPromise(fd: number): Promise<Stats>
async fstatPromise(fd: number, opts: {bigint: true}): Promise<BigIntStats>
async fstatPromise(fd: number, opts?: {bigint: boolean}): Promise<BigIntStats | Stats>
async fstatPromise(fd: number, opts?: {bigint: boolean}) {
return this.fstatSync(fd, opts);
}
fstatSync(fd: number): Stats
fstatSync(fd: number, opts: {bigint: true}): BigIntStats
fstatSync(fd: number, opts?: {bigint: boolean}): BigIntStats | Stats
fstatSync(fd: number, opts?: {bigint: boolean}) {
const entry = this.fds.get(fd);
if (typeof entry === `undefined`)
throw errors.EBADF(`fstatSync`);
const {p} = entry;
const resolvedP = this.resolveFilename(`stat '${p}'`, p);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`stat '${p}'`);
if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
throw errors.ENOTDIR(`stat '${p}'`);
return this.statImpl(`fstat '${p}'`, resolvedP, opts);
}
async lstatPromise(p: PortablePath): Promise<Stats>
async lstatPromise(p: PortablePath, opts: {bigint: true}): Promise<BigIntStats>
async lstatPromise(p: PortablePath, opts?: { bigint: boolean }): Promise<BigIntStats | Stats>
async lstatPromise(p: PortablePath, opts?: { bigint: boolean }) {
return this.lstatSync(p, opts);
}
lstatSync(p: PortablePath): Stats;
lstatSync(p: PortablePath, opts: {bigint: true}): BigIntStats;
lstatSync(p: PortablePath, opts?: { bigint: boolean }): BigIntStats | Stats
lstatSync(p: PortablePath, opts?: { bigint: boolean }): BigIntStats | Stats {
const resolvedP = this.resolveFilename(`lstat '${p}'`, p, false);
if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
throw errors.ENOENT(`lstat '${p}'`);
if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
throw errors.ENOTDIR(`lstat '${p}'`);
return this.statImpl(`lstat '${p}'`, resolvedP, opts);
}
private statImpl(reason: string, p: PortablePath, opts: {bigint?: boolean} = {}): Stats | BigIntStats {
const entry = this.entries.get(p);
// File, or explicit directory
if (typeof entry !== `undefined`) {
const stat = this.libzip.struct.statS();
const rc = this.libzip.statIndex(this.zip, entry, 0, 0, stat);
if (rc === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
const uid = this.stats.uid;
const gid = this.stats.gid;
const size = (this.libzip.struct.statSize(stat) >>> 0);
const blksize = 512;
const blocks = Math.ceil(size / blksize);
const mtimeMs = (this.libzip.struct.statMtime(stat) >>> 0) * 1000;
const atimeMs = mtimeMs;
const birthtimeMs = mtimeMs;
const ctimeMs = mtimeMs;
const atime = new Date(atimeMs);
const birthtime = new Date(birthtimeMs);
const ctime = new Date(ctimeMs);
const mtime = new Date(mtimeMs);
const type = this.listings.has(p)
? S_IFDIR
: this.isSymbolicLink(entry)
? S_IFLNK
: S_IFREG;
const defaultMode = type === S_IFDIR
? 0o755
: 0o644;
const mode = type | (this.getUnixMode(entry, defaultMode) & 0o777);
const crc = this.libzip.struct.statCrc(stat);
const statInstance = Object.assign(new statUtils.StatEntry(), {uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc});
return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance;
}
// Implicit directory
if (this.listings.has(p)) {
const uid = this.stats.uid;
const gid = this.stats.gid;
const size = 0;
const blksize = 512;
const blocks = 0;
const atimeMs = this.stats.mtimeMs;
const birthtimeMs = this.stats.mtimeMs;
const ctimeMs = this.stats.mtimeMs;
const mtimeMs = this.stats.mtimeMs;
const atime = new Date(atimeMs);
const birthtime = new Date(birthtimeMs);
const ctime = new Date(ctimeMs);
const mtime = new Date(mtimeMs);
const mode = S_IFDIR | 0o755;
const crc = 0;
const statInstance = Object.assign(new statUtils.StatEntry(), {uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc});
return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance;
}
throw new Error(`Unreachable`);
}
private getUnixMode(index: number, defaultMode: number) {
const rc = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
if (rc === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
return defaultMode;
return this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
}
private registerListing(p: PortablePath) {
let listing = this.listings.get(p);
if (listing)
return listing;
const parentListing = this.registerListing(ppath.dirname(p));
listing = new Set();
parentListing.add(ppath.basename(p));
this.listings.set(p, listing);
return listing;
}
private registerEntry(p: PortablePath, index: number) {
const parentListing = this.registerListing(ppath.dirname(p));
parentListing.add(ppath.basename(p));
this.entries.set(p, index);
}
private unregisterListing(p: PortablePath) {
this.listings.delete(p);
const parentListing = this.listings.get(ppath.dirname(p));
parentListing?.delete(ppath.basename(p));
}
private unregisterEntry(p: PortablePath) {
this.unregisterListing(p);
const entry = this.entries.get(p);
this.entries.delete(p);
if (typeof entry === `undefined`)
return;
this.fileSources.delete(entry);
if (this.isSymbolicLink(entry)) {
this.symlinkCount--;
}
}
private deleteEntry(p: PortablePath, index: number) {
this.unregisterEntry(p);
const rc = this.libzip.delete(this.zip, index);
if (rc === -1) {
throw this.makeLibzipError(this.libzip.getError(this.zip));
}
}
private resolveFilename(reason: string, p: PortablePath, resolveLastComponent: boolean = true): PortablePath {
if (!this.ready)
throw errors.EBUSY(`archive closed, ${reason}`);
let resolvedP = ppath.resolve(PortablePath.root, p);
if (resolvedP === `/`)
return PortablePath.root;
const fileIndex = this.entries.get(resolvedP);
if (resolveLastComponent && fileIndex !== undefined) {
if (this.symlinkCount !== 0 && this.isSymbolicLink(fileIndex)) {
const target = this.getFileSource(fileIndex).toString() as PortablePath;
return this.resolveFilename(reason, ppath.resolve(ppath.dirname(resolvedP), target), true);
} else {
return resolvedP;
}
}
while (true) {
const parentP = this.resolveFilename(reason, ppath.dirname(resolvedP), true);
const isDir = this.listings.has(parentP);
const doesExist = this.entries.has(parentP);
if (!isDir && !doesExist)
throw errors.ENOENT(reason);
if (!isDir)
throw errors.ENOTDIR(reason);
resolvedP = ppath.resolve(parentP, ppath.basename(resolvedP));
if (!resolveLastComponent || this.symlinkCount === 0)
break;
const index = this.libzip.name.locate(this.zip, resolvedP.slice(1));
if (index === -1)
break;
if (this.isSymbolicLink(index)) {
const target = this.getFileSource(index).toString() as PortablePath;
resolvedP = ppath.resolve(ppath.dirname(resolvedP), target);
} else {
break;
}
}
return resolvedP;
}
private allocateBuffer(content: string | Buffer | ArrayBuffer | DataView) {
if (!Buffer.isBuffer(content))
content = Buffer.from(content as any);
const buffer = this.libzip.malloc(content.byteLength);
if (!buffer)
throw new Error(`Couldn't allocate enough memory`);
// Copy the file into the Emscripten heap
const heap = new Uint8Array(this.libzip.HEAPU8.buffer, buffer, content.byteLength);
heap.set(content as any);
return {buffer, byteLength: content.byteLength};
}
private allocateUnattachedSource(content: string | Buffer | ArrayBuffer | DataView) {
const error = this.libzip.struct.errorS();
const {buffer, byteLength} = this.allocateBuffer(content);
const source = this.libzip.source.fromUnattachedBuffer(buffer, byteLength, 0, true, error);
if (source === 0) {
this.libzip.free(error);
throw this.makeLibzipError(error);
}
return source;
}
private allocateSource(content: string | Buffer | ArrayBuffer | DataView) {
const {buffer, byteLength} = this.allocateBuffer(content);
const source: number = this.libzip.source.fromBuffer(this.zip, buffer, byteLength, 0, true);
if (source === 0) {
this.libzip.free(buffer);
throw this.makeLibzipError(this.libzip.getError(this.zip));
}
return source;
}
private setFileSource(p: PortablePath, content: string | Buffer | ArrayBuffer | DataView) {
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content as any);
const target = ppath.relative(PortablePath.root, p);
const lzSource = this.allocateSource(content);
try {
const newIndex = this.libzip.file.add(this.zip, target, lzSource, this.libzip.ZIP_FL_OVERWRITE);
if (newIndex === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
if (this.level !== `mixed`) {
// Use store for level 0, and deflate for 1..9
let method;
if (this.level === 0)
method = this.libzip.ZIP_CM_STORE;
else
method = this.libzip.ZIP_CM_DEFLATE;
const rc = this.libzip.file.setCompression(this.zip, newIndex, 0, method, this.level);
if (rc === -1) {
throw this.makeLibzipError(this.libzip.getError(this.zip));
}
}
this.fileSources.set(newIndex, buffer);
return newIndex;
} catch (error) {
this.libzip.source.free(lzSource);
throw error;
}
}
private isSymbolicLink(index: number) {
if (this.symlinkCount === 0)
return false;
const attrs = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
if (attrs === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
return false;
const attributes = this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
return (attributes & S_IFMT) === S_IFLNK;
}
private getFileSource(index: number): Buffer
private getFileSource(index: number, opts: {asyncDecompress: false}): Buffer
private getFileSource(index: number, opts: {asyncDecompress: true}): Promise<Buffer>
private getFileSource(index: number, opts: {asyncDecompress: boolean}): Promise<Buffer> | Buffer
private getFileSource(index: number, opts: {asyncDecompress: boolean} = {asyncDecompress: false}): Promise<Buffer> | Buffer {
const cachedFileSource = this.fileSources.get(index);
if (typeof cachedFileSource !== `undefined`)
return cachedFileSource;
const stat = this.libzip.struct.statS();
const rc = this.libzip.statIndex(this.zip, index, 0, 0, stat);
if (rc === -1)
throw this.makeLibzipError(this.libzip.getError(this.zip));
const size = this.libzip.struct.statCompSize(stat);
const compressionMethod = this.libzip.struct.statCompMethod(stat);
const buffer = this.libzip.malloc(size);
try {
const file = this.libzip.fopenIndex(this.zip, index, 0, this.libzip.ZIP_FL_COMPRESSED);
if (file === 0)
throw this.makeLibzipError(this.libzip.getError(this.zip));
try {
const rc = this.libzip.fread(file, buffer, size, 0);
if (rc === -1)
throw this.makeLibzipError(this.libzip.file.getError(file));
else if (rc < size)
throw new Error(`Incomplete read`);
else if (rc > size)
throw new Error(`Overread`);
const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
const data = Buffer.from(memory);
if (compressionMethod === 0) {
this.fileSources.set(index, data);
return data;
} else if (opts.asyncDecompress) {
return new Promise((resolve, reject) => {
zlib.inflateRaw(data, (error, result) => {
if (error) {
reject(error);
} else {
this.fileSources.set(index, result);
resolve(result);
}
});
});
} else {
const decompressedData = zlib.inflateRawSync(data);
this.fileSources.set(index, decompressedData);
return decompressedData;
}
} finally {
this.libzip.fclose(file);
}
} finally {
this.libzip.free(buffer);
}
}
async chmodPromise(p: PortablePath, mask: number) {
return this.chmodSync(p, mask);
}
chmodSync(p: PortablePath, mask: number) {
if (this.readOnly)
throw errors.EROFS(`chmod '${p}'`);
// We don't allow to make the extracted entries group-writable
mask &= 0o755;