UNPKG

eas-cli

Version:
108 lines (107 loc) 3.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isPNGAsync = exports.ensurePNGIsNotTransparentAsync = exports.ImageTransparencyError = exports.ImageNonPngError = void 0; const tslib_1 = require("tslib"); const fs_extra_1 = tslib_1.__importDefault(require("fs-extra")); const pngjs_1 = require("pngjs"); const fetch_1 = tslib_1.__importDefault(require("../fetch")); class ImageNonPngError extends Error { } exports.ImageNonPngError = ImageNonPngError; class ImageTransparencyError extends Error { } exports.ImageTransparencyError = ImageTransparencyError; async function ensurePNGIsNotTransparentAsync(imagePathOrURL) { let hasAlreadyResolved = false; const stream = await getImageStreamAsync(imagePathOrURL); let metadata; await new Promise((res, rej) => { stream .pipe(new pngjs_1.PNG({ filterType: 4 })) .on('error', err => { if (err.message.match(/Invalid file signature/)) { rej(new ImageNonPngError()); } else { rej(err); } }) .on('metadata', _metadata => { metadata = _metadata; const { alpha } = metadata; if (!alpha) { hasAlreadyResolved = true; if (stream instanceof fs_extra_1.default.ReadStream) { stream.close(); } res(); } }) .on('parsed', (png) => { if (hasAlreadyResolved) { return; } try { // metadata should be set but assume the png is fine if it's not available if (!metadata) { res(); return; } validateAlphaChannelIsEmpty(png, { width: metadata.width, height: metadata.height }); res(); } catch (err) { rej(err); } }); }); } exports.ensurePNGIsNotTransparentAsync = ensurePNGIsNotTransparentAsync; async function isPNGAsync(imagePathOrURL) { const stream = await getImageStreamAsync(imagePathOrURL); return await new Promise((res, rej) => { stream .pipe(new pngjs_1.PNG({ filterType: 4 })) .on('error', err => { if (err.message.match(/Invalid file signature/)) { res(false); } else { rej(err); } }) .on('parsed', () => { res(true); }); }); } exports.isPNGAsync = isPNGAsync; async function getImageStreamAsync(imagePathOrURL) { if (isURL(imagePathOrURL)) { const response = await (0, fetch_1.default)(imagePathOrURL); return response.body; } else { return fs_extra_1.default.createReadStream(imagePathOrURL); } } function isURL(imagePathOrURL) { try { // eslint-disable-next-line no-new new URL(imagePathOrURL); return true; } catch { return false; } } function validateAlphaChannelIsEmpty(data, { width, height }) { for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const idx = (width * y + x) * 4; if (data[idx + 3] !== 255) { throw new ImageTransparencyError(); } } } }