import values from "lodash/values" ; import { RoleNotValidError } from "../../common/errors" ; import matchesName from "./matchesName" ; import matchesUrlMatcher from "./matchesUrlMatcher" ; import separatorChar from "./separatorChar" ; export enum RoleName { Root = "root" , AppManager = "app-manager" , EntrypointManager = "entrypoint-manager" , BundleManager = "bundle-manager" } export type RoleTuple = [ RoleName , string ? ] ; export function isRoleValid ( role ) { const tokens = role . split ( separatorChar ) ; const [ name ] = tokens ; return ( ( values ( RoleName ) as string [ ] ) . includes ( name ) && ( name === RoleName . Root ? tokens . length === 1 : tokens . length === 2 ) ) ; } export function validateRole ( role ) { if ( ! isRoleValid ( role ) ) { throw new RoleNotValidError ( role ) ; } } export function fromRoleTuple ( roleTuple ) { return roleTuple . join ( separatorChar ) ; } export function toRoleTuple ( role ) { return role . split ( separatorChar ) as RoleTuple ; } export function roleMatchesRole ( heldRole , requiredRole ) { const [ heldRoleName , heldRoleTarget ] = toRoleTuple ( heldRole ) ; const [ requiredRoleName , requiredRoleTarget ] = requiredRole ; switch ( requiredRoleName ) { case RoleName . Root : return heldRoleName === requiredRoleName ; case RoleName . AppManager : case RoleName . BundleManager : return ( heldRoleName === requiredRoleName && matchesName ( heldRoleTarget ! , requiredRoleTarget ! ) ) ; case RoleName . EntrypointManager : return ( heldRoleName === requiredRoleName && matchesUrlMatcher ( heldRoleTarget ! , requiredRoleTarget ! ) ) ; default : return false ; } } export function oneOfRolesMatchesRole ( heldRoles , requiredRole ) { return heldRoles . some ( ( inputRole ) => roleMatchesRole ( inputRole , requiredRole ) ) ; }