[Code Style] Use prototypes in framework layer

WTD-1482
This commit is contained in:
Victor Woeltjen 2015-08-14 14:42:25 -07:00
parent 7fe866060b
commit edca2a9f03
14 changed files with 750 additions and 676 deletions

View File

@ -40,24 +40,36 @@ define(
* *
* @memberof platform/framework * @memberof platform/framework
* @constructor * @constructor
* @param {BundleLoader} loader * @param {platform/framework.BundleLoader} loader
* @param {BundleResolver} resolver * @param {platform/framework.BundleResolver} resolver
* @param {ExtensionRegistrar} registrar * @param {platform/framework.ExtensionRegistrar} registrar
* @param {ApplicationBootstrapper} bootstrapper * @param {platform/framework.ApplicationBootstrapper} bootstrapper
*/ */
function FrameworkInitializer(loader, resolver, registrar, bootstrapper) { function FrameworkInitializer(loader, resolver, registrar, bootstrapper) {
this.loader = loader;
return { this.resolver = resolver;
runApplication: function (bundleList) { this.registrar = registrar;
return loader.loadBundles(bundleList) this.bootstrapper = bootstrapper;
.then(resolver.resolveBundles)
.then(registrar.registerExtensions)
.then(bootstrapper.bootstrap);
} }
function bind(method, thisArg) {
return function () {
return method.apply(thisArg, arguments);
}; };
} }
/**
* Run the application defined by this set of bundles.
* @param bundleList
* @returns {*}
*/
FrameworkInitializer.prototype.runApplication = function (bundleList) {
return this.loader.loadBundles(bundleList)
.then(bind(this.resolver.resolveBundles, this.resolver))
.then(bind(this.registrar.registerExtensions, this.registrar))
.then(bind(this.bootstrapper.bootstrap, this.bootstrapper));
};
return FrameworkInitializer; return FrameworkInitializer;
} }
); );

View File

@ -53,26 +53,14 @@ define(
*/ */
function LogLevel(level) { function LogLevel(level) {
// Find the numeric level associated with the string // Find the numeric level associated with the string
var index = LOG_LEVELS.indexOf(level); this.index = LOG_LEVELS.indexOf(level);
// Replace logging methods with no-ops, if they are
// not of an appropriate level.
function decorate(log) {
LOG_LEVELS.forEach(function (m, i) {
// Determine applicability based on index
// (since levels are in descending order)
if (i > index) {
log[m] = NOOP;
}
});
}
// Default to 'warn' level if unspecified // Default to 'warn' level if unspecified
if (index < 0) { if (this.index < 0) {
index = 1; this.index = 1;
}
} }
return {
/** /**
* Configure logging to suppress log output if it is * Configure logging to suppress log output if it is
* not of an appropriate level. Both the Angular app * not of an appropriate level. Both the Angular app
@ -86,7 +74,21 @@ define(
* @param $log Angular's $log (also configured) * @param $log Angular's $log (also configured)
* @memberof platform/framework.LogLevel# * @memberof platform/framework.LogLevel#
*/ */
configure: function (app, $log) { LogLevel.prototype.configure = function (app, $log) {
var index = this.index;
// Replace logging methods with no-ops, if they are
// not of an appropriate level.
function decorate(log) {
LOG_LEVELS.forEach(function (m, i) {
// Determine applicability based on index
// (since levels are in descending order)
if (i > index) {
log[m] = NOOP;
}
});
}
decorate($log); decorate($log);
app.config(function ($provide) { app.config(function ($provide) {
$provide.decorator('$log', function ($delegate) { $provide.decorator('$log', function ($delegate) {
@ -94,9 +96,7 @@ define(
return $delegate; return $delegate;
}); });
}); });
}
}; };
}
return LogLevel; return LogLevel;
} }

View File

