function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { pickBy } from 'lodash';
export var AuthScene = /*#__PURE__*/function (AuthScene) {
  AuthScene["LOGIN"] = "login";
  AuthScene["GET_ACCESS_TOKEN"] = "get_access_token";
  return AuthScene;
}({});
var AUTH_BROADCAST_CHANNEL_NAME = 'WeaveFox-Auth';
var AuthSceneUrlMap = _defineProperty(_defineProperty({}, AuthScene.LOGIN, '/login/github/oauth'), AuthScene.GET_ACCESS_TOKEN, '/login/github/access_token');
export function openAuthWindow(params) {
  try {
    var _ref = params || {},
      onSuccess = _ref.onSuccess,
      onFail = _ref.onFail,
      scene = _ref.scene,
      sceneParams = _ref.sceneParams;
    var broadcast = new BroadcastChannel(AUTH_BROADCAST_CHANNEL_NAME);
    var cleanedParams = pickBy(sceneParams, function (val) {
      return val !== undefined && val !== null;
    });
    var sceneParamsString = new URLSearchParams(cleanedParams).toString();
    sceneParamsString = sceneParamsString ? "?".concat(sceneParamsString) : '';
    window.open(AuthSceneUrlMap[scene] + sceneParamsString, 'github_auth', 'left=0,top=0,width=600,height=600');
    var handler = function handler(event) {
      if (event.data.source !== 'WeaveFox-Auth') return;
      // 验证来源是否可信
      if (event.origin !== window.location.origin) {
        console.warn('Untrusted origin: ', event.origin);
        return;
      }
      if (event.data.success) {
        if (onSuccess) {
          onSuccess(event.data);
        }
      } else if (onFail) {
        onFail(event.data);
      }
      window.removeEventListener('message', handler);
      broadcast.removeEventListener('message', handler);
    };
    window.addEventListener('message', handler, false);
    broadcast.addEventListener('message', handler, false);

    // 未解之谜，窗口可能会丢失 opener 信息，暂时用 5s 后强制刷新解决
    setTimeout(function () {
      window.location.reload();
    }, 5000);
  } catch (e) {
    console.error('auth unexpected error', e);
  }
}