-
Notifications
You must be signed in to change notification settings - Fork 1
/
FileCollection.ts
108 lines (97 loc) · 2.71 KB
/
FileCollection.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
import { FileCollectionItem } from './FileCollectionItem';
import { fileCollectionToZip } from './fileCollectionToZip';
export class FileCollection {
readonly files: FileCollectionItem[];
constructor(files: FileCollectionItem[]) {
this.files = files;
}
filter(callback: (file: FileCollectionItem) => unknown) {
return new FileCollection(this.files.filter(callback));
}
/**
* Zip the FileCollection
* This method returns a new FileCollection that contains only one FileItem that
* is the zipped file (called by default 'file.zip')
* Not sure this is super useful and we should probably remove it and replace it by fileCollectionToZip
*/
async zip() {
return fileCollectionToZip(this);
}
addText(
relativePath: string,
text: string,
options: { dateModified?: number } = {},
) {
this.files.push(getItemFromText(relativePath, text, options));
}
addArrayBuffer(
relativePath: string,
arrayBuffer: ArrayBuffer,
options: { dateModified?: number } = {},
) {
this.files.push(getItemFromArrayBuffer(relativePath, arrayBuffer, options));
}
addTypedArray(
relativePath: string,
typedArray: Uint8Array,
options: { dateModified?: number } = {},
) {
this.files.push(getItemFromTypedArray(relativePath, typedArray, options));
}
[Symbol.iterator]() {
return this.files.values();
}
}
function getItemFromText(
relativePath: string,
text: string,
options: { dateModified?: number } = {},
): FileCollectionItem {
const encoder = new TextEncoder();
const data = encoder.encode(text);
return {
relativePath,
name: relativePath.split('/').pop() as string,
lastModified: options.dateModified || Date.now(),
size: data.length,
text: async () => {
return text;
},
arrayBuffer: async () => {
return data.buffer;
},
stream: () => {
throw new Error('stream no implemented');
},
};
}
function getItemFromArrayBuffer(
relativePath: string,
arrayBuffer: ArrayBuffer,
options: { dateModified?: number } = {},
): FileCollectionItem {
const decoder = new TextDecoder();
const text = decoder.decode(arrayBuffer);
return {
relativePath,
name: relativePath.split('/').pop() as string,
lastModified: options.dateModified || Date.now(),
size: arrayBuffer.byteLength,
text: async () => {
return text;
},
arrayBuffer: async () => {
return arrayBuffer;
},
stream: () => {
throw new Error('stream no implemented');
},
};
}
function getItemFromTypedArray(
relativePath: string,
typedArray: Uint8Array,
options: { dateModified?: number } = {},
): FileCollectionItem {
return getItemFromArrayBuffer(relativePath, typedArray.buffer, options);
}