1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Big rework of registry.js

Part of #322

Loads node.html files before node.js files

Adds helper.unload which must be called by node tests
to clear the registery of nodes
This commit is contained in:
Nick O'Leary 2014-08-01 22:05:49 +01:00
parent a869642705
commit 79e9641c09
14 changed files with 494 additions and 305 deletions

View File

@ -63,7 +63,10 @@ module.exports = {
// Node type registry
registerType: registerType,
getType: registry.get,
getNodeList: registry.getNodeList,
getNodeConfigs: registry.getNodeConfigs,
getNodeConfig: registry.getNodeConfig,
clearRegistry: registry.clear,
// Flow handling
loadFlows: flows.load,

View File

@ -19,6 +19,7 @@ var when = require("when");
var whenNode = require('when/node');
var fs = require("fs");
var path = require("path");
var crypto = require("crypto");
var cheerio = require("cheerio");
var UglifyJS = require("uglify-js");
@ -27,11 +28,96 @@ var events = require("../events");
var Node;
var settings;
var node_types = {};
var node_configs = [];
var registry = (function() {
var nodeConfigCache = null;
var nodeConfigs = {};
var nodeList = [];
var nodeConstructors = {};
return {
addNodeSet: function(id,set) {
nodeConfigs[id] = set;
nodeList.push(id);
},
getNodeList: function() {
return nodeList.map(function(id) {
var n = nodeConfigs[id];
var r = {
id: n.id,
types: n.types,
name: n.name,
enabled: n.enabled
}
if (n.err) {
r.err = n.err.toString();
}
return r;
});
},
registerNodeConstructor: function(type,constructor) {
if (nodeConstructors[type]) {
throw new Error(type+" already registered");
}
util.inherits(constructor,Node);
nodeConstructors[type] = constructor;
events.emit("type-registered",type);
},
/**
* Gets all of the node template configs
* @return all of the node templates in a single string
*/
getAllNodeConfigs: function() {
if (!nodeConfigCache) {
var result = "";
var script = "";
for (var i=0;i<nodeList.length;i++) {
var config = nodeConfigs[nodeList[i]];
if (config.enabled) {
result += config.config||"";
script += config.script||"";
}
}
result += '<script type="text/javascript">';
result += UglifyJS.minify(script, {fromString: true}).code;
result += '</script>';
nodeConfigCache = result;
}
return nodeConfigCache;
},
getNodeConfig: function(id) {
var config = nodeConfigs[id];
if (config) {
var result = config.config||"";
result += '<script type="text/javascript">'+(config.script||"")+'</script>';
return result;
} else {
return null;
}
},
getNodeConstructor: function(type) {
return nodeConstructors[type];
},
clear: function() {
nodeConfigCache = null;
nodeConfigs = {};
nodeList = [];
nodeConstructors = {};
}
}
})();
//TODO: clear this cache whenever a node type is added/removed
var node_config_cache = null;
function init(_settings) {
Node = require("./Node");
settings = _settings;
}
/**
* Synchronously walks the directory looking for node files.
@ -41,13 +127,29 @@ var node_config_cache = null;
*/
function getNodeFiles(dir) {
var result = [];
var files = fs.readdirSync(dir);
var files = [];
try {
files = fs.readdirSync(dir);
} catch(err) {
return result;
}
files.sort();
files.forEach(function(fn) {
var stats = fs.statSync(path.join(dir,fn));
if (stats.isFile()) {
if (/\.js$/.test(fn)) {
result.push(path.join(dir,fn));
var valid = true;
if (settings.nodesExcludes) {
for (var i=0;i<settings.nodesExcludes.length;i++) {
if (settings.nodesExcludes[i] == fn) {
valid = false;
break;
}
}
}
if (valid) {
result.push(path.join(dir,fn));
}
}
} else if (stats.isDirectory()) {
// Ignore /.dirs/, /lib/ /node_modules/
@ -103,15 +205,14 @@ function scanTreeForNodesModules(moduleName) {
* Loads the nodes provided in an npm package.
* @param moduleDir the root directory of the package
* @param pkg the module's package.json object
* @return an array of promises returned by loadNode
*/
function loadNodesFromModule(moduleDir,pkg) {
var nodes = pkg['node-red'].nodes||{};
var promises = [];
var results = [];
var iconDirs = [];
for (var n in nodes) {
if (nodes.hasOwnProperty(n)) {
promises.push(loadNode(path.join(moduleDir,nodes[n]),pkg.name,n));
results.push(loadNodeConfig(path.join(moduleDir,nodes[n]),pkg.name+":"+n));
var iconDir = path.join(moduleDir,path.dirname(nodes[n]),"icons");
if (iconDirs.indexOf(iconDir) == -1) {
if (fs.existsSync(iconDir)) {
@ -121,89 +222,50 @@ function loadNodesFromModule(moduleDir,pkg) {
}
}
}
return promises;
return results;
}
/**
* Loads the specified node into the registry.
* @param nodeFile the fully qualified path of the node's .js file
* @param nodeModule the name of the module (npm nodes only)
* @param nodeName the name of the node (npm nodes only)
* @return a promise that resolves to a node info object
* Loads a node's configuration
* @param file the fully qualified path of the node's .js file
* @param name the name of the node
* @return the node object
* {
* id: a unqiue id for the node file
* name: the name of the node file, or label from the npm module
* module: the name of the node npm module (npm nodes only)
* path: the fully qualified path to the node's .js file
* file: the fully qualified path to the node's .js file
* template: the fully qualified path to the node's .html file
* config: the non-script parts of the node's .html file
* script: the script part of the node's .html file
* err: any error encountered whilst loading the node
* types: an array of node type names in this file
* }
* The node info object must be added to the node_config array by the caller.
* This allows nodes to be added in a defined order, regardless of how async
* their loading becomes.
*/
function loadNode(nodeFile, nodeModule, nodeName) {
var nodeDir = path.dirname(nodeFile);
var nodeFn = path.basename(nodeFile);
function loadNodeConfig(file,name) {
var id = crypto.createHash('sha1').update(file).digest("hex");
if (settings.nodesExcludes) {
for (var i=0;i<settings.nodesExcludes.length;i++) {
if (settings.nodesExcludes[i] == nodeFn) {
return when.resolve();
}
}
var node = {
id: id,
file: file,
name: name||path.basename(file),
template: file.replace(/\.js$/,".html"),
enabled: true
}
var nodeFilename = path.join(nodeDir,nodeFn);
var nodeInfo = {name:nodeFn, path:nodeFilename};
if (nodeModule) {
nodeInfo.name = nodeModule+":"+nodeName;
nodeInfo.module = nodeModule;
}
try {
var loadPromise = null;
var r = require(nodeFilename);
if (typeof r === "function") {
var promise = r(require('../red'));
if (promise != null && typeof promise.then === "function") {
loadPromise = promise.then(function() {
nodeInfo = loadTemplate(nodeInfo);
return when.resolve(nodeInfo);
}).otherwise(function(err) {
nodeInfo.err = err;
return when.resolve(nodeInfo);
});
}
}
if (loadPromise == null) {
nodeInfo = loadTemplate(nodeInfo);
loadPromise = when.resolve(nodeInfo);
}
return loadPromise;
} catch(err) {
nodeInfo.err = err;
return when.resolve(nodeInfo);
}
}
/**
* Loads the html template file for a node
* @param templateFilanem
*/
function loadTemplate(nodeInfo) {
var templateFilename = nodeInfo.path.replace(/\.js$/,".html");
var content = fs.readFileSync(templateFilename,'utf8');
var content = fs.readFileSync(node.template,'utf8');
var $ = cheerio.load(content);
var template = "";
var script = "";
var types = [];
$("*").each(function(i,el) {
if (el.type == "script" && el.attribs.type == "text/javascript") {
script += el.children[0].data;
} else if (el.name == "script" || el.name == "style") {
if (el.attribs.type == "text/x-red" && el.attribs['data-template-name']) {
types.push(el.attribs['data-template-name'])
}
var openTag = "<"+el.name;
var closeTag = "</"+el.name+">";
if (el.attribs) {
@ -217,27 +279,22 @@ function loadTemplate(nodeInfo) {
template += openTag+$(el).text()+closeTag;
}
});
node.types = types;
node.config = template;
node.script = script;
nodeInfo.template = templateFilename;
nodeInfo.config = template;
nodeInfo.script = script;
return nodeInfo;
}
function init(_settings) {
Node = require("./Node");
settings = _settings;
registry.addNodeSet(id,node);
return node;
}
/**
* Loads all palette nodes
* @param defaultNodesDir optional parameter, when set, it overrides the default location
* of nodeFiles
* @return a promise that resolves to a list of any errors encountered loading nodes
* @param defaultNodesDir optional parameter, when set, it overrides the default
* location of nodeFiles - used by the tests
* @return a promise that resolves on completion of loading
*/
function load(defaultNodesDir) {
return when.promise(function(resolve,reject) {
// Find all of the nodes to load
var nodeFiles;
if(defaultNodesDir) {
@ -255,77 +312,84 @@ function load(defaultNodesDir) {
nodeFiles = nodeFiles.concat(getNodeFiles(dir[i]));
}
}
// Find all of the modules containing nodes
var moduleFiles = scanTreeForNodesModules();
// Load all of the nodes in the order they were discovered
var loadPromises = [];
var nodes = [];
nodeFiles.forEach(function(file) {
loadPromises.push(loadNode(file));
nodes.push(loadNodeConfig(file));
});
moduleFiles.forEach(function(file) {
loadPromises = loadPromises.concat(loadNodesFromModule(file.dir,file.package));
});
when.settle(loadPromises).then(function(results) {
var errors = [];
results.forEach(function(result) {
if (result.value.err) {
// Store the error to pass up
errors.push(result.value);
} else {
node_configs.push(result.value);
}
// TODO: disabling npm module loading if defaultNodesDir set
// This indicates a test is being run - don't want to pick up
// unexpected nodes.
// Urgh.
if (!defaultNodesDir) {
// Find all of the modules containing nodes
var moduleFiles = scanTreeForNodesModules();
moduleFiles.forEach(function(moduleFile) {
nodes = nodes.concat(loadNodesFromModule(moduleFile.dir,moduleFile.package));
});
// Trigger a load of the configs to get it precached
getNodeConfigs();
resolve(errors);
}
var promises = [];
nodes.forEach(function(node) {
promises.push(loadNode(node));
});
//resolve([]);
when.settle(promises).then(function(results) {
// Trigger a load of the configs to get it precached
registry.getAllNodeConfigs();
resolve();
});
});
}
/**
* Gets all of the node template configs
* @return all of the node templates in a single string
* Loads the specified node into the runtime
* @param node a node info object - see loadNodeConfig
* @return a promise that resolves to an update node info object. The object
* has the following properties added:
* err: any error encountered whilst loading the node
*
*/
function getNodeConfigs() {
if (!node_config_cache) {
var result = "";
var script = "";
for (var i=0;i<node_configs.length;i++) {
var config = node_configs[i];
result += config.config||"";
script += config.script||"";
function loadNode(node) {
var nodeDir = path.dirname(node.file);
var nodeFn = path.basename(node.file);
try {
var loadPromise = null;
var r = require(node.file);
if (typeof r === "function") {
var promise = r(require('../red'));
if (promise != null && typeof promise.then === "function") {
loadPromise = promise.then(function() {
node.enabled = true;
return node;
}).otherwise(function(err) {
node.err = err;
node.enabled = false;
return node;
});
}
}
result += '<script type="text/javascript">';
result += UglifyJS.minify(script, {fromString: true}).code;
result += '</script>';
node_config_cache = result;
if (loadPromise == null) {
node.enabled = true;
loadPromise = when.resolve(node);
}
return loadPromise;
} catch(err) {
node.err = err;
node.enabled = false;
return when.resolve(node);
}
return node_config_cache;
}
module.exports = {
init:init,
load:load,
registerType: function(type,node) {
util.inherits(node,Node);
node_types[type] = node;
events.emit("type-registered",type);
},
get: function(type) {
return node_types[type];
},
getNodeConfigs: getNodeConfigs,
loadNode: function(filename) {
},
removeNode: function(filename) {
}
clear: registry.clear,
registerType: registry.registerNodeConstructor,
get: registry.getNodeConstructor,
getNodeList: registry.getNodeList,
getNodeConfigs: registry.getAllNodeConfigs,
getNodeConfig: registry.getNodeConfig,
}

View File

@ -71,7 +71,9 @@ function start() {
}
util.log("[red] Loading palette nodes");
redNodes.init(settings,storage);
redNodes.load().then(function(nodeErrors) {
redNodes.load().then(function() {
var nodes = redNodes.getNodeList();
var nodeErrors = nodes.filter(function(n) { return n.err!=null;});
if (nodeErrors.length > 0) {
util.log("------------------------------------------");
if (settings.verbose) {

View File

@ -23,6 +23,10 @@ describe('inject node', function() {
before(function(done) {
helper.startServer(done);
});
afterEach(function() {
helper.unload();
});
it('should inject once', function(done) {

View File

@ -24,6 +24,11 @@ describe('debug node', function() {
before(function(done) {
helper.startServer(done);
});
afterEach(function() {
helper.unload();
});
it('should be loaded', function(done) {
var flow = [{id:"n1", type:"debug", name: "Debug" }];

View File

@ -23,6 +23,10 @@ describe('function node', function() {
before(function(done) {
helper.startServer(done);
});
afterEach(function() {
helper.unload();
});
it('should be loaded', function(done) {
var flow = [{id:"n1", type:"function", name: "function" }];

View File

@ -23,6 +23,11 @@ describe('template node', function() {
before(function(done) {
helper.startServer(done);
});
afterEach(function() {
helper.unload();
});
it('should modify payload', function(done) {
var flow = [{id:"n1", type:"template", field: "payload", template: "payload={{payload}}",wires:[["n2"]]},{id:"n2",type:"helper"}];

View File

@ -20,6 +20,10 @@ var helper = require("../../helper.js");
describe('comment node', function() {
afterEach(function() {
helper.unload();
});
it('should be loaded', function(done) {
var flow = [{id:"n1", type:"comment", name: "comment" }];
helper.load(commentNode, flow, function() {

View File

@ -23,6 +23,10 @@ describe('JSON node', function() {
before(function(done) {
helper.startServer(done);
});
afterEach(function() {
helper.unload();
});
it('should be loaded', function(done) {
var flow = [{id:"jsonNode1", type:"json", name: "jsonNode" }];

View File

@ -42,7 +42,7 @@ describe('TailNode', function() {
});
afterEach(function(done) {
helper.unload();
fs.exists(fileToTail, function(exists) {
if(exists) {
fs.unlinkSync(fileToTail);

View File

@ -59,6 +59,10 @@ module.exports = {
cb();
});
},
unload: function() {
// TODO: any other state to remove between tests?
redNodes.clearRegistry();
},
getNode: function(id) {
return flows.get(id);

View File

@ -23,7 +23,11 @@ var index = require("../../../red/nodes/index");
var credentials = require("../../../red/nodes/credentials");
describe('Credentials', function() {
afterEach(function() {
index.clearRegistry();
});
it('loads from storage',function(done) {
var storage = {

View File

@ -23,7 +23,11 @@ var defer = when.defer();
var index = require("../../../red/nodes/index");
describe("red/nodes/index", function() {
afterEach(function() {
index.clearRegistry();
});
var testFlows = [{"type":"test","id":"tab1","label":"Sheet 1"}];
var storage = {
getFlows: function() {

View File

@ -15,9 +15,16 @@
**/
var should = require("should");
var RedNodes = require("../../../red/nodes");
var sinon = require("sinon");
var RedNodes = require("../../../red/nodes");
var RedNode = require("../../../red/nodes/Node");
var typeRegistry = require("../../../red/nodes/registry");
var events = require("../../../red/events");
afterEach(function() {
typeRegistry.clear();
});
describe('NodeRegistry', function() {
it('automatically registers new nodes',function() {
@ -29,170 +36,245 @@ describe('NodeRegistry', function() {
should.strictEqual(n,newNode);
});
});
describe('NodeRegistry', function() {
it('does not accept incorrect nodesDir',function(done) {
var typeRegistry = require("../../../red/nodes/registry");
var settings = {
nodesDir : "wontexist"
}
typeRegistry.init(null);
typeRegistry.load().then(function(){
try {
should.fail(null, null, "Loading of non-existing nodesDir should never succeed");
} catch (err) {
done(err);
}
}).catch(function(e) { // successful test, failed promise
it('handles nodes that export a function', function(done) {
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/TestNode1").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id");
list[0].should.have.property("name","TestNode1.js");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-1");
(typeof nodeConstructor).should.be.equal("function");
done();
});
});
it('fails to load additional node files from invalid nodesDir',function(done) {
var typeRegistry = require("../../../red/nodes/registry");
var settings = {
nodesDir : "wontexist"
}
typeRegistry.init(settings);
typeRegistry.load().then(function(){
try {
should.fail(null, null, "Loading of non-existing nodesDir should never succeed");
} catch (err) {
done(err);
}
}).catch(function(e) { // successful test, failed promise
done();
});
});
});
/*
* This test does the following:
* 1) injects settings that tell the registry to load its default nodes from
* tempNoNodesContainedDir that contains no valid nodes => this means that no default nodes are loaded
* 2) We only load a single node we pre-deploy into tempDir
* 3) This node (fakeNodeJS = reads "fake Node JavaScript"), when exported automatically creates a known
* file
* 4) We can assert that this file exists and make the loading test pass/fail
*/
describe("getNodeFiles", function() {
var fs = require('fs-extra');
var path = require('path');
var tempDir = path.join(__dirname,".tmp/");
var fakeNodeJS = tempDir + "testNode.js"; // when exported, this fake node creates a file we can assert on
var fakeNodeHTML = tempDir + "testNode.html"; // we assume it's going to be loaded by cheerio
var nodeInjectedFileName = "testInjected";
var nodeInjectedFilePath = path.join(tempDir, nodeInjectedFileName);
var tempNoNodesContainedDir = path.join(__dirname,".noNodes/");
beforeEach(function(done) {
fs.remove(tempDir,function(err) {
fs.mkdirSync(tempDir);
var fileContents = "var fs = require('fs');\n" +
"var path = require('path');\n" +
"var tempFile = path.join(__dirname, \"" + nodeInjectedFileName + "\");\n" +
"\n" +
"module.exports = function(RED) {\n" +
" fs.writeFileSync(tempFile, \"Test passes if this file has been written.\");\n" +
"}\n";
var htmlContents = "<script type=\"text/javascript\">\n" +
" RED.nodes.registerType('testFileInjector',{\n" +
" category: 'storage-input',\n" +
" inputs:0,\n" +
" outputs:1,\n" +
" icon: \"file.png\"\n" +
" });\n" +
"</script>\n" +
"<script type=\"text/x-red\" data-template-name=\"testFileInjector\">\n" +
" <div class=\"form-row\">\n" +
" <label for=\"node-input-name\"><i class=\"icon-tag\"></i> Name</label>\n" +
" <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n" +
" </div>\n" +
"</script>\n" +
"<script type=\"text/x-red\" data-help-name=\"node-type\">\n" +
" <p>This node is pretty useless</p>\n" +
"</script>";
fs.writeFileSync(fakeNodeJS, fileContents);
fs.writeFileSync(fakeNodeHTML, htmlContents);
fs.remove(tempNoNodesContainedDir,function(err) {
fs.mkdirSync(tempNoNodesContainedDir);
done();
});
});
});
afterEach(function(done) {
fs.exists(tempNoNodesContainedDir, function(exists) {
if(exists) {
fs.removeSync(tempNoNodesContainedDir);
}
});
fs.exists(nodeInjectedFilePath, function(exists) {
if(exists) {
fs.unlinkSync(nodeInjectedFilePath);
}
});
fs.exists(fakeNodeJS, function(exists) {
if(exists) {
fs.unlinkSync(fakeNodeJS);
}
fs.remove(tempDir);
});
fs.exists(fakeNodeHTML, function(exists) {
if(exists) {
fs.unlinkSync(fakeNodeHTML);
}
fs.remove(tempDir, done);
});
});
it('loads additional node files from specified external nodesDir',function(done) {
var typeRegistry = require("../../../red/nodes/registry");
var settings = {
nodesDir : tempDir
}
typeRegistry.init(settings);
typeRegistry.load(tempNoNodesContainedDir).then(function(){
var testConfig = typeRegistry.getNodeConfigs();
try {
testConfig.should.equal( "<script type=\"text/x-red\" data-template-name=\"testFileInjector\">\n" +
" <div class=\"form-row\">\n" +
" <label for=\"node-input-name\"><i class=\"icon-tag\"></i> Name</label>\n" +
" <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n" +
" </div>\n" +
"</script><script type=\"text/x-red\" data-help-name=\"node-type\">\n" +
" <p>This node is pretty useless</p>\n" +
"</script><script type=\"text/javascript\">RED.nodes.registerType(\"testFileInjector\",{category:\"storage-input\",inputs:0,outputs:1,icon:\"file.png\"});</script>");
} catch(err) {
done(err);
}
fs.exists(nodeInjectedFilePath, function(exists) {
if(exists) {
done();
} else {
try {
should.fail(null, null, nodeInjectedFilePath + " should be created by registered test node.");
} catch(err) {
done(err)
}
}
});
}).catch(function(e) {
try {
should.fail(null, null, "Loading of nodesDir should succeed");
} catch (err) {
done(err);
}
done(e);
});
});
it('handles nodes that export a function returning a resolving promise', function(done) {
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/TestNode2").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id");
list[0].should.have.property("name","TestNode2.js");
list[0].should.have.property("types",["test-node-2"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-2");
(typeof nodeConstructor).should.be.equal("function");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nodes that export a function returning a rejecting promise', function(done) {
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/TestNode3").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id");
list[0].should.have.property("name","TestNode3.js");
list[0].should.have.property("types",["test-node-3"]);
list[0].should.have.property("enabled",false);
list[0].should.have.property("err","fail");
var nodeConstructor = typeRegistry.get("test-node-3");
(typeof nodeConstructor).should.be.equal("undefined");
done();
}).catch(function(e) {
done(e);
});
});
it('handles files containing multiple nodes', function(done) {
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/MultipleNodes1").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id");
list[0].should.have.property("name","MultipleNodes1.js");
list[0].should.have.property("types",["test-node-multiple-1a","test-node-multiple-1b"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-multiple-1a");
(typeof nodeConstructor).should.be.equal("function");
nodeConstructor = typeRegistry.get("test-node-multiple-1b");
(typeof nodeConstructor).should.be.equal("function");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nested directories', function(done) {
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/NestedDirectoryNode").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id");
list[0].should.have.property("name","NestedNode.js");
list[0].should.have.property("types",["nested-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
done();
}).catch(function(e) {
done(e);
});
});
it('emits type-registered and node-icon-dir events', function(done) {
var eventEmitSpy = sinon.spy(events,"emit");
typeRegistry.init({});
typeRegistry.load(__dirname+"/resources/NestedDirectoryNode").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("name","NestedNode.js");
list[0].should.have.property("types",["nested-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
eventEmitSpy.calledTwice.should.be.true;
eventEmitSpy.firstCall.args[0].should.be.equal("node-icon-dir");
eventEmitSpy.firstCall.args[1].should.be.equal(__dirname+"/resources/NestedDirectoryNode/NestedNode/icons");
eventEmitSpy.secondCall.args[0].should.be.equal("type-registered");
eventEmitSpy.secondCall.args[1].should.be.equal("nested-node-1");
done();
}).catch(function(e) {
done(e);
}).finally(function() {
eventEmitSpy.restore();
});
});
it('rejects a duplicate node type registration', function(done) {
typeRegistry.init({
nodesDir:[__dirname+"/resources/TestNode1",__dirname+"/resources/DuplicateTestNode"]
});
typeRegistry.load("wontexist").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(2);
list[0].should.have.property("id");
list[0].should.have.property("name","TestNode1.js");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
list[1].should.have.property("id");
list[1].id.should.not.equal(list[0].id);
list[1].should.have.property("name","TestNode1.js");
list[1].should.have.property("types",["test-node-1"]);
list[1].should.have.property("enabled",false);
list[1].should.have.property("err");
/already registered/.test(list[1].err).should.be.true;
var nodeConstructor = typeRegistry.get("test-node-1");
// Verify the duplicate node hasn't replaced the original one
nodeConstructor.name.should.be.equal("TestNode");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nodesDir as a string', function(done) {
var settings = {
nodesDir : __dirname+"/resources/TestNode1"
}
typeRegistry.init(settings);
typeRegistry.load("wontexist").then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("types",["test-node-1"]);
done();
}).catch(function(e) {
done("Loading of non-existing nodesDir should succeed");
});
});
it('handles invalid nodesDir',function(done) {
var settings = {
nodesDir : "wontexist"
}
typeRegistry.init(settings);
typeRegistry.load("wontexist").then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
done();
}).catch(function(e) {
done("Loading of non-existing nodesDir should succeed");
});
});
it('returns nothing for an unregistered type config', function() {
typeRegistry.init({});
typeRegistry.load("wontexist").then(function(){
var config = typeRegistry.getNodeConfig("imaginary-shark");
(config === null).should.be.true;
}).catch(function(e) {
done(e);
});
});
it('excludes node files listed in nodesExcludes',function(done) {
typeRegistry.init({
nodesExcludes: [ "TestNode1.js" ],
nodesDir:[__dirname+"/resources/TestNode1",__dirname+"/resources/TestNode2"]
});
typeRegistry.load("wontexist").then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("types",["test-node-2"]);
done();
}).catch(function(e) {
done(e);
});
});
it('returns the node configurations', function(done) {
typeRegistry.init({
nodesDir:[__dirname+"/resources/TestNode1",__dirname+"/resources/TestNode2"]
});
typeRegistry.load("wontexist").then(function() {
var list = typeRegistry.getNodeList();
var nodeConfigs = typeRegistry.getNodeConfigs();
// TODO: this is brittle...
nodeConfigs.should.equal("<script type=\"text/x-red\" data-template-name=\"test-node-1\"></script><script type=\"text/x-red\" data-help-name=\"test-node-1\"></script><style></style><script type=\"text/x-red\" data-template-name=\"test-node-2\"></script><script type=\"text/x-red\" data-help-name=\"test-node-2\"></script><style></style><script type=\"text/javascript\">RED.nodes.registerType(\"test-node-1\",{}),RED.nodes.registerType(\"test-node-2\",{});</script>");
var nodeId = list[0].id;
var nodeConfig = typeRegistry.getNodeConfig(nodeId);
nodeConfig.should.equal("<script type=\"text/x-red\" data-template-name=\"test-node-1\"></script><script type=\"text/x-red\" data-help-name=\"test-node-1\"></script><style></style><script type=\"text/javascript\">RED.nodes.registerType('test-node-1',{});</script>");
done();
}).catch(function(e) {
done(e);
});
});
});