-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
200 lines (176 loc) · 4.84 KB
/
index.js
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
let path = require("path");
let FileFinder = require("faucet-pipeline-core/lib/util/files/finder");
let sharp = require("sharp");
let svgo = require("svgo");
let { stat, readFile } = require("fs").promises;
let { abort } = require("faucet-pipeline-core/lib/util");
// we can optimize the settings here, but some would require libvips
// to be compiled with additional stuff
let settings = {
svg: {
plugins: [
"preset-default",
// do not remove title and desc for accessibility reasons
{
name: "removeTitle",
active: false
},
{
name: "removeDesc",
active: false
},
// configurations recommended by Cassie Evans to reduce problems
// when you want to style or animate your SVGs
{
name: "cleanupIds",
active: false
},
{
name: "mergePaths",
active: false
},
{
name: "collapseGroups",
active: false
}
]
},
png: {
compressionLevel: 9,
adaptiveFiltering: true,
palette: true
},
jpeg: {
progressive: true,
mozjpeg: true
},
webp: {},
avif: {}
};
module.exports = {
key: "images",
bucket: "static",
plugin: faucetImages
};
function faucetImages(config, assetManager) {
let optimizers = config.map(optimizerConfig =>
makeOptimizer(optimizerConfig, assetManager));
return filepaths => Promise.all(optimizers.map(optimize => optimize(filepaths)));
}
function makeOptimizer(optimizerConfig, assetManager) {
let source = assetManager.resolvePath(optimizerConfig.source);
let target = assetManager.resolvePath(optimizerConfig.target, {
enforceRelative: true
});
let fileFinder = new FileFinder(source, {
skipDotfiles: true,
filter: optimizerConfig.filter ||
withFileExtension("avif", "jpg", "jpeg", "png", "webp", "svg")
});
let {
autorotate,
fingerprint,
format,
width,
height,
crop,
quality,
scale,
suffix
} = optimizerConfig;
return async filepaths => {
let [fileNames, targetDir] = await Promise.all([
(filepaths ? fileFinder.match(filepaths) : fileFinder.all()),
determineTargetDir(source, target)
]);
return processFiles(fileNames, {
assetManager,
source,
target,
targetDir,
fingerprint,
variant: {
autorotate, format, width, height, crop, quality, scale, suffix
}
});
};
}
// If `source` is a directory, `target` is used as target directory -
// otherwise, `target`'s parent directory is used
async function determineTargetDir(source, target) {
let results = await stat(source);
return results.isDirectory() ? target : path.dirname(target);
}
async function processFiles(fileNames, config) {
return Promise.all(fileNames.map(fileName => processFile(fileName, config)));
}
async function processFile(fileName,
{ source, target, targetDir, fingerprint, assetManager, variant }) {
let sourcePath = path.join(source, fileName);
let targetPath = determineTargetPath(path.join(target, fileName), variant);
let format = variant.format ? variant.format : extname(fileName);
let output = format === "svg" ?
await optimizeSVG(sourcePath) :
await optimizeBitmap(sourcePath, format, variant);
let writeOptions = { targetDir };
if(fingerprint !== undefined) {
writeOptions.fingerprint = fingerprint;
}
return assetManager.writeFile(targetPath, output, writeOptions);
}
async function optimizeSVG(sourcePath) {
let input = await readFile(sourcePath);
try {
let output = await svgo.optimize(input, settings.svg);
return output.data;
} catch(error) {
abort(`Only SVG can be converted to SVG: ${sourcePath}`);
}
}
async function optimizeBitmap(sourcePath, format,
{ autorotate, width, height, scale, quality, crop }) {
let image = sharp(sourcePath);
if(autorotate) {
image.rotate();
}
if(scale) {
let metadata = await image.metadata();
image.resize({ width: metadata.width * scale, height: metadata.height * scale });
}
if(width || height) {
let fit = crop ? "cover" : "inside";
image.resize({ width, height, fit: sharp.fit[fit] });
}
switch(format) {
case "jpg":
case "jpeg":
image.jpeg({ ...settings.jpeg, quality });
break;
case "png":
image.png(settings.png);
break;
case "webp":
image.webp({ ...settings.webp, quality });
break;
case "avif":
image.avif({ ...settings.avif, quality });
break;
default:
abort(`unsupported format ${format}. We support: AVIF, JPG, PNG, WebP, SVG`);
}
return image.toBuffer();
}
function determineTargetPath(filepath, { format, suffix = "" }) {
format = format ? `.${format}` : "";
let directory = path.dirname(filepath);
let extension = path.extname(filepath);
let basename = path.basename(filepath, extension);
return path.join(directory, `${basename}${suffix}${extension}${format}`);
}
function withFileExtension(...extensions) {
return filename => extensions.includes(extname(filename));
}
// extname follows this annoying idea that the dot belongs to the extension
function extname(filename) {
return path.extname(filename).slice(1).toLowerCase();
}