"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const child_process_1 = require("child_process"); const fs_1 = require("fs"); const loggers_1 = require("./loggers"); const logger = (0, loggers_1.getLogger)('gifski'); const sizeLimit = 8000000; const roundToEven = (n) => Math.ceil(n / 2) * 2; exports.default = (inputFilePath, targetWidth) => __awaiter(void 0, void 0, void 0, function* () { const outputFilePath = inputFilePath.replace(/(?:\.[^.]*)?$/, '.gif'); if ((0, fs_1.existsSync)(outputFilePath) && (0, fs_1.statSync)(outputFilePath).size > 0) { logger.info(`converted gif exists, skipping conversion...`); return outputFilePath; } try { const args = [ inputFilePath, '-o', outputFilePath, '--fps', '11.988', '--quiet', '--quality', '95', ]; if (typeof (targetWidth) === 'number') { args.push('--width', roundToEven(targetWidth).toString()); } logger.info(` gifski ${args.join(' ')}`); const gifskiSpawn = (0, child_process_1.spawn)('gifski', args); const gifskiResult = new Promise((resolve, reject) => { const sizeChecker = setInterval(() => { if ((0, fs_1.existsSync)(outputFilePath) && (0, fs_1.statSync)(outputFilePath).size > sizeLimit) gifskiSpawn.kill(); }, 5000); gifskiSpawn.on('exit', () => { clearInterval(sizeChecker); if (!(0, fs_1.existsSync)(outputFilePath) || (0, fs_1.statSync)(outputFilePath).size === 0) return reject('no file was created on exit'); logger.info(`gif conversion succeeded, file path: ${outputFilePath}`); resolve(outputFilePath); }); }); const stderr = []; gifskiSpawn.stderr.on('data', errdata => stderr.push(errdata)); gifskiSpawn.stderr.on('end', () => { if (stderr.length !== 0) { if (!gifskiSpawn.killed) gifskiSpawn.kill(); throw Error(Buffer.concat(stderr).toString()); } }); return yield gifskiResult; } catch (error) { logger.error(`error converting video to gif ${error ? `message: ${error}` : ''}`); throw Error('error converting video to gif'); } });