-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
106 lines (88 loc) · 2.83 KB
/
index.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
import * as PluginError from 'plugin-error'
import * as stream from 'stream'
import * as through from 'through2'
import * as zlib from 'zlib'
type CompressFunctionType = typeof compress
interface IExportedApi extends CompressFunctionType {
compress: CompressFunctionType
decompress: typeof decompress
}
interface IOptions extends zlib.BrotliOptions {
extension?: string
}
interface ICompressionOptions extends IOptions {
skipLarger?: boolean
}
const PLUGIN_NAME = 'gulp-brotli'
function compress(options: ICompressionOptions = {}): stream.Transform {
const extension = `.${options.extension || 'br'}`
// tslint:disable-next-line:variable-name
return through.obj((file, _encoding, callback) => {
try {
file.extname += extension
} catch (pathNotSetError) {
// The file's path is not set, therefore this is most likely a virtual in-memory file. Ignore.
}
switch (true) {
case file.isNull():
callback(null, file)
break
case file.isStream():
const brotliCompression = zlib.createBrotliCompress(options)
file.contents = file.contents.pipe(brotliCompression)
callback(null, file)
break
case file.isBuffer():
zlib.brotliCompress(file.contents, options, (error, compressedContents) => {
if (error) {
callback(new PluginError(PLUGIN_NAME, error))
return
}
if (!options.skipLarger || compressedContents.length < file.contents.length) {
file.contents = compressedContents
callback(null, file)
} else {
callback()
}
})
break
}
})
}
function decompress(options: IOptions = {}): stream.Transform {
const extension = `.${options.extension || 'br'}`
// tslint:disable-next-line:variable-name
return through.obj((file, _encoding, callback) => {
try {
if (file.extname.endsWith(extension)) {
file.extname = file.extname.slice(0, -extension.length)
}
} catch (pathNotSetError) {
// The file's path is not set, therefore this is most likely a virtual in-memory file. Ignore.
}
switch (true) {
case file.isNull():
callback(null, file)
break
case file.isStream():
const brotliDecompression = zlib.createBrotliDecompress(options)
file.contents = file.contents.pipe(brotliDecompression)
callback(null, file)
break
case file.isBuffer():
zlib.brotliDecompress(file.contents, options, (error, decompressedContents) => {
if (error) {
callback(new PluginError(PLUGIN_NAME, error))
}
file.contents = decompressedContents
callback(null, file)
})
break
}
})
}
const exportedApi: IExportedApi = Object.assign(compress, {
compress,
decompress,
})
export = exportedApi