This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigContainer.ts
94 lines (82 loc) · 2.37 KB
/
ConfigContainer.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { JsonObject, ResolveConfigResult } from "./messageProcessor.ts";
interface StoredConfig<TConfig> {
globalConfig: JsonObject;
pluginConfig: JsonObject;
resolveContext: Lazy<ResolveConfigResult<TConfig>>;
}
export class ConfigContainer<TConfig> {
#configs: Map<number, StoredConfig<TConfig>> = new Map();
#resolveConfigCallback: (
pluginConfig: JsonObject,
globalConfig: JsonObject,
) => ResolveConfigResult<TConfig>;
constructor(
resolveConfig: (
pluginConfig: JsonObject,
globalConfig: JsonObject,
) => ResolveConfigResult<TConfig>,
) {
this.#resolveConfigCallback = resolveConfig;
}
set(configId: number, globalConfig: JsonObject, pluginConfig: JsonObject) {
this.#configs.set(configId, {
globalConfig,
pluginConfig,
resolveContext: new Lazy(() =>
this.#resolveConfig(pluginConfig, globalConfig, undefined)
),
});
}
#resolveConfig(
pluginConfig: JsonObject,
globalConfig: JsonObject,
overrideConfig: JsonObject | undefined,
) {
if (overrideConfig != null) {
pluginConfig = { ...pluginConfig };
for (const prop of Object.keys(overrideConfig)) {
pluginConfig[prop] = overrideConfig[prop];
}
}
return this.#resolveConfigCallback(pluginConfig, globalConfig);
}
release(configId: number) {
this.#configs.delete(configId);
}
getResolvedConfig(configId: number, overrideConfig: JsonObject | undefined) {
const config = this.#getStoredConfig(configId);
if (overrideConfig == null || Object.keys(overrideConfig).length === 0) {
return config.resolveContext.value.config;
} else {
return this.#resolveConfig(
config.pluginConfig,
config.globalConfig,
overrideConfig,
).config;
}
}
getDiagnostics(configId: number) {
const config = this.#getStoredConfig(configId);
return config.resolveContext.value.diagnostics;
}
#getStoredConfig(configId: number) {
const config = this.#configs.get(configId);
if (config == null) {
throw new Error(`Config '${configId}' not found`);
}
return config;
}
}
class Lazy<T> {
#value: T | undefined = undefined;
#getValue: () => T;
constructor(getValue: () => T) {
this.#getValue = getValue;
}
get value() {
if (this.#value == null) {
this.#value = this.#getValue();
}
return this.#value;
}
}