@ -42,24 +42,26 @@ define(
* @constructor * @constructor
*/ */
function ApplicationBootstrapper(angular, document, $log) { function ApplicationBootstrapper(angular, document, $log) {
return { this.angular = angular;
this.document = document;
this.$log = $log;
}
/** /**
* Bootstrap the application. * Bootstrap the application.
* *
* @method
* @memberof ApplicationBootstrapper#
* @param {angular.Module} app the Angular application to * @param {angular.Module} app the Angular application to
* bootstrap * bootstrap
* @memberof platform/framework.ApplicationBootstrapper#
*/ */
bootstrap: function (app) { ApplicationBootstrapper.prototype.bootstrap = function (app) {
var angular = this.angular,
document = this.document,
$log = this.$log;
$log.info("Bootstrapping application " + (app || {}).name); $log.info("Bootstrapping application " + (app || {}).name);
angular.element(document).ready(function () { angular.element(document).ready(function () {
angular.bootstrap(document, [app.name]); angular.bootstrap(document, [app.name]);
}); });
}
}; };
}
return ApplicationBootstrapper; return ApplicationBootstrapper;
} }

View File

@ -56,13 +56,7 @@ define(
function Bundle(path, bundleDefinition) { function Bundle(path, bundleDefinition) {
// Start with defaults // Start with defaults
var definition = Object.create(Constants.DEFAULT_BUNDLE), var definition = Object.create(Constants.DEFAULT_BUNDLE),
logName = path, logName = path;
self;
// Utility function for resolving paths in this bundle
function resolvePath(elements) {
return [path].concat(elements || []).join(Constants.SEPARATOR);
}
// Override defaults with specifics from bundle definition // Override defaults with specifics from bundle definition
Object.keys(bundleDefinition).forEach(function (k) { Object.keys(bundleDefinition).forEach(function (k) {
@ -81,135 +75,138 @@ define(
logName += ")"; logName += ")";
} }
self = { this.path = path;
this.definition = definition;
this.logName = logName;
}
// Utility function for resolving paths in this bundle
Bundle.prototype.resolvePath = function (elements) {
var path = this.path;
return [path].concat(elements || []).join(Constants.SEPARATOR);
};
/** /**
* Get the path to this bundle. * Get the path to this bundle.
* @memberof Bundle# * @returns {string} path to this bundle;
* @returns {string}
* @memberof platform/framework.Bundle#
*/ */
getPath: function () { Bundle.prototype.getPath = function () {
return path; return this.path;
}, };
/** /**
* Get the path to this bundle's source folder. If an * Get the path to this bundle's source folder. If an
* argument is provided, the path will be to the source * argument is provided, the path will be to the source
* file within the bundle's source file. * file within the bundle's source file.
* *
* @memberof Bundle#
* @param {string} [sourceFile] optionally, give a path to * @param {string} [sourceFile] optionally, give a path to
* a specific source file in the bundle. * a specific source file in the bundle.
* @returns {string} * @returns {string} path to the source folder (or to the
* @memberof platform/framework.Bundle# * source file within it)
*/ */
getSourcePath: function (sourceFile) { Bundle.prototype.getSourcePath = function (sourceFile) {
var subpath = sourceFile ? var subpath = sourceFile ?
[ definition.sources, sourceFile ] : [ this.definition.sources, sourceFile ] :
[ definition.sources ]; [ this.definition.sources ];
return this.resolvePath(subpath);
};
return resolvePath(subpath);
},
/** /**
* Get the path to this bundle's resource folder. If an * Get the path to this bundle's resource folder. If an
* argument is provided, the path will be to the resource * argument is provided, the path will be to the resource
* file within the bundle's resource file. * file within the bundle's resource file.
* *
* @memberof Bundle#
* @param {string} [resourceFile] optionally, give a path to * @param {string} [resourceFile] optionally, give a path to
* a specific resource file in the bundle. * a specific resource file in the bundle.
* @returns {string} * @returns {string} path to the resource folder (or to the
* @memberof platform/framework.Bundle# * resource file within it)
*/ */
getResourcePath: function (resourceFile) { Bundle.prototype.getResourcePath = function (resourceFile) {
var subpath = resourceFile ? var subpath = resourceFile ?
[ definition.resources, resourceFile ] : [ this.definition.resources, resourceFile ] :
[ definition.resources ]; [ this.definition.resources ];
return this.resolvePath(subpath);
};
return resolvePath(subpath);
},
/** /**
* Get the path to this bundle's library folder. If an * Get the path to this bundle's library folder. If an
* argument is provided, the path will be to the library * argument is provided, the path will be to the library
* file within the bundle's resource file. * file within the bundle's resource file.
* *
* @memberof Bundle#
* @param {string} [libraryFile] optionally, give a path to * @param {string} [libraryFile] optionally, give a path to
* a specific library file in the bundle. * a specific library file in the bundle.
* @returns {string} * @returns {string} path to the resource folder (or to the
* @memberof platform/framework.Bundle# * resource file within it)
*/ */
getLibraryPath: function (libraryFile) { Bundle.prototype.getLibraryPath = function (libraryFile) {
var subpath = libraryFile ? var subpath = libraryFile ?
[ definition.libraries, libraryFile ] : [ this.definition.libraries, libraryFile ] :
[ definition.libraries ]; [ this.definition.libraries ];
return this.resolvePath(subpath);
};
return resolvePath(subpath);
},
/** /**
* Get library configuration for this bundle. This is read * Get library configuration for this bundle. This is read
* from the bundle's definition; if the bundle is well-formed, * from the bundle's definition; if the bundle is well-formed,
* it will resemble a require.config object. * it will resemble a require.config object.
* @memberof Bundle# * @returns {object} library configuration
* @returns {object}
* @memberof platform/framework.Bundle#
*/ */
getConfiguration: function () { Bundle.prototype.getConfiguration = function () {
return definition.configuration || {}; return this.definition.configuration || {};
}, };
/** /**
* Get a log-friendly name for this bundle; this will * Get a log-friendly name for this bundle; this will
* include both the key (machine-readable name for this * include both the key (machine-readable name for this
* bundle) and the name (human-readable name for this * bundle) and the name (human-readable name for this
* bundle.) * bundle.)
* @returns {string} log-friendly name for this bundle * @returns {string} log-friendly name for this bundle
* @memberof platform/framework.Bundle#
*/ */
getLogName: function () { Bundle.prototype.getLogName = function () {
return logName; return this.logName;
}, };
/** /**
* Get all extensions exposed by this bundle of a given * Get all extensions exposed by this bundle of a given
* category. * category.
* *
* @param category * @param {string} category name of the extension category
* @memberof Bundle# * @returns {Array} extension definitions of that cataegory
* @returns {Array}
* @memberof platform/framework.Bundle#
*/ */
getExtensions: function (category) { Bundle.prototype.getExtensions = function (category) {
var extensions = definition.extensions[category] || []; var extensions = this.definition.extensions[category] || [],
self = this;
return extensions.map(function objectify(extDefinition) { return extensions.map(function objectify(extDefinition) {
return new Extension(self, category, extDefinition); return new Extension(self, category, extDefinition);
}); });
}, };
/** /**
* Get a list of all categories of extension exposed by * Get a list of all extension categories exposed by this bundle.
* this bundle.
* *
* @memberof Bundle# * @returns {string[]} the extension categories
* @returns {Array}
* @memberof platform/framework.Bundle#
*/ */
getExtensionCategories: function () { Bundle.prototype.getExtensionCategories = function () {
return Object.keys(definition.extensions); return Object.keys(this.definition.extensions);
}, };
/** /**
* Get the plain definition of this bundle, as read from * Get the plain definition of this bundle, as read from
* its JSON declaration. * its JSON declaration.
* *
* @memberof Bundle# * @returns {platform/framework.BundleDefinition} the raw
* @returns {BundleDefinition} the raw definition of this bundle * definition of this bundle
* @memberof platform/framework.Bundle#
*/ */
getDefinition: function () { Bundle.prototype.getDefinition = function () {
return definition; return this.definition;
}
}; };
return self;
}
return Bundle; return Bundle;
} }
); );

