All files index.js

85.23% Statements 75/88
58.82% Branches 20/34
100% Functions 14/14
90.24% Lines 74/82
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 2111x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x     5x                     5x   5x             5x         5x   5x                         5x 5x 5x 5x 5x         1x                                                                                                 1x 3x 3x 3x 3x 3x 3x 3x         3x 1x   1x     2x     1x 5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x 5x               5x           5x 1x   1x     4x     1x 46x 13x 13x 8x 8x   5x 2x       1x 5x 5x       5x     5x 5x 5x 5x   8x     5x 30x     5x           1x  
const fs = require('fs-extra');
const Boom = require('boom');
const _ = require('lodash');
const Frisbee = require('frisbee');
const FormData = require('form-data');
const safeStringify = require('fast-safe-stringify');
const debug = require('debug')('lipo');
const boolean = require('boolean');
const sharp = require('sharp');
 
const INVALID_FILE = 'File upload was invalid.';
const INVALID_QUEUE = 'Image transformation queue was invalid.';
 
function Lipo(options = {}) {
  this.__options = Object.assign(
    {
      key: '',
      baseURI:
        process.env.NODE_ENV === 'test'
          ? 'http://localhost:3000'
          : 'https://lipo.io'
    },
    options
  );
 
  debug('options %o', this.__options);
 
  this.__api = new Frisbee({
    baseURI: this.__options.baseURI,
    headers: {
      Accept: 'application/json'
    }
  });
 
  Iif (this.__options.key) {
    debug('using auth key %s', this.__options.key);
    this.__api.auth(this.__options.key);
  }
 
  this.__queue = [];
 
  return (input, options = {}) => {
    // input = Buffer | String
    // options = Object
    // - density (Number)
    // - raw (Object)
    //   - width (Number)
    //   - height (Number)
    //   - channels (Number; 1-4)
    // - create (Object)
    //   - width (Number)
    //   - height (Number)
    //   - channels (Number; 3-4)
    //   - background (String | Object)
    debug('set input to %s', input);
    this.__input = input;
    debug('set options to %o', options);
    this.__options = options;
    return this;
  };
}
 
// Object.keys(require('sharp').prototype).filter(key => !key.startsWith('_'))
const keys = [
  'clone',
  'metadata',
  'limitInputPixels',
  'sequentialRead',
  'resize',
  'crop',
  'embed',
  'max',
  'min',
  'ignoreAspectRatio',
  'withoutEnlargement',
  'overlayWith',
  'rotate',
  'extract',
  'flip',
  'flop',
  'sharpen',
  'blur',
  'extend',
  'flatten',
  'trim',
  'gamma',
  'negate',
  'normalise',
  'normalize',
  'convolve',
  'threshold',
  'boolean',
  'background',
  'greyscale',
  'grayscale',
  'toColourspace',
  'toColorspace',
  'extractChannel',
  'joinChannel',
  'bandbool',
  'toFile',
  'toBuffer',
  'withMetadata',
  'jpeg',
  'png',
  'webp',
  'tiff',
  'raw',
  'toFormat',
  'tile'
];
 
Lipo.prototype.__toFile = function(fileOut, fn) {
  debug('fileOut %s', fileOut);
  Iif (!_.isString(fileOut)) throw new Error('File output path required');
  const promise = new Promise(async (resolve, reject) => {
    try {
      const data = await this.__toBuffer();
      await fs.writeFile(fileOut, data);
      resolve(this.__info);
    } catch (err) {
      reject(err);
    }
  });
  if (_.isFunction(fn))
    promise
      .then(data => {
        fn(null, data);
      })
      .catch(fn);
  else return promise;
};
 
Lipo.prototype.__toBuffer = function(fn) {
  debug('queue', this.__queue);
  debug('input', this.__input);
  const promise = new Promise(async (resolve, reject) => {
    try {
      const body = new FormData();
      Eif (_.isString(this.__input))
        body.append('input', fs.createReadStream(this.__input));
      else if (_.isBuffer(this.__input)) body.append('input', this.__input);
      else throw new Error('Input must be a String or Buffer');
      body.append('queue', safeStringify(this.__queue));
      this.__queue = [];
      const res = await this.__api.post('/', { body });
      Iif (res.err) throw res.err;
      this.__info = {
        format: res.headers.get('x-sharp-format'),
        size: Number(res.headers.get('x-sharp-size')),
        width: Number(res.headers.get('x-sharp-width')),
        height: Number(res.headers.get('x-sharp-height')),
        channels: Number(res.headers.get('x-sharp-channels')),
        premultiplied: boolean(res.headers.get('x-sharp-multiplied'))
      };
      resolve(Buffer.concat(res.originalResponse._raw));
    } catch (err) {
      reject(err);
    }
  });
 
  if (_.isFunction(fn))
    promise
      .then(data => {
        fn(null, data, this.__info);
      })
      .catch(fn);
  else return promise;
};
 
keys.forEach(key => {
  Lipo.prototype[key] = function() {
    debug(`${key} called with arguments`, [].slice.call(arguments));
    if (!['toFile', 'toBuffer'].includes(key)) {
      this.__queue.push([key].concat([].slice.call(arguments)));
      return this;
    }
    if (key === 'toFile') return this.__toFile(...[].slice.call(arguments));
    return this.__toBuffer(...[].slice.call(arguments));
  };
});
 
Lipo.middleware = async function(ctx) {
  try {
    Iif (!ctx.req.file)
      throw Boom.badRequest(
        _.isFunction(ctx.req.t) ? ctx.req.t(INVALID_FILE) : INVALID_FILE
      );
    const err = Boom.badRequest(
      _.isFunction(ctx.req.t) ? ctx.req.t(INVALID_QUEUE) : INVALID_QUEUE
    );
    Iif (!_.isString(ctx.req.body.queue)) throw Boom.badRequest(err);
    const queue = JSON.parse(ctx.req.body.queue);
    Iif (!_.isArray(queue) || _.isEmpty(queue)) throw Boom.badRequest(err);
    const transform = _.reduce(
      queue,
      (transform, task) => transform[task.shift()](...task),
      sharp()
    ).on('info', info => {
      Object.keys(info).forEach(key => {
        ctx.set(`x-sharp-${key}`, info[key]);
      });
    });
    ctx.body = ctx.req.file.stream.pipe(transform);
  } catch (err) {
    ctx.throw(err);
  }
};
 
module.exports = Lipo;