-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathsqip.ts
More file actions
519 lines (453 loc) · 12.9 KB
/
sqip.ts
File metadata and controls
519 lines (453 loc) · 12.9 KB
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
import path from 'path'
import Debug from 'debug'
import fs from 'fs-extra'
import Vibrant from '@behold/sharp-vibrant'
import type { Palette } from '@behold/sharp-vibrant/lib/color.js'
import { Swatch } from '@behold/sharp-vibrant/lib/color.js'
import sharp from 'sharp'
import termimg, { UnsupportedTerminalError } from 'term-img'
import Table from 'cli-table3'
import chalk from 'chalk'
import mime from 'mime'
import { OptionDefinition } from 'command-line-args'
import { findBackgroundColor, locateFiles } from './helpers.js'
export { loadSVG, parseColor } from './helpers.js'
const debug = Debug('sqip')
const mainKeys = [
'filename',
'originalWidth',
'originalHeight',
'width',
'height',
'type',
'mimeType'
]
const PALETTE_KEYS: (keyof Palette)[] = [
'Background',
'Vibrant',
'DarkVibrant',
'LightVibrant',
'Muted',
'DarkMuted',
'LightMuted'
]
export interface SqipResult {
content: Buffer
metadata: SqipImageMetadata
}
export interface SqipCliOptionDefinition extends OptionDefinition {
description?: string
required?: boolean
default?: boolean
}
export interface PluginOptions {
[key: string]: unknown
}
export interface PluginResolver {
name: string
options?: PluginOptions
}
export interface SqipOptions {
input: string | Buffer
outputFileName?: string
output?: string
silent?: boolean
parseableOutput?: boolean
plugins?: PluginType[]
width?: number
print?: boolean
}
// @todo why do we have this twice?
interface SqipConfig {
input: string | Buffer
outputFileName?: string
output?: string
silent?: boolean
parseableOutput?: boolean
plugins: PluginType[]
width?: number
print?: boolean
}
interface ProcessFileOptions {
filePath: string
buffer: Buffer
outputFileName: string
config: SqipConfig
}
export interface SqipImageMetadata {
originalWidth: number
originalHeight: number
palette: Palette
backgroundColor: string
height: number
width: number
type: 'unknown' | 'pixel' | 'svg'
mimeType: string
filename: string
[key: string]: unknown
}
export type PluginType = PluginResolver | string
export interface SqipPluginOptions {
pluginOptions: PluginOptions
options: PluginOptions
sqipConfig: SqipConfig
}
export interface SqipPluginInterface {
sqipConfig: SqipConfig
apply(
imageBuffer: Buffer,
metadata?: SqipImageMetadata
): Promise<Buffer> | Buffer
}
export class SqipPlugin implements SqipPluginInterface {
public sqipConfig: SqipConfig
public options: PluginOptions
static cliOptions: SqipCliOptionDefinition[]
constructor(options: SqipPluginOptions) {
const { sqipConfig } = options
this.sqipConfig = sqipConfig || {}
this.options = {}
}
apply(
imageBuffer: Buffer,
metadata: SqipImageMetadata
): Promise<Buffer> | Buffer {
console.log(metadata)
return imageBuffer
}
}
// Resolves plugins based on a given config
// Array of plugin names or config objects, even mixed.
export async function resolvePlugins(
plugins: PluginType[]
): Promise<(PluginResolver & { Plugin: typeof SqipPlugin })[]> {
return Promise.all(
plugins.map(async (plugin) => {
if (typeof plugin === 'string') {
plugin = { name: plugin }
}
const { name } = plugin
if (!name) {
throw new Error(
`Unable to read plugin name from:\n${JSON.stringify(plugin, null, 2)}`
)
}
const moduleName =
name.indexOf('sqip-plugin-') !== -1 ? name : `sqip-plugin-${name}`
try {
debug(`Loading ${moduleName}`)
const { default: Plugin } = await import(moduleName)
return { ...plugin, Plugin: Plugin.default || Plugin }
} catch (err) {
console.error(err)
throw new Error(
`Unable to load plugin "${moduleName}". Try installing it via:\n\n npm install ${moduleName}`
)
}
})
)
}
async function processFile({
filePath,
buffer,
outputFileName,
config
}: ProcessFileOptions) {
const { output, silent, parseableOutput, print } = config
const result = await processImage({ filePath, buffer, config })
const { content, metadata } = result
let outputPath
debug(`Processed ${outputFileName}`)
// Write result svg if desired
if (output) {
try {
// Test if output path already exists
const stats = await fs.stat(output)
// Throw if it is a file and already exists
if (!stats.isDirectory()) {
throw new Error(
`File ${output} already exists. Overwriting is not yet supported.`
)
}
outputPath = path.resolve(output, `${outputFileName}.svg`)
} catch {
// Output directory or file does not exist. We will create it later on.
outputPath = output
}
debug(`Writing ${outputPath}`)
await fs.writeFile(outputPath, content as Uint8Array)
}
// Gather CLI output information
if (!silent) {
if (outputPath) {
console.log(`Stored at: ${outputPath}`)
}
// Generate preview
if (!parseableOutput) {
// Convert to png for image preview
const preview = await sharp(Buffer.from(content)).png().toBuffer()
try {
termimg(preview, {
fallback: () => {
// SVG results can still be outputted as string
if (metadata.type === 'svg') {
console.log(content.toString())
return
}
// No fallback preview solution yet for non-svg files.
console.log(
`Unable to render a preview for ${metadata.type} files on this machine. Try using https://iterm2.com/`
)
}
})
} catch (err) {
if (err instanceof UnsupportedTerminalError) {
if (err.name === 'UnsupportedTerminalError') {
throw err
}
}
}
}
// Metadata
const tableConfig = parseableOutput
? {
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
bottom: '',
'bottom-mid': '',
'bottom-left': '',
'bottom-right': '',
left: '',
'left-mid': '',
mid: '',
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' '
},
style: { 'padding-left': 0, 'padding-right': 0 }
}
: undefined
// Figure out which metadata keys to show
// @todo why is this unused?
// const allKeys = [...mainKeys, 'palette']
const mainTable = new Table(tableConfig)
mainTable.push(mainKeys)
mainTable.push(
mainKeys.map((key) => String(metadata[key]) || 'can not display')
)
console.log(mainTable.toString())
// Show color palette
const paletteTable = new Table(tableConfig)
paletteTable.push(PALETTE_KEYS as string[])
paletteTable.push(
[
metadata.backgroundColor,
...PALETTE_KEYS.map((key) => metadata.palette[key]?.hex)
]
.filter<string>((hex): hex is string => typeof hex === 'string')
.map((hex) => chalk.hex(hex)(hex))
)
console.log(paletteTable.toString())
Object.keys(metadata)
.filter((key) => ![...mainKeys, 'palette', 'backgroundColor'].includes(key))
.forEach((key) => {
console.log(chalk.bold(`${key}:`))
console.log(metadata[key])
})
if (metadata.type === 'svg' && print) {
console.log(`Resulting SVG:\n${result.content.toString()}`)
}
}
// Print to stdout even when silent (for piping)
if (silent && print && metadata.type === 'svg') {
process.stdout.write(result.content.toString())
}
return result
}
interface ProcessImageOptions {
filePath: string
buffer: Buffer
config: SqipConfig
}
async function processImage({
filePath,
buffer,
config
}: ProcessImageOptions): Promise<SqipResult> {
// Extract the palette from the image. We delegate to node-vibrant (which is
// using jimp internally), and it only supports some image formats. In
// particular, it does not support WebP and HEIC yet.
//
// So we try with the given image buffer, and if the code throws an exception
// we try again after converting to TIFF. If that fails again we give up.
const paletteResult = await (async () => {
const getPalette = (buffer: Buffer) =>
Vibrant.from(buffer).quality(0).getPalette()
try {
return await getPalette(buffer)
} catch {
return getPalette(await sharp(buffer).tiff().toBuffer())
}
})()
const backgroundColor = await findBackgroundColor(buffer)
let filename: string
let mimeType: string
if (filePath === '-') {
// Input from stdin — detect format from buffer contents
const sharpMeta = await sharp(buffer).metadata()
filename = config.outputFileName || 'stdin'
mimeType = sharpMeta.format
? mime.getType(sharpMeta.format) || `image/${sharpMeta.format}`
: 'unknown'
} else {
filename = path.parse(filePath).name
mimeType = mime.getType(filePath) || 'unknown'
}
const metadata: SqipImageMetadata = {
filename,
mimeType,
originalWidth: paletteResult.imageDimensions.width,
originalHeight: paletteResult.imageDimensions.height,
palette: paletteResult.palette,
backgroundColor,
// @todo this should be set by plugins and detected initially
type: 'unknown',
width: 0,
height: 0
}
// Load plugins
const plugins = await resolvePlugins(config.plugins)
// Determine output image size
if (config.width && config.width > 0) {
// Resize to desired output width
try {
buffer = await sharp(buffer).resize(config.width).toBuffer()
const resizedMetadata = await sharp(buffer).metadata()
metadata.width = resizedMetadata.width || 0
metadata.height = resizedMetadata.height || 0
} catch {
throw new Error('Unable to resize')
}
} else {
// Fall back to original size, keep image as is
metadata.width = metadata.originalWidth
metadata.height = metadata.originalHeight
}
// Interate through plugins and apply them to last returned image
for (const { name, options: pluginOptions, Plugin } of plugins) {
try {
debug(`Construct ${name}`)
const plugin = new Plugin({
sqipConfig: config,
pluginOptions: pluginOptions || {},
options: {}
})
debug(`Apply ${name}`)
buffer = await plugin.apply(buffer, metadata)
} catch (err) {
console.log(`Error thrown in plugin ${name}.`)
console.dir({ metadata }, { depth: 3 })
throw err
}
}
return { content: buffer, metadata }
}
export async function sqip(
options: SqipOptions
): Promise<SqipResult | SqipResult[]> {
// Build configuration based on passed options and default options
const defaultOptions = {
plugins: [
{ name: 'primitive', options: { numberOfPrimitives: 8, mode: 0 } },
'blur',
'svgo',
'data-uri'
],
width: 300,
parseableOutput: false,
silent: true,
print: false
}
const config: SqipConfig = Object.assign({}, defaultOptions, options)
const { input, outputFileName, parseableOutput, silent } = config
if (parseableOutput) {
chalk.level = 0
}
// Validate configuration
if (!input || input.length === 0) {
throw new Error(
'Please provide an input image, e.g. sqip({ input: "input.jpg" })'
)
}
// If input is a Buffer
if (Buffer.isBuffer(input)) {
if (!outputFileName) {
throw new Error('OutputFileName is required when passing image as buffer')
}
return processFile({
filePath: '-',
buffer: input,
outputFileName,
config
})
}
const files = await locateFiles(input)
debug('Found files:')
debug(files)
// Test if all files are accessable
for (const file of files) {
try {
debug('check file ' + file)
await fs.access(file, fs.constants.R_OK)
} catch {
throw new Error(`Unable to read file ${file}`)
}
}
// Iterate over all files
const results = []
for (const filePath of files) {
// Apply plugins to files
if (!silent) {
console.log(`Processing: ${filePath}`)
} else {
debug(`Processing ${filePath}`)
}
const buffer = await fs.readFile(filePath)
const result = await processFile({
filePath,
buffer,
outputFileName: outputFileName || path.parse(filePath).name,
config
})
results.push(result)
}
debug(`Finished`)
// Return as array when input was array or results is only one file
if (Array.isArray(input) || results.length === 0) {
return results
}
return results[0]
}
export * from './helpers.js'
export const mockedMetadata: SqipImageMetadata = {
filename: 'mocked',
mimeType: 'image/mocked',
width: 1024,
height: 640,
type: 'svg',
originalHeight: 1024,
originalWidth: 640,
backgroundColor: '#FFFFFF00',
palette: {
DarkMuted: new Swatch([4, 2, 0], 420),
DarkVibrant: new Swatch([4, 2, 1], 421),
LightMuted: new Swatch([4, 2, 2], 422),
LightVibrant: new Swatch([4, 2, 3], 423),
Muted: new Swatch([4, 2, 4], 424),
Vibrant: new Swatch([4, 2, 5], 425)
}
}