var __assign = this && this.__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import CheckPermissions from "./CheckPermissions";
import Exception403 from "./Exception403";
export var isComponentClass = function isComponentClass(component) {
  if (!component) return false;
  var proto = Object.getPrototypeOf(component);
  if (proto === React.Component || proto === Function.prototype) return true;
  return isComponentClass(proto);
}; // Determine whether the incoming component has been instantiated
// AuthorizedRoute is already instantiated
// Authorized  render is already instantiated, children is no instantiated
// Secured is not instantiated

var checkIsInstantiation = function checkIsInstantiation(target) {
  if (isComponentClass(target)) {
    var Target_1 = target;
    return function (props) {
      return _jsx(Target_1, __assign({}, props), void 0);
    };
  }

  if ( /*#__PURE__*/React.isValidElement(target)) {
    return function (props) {
      return /*#__PURE__*/React.cloneElement(target, props);
    };
  }

  return function () {
    return target;
  };
};
/**
 * 用于判断是否拥有权限访问此 view 权限
 * authority 支持传入 string, () => boolean | Promise
 * e.g. 'user' 只有 user 用户能访问
 * e.g. 'user,admin' user 和 admin 都能访问
 * e.g. ()=>boolean 返回true能访问,返回false不能访问
 * e.g. Promise  then 能访问   catch不能访问
 * e.g. authority support incoming string, () => boolean | Promise
 * e.g. 'user' only user user can access
 * e.g. 'user, admin' user and admin can access
 * e.g. () => boolean true to be able to visit, return false can not be accessed
 * e.g. Promise then can not access the visit to catch
 * @param {string | function | Promise} authority
 * @param {ReactNode} error 非必需参数
 * @param {boolean} allowCheck
 */


var authorize = function authorize(authority, error, allowCheck) {
  /**
   * conversion into a class
   * 防止传入字符串时找不到staticContext造成报错
   * String parameters can cause staticContext not found error
   */
  var classError = false;

  if (error) {
    classError = function classError() {
      return error;
    };
  }

  if (!authority) {
    throw new Error('authority is required');
  }

  return function decideAuthority(target) {
    var component = CheckPermissions(authority, target, classError || Exception403, allowCheck);
    return checkIsInstantiation(component);
  };
};

export default authorize;

