@serenity-js/core
Version:
The core Serenity/JS framework, providing the Screenplay Pattern interfaces, as well as the test reporting and integration infrastructure
58 lines • 3.21 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClassLoader = void 0;
const errors_1 = require("../../errors");
const format_1 = require("../format");
class ClassLoader {
loader;
parser;
constructor(loader, parser) {
this.loader = loader;
this.parser = parser;
}
looksLoadable(description) {
return this.parser.looksLikeClassDescription(description);
}
instantiate(description) {
const descriptor = this.parser.parse(description);
const requiredModule = this.loader.require(descriptor.moduleId);
const requiredType = requiredModule[descriptor.className];
if (typeof requiredType !== 'function') {
throw new errors_1.ConfigurationError((0, format_1.d) `Module ${descriptor.moduleId} doesn't seem to export ${descriptor.className}. Exported members include: ${Object.keys(requiredModule).join(', ')}`);
}
const needsParameter = Boolean(descriptor.parameter);
if (needsParameter && typeof requiredType.fromJSON === 'function') {
return this.ensureDefined(requiredType.fromJSON(descriptor.parameter), `${requiredType}.fromJSON(${descriptor.parameter})`);
}
if (needsParameter && requiredType.length > 1) {
throw new errors_1.ConfigurationError((0, format_1.d) `${descriptor.className} exported by ${descriptor.moduleId} must be a class with a static fromJSON(config) method or a function that accepts a single config parameter: ${descriptor.parameter}`);
}
if (!needsParameter && requiredType.length > 0) {
throw new errors_1.ConfigurationError((0, format_1.d) `${descriptor.className} exported by ${descriptor.moduleId} must be a parameterless function since no config parameter is specified`);
}
try {
return this.ensureDefined(requiredType(descriptor.parameter), `${requiredType}(${descriptor.parameter})`);
}
catch (error) {
if (error instanceof TypeError && error.message.includes('constructor')) {
return new requiredType(descriptor.parameter);
}
const errorMessage = [
(0, format_1.d) `${descriptor.className} exported by ${descriptor.moduleId} must be either:`,
descriptor.parameter && (0, format_1.d) `- a class with a static fromJSON(config) method`,
descriptor.parameter ? '- a no-arg constructor function' : '- a constructor function accepting config',
descriptor.parameter ? '- a no-arg function' : '- a function accepting config',
descriptor.parameter && (0, format_1.d) `where config is: ${descriptor.parameter}`,
].filter(Boolean).join('\n');
throw new errors_1.ConfigurationError(errorMessage);
}
}
ensureDefined(value, operation) {
if (value === undefined || value === null) {
throw new errors_1.ConfigurationError(`Calling ${operation} produced ${value}, which might indicate a configuration or programming error`);
}
return value;
}
}
exports.ClassLoader = ClassLoader;
//# sourceMappingURL=ClassLoader.js.map
;