docusaurus/packages/lqip-loader/src/lqip.ts
Joshua Chen 87592bca03
refactor: ensure all types are using index signature instead of Record (#6995)
* refactor: ensure all types are using index signature instead of Record

* kick CI
2022-03-25 18:06:30 +08:00

46 lines
1.3 KiB
TypeScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import logger from '@docusaurus/logger';
import path from 'path';
import sharp from 'sharp';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {version} = require('../package.json');
const ERROR_EXT = `Error: Input file is missing or uses unsupported image format, lqip v${version}`;
const SUPPORTED_MIMES: {[ext: string]: string} = {
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
png: 'image/png',
};
/**
* it returns a Base64 image string with required formatting
* to work on the web (<img src=".." /> or in CSS url('..'))
*/
const toBase64 = (extMimeType: string, data: Buffer): string =>
`data:${extMimeType};base64,${data.toString('base64')}`;
export async function base64(file: string): Promise<string> {
let extension = path.extname(file);
extension = extension.split('.').pop()!;
const mime = SUPPORTED_MIMES[extension];
if (!mime) {
throw new Error(ERROR_EXT);
}
try {
const data = await sharp(file).resize(10).toBuffer();
return toBase64(mime, data);
} catch (err) {
logger.error`Generation of base64 failed for image path=${file}.`;
throw err;
}
}