import { isDate } from 'lodash' ; import { LicenseType } from '../../common/types' ; public export interface FeatureUsageServiceSetup { /**
     * Register a feature to be able to notify of it's usages using the  FeatureUsageServiceStart .
      register ( featureName , licenseType ) : void ; } export interface LastFeatureUsage { name : string ; lastUsed : Date | null ; licenseType : LicenseType ; } public export interface FeatureUsageServiceStart { param featureName param usedAt notifyUsage ( featureName , usedAt ? ) : void ; /**
     * Return a map containing last usage timestamp for all features.
     * Features that were not used yet do not appear in the map.
     */ getLastUsages ( ) : LastFeatureUsage [ ] ; } export class FeatureUsageService { private readonly lastUsages = new Map < string , LastFeatureUsage > ( ) ; public setup ( ) { return { register : ( featureName , licenseType ) => { const registered = this . lastUsages . get ( featureName ) ; if ( registered ) { if ( registered . licenseType !== licenseType ) { throw new Error ( `Feature '${ featureName }' has already been registered with another license type. (current: ${ registered . licenseType }, new: ${ licenseType })` ) ; } } else { this . lastUsages . set ( featureName , { name : featureName , lastUsed : null , licenseType , } ) ; } } , } ; } public start ( ) { return { notifyUsage : ( featureName , usedAt = Date . now ( ) ) => { const usage = this . lastUsages . get ( featureName ) ; if ( ! usage ) { throw new Error ( `Feature '${ featureName }' is not registered.` ) ; } const lastUsed = isDate ( usedAt ) ? usedAt : new Date ( usedAt ) ; if ( usage . lastUsed == null || lastUsed > usage . lastUsed ) { usage . lastUsed = lastUsed ; } } , getLastUsages : ( ) => Array . from ( this . lastUsages . values ( ) ) , } ; } }