-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathComponentsManagerBuilder.ts
More file actions
245 lines (231 loc) · 9.08 KB
/
Copy pathComponentsManagerBuilder.ts
File metadata and controls
245 lines (231 loc) · 9.08 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import type { Resource } from 'rdf-object';
import { RdfObjectLoader } from 'rdf-object';
import type { Logger } from 'winston';
import { createLogger, format, transports } from 'winston';
// eslint-disable-next-line import/extensions
import contextJson from '../../components/context.json';
import { ComponentsManager } from '../ComponentsManager';
import { ConfigConstructorPool } from '../construction/ConfigConstructorPool';
import type { IConfigConstructorPool } from '../construction/IConfigConstructorPool';
import { ConstructionStrategyCommonJs } from '../construction/strategy/ConstructionStrategyCommonJs';
import type { IConstructionStrategy } from '../construction/strategy/IConstructionStrategy';
import { ConfigPreprocessorComponent } from '../preprocess/ConfigPreprocessorComponent';
import { ConfigPreprocessorComponentMapped } from '../preprocess/ConfigPreprocessorComponentMapped';
import { ConfigPreprocessorOverride } from '../preprocess/ConfigPreprocessorOverride';
import { ParameterHandler } from '../preprocess/ParameterHandler';
import { RdfParser } from '../rdf/RdfParser';
import type { LogLevel } from '../util/LogLevel';
import { ComponentRegistry } from './ComponentRegistry';
import { ComponentRegistryFinalizer } from './ComponentRegistryFinalizer';
import { ConfigRegistry } from './ConfigRegistry';
import { ModuleStateBuilder } from './ModuleStateBuilder';
import type { IModuleState } from './ModuleStateBuilder';
/**
* Builds {@link ComponentsManager}'s based on given options.
*/
export class ComponentsManagerBuilder<TInstance = any> {
private readonly mainModulePath: string;
private readonly componentLoader: (registry: ComponentRegistry) => Promise<void>;
private readonly configLoader: (registry: ConfigRegistry) => Promise<void>;
private readonly constructionStrategy: IConstructionStrategy<TInstance>;
private readonly dumpErrorState: boolean;
private readonly logger: Logger;
private readonly moduleState?: IModuleState;
private readonly skipContextValidation: boolean;
private readonly typeChecking: boolean;
private readonly remoteContextLookups: boolean;
public constructor(options: IComponentsManagerBuilderOptions<TInstance>) {
this.mainModulePath = options.mainModulePath;
this.componentLoader = options.moduleLoader ?? (async registry => registry.registerAvailableModules());
this.configLoader = options.configLoader ?? (async() => {
// Do nothing
});
this.constructionStrategy = options.constructionStrategy ?? new ConstructionStrategyCommonJs({ req: require });
this.dumpErrorState = options.dumpErrorState === undefined ? true : Boolean(options.dumpErrorState);
this.logger = ComponentsManagerBuilder.createLogger(options.logLevel);
this.moduleState = options.moduleState;
this.skipContextValidation = options.skipContextValidation === undefined ?
true :
Boolean(options.skipContextValidation);
this.typeChecking = options.typeChecking === undefined ?
true :
Boolean(options.typeChecking);
this.remoteContextLookups = options.remoteContextLookups === undefined ?
false :
Boolean(options.typeChecking);
}
public static createLogger(logLevel: LogLevel = 'warn'): Logger {
return createLogger({
level: logLevel,
format: format.combine(
format.label({ label: 'Components.js' }),
format.colorize(),
format.timestamp(),
format.printf(({ level: levelInner, message, label: labelInner, timestamp }: Record<string, any>): string =>
`${timestamp} [${labelInner}] ${levelInner}: ${message}`),
),
transports: [ new transports.Console({
stderrLevels: [ 'error', 'warn', 'info', 'verbose', 'debug', 'silly' ],
}) ],
});
}
public static createObjectLoader(): RdfObjectLoader {
return new RdfObjectLoader({
uniqueLiterals: true,
context: contextJson,
});
}
/**
* @return A new instance of {@link ComponentsManager}.
*/
public async build(): Promise<ComponentsManager<TInstance>> {
// Initialize module state
let moduleState: IModuleState;
if (this.moduleState) {
moduleState = this.moduleState;
} else {
this.logger.info(`Initiating component discovery from ${this.mainModulePath}`);
moduleState = await new ModuleStateBuilder(this.logger)
.buildModuleState(require, this.mainModulePath);
this.logger.info(`Discovered ${Object.keys(moduleState.componentModules).length} component packages within ${moduleState.nodeModulePaths.length} packages`);
}
// Initialize object loader with built-in context
const objectLoader: RdfObjectLoader = ComponentsManagerBuilder.createObjectLoader();
// Create a single, cache-bearing JSON-LD context parser (with one shared prefetched document
// loader) that is reused across every component and config file. This avoids re-loading and
// re-normalizing the shared well-known @contexts once per file.
const contextParser = RdfParser.createSharedContextParser({
contexts: moduleState.contexts,
logger: this.logger,
remoteContextLookups: this.remoteContextLookups,
skipContextValidation: this.skipContextValidation,
});
// Load modules
this.logger.info(`Initiating component loading`);
const componentResources: Record<string, Resource> = {};
const componentRegistry = new ComponentRegistry({
moduleState,
objectLoader,
logger: this.logger,
componentResources,
skipContextValidation: this.skipContextValidation,
remoteContextLookups: this.remoteContextLookups,
contextParser,
});
await this.componentLoader(componentRegistry);
const componentFinalizer = new ComponentRegistryFinalizer({
objectLoader,
logger: this.logger,
componentResources,
componentRegistry,
});
componentFinalizer.finalize();
// Load configs
const configRegistry = new ConfigRegistry({
moduleState,
objectLoader,
logger: this.logger,
skipContextValidation: this.skipContextValidation,
remoteContextLookups: this.remoteContextLookups,
contextParser,
});
await this.configLoader(configRegistry);
this.logger.info(`Loaded configs`);
// Build constructor pool
const runTypeConfigs = {};
const parameterHandler = new ParameterHandler({ objectLoader, typeChecking: this.typeChecking });
const configConstructorPool: IConfigConstructorPool<TInstance> = new ConfigConstructorPool({
objectLoader,
configPreprocessors: [
new ConfigPreprocessorOverride({
objectLoader,
componentResources,
logger: this.logger,
}),
new ConfigPreprocessorComponentMapped({
objectLoader,
runTypeConfigs,
componentResources,
parameterHandler,
logger: this.logger,
}),
new ConfigPreprocessorComponent({
objectLoader,
componentResources,
runTypeConfigs,
parameterHandler,
logger: this.logger,
}),
],
constructionStrategy: this.constructionStrategy,
moduleState,
});
return new ComponentsManager<TInstance>({
moduleState,
objectLoader,
componentResources,
dumpErrorState: this.dumpErrorState,
configConstructorPool,
configRegistry,
logger: this.logger,
});
}
}
export interface IComponentsManagerBuilderOptions<TInstance> {
/* ----- REQUIRED FIELDS ----- */
/**
* Absolute path to the package root from which module resolution should start.
*/
mainModulePath: string;
/* ----- OPTIONAL FIELDS ----- */
/**
* Callback for registering components and modules.
* Defaults to an invocation of {@link ComponentRegistry.registerAvailableModules}.
* @param registry A registry that accept component and module registrations.
*/
moduleLoader?: (registry: ComponentRegistry) => Promise<void>;
/**
* Callback for registering configurations.
* Defaults to no config registrations.
* @param registry A registry that accepts configuration registrations.
*/
configLoader?: (registry: ConfigRegistry) => Promise<void>;
/**
* A strategy for constructing instances.
* Defaults to {@link ConstructionStrategyCommonJs}.
*/
constructionStrategy?: IConstructionStrategy<TInstance>;
/**
* If the error state should be dumped into `componentsjs-error-state.json`
* after failed instantiations.
* Defaults to `true`.
*/
dumpErrorState?: boolean;
/**
* The logging level.
* Defaults to `'warn'`.
*/
logLevel?: LogLevel;
/**
* The module state.
* Defaults to a newly created instances on the {@link mainModulePath}.
*/
moduleState?: IModuleState;
/**
* If JSON-LD context validation should be skipped.
* Defaults to `true`.
*/
skipContextValidation?: boolean;
/**
* If values for parameters should be type-checked.
* Defaults to `true`.
*/
typeChecking?: boolean;
/**
* If remote context lookups are allowed.
* If not allowed, an error is thrown if a remote lookup occurs.
* If allowed, only a warning is emitted.
* Defaults to `false`.
*/
remoteContextLookups?: boolean;
}