View File

@ -41,10 +41,26 @@ define(
* *
* @memberof platform/framework * @memberof platform/framework
* @constructor * @constructor
* @param {object} $http Angular's HTTP requester * @param $http Angular's HTTP requester
* @param {object} $log Angular's logging service * @param $log Angular's logging service
*/ */
function BundleLoader($http, $log) { function BundleLoader($http, $log) {
this.$http = $http;
this.$log = $log;
}
/**
* Load a group of bundles, to be used to constitute the
* application by later framework initialization phases.
*
* @param {string|string[]} an array of bundle names to load, or
* the name of a JSON file containing that array
* @returns {Promise.<Bundle[]>} a promise for the loaded bundles
*/
BundleLoader.prototype.loadBundles = function (bundles) {
var $http = this.$http,
$log = this.$log;
// Utility function; load contents of JSON file using $http // Utility function; load contents of JSON file using $http
function getJSON(file) { function getJSON(file) {
@ -101,31 +117,10 @@ define(
return getJSON(listFile).then(loadBundlesFromArray); return getJSON(listFile).then(loadBundlesFromArray);
} }
// Load all indicated bundles. If the argument is an array,
// this is taken to be a list of all bundles to load; if it
// is a string, then it is treated as the name of a JSON
// file containing the list of bundles to load.
function loadBundles(bundles) {
return Array.isArray(bundles) ? loadBundlesFromArray(bundles) : return Array.isArray(bundles) ? loadBundlesFromArray(bundles) :
(typeof bundles === 'string') ? loadBundlesFromFile(bundles) : (typeof bundles === 'string') ? loadBundlesFromFile(bundles) :
Promise.reject(new Error(INVALID_ARGUMENT_MESSAGE)); Promise.reject(new Error(INVALID_ARGUMENT_MESSAGE));
}
return {
/**
* Load a group of bundles, to be used to constitute the
* application by later framework initialization phases.
*
* @memberof BundleLoader#
* @param {string|string[]} an array of bundle names to load, or
* the name of a JSON file containing that array
* @returns {Promise.<Bundle[]>}
* @memberof platform/framework.BundleLoader#
*/
loadBundles: loadBundles
}; };
}
return BundleLoader; return BundleLoader;
} }

