define('@cardstack/authentication/cardstack-authenticator', ['exports', 'ember-simple-auth/authenticators/base', '@cardstack/plugin-utils/environment'], function (exports, _base, _environment) {
  'use strict';

  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  function _asyncToGenerator(fn) {
    return function () {
      var gen = fn.apply(this, arguments);
      return new Promise(function (resolve, reject) {
        function step(key, arg) {
          try {
            var info = gen[key](arg);
            var value = info.value;
          } catch (error) {
            reject(error);
            return;
          }

          if (info.done) {
            resolve(value);
          } else {
            return Promise.resolve(value).then(function (value) {
              step("next", value);
            }, function (err) {
              step("throw", err);
            });
          }
        }

        return step("next");
      });
    };
  }

  exports.default = _base.default.extend({
    cardstackSession: Ember.inject.service(),
    session: Ember.inject.service(),

    restore: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(rawSession) {
        var _this = this;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt('return', new Ember.RSVP.Promise(function (resolve, reject) {
                  var potentiallyValidSession = rawSession && rawSession.data && rawSession.data.meta && rawSession.data.meta.validUntil && rawSession.data.meta.validUntil > Date.now() / 1000;

                  var partialSession = rawSession.meta && rawSession.meta['partial-session'];

                  var secret = localStorage.getItem('cardstack-secret-token'),
                      authenticationSource = localStorage.getItem('cardstack-authentication-source');

                  if (!potentiallyValidSession && secret && authenticationSource) {
                    localStorage.removeItem('cardstack-secret-token'), localStorage.removeItem('cardstack-authentication-source');
                    _this.authenticate(authenticationSource, { secret: secret }).then(resolve, reject);
                  } else if (potentiallyValidSession && authenticationSource) {
                    // dont assume the session you have is valid just because session token hasn't yet expired
                    localStorage.removeItem('cardstack-authentication-source');
                    var token = rawSession.data.meta.token;

                    fetch(_environment.hubURL + '/auth/' + authenticationSource + '/status', {
                      method: 'GET',
                      headers: { 'authorization': 'Bearer ' + token }
                    }).then(function (response) {
                      if (response.status === 200) {
                        localStorage.setItem('cardstack-authentication-source', authenticationSource);
                        resolve(response.json());
                      } else {
                        reject();
                      }
                    });
                  } else if (partialSession) {
                    resolve(rawSession);
                  } else {
                    reject();
                  }
                }));

              case 1:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function restore(_x) {
        return _ref.apply(this, arguments);
      }

      return restore;
    }(),
    authenticate: function authenticate(authenticationSource, payload) {
      var tokenExchangeUri = _environment.hubURL + '/auth/' + authenticationSource;
      return fetch(tokenExchangeUri, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      }).then(function (response) {
        if (response.status !== 200) {
          throw new Error("Authentication attempt failed");
        }

        localStorage.setItem('cardstack-authentication-source', authenticationSource);

        if (response.headers.get("content-type") && response.headers.get("content-type").toLowerCase().indexOf("application/json") >= 0) {
          return response.json();
        } else {
          (true && Ember.warn('Got a non-json response from ' + _environment.hubURL + '/auth/' + authenticationSource, false, { id: 'cardstack-authentication-nonjson-response' }));

          return {};
        }
      });
    },
    fetchConfig: function fetchConfig(authenticationSource) {
      var tokenExchangeUri = _environment.hubURL + '/auth/' + authenticationSource;
      return fetch(tokenExchangeUri).then(function (response) {
        return response.json();
      });
    }
  });
});