Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Replace whitespace tabs with spaces

  • Loading branch information...
commit e42ff431f7500d756ab06c13874f69a87a3f02c9 1 parent 15f8b95
Alexander Dorofeev authored
104 cache.js
View
@@ -14,42 +14,42 @@ var needFlush = [];
*
* @example
*
- * var sys = require("sys");
- * var cache = require("./cache");
+ * var sys = require("sys");
+ * var cache = require("./cache");
*
- * for (var i = 0; i < 100; i++) {
- * cache("key",
- * function(value){ // Getter
- * sys.debug("Getted: " + value);
- * },
- * function(callback){
- * setTimeout(function(){
- * sys.debug("Do render");
- * callback("test");
- * }, 2000);
- * }
- * );
- * }
+ * for (var i = 0; i < 100; i++) {
+ * cache("key",
+ * function(value){ // Getter
+ * sys.debug("Getted: " + value);
+ * },
+ * function(callback){
+ * setTimeout(function(){
+ * sys.debug("Do render");
+ * callback("test");
+ * }, 2000);
+ * }
+ * );
+ * }
*
* @param key Key in cache
* @param getter Function that fires if value for key is found.
- * Takes one argument - value from cache.
+ * Takes one argument - value from cache.
* @param setter Function that fires if value for key is not found.
- * Takes one argument - callback. Callback takes one argument too -
- * generated value.
+ * Takes one argument - callback. Callback takes one argument too -
+ * generated value.
*/
function operate(key, getter, setter) {
- if (key in cache) {
- getter(cache[key]);
- } else if (key in waiters) { // no cache look for waiters
- waiters[key].push(getter);
- } else { // no cache, no waiters - executing setter
- waiters[key] = [];
- waiters[key].push(getter);
- setter(function(value) {
- put(key, value);
- });
- }
+ if (key in cache) {
+ getter(cache[key]);
+ } else if (key in waiters) { // no cache look for waiters
+ waiters[key].push(getter);
+ } else { // no cache, no waiters - executing setter
+ waiters[key] = [];
+ waiters[key].push(getter);
+ setter(function(value) {
+ put(key, value);
+ });
+ }
}
exports.operate = operate;
@@ -59,32 +59,32 @@ exports.operate = operate;
* @param prefix Prefix of keys. If not defined - all cache will flushed.
*/
function flush(prefix) {
- prefix = (prefix || "");
-
- Object.keys(waiters).forEach(function(waiter) {
- if (waiter.indexOf(prefix) == 0) {
- needFlush.push(waiter);
- }
- });
- // delete all not locked keys in cache
- for (var key in cache) {
- if (key.indexOf(prefix) == 0 && needFlush.indexOf(key) == -1) {
- delete cache[key];
- }
- }
+ prefix = (prefix || "");
+
+ Object.keys(waiters).forEach(function(waiter) {
+ if (waiter.indexOf(prefix) == 0) {
+ needFlush.push(waiter);
+ }
+ });
+ // delete all not locked keys in cache
+ for (var key in cache) {
+ if (key.indexOf(prefix) == 0 && needFlush.indexOf(key) == -1) {
+ delete cache[key];
+ }
+ }
}
exports.flush = flush;
// private
function put(key, value) {
- cache[key] = value;
- waiters[key].forEach(function(action) {
- action(value);
- });
- delete waiters[key];
- var kill = needFlush.indexOf(key);
- if (kill != -1) {
- delete cache[key];
- needFlush.splice(kill, 1);
- }
+ cache[key] = value;
+ waiters[key].forEach(function(action) {
+ action(value);
+ });
+ delete waiters[key];
+ var kill = needFlush.indexOf(key);
+ if (kill != -1) {
+ delete cache[key];
+ needFlush.splice(kill, 1);
+ }
}
326 compiler.js
View
@@ -3,67 +3,67 @@ var Script = process.binding('evals').Script;
var HStream = require("./hstream").HStream;
var bundle = {
- HStream : HStream,
- section : section,
- sectionNormal : sectionNormal,
- sectionInverted : sectionInverted,
- lookup : lookup,
- unescaped : unescaped,
- process : process
+ HStream : HStream,
+ section : section,
+ sectionNormal : sectionNormal,
+ sectionInverted : sectionInverted,
+ lookup : lookup,
+ unescaped : unescaped,
+ process : process
};
/**
* Compile parsed template to native JS function.
* @param stream Parsed template. Represented as Array of
- * {op:string, value: string}
+ * {op:string, value: string}
* @param callback Function that takes compiled function.
*/
function compile(stream, callback) {
- var codeStart =
- '__fn=function(context) {\n' +
- 'context = context || {};\n' +
- 'var HS = new HStream();\n' +
- 'var target = context;\n' +
- 'var prefix = "";\n' +
- 'process.nextTick(function() { var __a = [\n';
- var codeEnd =
- 'function() {HS.end("");}];\n' +
- 'for(var i=0;i<__a.length;i++){__a[i]()}\n' +
- '});\n' +
- 'return HS; }';
-
- var code = codeStart;
+ var codeStart =
+ '__fn=function(context) {\n' +
+ 'context = context || {};\n' +
+ 'var HS = new HStream();\n' +
+ 'var target = context;\n' +
+ 'var prefix = "";\n' +
+ 'process.nextTick(function() { var __a = [\n';
+ var codeEnd =
+ 'function() {HS.end("");}];\n' +
+ 'for(var i=0;i<__a.length;i++){__a[i]()}\n' +
+ '});\n' +
+ 'return HS; }';
+
+ var code = codeStart;
- var resolveTarget = function(name) {
- return (name.charAt(0) === '.' ?
- "context" + name : "target." + name);
- };
- stream.forEach(function(chunk) {
- if (chunk.op === 'raw') {
- code += 'function() {HS.map(prefix+i); HS.write(prefix+i,"' +
- chunk.value.replace(/\n/g, "\\n")
- + '");},\n';
- } else if (chunk.op === 'lookup' || chunk.op === 'unescaped') {
- code += 'function(){HS.map(prefix+i);' +
- chunk.op +
- '(HS,prefix+i,' +
- resolveTarget(chunk.value) +
- ',target);},\n';
- } else if (chunk.op === 'section') {
- code += 'function() {section(HS,sectionNormal,prefix+i,' +
- resolveTarget(chunk.value) +
- ',target,function(prefix,target){var __a = [\n';
- } else if (chunk.op === 'inverted') {
- code += 'function() {section(HS,sectionInverted,prefix+i,' +
- resolveTarget(chunk.value) +
- ',target,function(prefix,target){var __a = [\n';
- } else if (chunk.op === 'end') {
- code += ']; for(var i=0;i<__a.length;i++){__a[i]()} }); },\n';
- }
- });
-
- //sys.debug(code+ codeEnd);
- callback(Script.runInNewContext(code + codeEnd, bundle));
+ var resolveTarget = function(name) {
+ return (name.charAt(0) === '.' ?
+ "context" + name : "target." + name);
+ };
+ stream.forEach(function(chunk) {
+ if (chunk.op === 'raw') {
+ code += 'function() {HS.map(prefix+i); HS.write(prefix+i,"' +
+ chunk.value.replace(/\n/g, "\\n")
+ + '");},\n';
+ } else if (chunk.op === 'lookup' || chunk.op === 'unescaped') {
+ code += 'function(){HS.map(prefix+i);' +
+ chunk.op +
+ '(HS,prefix+i,' +
+ resolveTarget(chunk.value) +
+ ',target);},\n';
+ } else if (chunk.op === 'section') {
+ code += 'function() {section(HS,sectionNormal,prefix+i,' +
+ resolveTarget(chunk.value) +
+ ',target,function(prefix,target){var __a = [\n';
+ } else if (chunk.op === 'inverted') {
+ code += 'function() {section(HS,sectionInverted,prefix+i,' +
+ resolveTarget(chunk.value) +
+ ',target,function(prefix,target){var __a = [\n';
+ } else if (chunk.op === 'end') {
+ code += ']; for(var i=0;i<__a.length;i++){__a[i]()} }); },\n';
+ }
+ });
+
+ //sys.debug(code+ codeEnd);
+ callback(Script.runInNewContext(code + codeEnd, bundle));
}
exports.compile = compile;
@@ -73,39 +73,39 @@ exports.compile = compile;
*
* @param hStream HStream instance
* @param manner Normal or inverted section: sectionNormal or sectionInverted.
- * This calls if context is not function or if function is not Lambda.
+ * This calls if context is not function or if function is not Lambda.
* @param id Root ID
* @param target Lookup for in context
* @param context Local context
* @param action Bundle of actions
*/
function section(hStream, manner, id, target, context, action) {
- hStream.map(id); // mapping root
-
- if (typeof target === 'function') { // Function
- var target = target(context);
- if (typeof target === 'function') { // Async function
- target(context, function(err, target) {
- if (typeof target === 'function') {// lambda
- hStream.lambda(id, function(data, callback) {
- target(data, context, function(data) {
- callback(typeof data === 'undefined' ? ''
- : data.toString());
- });
- });
- action(id + "/", context);
- hStream.end(id);
- } else { // No lambda
- manner(hStream, id, target, context, action);
- }
- });
- } else { // Sync function
- manner(hStream, id, target, context, action);
- }
- } else { // Just context
+ hStream.map(id); // mapping root
+
+ if (typeof target === 'function') { // Function
+ var target = target(context);
+ if (typeof target === 'function') { // Async function
+ target(context, function(err, target) {
+ if (typeof target === 'function') {// lambda
+ hStream.lambda(id, function(data, callback) {
+ target(data, context, function(data) {
+ callback(typeof data === 'undefined' ? ''
+ : data.toString());
+ });
+ });
+ action(id + "/", context);
+ hStream.end(id);
+ } else { // No lambda
+ manner(hStream, id, target, context, action);
+ }
+ });
+ } else { // Sync function
+ manner(hStream, id, target, context, action);
+ }
+ } else { // Just context
- manner(hStream, id, target, context, action);
- }
+ manner(hStream, id, target, context, action);
+ }
}
/**
@@ -118,34 +118,34 @@ function section(hStream, manner, id, target, context, action) {
* @param action Bundle of actions
*/
function sectionNormal(hStream, id, target, context, action) {
- if (target instanceof Array && target.length) {
- var streamId = id;
- for (var i = 0; i < target.length; i++) {
- var subid = streamId + "/" + i;
- hStream.map(subid);
- action(subid, target[i]);
- hStream.end(subid);
- }
- hStream.end(id);
- } else if (
- target !== undefined &&
- target != "" &&
- target != 0 &&
- target != false &&
- target != null &&
- typeof target !== 'object') {
- action(id + "/", context);
- hStream.end(id);
- } else if (typeof target === 'object' && target != null) {
- if (!Object.keys(target).length){
- hStream.write(id, "");
- } else {
- action(id + "/", target);
- hStream.end(id);
- }
- } else {
- hStream.write(id, "");
- }
+ if (target instanceof Array && target.length) {
+ var streamId = id;
+ for (var i = 0; i < target.length; i++) {
+ var subid = streamId + "/" + i;
+ hStream.map(subid);
+ action(subid, target[i]);
+ hStream.end(subid);
+ }
+ hStream.end(id);
+ } else if (
+ target !== undefined &&
+ target != "" &&
+ target != 0 &&
+ target != false &&
+ target != null &&
+ typeof target !== 'object') {
+ action(id + "/", context);
+ hStream.end(id);
+ } else if (typeof target === 'object' && target != null) {
+ if (!Object.keys(target).length){
+ hStream.write(id, "");
+ } else {
+ action(id + "/", target);
+ hStream.end(id);
+ }
+ } else {
+ hStream.write(id, "");
+ }
};
/**
@@ -158,19 +158,19 @@ function sectionNormal(hStream, id, target, context, action) {
* @param action Bundle of actions
*/
function sectionInverted(hStream, id, target, context, action) {
- if (target == undefined ||
- target == "" ||
- target == false ||
- target == null ||
- target == 0 ||
- (target instanceof Array && !target.length) ||
- (typeof target === 'object' && !Object.keys(target).length)
- ) {
- action(id + "/", target);
- hStream.end(id);
- } else {
- hStream.write(id, "");
- }
+ if (target == undefined ||
+ target == "" ||
+ target == false ||
+ target == null ||
+ target == 0 ||
+ (target instanceof Array && !target.length) ||
+ (typeof target === 'object' && !Object.keys(target).length)
+ ) {
+ action(id + "/", target);
+ hStream.end(id);
+ } else {
+ hStream.write(id, "");
+ }
};
/**
@@ -182,33 +182,33 @@ function sectionInverted(hStream, id, target, context, action) {
* @param context Context
*/
function lookup(hStream, id, target, context) {
- function escapeReplace (char) {
- switch (char) {
- case '<': return '&lt;';
- case '>': return '&gt;';
- case '&': return '&amp;';
- case '"': return '&quot;';
- default: return char;
- }
- };
- function out(string) {
- return typeof string === 'undefined' ? '' : string.toString()
- .replace(/[&<>"]/g, escapeReplace);
- };
- if (typeof target === 'function'){ // Lambda
- var target = target(context);
- if (typeof target === 'function') { // Async
- hStream.lambda(id, function(data, callback) {
- target(context, function(err, data) {
- callback(out(data));
- }); });
- hStream.write(id, "");
- } else {
- hStream.write(id, out(target));
- }
- } else {
- hStream.write(id, out(target));
- }
+ function escapeReplace (char) {
+ switch (char) {
+ case '<': return '&lt;';
+ case '>': return '&gt;';
+ case '&': return '&amp;';
+ case '"': return '&quot;';
+ default: return char;
+ }
+ };
+ function out(string) {
+ return typeof string === 'undefined' ? '' : string.toString()
+ .replace(/[&<>"]/g, escapeReplace);
+ };
+ if (typeof target === 'function'){ // Lambda
+ var target = target(context);
+ if (typeof target === 'function') { // Async
+ hStream.lambda(id, function(data, callback) {
+ target(context, function(err, data) {
+ callback(out(data));
+ }); });
+ hStream.write(id, "");
+ } else {
+ hStream.write(id, out(target));
+ }
+ } else {
+ hStream.write(id, out(target));
+ }
}
/**
@@ -220,22 +220,22 @@ function lookup(hStream, id, target, context) {
* @param context Context
*/
function unescaped(hStream, id, target, context) {
- function out (string) {
- return typeof string === 'undefined' ? '' : string.toString();
- };
- if (typeof target === 'function'){ // Lambda
- var target = target(context);
- if (typeof target === 'function') { // Async
- hStream.lambda(id, function(data, callback) {
- target(context, function(err, data) {
- callback(out(data));
- }); });
- hStream.write(id, "");
- } else {
- hStream.write(id, out(target));
- }
- } else {
- hStream.write(id, out(target));
- }
+ function out (string) {
+ return typeof string === 'undefined' ? '' : string.toString();
+ };
+ if (typeof target === 'function'){ // Lambda
+ var target = target(context);
+ if (typeof target === 'function') { // Async
+ hStream.lambda(id, function(data, callback) {
+ target(context, function(err, data) {
+ callback(out(data));
+ }); });
+ hStream.write(id, "");
+ } else {
+ hStream.write(id, out(target));
+ }
+ } else {
+ hStream.write(id, out(target));
+ }
}
240 hstream.js
View
@@ -8,10 +8,10 @@ var events = require('events');
* @constructor
*/
function HStream() {
- events.EventEmitter.call(this);
- this.writes = [];
- this.stream = [];
- this.closed = false;
+ events.EventEmitter.call(this);
+ this.writes = [];
+ this.stream = [];
+ this.closed = false;
}
sys.inherits(HStream, events.EventEmitter);
exports.HStream = HStream;
@@ -22,21 +22,21 @@ exports.HStream = HStream;
* @param id String identifier in form "[parent/[parent.../]]id"
*/
HStream.prototype.map = function (id) {
- var id = id.split("/");
-
- var target = this;
- if (id.length > 1) {
- var target = this.__getChunk(id.slice(0,-1));
- if (target.stream === undefined) target.stream = [];
- if (target.data === undefined) target.data = '';
- }
-
- target.stream.push({
- id:id[id.length-1],
- data: undefined,
- proc: undefined,
- stream: undefined
- });
+ var id = id.split("/");
+
+ var target = this;
+ if (id.length > 1) {
+ var target = this.__getChunk(id.slice(0,-1));
+ if (target.stream === undefined) target.stream = [];
+ if (target.data === undefined) target.data = '';
+ }
+
+ target.stream.push({
+ id:id[id.length-1],
+ data: undefined,
+ proc: undefined,
+ stream: undefined
+ });
};
/**
@@ -44,107 +44,107 @@ HStream.prototype.map = function (id) {
*
* @param id String identifier in form "[parent/[parent.../]]id"
* @param lambda Function that takes two arguments: data to transform and
- * callback. Callback takes one argument - warped data.
+ * callback. Callback takes one argument - warped data.
*/
HStream.prototype.lambda = function(id, lambda) {
- var id = id.split("/");
- var target =this.__getChunk(id);
- target.proc = lambda;
- this.__process(id);
+ var id = id.split("/");
+ var target =this.__getChunk(id);
+ target.proc = lambda;
+ this.__process(id);
};
HStream.prototype.write = function(id, data) {
- var id = id.split("/");
- this.__write(id, data);
+ var id = id.split("/");
+ this.__write(id, data);
};
HStream.prototype.__write = function(id, data){
- var chunk =this.__getChunk(id);
-
- if (typeof chunk.proc === 'function') { // it's lambda
- var lambda = chunk.proc;
- chunk.proc = undefined;
- var self = this;
- lambda(data, function(data) {
- self.__write(id, data);
- });
- } else {
- chunk.data = data;
- chunk.stream = true;
- this.__process(id);
- }
+ var chunk =this.__getChunk(id);
+
+ if (typeof chunk.proc === 'function') { // it's lambda
+ var lambda = chunk.proc;
+ chunk.proc = undefined;
+ var self = this;
+ lambda(data, function(data) {
+ self.__write(id, data);
+ });
+ } else {
+ chunk.data = data;
+ chunk.stream = true;
+ this.__process(id);
+ }
};
HStream.prototype.__process = function(id) {
- if (id.length == 1) {
- this.__poll();
- } else {
- var parent = this.__getChunk(id.slice(0,-1));
- var stream = parent.stream;
- var buffer = parent.data;
- var ended = false;
- while (stream.length) {
- if (stream[0].stream === true) {
- var chunk = stream.shift();
- buffer += chunk.data;
- } else if (stream[0].id === '_') {
- stream = [];
- ended = true;
- } else {
- break;
- }
- }
- if (!ended) {
- parent.data = buffer;
- this.__poll();
- } else {
- parent.data = undefined;
- parent.stream = undefined;
- this.write(id.slice(0,-1).join("/"), buffer);
- //this.__poll();
- }
- }
+ if (id.length == 1) {
+ this.__poll();
+ } else {
+ var parent = this.__getChunk(id.slice(0,-1));
+ var stream = parent.stream;
+ var buffer = parent.data;
+ var ended = false;
+ while (stream.length) {
+ if (stream[0].stream === true) {
+ var chunk = stream.shift();
+ buffer += chunk.data;
+ } else if (stream[0].id === '_') {
+ stream = [];
+ ended = true;
+ } else {
+ break;
+ }
+ }
+ if (!ended) {
+ parent.data = buffer;
+ this.__poll();
+ } else {
+ parent.data = undefined;
+ parent.stream = undefined;
+ this.write(id.slice(0,-1).join("/"), buffer);
+ //this.__poll();
+ }
+ }
};
HStream.prototype.end = function(id) {
- if (id == '' ) {
- this.map("_");
- this.__poll();
- } else {
- var streamId = id.split("/");
- var id = id + "/_";
- this.map(id);
- this.__process(id.split("/"));
- }
+ if (id == '' ) {
+ this.map("_");
+ this.__poll();
+ } else {
+ var streamId = id.split("/");
+ var id = id + "/_";
+ this.map(id);
+ this.__process(id.split("/"));
+ }
};
HStream.prototype.__poll = function() {
- if (this.closed) return;
- var stream = this.stream;
- while (stream.length) {
- if ((stream[0].data != undefined) &&
- (stream[0].proc === undefined )) {
-
- if (stream[0].stream === true) {
- if (stream[0].data.length > 0) {
- this.emit('data', stream[0].data);
- }
- stream.shift();
- } else if (stream[0].stream instanceof Array &&
- stream[0].data !== '') {
- this.emit('data', stream[0].data);
- stream[0].data = '';
- break;
- } else {
- break;
- }
- } else if (this.stream[0].id == '_') {
- this.emit('end');
- stream = [];
- this.closed = true;
- break;
- } else {
- break;
- }
- }
+ if (this.closed) return;
+ var stream = this.stream;
+ while (stream.length) {
+ if ((stream[0].data != undefined) &&
+ (stream[0].proc === undefined )) {
+
+ if (stream[0].stream === true) {
+ if (stream[0].data.length > 0) {
+ this.emit('data', stream[0].data);
+ }
+ stream.shift();
+ } else if (stream[0].stream instanceof Array &&
+ stream[0].data !== '') {
+ this.emit('data', stream[0].data);
+ stream[0].data = '';
+ break;
+ } else {
+ break;
+ }
+ } else if (this.stream[0].id == '_') {
+ this.emit('end');
+ stream = [];
+ this.closed = true;
+ break;
+ } else {
+ break;
+ }
+ }
};
/**
* returns chunk for id
@@ -152,19 +152,19 @@ HStream.prototype.__poll = function() {
* @returns
*/
HStream.prototype.__getChunk = function(id) {
- var stream = this.stream;
- for (var i=0; i<id.length; i++) {
- for (var j=0; j < stream.length; j++) {
- if (stream[j].id == id[i]) {
- if (i == id.length-1) {
- // found
- return stream[j];
- } else {
- stream = stream[j].stream;
- break;
- }
- }
- }
- }
- return undefined;
+ var stream = this.stream;
+ for (var i=0; i<id.length; i++) {
+ for (var j=0; j < stream.length; j++) {
+ if (stream[j].id == id[i]) {
+ if (i == id.length-1) {
+ // found
+ return stream[j];
+ } else {
+ stream = stream[j].stream;
+ break;
+ }
+ }
+ }
+ }
+ return undefined;
};
118 index.js
View
@@ -21,57 +21,57 @@ var cache = require("./cache");
* @param callback
*/
function compile(origin, options, callback) {
- process.nextTick(function () {
- origin = path.normalize(origin);
-
- // determine caching
- var key = "__tpl__" + origin;
- if (options && options.cache == false) key = false;
-
- // If caching enabled -
- if (key) {
- if (have_openssl) {
- // if have openssl, add options hash to key
- key += crypto.createHash("sha1").
- update(options).digest("hex");
- }
- cache.operate(key,
- function(fn) { // getter
- callback(undefined, fn);
- },
- function(cb) { // setter
- make(origin, options, function(err, fn) {
- if (err) {
- callback(err);
- return;
- }
- cb(fn);
- });
- }
- );
- } else {
- // Caching disabled - make and out
- make(origin, options, function(err, fn) {
- if (err) {
- callback(err);
- return;
- }
- callback(undefined, fn);
- });
- }
- });
+ process.nextTick(function () {
+ origin = path.normalize(origin);
+
+ // determine caching
+ var key = "__tpl__" + origin;
+ if (options && options.cache == false) key = false;
+
+ // If caching enabled -
+ if (key) {
+ if (have_openssl) {
+ // if have openssl, add options hash to key
+ key += crypto.createHash("sha1").
+ update(options).digest("hex");
+ }
+ cache.operate(key,
+ function(fn) { // getter
+ callback(undefined, fn);
+ },
+ function(cb) { // setter
+ make(origin, options, function(err, fn) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ cb(fn);
+ });
+ }
+ );
+ } else {
+ // Caching disabled - make and out
+ make(origin, options, function(err, fn) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ callback(undefined, fn);
+ });
+ }
+ });
}
exports.compile = compile;
function render(origin, context, options, callback){
- compile(origin, options, function(err, template) {
- if (err) {
- callback(err);
- return;
- }
-
- callback(undefined, template(context));
- });
+ compile(origin, options, function(err, template) {
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ callback(undefined, template(context));
+ });
}
exports.render = render;
@@ -81,8 +81,8 @@ exports.render = render;
* @param filter Filter
*/
function setFilter(name, filter) {
- cache.flush();
- parser.defaultFilters[name] = filter;
+ cache.flush();
+ parser.defaultFilters[name] = filter;
}
exports.setFilter = setFilter;
@@ -93,15 +93,15 @@ exports.setFilter = setFilter;
* @param callback
*/
function make(origin, options, callback){
- parser.parse(origin, options, function(err, stream) {
- if (err) {
- callback(err);
- return;
- }
-
- compiler.compile(stream, function(fn) {
- callback(undefined, fn);
- });
- });
+ parser.parse(origin, options, function(err, stream) {
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ compiler.compile(stream, function(fn) {
+ callback(undefined, fn);
+ });
+ });
}
734 parser.js
View
@@ -4,29 +4,29 @@ var path = require("path");
var Buffer = require('buffer').Buffer;
var defaultFilters = {
- escape: function(data, callback) {
- var escapeReplace = function (char) {
- switch (char) {
- case '<': return '&lt;';
- case '>': return '&gt;';
- case '&': return '&amp;';
- case '"': return '&quot;';
- default: return char;
- }
- };
- var data = data.replace(/[&<>"]/g, escapeReplace);
- callback(undefined, data);
- },
- compress: function(data, callback) {
+ escape: function(data, callback) {
+ var escapeReplace = function (char) {
+ switch (char) {
+ case '<': return '&lt;';
+ case '>': return '&gt;';
+ case '&': return '&amp;';
+ case '"': return '&quot;';
+ default: return char;
+ }
+ };
+ var data = data.replace(/[&<>"]/g, escapeReplace);
+ callback(undefined, data);
+ },
+ compress: function(data, callback) {
callback(undefined, data
- .replace(/ */g, ' ')
- .replace(/\n /g, '\n')
- .replace(/\n\n*/g, '\n')
- );
+ .replace(/ */g, ' ')
+ .replace(/\n /g, '\n')
+ .replace(/\n\n*/g, '\n')
+ );
},
undefinedFilter: function(data, callback) {
- callback(undefined, data);
- }
+ callback(undefined, data);
+ }
};
exports.defaultFilters = defaultFilters;
@@ -36,20 +36,20 @@ exports.defaultFilters = defaultFilters;
* @param origin Absolute path to file
* @param filters Custom compile-phase filters
* @param callback Function that takes two arguments:
- * Error and tokenized stream.
+ * Error and tokenized stream.
*/
function parse(origin, customOptions, callback) {
- loader(origin, function(err, source) {
- if (err) {
- callback(err);
- return;
- }
-
- parseText(source, origin, customOptions, function(err, stream) {
- //sys.puts(sys.inspect(stream));
- callback(err, stream);
- });
- });
+ loader(origin, function(err, source) {
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ parseText(source, origin, customOptions, function(err, stream) {
+ //sys.puts(sys.inspect(stream));
+ callback(err, stream);
+ });
+ });
}
exports.parse = parse;
@@ -60,30 +60,30 @@ exports.parse = parse;
* @param origin Absolute path to root directory
* @param filters Custom compile-phase filters
* @param callback Function that takes two arguments:
- * Error and tokenized stream.
+ * Error and tokenized stream.
*/
function parseText(source, origin, customOptions, callback) {
- var origin = (origin || __dirname + "/" + "fake.template");
-
- // parse options
- var options = { filters: {}, compress: false };
- for (var i in defaultFilters) options.filters[i] = defaultFilters[i];
-
- if (customOptions) {
- options.compress = customOptions.compress == true ? true : false;
- if (customOptions.filters) {
- for (var i in customOptions.filters)
- options.filters[i] = customOptions.filters[i];
- }
- }
-
- tokenize(source, options, function(err, stream) {
- applyOverrides(err, stream, {}, origin, options, function(err, stream) {
- expandPartials(err, stream, origin, options, function(err, stream) {
- applyFilters(err, stream, options, function(err, stream) {
- cleanup(err, stream, 'meta', function(err, stream) {
- callback(err, stream);
- }); }); }); }); });
+ var origin = (origin || __dirname + "/" + "fake.template");
+
+ // parse options
+ var options = { filters: {}, compress: false };
+ for (var i in defaultFilters) options.filters[i] = defaultFilters[i];
+
+ if (customOptions) {
+ options.compress = customOptions.compress == true ? true : false;
+ if (customOptions.filters) {
+ for (var i in customOptions.filters)
+ options.filters[i] = customOptions.filters[i];
+ }
+ }
+
+ tokenize(source, options, function(err, stream) {
+ applyOverrides(err, stream, {}, origin, options, function(err, stream) {
+ expandPartials(err, stream, origin, options, function(err, stream) {
+ applyFilters(err, stream, options, function(err, stream) {
+ cleanup(err, stream, 'meta', function(err, stream) {
+ callback(err, stream);
+ }); }); }); }); });
}
exports.parseText = parseText;
@@ -94,67 +94,67 @@ exports.parseText = parseText;
* override template.
*/
function applyOverrides(err, stream, metas, origin, options, callback) {
- if (err) {
- callback(err);
- return;
- }
-
- // determine override state
- var over = false;
- stream.forEach(function(chunk) {
- if (chunk.op == 'override') over = chunk.value;
- });
- if (over) { // it's override
- // collect metas and call base template
- var huntFor = "";
- var ingest = false;
- stream.forEach(function(chunk) {
- if (chunk.op == 'meta') {
- huntFor = chunk.value;
- if (!metas[huntFor]) {
- metas[huntFor] = [];
- ingest = true;
- } else {
- ingest = false;
- }
- } else if (chunk.op == 'end' && chunk.value == huntFor) {
- huntFor = "";
- } else if (huntFor) {
- if (ingest) metas[huntFor].push(chunk);
- }
- });
-
- bOrigin = makePath(origin, over);
- loader(origin, function(err, source) {
- if (err) {
- callback(err);
- return;
- }
- tokenize(source, options, function(err, stream) {
- applyOverrides(err, stream, metas, bOrigin, options,
- function(err, stream) {
- callback(err, stream);
- }); }); });
- } else if (Object.keys(metas).join("") != "") {
- // base template and metas, apply metas and out
- var out = [];
- var huntFor = "";
- stream.forEach(function(chunk) {
- if (chunk.op == "meta" && (chunk.value in metas)) {
- huntFor = chunk.value;
- } else if (chunk.op == "end" && chunk.value == huntFor) {
- Array.prototype.push.apply(out, metas[huntFor]);
- huntFor = "";
- } else if (!huntFor) {
- out.push(chunk);
- }
- });
- callback(undefined, out);
- } else { // Base template, no metas - just clean metas
- cleanup(undefined, stream, 'meta', function(err, stream) {
- callback(err, stream);
- });
- }
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ // determine override state
+ var over = false;
+ stream.forEach(function(chunk) {
+ if (chunk.op == 'override') over = chunk.value;
+ });
+ if (over) { // it's override
+ // collect metas and call base template
+ var huntFor = "";
+ var ingest = false;
+ stream.forEach(function(chunk) {
+ if (chunk.op == 'meta') {
+ huntFor = chunk.value;
+ if (!metas[huntFor]) {
+ metas[huntFor] = [];
+ ingest = true;
+ } else {
+ ingest = false;
+ }
+ } else if (chunk.op == 'end' && chunk.value == huntFor) {
+ huntFor = "";
+ } else if (huntFor) {
+ if (ingest) metas[huntFor].push(chunk);
+ }
+ });
+
+ bOrigin = makePath(origin, over);
+ loader(origin, function(err, source) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ tokenize(source, options, function(err, stream) {
+ applyOverrides(err, stream, metas, bOrigin, options,
+ function(err, stream) {
+ callback(err, stream);
+ }); }); });
+ } else if (Object.keys(metas).join("") != "") {
+ // base template and metas, apply metas and out
+ var out = [];
+ var huntFor = "";
+ stream.forEach(function(chunk) {
+ if (chunk.op == "meta" && (chunk.value in metas)) {
+ huntFor = chunk.value;
+ } else if (chunk.op == "end" && chunk.value == huntFor) {
+ Array.prototype.push.apply(out, metas[huntFor]);
+ huntFor = "";
+ } else if (!huntFor) {
+ out.push(chunk);
+ }
+ });
+ callback(undefined, out);
+ } else { // Base template, no metas - just clean metas
+ cleanup(undefined, stream, 'meta', function(err, stream) {
+ callback(err, stream);
+ });
+ }
}
/**
@@ -165,45 +165,45 @@ function applyOverrides(err, stream, metas, origin, options, callback) {
* @param callback
*/
function expandPartials(err, stream, origin, options, callback) {
- if (err) {
- callback(err);
- return;
- }
-
- var partials = stream.map(function(chunk) {
- return chunk.op == 'partial' ? chunk.value : false;
- }).filter(filterFalsy);
-
- if (partials.length) {
- var actions = partials.map(function(candidate) {
- var absPath = makePath(origin, candidate);
- return function(callback) {
- parse(absPath, options, function(err, stream) {
- callback(err, stream, candidate);
- });
- };
- });
- parallel(actions, function(results) {
- var partials = {};
- results.forEach(function (result) {
- if (result.type === 'success') {
- partials[result.values[1]] = result.values[0];
- }
- });
- var out = [];
- stream.forEach(function(chunk) {
- if (chunk.op == 'partial' && chunk.value in partials) {
- Array.prototype.push.apply(out,
- partials[chunk.value]);
- } else {
- out.push(chunk);
- }
- });
- callback(err, out);
- });
- } else {
- callback(err, stream);
- }
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ var partials = stream.map(function(chunk) {
+ return chunk.op == 'partial' ? chunk.value : false;
+ }).filter(filterFalsy);
+
+ if (partials.length) {
+ var actions = partials.map(function(candidate) {
+ var absPath = makePath(origin, candidate);
+ return function(callback) {
+ parse(absPath, options, function(err, stream) {
+ callback(err, stream, candidate);
+ });
+ };
+ });
+ parallel(actions, function(results) {
+ var partials = {};
+ results.forEach(function (result) {
+ if (result.type === 'success') {
+ partials[result.values[1]] = result.values[0];
+ }
+ });
+ var out = [];
+ stream.forEach(function(chunk) {
+ if (chunk.op == 'partial' && chunk.value in partials) {
+ Array.prototype.push.apply(out,
+ partials[chunk.value]);
+ } else {
+ out.push(chunk);
+ }
+ });
+ callback(err, out);
+ });
+ } else {
+ callback(err, stream);
+ }
}
/**
@@ -214,110 +214,110 @@ function expandPartials(err, stream, origin, options, callback) {
* @param callback
*/
function applyFilters(err, stream, options, callback) {
- /**
- * Join raw chunks.
- * @param err
- * @param stream
- * @param callback
- */
- function compress(err, stream, callback) {
- if (err) {
- callback(err);
- return;
- }
- var out = [];
- stream.forEach(function(chunk) {
- if (chunk.op == 'raw' && out.length &&
- out[out.length-1].op == 'raw') {
- out[out.length-1].value =
- (out[out.length-1].value + chunk.value);
- } else {
- out.push(chunk);
- }
- });
- callback(undefined, out);
- }
-
- if (err) {
- callback(err);
- return;
- }
-
- compress(err, stream, function(err, stream) {
- // collect filters without nested filters
- collected = [];
- nested = false;
- buffer = [];
- huntFor = "";
- huntId = undefined;
- for ( var i = 0; i < stream.length; i++) {
- if (stream[i].op == 'filter') {
- if (huntFor) nested = true;
- huntFor = stream[i].value;
- huntId = i;
- buffer = [];
- } else if (stream[i].op == "end"
- && stream[i].value == huntFor) {
- Array.prototype.push.apply(collected, buffer);
- } else if (huntFor && stream[i].op == "raw") {
- buffer.push({id:i,
- value: stream[i].value,
- filter: huntFor,
- fId: huntId});
- }
- }
-
- if (collected.length) {
- var actions = collected.map(function(sign) {
- return function(callback) {
- (options.filters[sign.filter] ||
- options.filters.undefinedFilter)
- (sign.value, function(err, value) {
- callback(err, value, sign.id, sign.fId);
- });
- };
- });
- parallel(actions, function(results) {
- var toKill = []; // filter chunks
- results.forEach(function(result) {
- if (result.type === 'success') {
- var value = result.values[0];
- var id = result.values[1];
- var fId = result.values[2];
- stream[id].value = value;
- stream[fId].op = "TO_KILL";
- }
- });
- cleanup(err, stream, "TO_KILL", function(err, stream) {
- nested ? applyFilters(err, stream, options, callback)
- : callback(undefined, stream);
- });
- });
- } else { // no filters - just do callback
- callback(undefined, stream);
- }
- });
+ /**
+ * Join raw chunks.
+ * @param err
+ * @param stream
+ * @param callback
+ */
+ function compress(err, stream, callback) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ var out = [];
+ stream.forEach(function(chunk) {
+ if (chunk.op == 'raw' && out.length &&
+ out[out.length-1].op == 'raw') {
+ out[out.length-1].value =
+ (out[out.length-1].value + chunk.value);
+ } else {
+ out.push(chunk);
+ }
+ });
+ callback(undefined, out);
+ }
+
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ compress(err, stream, function(err, stream) {
+ // collect filters without nested filters
+ collected = [];
+ nested = false;
+ buffer = [];
+ huntFor = "";
+ huntId = undefined;
+ for ( var i = 0; i < stream.length; i++) {
+ if (stream[i].op == 'filter') {
+ if (huntFor) nested = true;
+ huntFor = stream[i].value;
+ huntId = i;
+ buffer = [];
+ } else if (stream[i].op == "end"
+ && stream[i].value == huntFor) {
+ Array.prototype.push.apply(collected, buffer);
+ } else if (huntFor && stream[i].op == "raw") {
+ buffer.push({id:i,
+ value: stream[i].value,
+ filter: huntFor,
+ fId: huntId});
+ }
+ }
+
+ if (collected.length) {
+ var actions = collected.map(function(sign) {
+ return function(callback) {
+ (options.filters[sign.filter] ||
+ options.filters.undefinedFilter)
+ (sign.value, function(err, value) {
+ callback(err, value, sign.id, sign.fId);
+ });
+ };
+ });
+ parallel(actions, function(results) {
+ var toKill = []; // filter chunks
+ results.forEach(function(result) {
+ if (result.type === 'success') {
+ var value = result.values[0];
+ var id = result.values[1];
+ var fId = result.values[2];
+ stream[id].value = value;
+ stream[fId].op = "TO_KILL";
+ }
+ });
+ cleanup(err, stream, "TO_KILL", function(err, stream) {
+ nested ? applyFilters(err, stream, options, callback)
+ : callback(undefined, stream);
+ });
+ });
+ } else { // no filters - just do callback
+ callback(undefined, stream);
+ }
+ });
}
function cleanup(err, stream, op, callback){
- if (err) {
- callback(err);
- return;
- }
-
- var huntFor = "";
- var out = stream.filter(function(chunk) {
- if (chunk.op == op) {
- huntFor = chunk.value;
- return false;
- } else if (chunk.op == "end" && chunk.value == huntFor) {
- huntFor = "";
- return false;
- } else {
- return true;
- }
- });
- callback(undefined, out);
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ var huntFor = "";
+ var out = stream.filter(function(chunk) {
+ if (chunk.op == op) {
+ huntFor = chunk.value;
+ return false;
+ } else if (chunk.op == "end" && chunk.value == huntFor) {
+ huntFor = "";
+ return false;
+ } else {
+ return true;
+ }
+ });
+ callback(undefined, out);
}
/**
@@ -329,96 +329,96 @@ function cleanup(err, stream, op, callback){
* @param {function(parsed)} callback - Callback
*/
function tokenize(source, options, callback) {
- var escapeRegex = function(text) {
- if (!arguments.callee.sRE) {
- var specials = [ '/', '.', '*', '+', '?', '|', '(', ')',
- '[', ']', '{', '}', '\\' ];
- arguments.callee.sRE = new RegExp('(\\' +
- specials.join('|\\') + ')', 'g');
- }
- return text.replace(arguments.callee.sRE, '\\$1');
- };
-
- // replace all unneeded characters
- source = source
- .replace(/\\+/g, '\\\\')
- .replace(/\r/g, "")
- .replace(/\t/g, ' ')
- .replace(/"/g, "\\\"")
- .replace(/ +\n/g, '\n');
-
-
- if(options.compress == true) {
- source = source.
- replace(/ */g, ' ')
- .replace(/\n /g, '\n')
- .replace(/\n\n*/g, '\n');
- }
-
- var tokenRe;
- var opRe;
- var opsSig = {
- '&' : 'unescaped',
- '#' : 'section',
- '^' : 'inverted',
- '/' : 'end',
- '<' : 'override',
- '>' : 'partial',
- '+' : 'meta',
- '~' : 'filter'
- };
- var setRe = function (oTag, cTag) {
- tokenRe = new RegExp(
- "(" + escapeRegex(oTag) + ".+?" + escapeRegex(cTag) + ")");
- opRe = new RegExp(escapeRegex(oTag) + " *(.) *(.*) *" +
- escapeRegex(cTag) );
- };
- setRe("{{", "}}");
-
- var lines = source.split(/\n/g);
- var output = lines.reduce(function(buffer, line) {
- var tokens = line.split(tokenRe);
- // chop whitespace for single line tokens
- if (
- tokens.length == 3
- && tokens[0].search(/^ *$/) != -1
- && tokens[2] == ""
- && (tokens[1].match(opRe))[1].search(/[<>+!~#^\/=]/) != -1
- ) {
- tokens = [tokens[1]];
- }
- while (tokens.length) {
- var op = tokens[0].match(opRe);
-
- if (!op) { // Raw value
- buffer.push({
- op: 'raw',
- value: tokens[0] + (tokens.length==1 ? "\n" : "")
- });
- tokens.shift();
- } else if (op[1] == "!") { // comment
- tokens.shift();
- } else if (op[1] == "=") { // shapeshift
- var shaped = op[2].split(" ");
- setRe(shaped[0], shaped[1]);
- tokens.shift();
- if (tokens.length) {
- tokens = tokens.join("").split(tokenRe);
- }
- } else if (op[1] in opsSig) { // some op
- buffer.push({op:opsSig[op[1]], value: op[2]});
- tokens.shift();
- } else { // lookup
- buffer.push({op:"lookup", value: op[1] + op[2]});
- tokens.shift();
- }
- };
- return buffer;
- }, []);
+ var escapeRegex = function(text) {
+ if (!arguments.callee.sRE) {
+ var specials = [ '/', '.', '*', '+', '?', '|', '(', ')',
+ '[', ']', '{', '}', '\\' ];
+ arguments.callee.sRE = new RegExp('(\\' +
+ specials.join('|\\') + ')', 'g');
+ }
+ return text.replace(arguments.callee.sRE, '\\$1');
+ };
+
+ // replace all unneeded characters
+ source = source
+ .replace(/\\+/g, '\\\\')
+ .replace(/\r/g, "")
+ .replace(/\t/g, ' ')
+ .replace(/"/g, "\\\"")
+ .replace(/ +\n/g, '\n');
+
+
+ if(options.compress == true) {
+ source = source.
+ replace(/ */g, ' ')
+ .replace(/\n /g, '\n')
+ .replace(/\n\n*/g, '\n');
+ }
+
+ var tokenRe;
+ var opRe;
+ var opsSig = {
+ '&' : 'unescaped',
+ '#' : 'section',
+ '^' : 'inverted',
+ '/' : 'end',
+ '<' : 'override',
+ '>' : 'partial',
+ '+' : 'meta',
+ '~' : 'filter'
+ };
+ var setRe = function (oTag, cTag) {
+ tokenRe = new RegExp(
+ "(" + escapeRegex(oTag) + ".+?" + escapeRegex(cTag) + ")");
+ opRe = new RegExp(escapeRegex(oTag) + " *(.) *(.*) *" +
+ escapeRegex(cTag) );
+ };
+ setRe("{{", "}}");
+
+ var lines = source.split(/\n/g);
+ var output = lines.reduce(function(buffer, line) {
+ var tokens = line.split(tokenRe);
+ // chop whitespace for single line tokens
+ if (
+ tokens.length == 3
+ && tokens[0].search(/^ *$/) != -1
+ && tokens[2] == ""
+ && (tokens[1].match(opRe))[1].search(/[<>+!~#^\/=]/) != -1
+ ) {
+ tokens = [tokens[1]];
+ }
+ while (tokens.length) {
+ var op = tokens[0].match(opRe);
+
+ if (!op) { // Raw value
+ buffer.push({
+ op: 'raw',
+ value: tokens[0] + (tokens.length==1 ? "\n" : "")
+ });
+ tokens.shift();
+ } else if (op[1] == "!") { // comment
+ tokens.shift();
+ } else if (op[1] == "=") { // shapeshift
+ var shaped = op[2].split(" ");
+ setRe(shaped[0], shaped[1]);
+ tokens.shift();
+ if (tokens.length) {
+ tokens = tokens.join("").split(tokenRe);
+ }
+ } else if (op[1] in opsSig) { // some op
+ buffer.push({op:opsSig[op[1]], value: op[2]});
+ tokens.shift();
+ } else { // lookup
+ buffer.push({op:"lookup", value: op[1] + op[2]});
+ tokens.shift();
+ }
+ };
+ return buffer;
+ }, []);
- //sys.debug(sys.inspect(output));
-
- callback(undefined, output);
+ //sys.debug(sys.inspect(output));
+
+ callback(undefined, output);
};
/**
@@ -426,33 +426,33 @@ function tokenize(source, options, callback) {
*
* @param path Absolute path to file
* @param callback Callback function that takes two arguments: Error
- * and loaded string.
+ * and loaded string.
*/
function loader(file, callback) {
- fs.readFile(file, 'utf8', function(err, contents) {
- if (err) {
- callback(err);
- return;
- }
- callback(undefined, contents);
- });
+ fs.readFile(file, 'utf8', function(err, contents) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ callback(undefined, contents);
+ });
};
function parallel(callbacks, callback) {
- var results = [];
- var acc = function(err) {
- var result = Array.prototype.slice.call(arguments, 1);
- results.push( {
- type : err ? 'error' : 'success',
- values : err || result
- });
- if (results.length === callbacks.length) {
- callback(results);
- }
- };
- callbacks.forEach(function(cb) {
- cb(acc);
- });
+ var results = [];
+ var acc = function(err) {
+ var result = Array.prototype.slice.call(arguments, 1);
+ results.push( {
+ type : err ? 'error' : 'success',
+ values : err || result
+ });
+ if (results.length === callbacks.length) {
+ callback(results);
+ }
+ };
+ callbacks.forEach(function(cb) {
+ cb(acc);
+ });
}
/**
@@ -464,5 +464,5 @@ function filterFalsy(item) {
}
function makePath(origin, name) {
- return path.normalize(path.dirname(origin) + "/" + name);
+ return path.normalize(path.dirname(origin) + "/" + name);
}
58 test/common.js
View
@@ -7,45 +7,45 @@ var Buffer = require('buffer').Buffer;
var nun = exports.nun = require("../");
file = exports.file = function(name) {
- return path.normalize(__dirname + "/fixtures/" + name + ".html");
+ return path.normalize(__dirname + "/fixtures/" + name + ".html");
};
assertFile = exports.assertFile = function(actual, name) {
- file = path.normalize(__dirname + "/expects/" + name + ".html");
- fs.readFile(file, 'utf8', function(err, expected) {
- if (err) {
- throw err;
- }
- assert.equal(actual, expected);
- });
+ file = path.normalize(__dirname + "/expects/" + name + ".html");
+ fs.readFile(file, 'utf8', function(err, expected) {
+ if (err) {
+ throw err;
+ }
+ assert.equal(actual, expected);
+ });
};
var ended = false;
exports.test = function(name, context, options, callback) {
- var fixture = {context: {}, options: {}};
- if (!context || !options) {
- overFixture = require("./fixtures/" + name);
- }
- fixture.context = context ? context : overFixture.context;
- fixture.options = options ? options : overFixture.options;
-
- nun.render(file(name), fixture.context, fixture.options,
- function(err, output){
- if (err) throw err;
-
- var buffer = ''; // all tests must produce data
- output
- .addListener('data', function(data){ buffer += data; })
- .addListener('end', function(){
- ended = true;
- //sys.debug(buffer);
- assertFile(buffer, name);
- });
- });
+ var fixture = {context: {}, options: {}};
+ if (!context || !options) {
+ overFixture = require("./fixtures/" + name);
+ }
+ fixture.context = context ? context : overFixture.context;
+ fixture.options = options ? options : overFixture.options;
+
+ nun.render(file(name), fixture.context, fixture.options,
+ function(err, output){
+ if (err) throw err;
+
+ var buffer = ''; // all tests must produce data
+ output
+ .addListener('data', function(data){ buffer += data; })
+ .addListener('end', function(){
+ ended = true;
+ //sys.debug(buffer);
+ assertFile(buffer, name);
+ });
+ });
};
process.addListener("exit", function () {
- assert.ok(ended);
+ assert.ok(ended);
});
2  test/fixtures/basic.js
View
@@ -3,5 +3,5 @@ exports.context = {
};
exports.options = {
-
+
};
2  test/fixtures/big-utf8.js
View
@@ -3,5 +3,5 @@ exports.context = {
};
exports.options = {
-
+
};
46 test/fixtures/complex.js
View
@@ -1,27 +1,27 @@
exports.context = {
- header: function(context) {
- return function(context, callback) {
- process.nextTick(function() {
- callback(undefined, "Colors");
- });
- };
- },
-
-
- item: [
- {name: "red", current: true, url: "#Red"},
- {name: "green", current: false, url: "#Green"},
- {name: "blue", current: false, url: "#Blue"}
- ],
- link: function(context) {
- return context["current"] !== true;
- },
- list: function(context) {
- return context.item.length !== 0;
- },
- empty: function(context) {
- return context.item.length === 0;
- }
+ header: function(context) {
+ return function(context, callback) {
+ process.nextTick(function() {
+ callback(undefined, "Colors");
+ });
+ };
+ },
+
+
+ item: [
+ {name: "red", current: true, url: "#Red"},
+ {name: "green", current: false, url: "#Green"},
+ {name: "blue", current: false, url: "#Blue"}
+ ],
+ link: function(context) {
+ return context["current"] !== true;
+ },
+ list: function(context) {
+ return context.item.length !== 0;
+ },
+ empty: function(context) {
+ return context.item.length === 0;
+ }
};
exports.options = {};
16 test/fixtures/filters.js
View
@@ -3,12 +3,12 @@ exports.context = {
};
exports.options = {
- filters: {
- upper: function(data, callback) {
- callback(undefined, data.toUpperCase());
- },
- wrap: function(data, callback) {
- callback(undefined, "<" + data + ">");
- }
- }
+ filters: {
+ upper: function(data, callback) {
+ callback(undefined, data.toUpperCase());
+ },
+ wrap: function(data, callback) {
+ callback(undefined, "<" + data + ">");
+ }
+ }
};
22 test/fixtures/lookup-async.js
View
@@ -1,16 +1,16 @@
exports.context = {
- name: "John Dow",
- year: function(context) {
- return function(context, callback) {
- setTimeout(function() {
- callback(undefined, context.value);
- }, 200);
- };
- },
- value: 1968,
- tag: "<tag>"
+ name: "John Dow",
+ year: function(context) {
+ return function(context, callback) {
+ setTimeout(function() {
+ callback(undefined, context.value);
+ }, 200);
+ };
+ },
+ value: 1968,
+ tag: "<tag>"
};
exports.options = {
-
+
};
14 test/fixtures/lookup-simple.js
View
@@ -1,12 +1,12 @@
exports.context = {
- name: "John Dow",
- year: function(context) {
- return context.value;
- },
- value: 1968,
- tag: "<tag>"
+ name: "John Dow",
+ year: function(context) {
+ return context.value;
+ },
+ value: 1968,
+ tag: "<tag>"
};
exports.options = {
-
+
};
30 test/fixtures/sections-inverted.js
View
@@ -1,20 +1,20 @@
exports.context = {
- emptyString: "",
- isNull: null,
- isZero: 0,
- isFalse: false,
- emptyArray: [],
- emptyObject: {},
-
- def: "Defined",
- string: "String",
- notNull: 1234,
- nonZero: 12423,
- notFalse: true,
- array: ["test", "me"],
- obj: {val: "Val"}
+ emptyString: "",
+ isNull: null,
+ isZero: 0,
+ isFalse: false,
+ emptyArray: [],
+ emptyObject: {},
+
+ def: "Defined",
+ string: "String",
+ notNull: 1234,
+ nonZero: 12423,
+ notFalse: true,
+ array: ["test", "me"],
+ obj: {val: "Val"}
};
exports.options = {
-
+
};
30 test/fixtures/sections.js
View
@@ -1,20 +1,20 @@
exports.context = {
- emptyString: "",
- isNull: null,
- isZero: 0,
- isFalse: false,
- emptyArray: [],
- emptyObject: {},
-
- def: "Defined",
- string: "String",
- notNull: 1234,
- nonZero: 12423,
- notFalse: true,
- array: ["test", "me"],
- obj: {val: "Val"}
+ emptyString: "",
+ isNull: null,
+ isZero: 0,
+ isFalse: false,
+ emptyArray: [],
+ emptyObject: {},
+
+ def: "Defined",
+ string: "String",
+ notNull: 1234,
+ nonZero: 12423,
+ notFalse: true,
+ array: ["test", "me"],
+ obj: {val: "Val"}
};
exports.options = {
-
+
};
32 test/make-expect.js
View
@@ -18,23 +18,23 @@ var e = fs.openSync(path.normalize(__dirname + "/expects/"+example+".html"), 'w'
var fixture = {context: {}, options: {}};
if (!nofixture) {
- fixture = require("./fixtures/" + example);
+ fixture = require("./fixtures/" + example);
}
nun.render(f, fixture.context, fixture.options,
- function(err, output){
- if (err) throw err;
-
- var buffer = '';
- output
- .addListener('data', function(data){
- buffer += data;
- })
- .addListener('end', function(){
- var b = new Buffer(Buffer.byteLength(buffer, 'utf8'));
- b.write(buffer, 'utf8');
- sys.debug(b);
-
- fs.write(e, b, 0, Buffer.byteLength(buffer, 'utf8'), 0);
- });
+ function(err, output){
+ if (err) throw err;
+
+ var buffer = '';
+ output
+ .addListener('data', function(data){
+ buffer += data;
+ })
+ .addListener('end', function(){
+ var b = new Buffer(Buffer.byteLength(buffer, 'utf8'));
+ b.write(buffer, 'utf8');
+ sys.debug(b);
+
+ fs.write(e, b, 0, Buffer.byteLength(buffer, 'utf8'), 0);
+ });
});
34 test/test-cache.js
View
@@ -6,24 +6,24 @@ var renders = 0;
var gets = 0;
for (var i = 0; i < 4; i++) {
- var key = i.toString();
- for (var j = 0; j < 1000; j++) {
- cache.operate(key,
- function(value) {
- if (value == key) {
- gets++;
- }
- },
- function(callback) {
- setTimeout(function(){
- renders++;
- callback(key);
- }, 200);
- });
- }
+ var key = i.toString();
+ for (var j = 0; j < 1000; j++) {
+ cache.operate(key,
+ function(value) {
+ if (value == key) {
+ gets++;
+ }
+ },
+ function(callback) {
+ setTimeout(function(){
+ renders++;
+ callback(key);
+ }, 200);
+ });
+ }
}
process.addListener("exit", function () {
- assert.equal(renders, 4);
- assert.equal(gets, 4000);
+ assert.equal(renders, 4);
+ assert.equal(gets, 4000);
});
2  test/test-error-notfound.js
View
@@ -3,5 +3,5 @@ var assert = require("assert");
var nun = require('../');
nun.render('notfound.html', {}, {}, function(err, tpl) {
- assert.ifError(!err);
+ assert.ifError(!err);
});
8 test/test-filters-set.js
View
@@ -1,13 +1,13 @@
var c = require("./common");
c.nun.setFilter('upper', function(data, callback) {
- callback(undefined, data.toUpperCase());
+ callback(undefined, data.toUpperCase());
});
var filters = {
- wrap: function(data, callback) {
- callback(undefined, "<" + data + ">");
- }
+ wrap: function(data, callback) {
+ callback(undefined, "<" + data + ">");
+ }
};
c.test("filters", {}, {filters:filters});
14 test/test-hstream.js
View
@@ -3,9 +3,9 @@ var assert = require('assert');
var HStream = require("../hstream").HStream;
var lambda = function(data, callback) {
- setTimeout(function() {
- callback("[" + data + "]");
- },300);
+ setTimeout(function() {
+ callback("[" + data + "]");
+ },300);
};
var buffer = '';
@@ -15,11 +15,11 @@ var ended = false;
var hs = new HStream();
hs
.addListener('data', function(data) {
- buffer += data + ":";
+ buffer += data + ":";
})
.addListener('end', function() {
- ended = true;
- assert.equal(buffer, expect);
+ ended = true;
+ assert.equal(buffer, expect);
});
hs.map('0');
@@ -50,5 +50,5 @@ hs.write('4', '<4>');
hs.write('1/1', '<1/1>');
process.addListener("exit", function () {
- assert.ok(ended);
+ assert.ok(ended);
});
Please sign in to comment.
Something went wrong with that request. Please try again.