File size: 1,400 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { Disposable, type IDisposable } from '#/_base/di/lifecycle';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { BugIndicatingError } from '#/errors';

import {
  type FlagDefinitionInput,
  type FlagId,
  getContributedFlags,
  IFlagRegistry,
} from './flagRegistry';

export class FlagRegistryService extends Disposable implements IFlagRegistry {
  declare readonly _serviceBrand: undefined;
  private readonly byId = new Map<FlagId, FlagDefinitionInput>();

  constructor() {
    super();
    for (const def of getContributedFlags()) {
      this.add(def);
    }
  }

  register(definition: FlagDefinitionInput): IDisposable {
    this.add(definition);
    return this._register({
      dispose: () => {
        this.byId.delete(definition.id);
      },
    });
  }

  get(id: FlagId): FlagDefinitionInput | undefined {
    return this.byId.get(id);
  }

  list(): readonly FlagDefinitionInput[] {
    return [...this.byId.values()];
  }

  private add(definition: FlagDefinitionInput): void {
    if (this.byId.has(definition.id)) {
      throw new BugIndicatingError(`Flag '${definition.id}' is already registered`);
    }
    this.byId.set(definition.id, definition);
  }
}

registerScopedService(
  LifecycleScope.App,
  IFlagRegistry,
  FlagRegistryService,
  ScopeActivation.OnScopeCreated,
  'flag',
);