-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
generate-sqip.js
80 lines (65 loc) · 1.75 KB
/
generate-sqip.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
const crypto = require(`crypto`)
const { resolve, parse } = require(`path`)
const Debug = require(`debug`)
const { exists, readFile, writeFile } = require(`fs-extra`)
const svgToMiniDataURI = require(`mini-svg-data-uri`)
const PQueue = require(`p-queue`)
const sqip = require(`sqip`)
const queue = new PQueue({ concurrency: 1 })
const debug = Debug(`gatsby-transformer-sqip`)
module.exports = async function generateSqip(options) {
const {
cache,
absolutePath,
numberOfPrimitives,
blur,
mode,
cacheDir,
} = options
debug({ options })
const { name } = parse(absolutePath)
const sqipOptions = {
numberOfPrimitives,
blur,
mode,
}
const optionsHash = crypto
.createHash(`md5`)
.update(JSON.stringify(sqipOptions))
.digest(`hex`)
const cacheKey = `sqip-${name}-${optionsHash}`
const cachePath = resolve(cacheDir, `${name}-${optionsHash}.svg`)
let primitiveData = await cache.get(cacheKey)
debug({ primitiveData })
if (!primitiveData) {
let svg
if (await exists(cachePath)) {
const svgBuffer = await readFile(cachePath)
svg = svgBuffer.toString()
} else {
debug(`generate sqip for ${name}`)
const result = await queue.add(
async () =>
new Promise((resolve, reject) => {
try {
const result = sqip({
filename: absolutePath,
...sqipOptions,
})
resolve(result)
} catch (error) {
reject(error)
}
})
)
svg = result.final_svg
await writeFile(cachePath, svg)
}
primitiveData = {
svg,
dataURI: svgToMiniDataURI(svg),
}
await cache.set(cacheKey, primitiveData)
}
return primitiveData
}