text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports["default"] = downloadLocally;
  
  var _tmp = _interopRequireDefault(require("tmp"));
  
  var _got = _interopRequireDefault(require("got"));
  
  var _fs = _interopRequireDefault(require("fs"));
  
  var _path = _interopRequireDefault(require("path"));
  
  var _url = _interopRequireDefault(require("url"));
  
  var _decode = _interopRequireDefault(require("./decode"));
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  
  function downloadLocally(fileUrl) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var isCancelled = false;
    var request = null;
  
    var start = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var _tmp$dirSync, tmpDir, deleteTmpDir, encodedFileUrl, response, _url$parse, pathname, filePath;
  
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _tmp$dirSync = _tmp["default"].dirSync(), tmpDir = _tmp$dirSync.name, deleteTmpDir = _tmp$dirSync.removeCallback;
                encodedFileUrl = (0, _decode["default"])(fileUrl);
                request = (0, _got["default"])(encodedFileUrl, {
                  responseType: 'buffer',
                  maxRedirects: 10
                });
  
                if (typeof options.onProgress === 'function') {
                  request.on('downloadProgress', function (_ref2) {
                    var percent = _ref2.percent;
  
                    if (isCancelled) {
                      return;
                    }
  
                    options.onProgress({
                      type: 'download',
                      payload: {
                        percent: Math.round(percent * 100)
                      }
                    });
                  });
                }
  
                _context.prev = 4;
                _context.next = 7;
                return request;
  
              case 7:
                response = _context.sent;
                _url$parse = _url["default"].parse((0, _decode["default"])(response.url)), pathname = _url$parse.pathname;
                filePath = _path["default"].join(tmpDir, _path["default"].basename(pathname));
  
                _fs["default"].writeFileSync(filePath, response.body);
  
                return _context.abrupt("return", {
                  filePath: filePath,
                  deleteTmpFile: function deleteTmpFile() {
                    _fs["default"].unlinkSync(filePath);
  
                    deleteTmpDir();
                  }
                });
  
              case 14:
                _context.prev = 14;
                _context.t0 = _context["catch"](4);
                deleteTmpDir();
  
                if (!(_context.t0 instanceof _got["default"].CancelError)) {
                  _context.next = 21;
                  break;
                }
  
                throw new Error('upload aborted');
  
              case 21:
                if (!_context.t0.response) {
                  _context.next = 25;
                  break;
                }
  
                throw new Error("Invalid status code for ".concat(encodedFileUrl, ": ").concat(_context.t0.response.statusCode));
  
              case 25:
                throw _context.t0;
  
              case 26:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[4, 14]]);
      }));
  
      return function start() {
        return _ref.apply(this, arguments);
      };
    }();
  
    return {
      promise: start(),
      cancel: function cancel() {
        isCancelled = true;
  
        if (request) {
          request.cancel();
        }
      }
    };
  }