View File

@ -78,37 +78,41 @@ define(
// Attach bundle metadata // Attach bundle metadata
extensionDefinition.bundle = bundle.getDefinition(); extensionDefinition.bundle = bundle.getDefinition();
return { this.logName = logName;
this.bundle = bundle;
this.category = category;
this.definition = definition;
this.extensionDefinition = extensionDefinition;
}
/** /**
* Get the machine-readable identifier for this extension. * Get the machine-readable identifier for this extension.
* *
* @returns {string} * @returns {string} the identifier for this extension
* @memberof platform/framework.Extension#
*/ */
getKey: function () { Extension.prototype.getKey = function () {
return definition.key || "undefined"; return this.definition.key || "undefined";
}, };
/** /**
* Get the bundle which declared this extension. * Get the bundle which declared this extension.
* *
* @memberof Extension# * @returns {Bundle} the declaring bundle
* @returns {Bundle}
* @memberof platform/framework.Extension#
*/ */
getBundle: function () { Extension.prototype.getBundle = function () {
return bundle; return this.bundle;
}, };
/** /**
* Get the category into which this extension falls. * Get the category into which this extension falls.
* (e.g. "directives") * (e.g. "directives")
* *
* @memberof Extension# * @returns {string} the extension category
* @returns {string}
* @memberof platform/framework.Extension#
*/ */
getCategory: function () { Extension.prototype.getCategory = function () {
return category; return this.category;
}, };
/** /**
* Check whether or not this extension should have an * Check whether or not this extension should have an
* associated implementation module which may need to * associated implementation module which may need to
@ -116,36 +120,36 @@ define(
* *
* @returns {boolean} true if an implementation separate * @returns {boolean} true if an implementation separate
* from this definition should also be loaded * from this definition should also be loaded
* @memberof platform/framework.Extension#
*/ */
hasImplementation: function () { Extension.prototype.hasImplementation = function () {
return definition.implementation !== undefined; return this.definition.implementation !== undefined;
}, };
/** /**
* Get the path to the AMD module which implements this * Get the path to the AMD module which implements this
* extension. Will return undefined if there is no * extension. Will return undefined if there is no
* implementation associated with this extension. * implementation associated with this extension.
* *
* @memberof Extension#
* @returns {string} path to implementation, or undefined * @returns {string} path to implementation, or undefined
* @memberof platform/framework.Extension#
*/ */
getImplementationPath: function () { Extension.prototype.getImplementationPath = function () {
return definition.implementation ? return this.definition.implementation ?
bundle.getSourcePath(definition.implementation) : this.bundle.getSourcePath(this.definition.implementation) :
undefined; undefined;
}, };
/** /**
* Get a log-friendly name for this extension; this will * Get a log-friendly name for this extension; this will
* include both the key (machine-readable name for this * include both the key (machine-readable name for this
* extension) and the name (human-readable name for this * extension) and the name (human-readable name for this
* extension.) * extension.)
*
* @returns {string} log-friendly name for this extension * @returns {string} log-friendly name for this extension
* @memberof platform/framework.Extension#
*/ */
getLogName: function () { Extension.prototype.getLogName = function () {
return logName; return this.logName;
}, };
/** /**
* Get the plain definition of the extension. * Get the plain definition of the extension.
* *
@ -153,18 +157,13 @@ define(
* field which points back to the bundle which defined the * field which points back to the bundle which defined the
* extension, as a convenience. * extension, as a convenience.
* *
* @memberof Extension#
* @returns {ExtensionDefinition} the plain definition of * @returns {ExtensionDefinition} the plain definition of
* this extension, as read from the bundle * this extension, as read from the bundle
* declaration. * declaration.
* @memberof platform/framework.Extension#
*/ */
getDefinition: function () { Extension.prototype.getDefinition = function () {
return extensionDefinition; return this.extensionDefinition;
}
}; };
}
return Extension; return Extension;

View File

@ -37,13 +37,25 @@ define(
* @constructor * @constructor
*/ */
function CustomRegistrars(app, $log) { function CustomRegistrars(app, $log) {
this.app = app;
this.$log = $log;
}
// Utility; bind a function to a "this" pointer
function bind(fn, thisArg) {
return function () {
return fn.apply(thisArg, arguments);
};
}
// Used to create custom registration functions which map to // Used to create custom registration functions which map to
// named methods on Angular modules, which follow the normal // named methods on Angular modules, which follow the normal
// app.method(key, [ deps..., function ]) pattern. // app.method(key, [ deps..., function ]) pattern.
function CustomRegistrar(angularFunction) { function customRegistrar(angularFunction) {
return function (extension, index) { return function (extension, index) {
var key = extension.key, var app = this.app,
$log = this.$log,
key = extension.key,
dependencies = extension.depends || []; dependencies = extension.depends || [];
if (!key) { if (!key) {
@ -71,7 +83,9 @@ define(
} }
function registerConstant(extension) { function registerConstant(extension) {
var key = extension.key, var app = this.app,
$log = this.$log,
key = extension.key,
value = extension.value; value = extension.value;
if (typeof key === "string" && value !== undefined) { if (typeof key === "string" && value !== undefined) {
@ -95,6 +109,9 @@ define(
// Custom registration function for extensions of category "runs" // Custom registration function for extensions of category "runs"
function registerRun(extension) { function registerRun(extension) {
var app = this.app,
$log = this.$log;
if (typeof extension === 'function') { if (typeof extension === 'function') {
// Prepend dependencies, and schedule to run // Prepend dependencies, and schedule to run
app.run((extension.depends || []).concat([extension])); app.run((extension.depends || []).concat([extension]));
@ -110,7 +127,9 @@ define(
// Custom registration function for extensions of category "route" // Custom registration function for extensions of category "route"
function registerRoute(extension) { function registerRoute(extension) {
var route = Object.create(extension); var app = this.app,
$log = this.$log,
route = Object.create(extension);
// Adjust path for bundle // Adjust path for bundle
if (route.templateUrl) { if (route.templateUrl) {
@ -136,6 +155,8 @@ define(
// Handle service compositing // Handle service compositing
function registerComponents(components) { function registerComponents(components) {
var app = this.app,
$log = this.$log;
return new ServiceCompositor(app, $log) return new ServiceCompositor(app, $log)
.registerCompositeServices(components); .registerCompositeServices(components);
} }
@ -144,23 +165,62 @@ define(
// (which acts on single objects) to one which acts upon arrays. // (which acts on single objects) to one which acts upon arrays.
function mapUpon(func) { function mapUpon(func) {
return function (array) { return function (array) {
return array.map(func); return array.map(bind(func, this));
}; };
} }
// More like key-value pairs than methods; key is the // More like key-value pairs than methods; key is the
// name of the extension category to be handled, and the value // name of the extension category to be handled, and the value
// is the function which handles it. // is the function which handles it.
return {
constants: mapUpon(registerConstant), /**
routes: mapUpon(registerRoute), * Register constant values.
directives: mapUpon(new CustomRegistrar("directive")), * @param {Array} extensions the resolved extensions
controllers: mapUpon(new CustomRegistrar("controller")), */
services: mapUpon(new CustomRegistrar("service")), CustomRegistrars.prototype.constants =
runs: mapUpon(registerRun), mapUpon(registerConstant);
components: registerComponents
}; /**
} * Register Angular routes.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.routes =
mapUpon(registerRoute);
/**
* Register Angular directives.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.directives =
mapUpon(customRegistrar("directive"));
/**
* Register Angular controllers.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.controllers =
mapUpon(customRegistrar("controller"));
/**
* Register Angular services.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.services =
mapUpon(customRegistrar("service"));
/**
* Register functions which will run after bootstrapping.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.runs =
mapUpon(registerRun);
/**
* Register components of composite services.
* @param {Array} extensions the resolved extensions
*/
CustomRegistrars.prototype.components =
registerComponents;
return CustomRegistrars; return CustomRegistrars;
} }

View File

@ -47,7 +47,34 @@ define(
// Track which extension categories have already been registered. // Track which extension categories have already been registered.
// Exceptions will be thrown if the same extension category is // Exceptions will be thrown if the same extension category is
// registered twice. // registered twice.
var registeredCategories = {}; this.registeredCategories = {};
this.customRegistrars = customRegistrars || {};
this.app = app;
this.sorter = sorter;
this.$log = $log;
}
/**
* Register a group of resolved extensions with the Angular
* module managed by this registrar.
*
* For convenient chaining (particularly from the framework
* initializer's perspective), this returns the Angular
* module with which extensions were registered.
*
* @param {Object.<string, object[]>} extensionGroup an object
* containing key-value pairs, where keys are extension
* categories and values are arrays of resolved
* extensions
* @returns {angular.Module} the application module with
* which extensions were registered
*/
ExtensionRegistrar.prototype.registerExtensions = function (extensionGroup) {
var registeredCategories = this.registeredCategories,
customRegistrars = this.customRegistrars,
app = this.app,
sorter = this.sorter,
$log = this.$log;
// Used to build unique identifiers for individual extensions, // Used to build unique identifiers for individual extensions,
// so that these can be registered separately with Angular // so that these can be registered separately with Angular
@ -179,7 +206,6 @@ define(
}); });
} }
function registerExtensionGroup(extensionGroup) {
// Announce we're entering a new phase // Announce we're entering a new phase
$log.info("Registering extensions..."); $log.info("Registering extensions...");
@ -197,30 +223,7 @@ define(
// Return the application to which these extensions // Return the application to which these extensions
// have been registered // have been registered
return app; return app;
}
customRegistrars = customRegistrars || {};
return {
/**
* Register a group of resolved extensions with the Angular
* module managed by this registrar.
*
* For convenient chaining (particularly from the framework
* initializer's perspective), this returns the Angular
* module with which extensions were registered.
*
* @param {Object.<string, object[]>} extensionGroup an object
* containing key-value pairs, where keys are extension
* categories and values are arrays of resolved
* extensions
* @returns {angular.Module} the application module with
* which extensions were registered
* @memberof platform/framework.ExtensionRegistrar#
*/
registerExtensions: registerExtensionGroup
}; };
}
return ExtensionRegistrar; return ExtensionRegistrar;
} }

View File

@ -38,6 +38,17 @@ define(
* @constructor * @constructor
*/ */
function ExtensionSorter($log) { function ExtensionSorter($log) {
this.$log = $log;
}
/**
* Sort extensions according to priority.
*
* @param {object[]} extensions array of resolved extensions
* @returns {object[]} the same extensions, in priority order
*/
ExtensionSorter.prototype.sort = function (extensions) {
var $log = this.$log;
// Handle unknown or malformed priorities specified by extensions // Handle unknown or malformed priorities specified by extensions
function unrecognizedPriority(extension) { function unrecognizedPriority(extension) {
@ -98,22 +109,11 @@ define(
return (b.priority - a.priority) || (a.index - b.index); return (b.priority - a.priority) || (a.index - b.index);
} }
return {
/**
* Sort extensions according to priority.
*
* @param {object[]} extensions array of resolved extensions
* @returns {object[]} the same extensions, in priority order
* @memberof platform/framework.ExtensionSorter#
*/
sort: function (extensions) {
return (extensions || []) return (extensions || [])
.map(prioritize) .map(prioritize)
.sort(compare) .sort(compare)
.map(deprioritize); .map(deprioritize);
}
}; };
}
return ExtensionSorter; return ExtensionSorter;
} }

View File

@ -37,8 +37,30 @@ define(
* @constructor * @constructor
*/ */
function ServiceCompositor(app, $log) { function ServiceCompositor(app, $log) {
var latest = {}, this.latest = {};
providerLists = {}; // Track latest services registered this.providerLists = {}; // Track latest services registered
this.app = app;
this.$log = $log;
}
/**
* Register composite services with Angular. This will build
* up a dependency hierarchy between providers, aggregators,
* and/or decorators, such that a dependency upon the service
* type they expose shall be satisfied by their fully-wired
* whole.
*
* Note that this method assumes that a complete set of
* components shall be provided. Multiple calls to this
* method may not behave as expected.
*
* @param {Array} components extensions of category component
*/
ServiceCompositor.prototype.registerCompositeServices = function (components) {
var latest = this.latest,
providerLists = this.providerLists,
app = this.app,
$log = this.$log;
// Log a warning; defaults to "no service provided by" // Log a warning; defaults to "no service provided by"
function warn(extension, category, message) { function warn(extension, category, message) {
@ -200,33 +222,13 @@ define(
registerLatest(); registerLatest();
} }
// Initial point of entry; just separate components by type // Initial point of entry; split into three component types.
function registerCompositeServices(components) {
registerComposites( registerComposites(
components.filter(hasType("provider")), components.filter(hasType("provider")),
components.filter(hasType("aggregator")), components.filter(hasType("aggregator")),
components.filter(hasType("decorator")) components.filter(hasType("decorator"))
); );
}
return {
/**
* Register composite services with Angular. This will build
* up a dependency hierarchy between providers, aggregators,
* and/or decorators, such that a dependency upon the service
* type they expose shall be satisfied by their fully-wired
* whole.
*
* Note that this method assumes that a complete set of
* components shall be provided. Multiple calls to this
* method may not behave as expected.
*
* @param {Array} components extensions of category component
* @memberof platform/framework.ServiceCompositor#
*/
registerCompositeServices: registerCompositeServices
}; };
}
return ServiceCompositor; return ServiceCompositor;
} }

View File

@ -38,8 +38,27 @@ define(
* @constructor * @constructor
*/ */
function BundleResolver(extensionResolver, requireConfigurator, $log) { function BundleResolver(extensionResolver, requireConfigurator, $log) {
this.extensionResolver = extensionResolver;
this.requireConfigurator = requireConfigurator;
this.$log = $log;
}
/** /**
* Resolve all extensions exposed by these bundles.
*
* @param {Bundle[]} bundles the bundles to resolve
* @returns {Promise.<Object.<string, object[]>>} an promise
* for an object containing
* key-value pairs, where keys are extension
* categories and values are arrays of resolved
* extensions belonging to those categories
*/
BundleResolver.prototype.resolveBundles = function (bundles) {
var extensionResolver = this.extensionResolver,
requireConfigurator = this.requireConfigurator,
$log = this.$log;
/*
* Merge resolved bundles (where each is expressed as an * Merge resolved bundles (where each is expressed as an
* object containing key-value pairs, where keys are extension * object containing key-value pairs, where keys are extension
* categories and values are arrays of resolved extensions) * categories and values are arrays of resolved extensions)
@ -99,28 +118,13 @@ define(
.then(giveResult); .then(giveResult);
} }
return {
/**
* Resolve all extensions exposed by these bundles.
*
* @param {Bundle[]} bundles the bundles to resolve
* @returns {Promise.<Object.<string, object[]>>} an promise
* for an object containing
* key-value pairs, where keys are extension
* categories and values are arrays of resolved
* extensions belonging to those categories
* @memberof platform/framework.BundleResolver#
*/
resolveBundles: function (bundles) {
// First, make sure Require is suitably configured // First, make sure Require is suitably configured
requireConfigurator.configure(bundles); requireConfigurator.configure(bundles);
// Then, resolve all extension implementations. // Then, resolve all extension implementations.
return Promise.all(bundles.map(resolveBundle)) return Promise.all(bundles.map(resolveBundle))
.then(mergeResolvedBundles); .then(mergeResolvedBundles);
}
}; };
}
return BundleResolver; return BundleResolver;
} }

View File

@ -39,6 +39,27 @@ define(
* @constructor * @constructor
*/ */
function ExtensionResolver(loader, $log) { function ExtensionResolver(loader, $log) {
this.loader = loader;
this.$log = $log;
}
/**
* Resolve the provided extension; this will give a promise
* for the extension's implementation, if one has been
* specified, or for the plain definition of the extension
* otherwise. The plain definition will also be given
* if the implementation fails to load for some reason.
*
* All key-value pairs from the extension definition
* will additionally be attached to any loaded implementation.
*
* @param {Extension} extension the extension to resolve
* @returns {Promise} a promise for the resolved extension
*/
ExtensionResolver.prototype.resolve = function (extension) {
var loader = this.loader,
$log = this.$log;
function loadImplementation(extension) { function loadImplementation(extension) {
var implPath = extension.getImplementationPath(), var implPath = extension.getImplementationPath(),
implPromise = loader.load(implPath), implPromise = loader.load(implPath),
@ -107,21 +128,6 @@ define(
return implPromise.then(attachDefinition, handleError); return implPromise.then(attachDefinition, handleError);
} }
return {
/**
* Resolve the provided extension; this will give a promise
* for the extension's implementation, if one has been
* specified, or for the plain definition of the extension
* otherwise. The plain definition will also be given
* if the implementation fails to load for some reason.
*
* All key-value pairs from the extension definition
* will additionally be attached to any loaded implementation.
*
* @param {Extension} extension
* @memberof platform/framework.ExtensionResolver#
*/
resolve: function (extension) {
// Log that loading has begun // Log that loading has begun
$log.info([ $log.info([
"Resolving extension ", "Resolving extension ",
@ -131,9 +137,7 @@ define(
return extension.hasImplementation() ? return extension.hasImplementation() ?
loadImplementation(extension) : loadImplementation(extension) :
Promise.resolve(extension.getDefinition()); Promise.resolve(extension.getDefinition());
}
}; };
}
return ExtensionResolver; return ExtensionResolver;
} }

View File

@ -39,13 +39,9 @@ define(
* @param {*} $log Angular's logging service * @param {*} $log Angular's logging service
*/ */
function ImplementationLoader(require) { function ImplementationLoader(require) {
function loadModule(path) { this.require = require;
return new Promise(function (fulfill, reject) {
require([path], fulfill, reject);
});
} }
return {
/** /**
* Load an extension's implementation; or, equivalently, * Load an extension's implementation; or, equivalently,
* load an AMD module. This is fundamentally similar * load an AMD module. This is fundamentally similar
@ -54,15 +50,15 @@ define(
* with the loaded module, or rejected with the error * with the loaded module, or rejected with the error
* reported by Require. * reported by Require.
* *
* @method
* @memberof ImplementationLoader#
* @param {string} path the path to the module to load * @param {string} path the path to the module to load
* @returns {Promise} a promise for the specified module. * @returns {Promise} a promise for the specified module.
* @memberof platform/framework.ImplementationLoader#
*/ */
load: loadModule ImplementationLoader.prototype.load = function loadModule(path) {
var require = this.require;
return new Promise(function (fulfill, reject) {
require([path], fulfill, reject);
});
}; };
}
return ImplementationLoader; return ImplementationLoader;
} }

View File

@ -35,6 +35,9 @@ define(
* @param requirejs an instance of RequireJS * @param requirejs an instance of RequireJS
*/ */
function RequireConfigurator(requirejs) { function RequireConfigurator(requirejs) {
this.requirejs = requirejs;
}
// Utility function to clone part of a bundle definition // Utility function to clone part of a bundle definition
function clone(obj) { function clone(obj) {
return JSON.parse(JSON.stringify(obj)); return JSON.parse(JSON.stringify(obj));
@ -93,7 +96,6 @@ define(
); );
} }
return {
/** /**
* Configure RequireJS to utilize any path/shim definitions * Configure RequireJS to utilize any path/shim definitions
* provided by these bundles. * provided by these bundles.
@ -102,11 +104,9 @@ define(
* configuration * configuration
* @memberof platform/framework.RequireConfigurator# * @memberof platform/framework.RequireConfigurator#
*/ */
configure: function (bundles) { RequireConfigurator.prototype.configure = function (bundles) {
return requirejs.config(buildConfiguration(bundles)); return this.requirejs.config(buildConfiguration(bundles));
}
}; };
}
return RequireConfigurator; return RequireConfigurator;