1 (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
4 * EJS Embedded JavaScript templates
5 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
23 var fs = require('fs')
24 , utils = require('./utils')
26 , _VERSION_STRING = require('../package.json').version
27 , _DEFAULT_DELIMITER = '%'
28 , _DEFAULT_LOCALS_NAME = 'locals'
29 , _REGEX_STRING = '(<%%|<%=|<%-|<%#|<%|%>|-%>)'
30 , _OPTS = [ 'cache', 'filename', 'delimiter', 'scope', 'context'
31 , 'debug', 'compileDebug', 'client', '_with'
33 , _TRAILING_SEMCOL = /;\s*$/;
35 exports.localsName = _DEFAULT_LOCALS_NAME;
37 exports.resolveInclude = function(name, filename) {
38 var path = require('path')
39 , dirname = path.dirname
40 , extname = path.extname
41 , resolve = path.resolve
42 , includePath = resolve(dirname(filename), name)
43 , ext = extname(name);
45 includePath += '.ejs';
51 // Returns a possibly cached template function, set by options.cache.
52 // `template` is the string of EJS to compile.
53 // If template is undefined then the file specified in options.filename is
55 function handleCache(options, template) {
57 , path = options.filename
58 , hasTemplate = template !== undefined;
62 throw new Error('cache option requires a filename');
69 template = fs.readFileSync(path, {encoding: 'utf8'});
72 else if (!hasTemplate) {
74 throw new Error('Internal EJS error: no file name or template '
77 template = fs.readFileSync(path, {encoding: 'utf8'});
79 fn = exports.compile(template.trim(), options);
86 function includeFile(path, options) {
87 var opts = utils.shallowCopy({}, options || /* istanbul ignore next */ {});
89 throw new Error('`include` requires the \'filename\' option.');
91 opts.filename = exports.resolveInclude(path, opts.filename);
92 return handleCache(opts);
95 function includeSource(path, options) {
96 var opts = utils.shallowCopy({}, options || {})
100 throw new Error('`include` requires the \'filename\' option.');
102 includePath = exports.resolveInclude(path, opts.filename);
103 template = fs.readFileSync(includePath).toString().trim();
105 opts.filename = includePath;
106 var templ = new Template(template, opts);
107 templ.generateSource();
111 function rethrow(err, str, filename, lineno){
112 var lines = str.split('\n')
113 , start = Math.max(lineno - 3, 0)
114 , end = Math.min(lines.length, lineno + 3);
117 var context = lines.slice(start, end).map(function (line, i){
118 var curr = i + start + 1;
119 return (curr == lineno ? ' >> ' : ' ')
125 // Alter exception message
127 err.message = (filename || 'ejs') + ':'
135 function cpOptsInData(data, opts) {
136 _OPTS.forEach(function (p) {
137 if (typeof data[p] != 'undefined') {
141 delete data.__expressRender__;
144 function compile(template, opts) {
148 // 'scope' is 'context'
149 // FIXME: Remove this in a future version
150 if (opts && opts.scope) {
152 opts.context = opts.scope;
156 templ = new Template(template, opts);
157 return templ.compile();
159 exports.compile = compile;
161 // template, [data], [opts]
162 // Have to include an empty data object if you want opts and no data
163 exports.render = function (template, data, opts) {
168 // No options object -- if there are optiony names
169 // in the data, copy them to options
170 if (arguments.length == 2) {
171 cpOptsInData(data, opts);
174 fn = handleCache(opts, template);
175 return fn.call(opts.context, data);
178 // path, [data], [opts], cb
179 // Have to include an empty data object if you want opts and no data
180 exports.renderFile = function () {
181 var args = Array.prototype.slice.call(arguments)
182 , path = args.shift()
184 , data = args.shift() || {}
185 , opts = args.pop() || {}
189 // No options object -- if there are optiony names
190 // in the data, copy them to options
191 if (arguments.length == 3) {
192 cpOptsInData(data, opts);
194 opts.filename = path;
197 result = handleCache(opts)(data);
200 return process.nextTick(function () {
204 process.nextTick(function () {
209 exports.clearCache = function () {
213 function Template(text, opts) {
216 this.templateText = text;
218 this.truncate = false;
219 this.currentLine = 1;
221 options.client = opts.client || false;
222 options.escapeFunction = opts.escape || utils.escapeXML;
223 options.compileDebug = opts.compileDebug !== false;
224 options.debug = !!opts.debug;
225 options.filename = opts.filename;
226 options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
227 options._with = typeof opts._with != 'undefined' ? opts._with : true;
228 options.cache = opts.cache || false;
231 this.regex = this.createRegex();
242 Template.prototype = new function () {
243 this.createRegex = function () {
244 var str = _REGEX_STRING
245 , delim = utils.escapeRegExpChars(this.opts.delimiter);
246 str = str.replace(/%/g, delim);
247 return new RegExp(str);
250 this.compile = function () {
254 , escape = opts.escapeFunction;
257 this.generateSource();
258 var prepended = 'var __output = [];';
259 if (opts._with !== false) {
260 prepended += ' with (' + exports.localsName + ' || {}) { ';
262 this.source = prepended + this.source;
263 if (opts._with !== false) {
266 this.source += ';return __output.join("").trim();';
269 if (opts.compileDebug) {
270 src = 'var __line = 1' +
271 ', __lines = ' + JSON.stringify(this.templateText) +
272 ', __filename = ' + (opts.filename ?
273 JSON.stringify(opts.filename) : 'undefined') +
275 this.source + '} catch (e) { rethrow(e, __lines, __filename, __line); }';
286 if (escape !== utils.escapeXML) {
287 src = 'escape = escape || ' + escape.toString() + ';\n' + src;
290 src = utils.escapeFuncStr
291 + 'escape = escape || '
292 + escape.toString() + ';\n'
295 if (opts.compileDebug) {
296 src = 'rethrow = rethrow || ' + rethrow.toString() + ';\n' + src;
301 fn = new Function(exports.localsName + ', escape, include, rethrow', src);
304 if (e instanceof SyntaxError) {
306 e.message += ' in ' + opts.filename;
308 e.message += ' while compiling ejs';
317 // Return a callable function which will execute the function
318 // created by the source-code, with the passed data as locals
319 return function (data) {
320 var include = function (path, includeData) {
321 var d = utils.shallowCopy({}, data);
323 d = utils.shallowCopy(d, includeData);
325 return includeFile(path, opts)(d);
327 return fn(data || {}, escape, include, rethrow);
332 this.generateSource = function () {
334 , matches = this.parseTemplateText()
335 , d = this.opts.delimiter;
337 if (matches && matches.length) {
338 matches.forEach(function (line, index) {
343 // If this is an opening tag, check for closing tags
344 // FIXME: May end up with some false positives here
345 // Better to store modes as k/v with '<' + delimiter as key
346 // Then this can simply check against the map
347 if ( line.indexOf('<' + d) === 0 // If it is a tag
348 && line.indexOf('<' + d + d) !== 0) { // and is not escaped
349 closing = matches[index + 2];
350 if (!(closing == d + '>' || closing == '-' + d + '>')) {
351 throw new Error('Could not find matching close tag for "' + line + '".');
354 // HACK: backward-compat `include` preprocessor directives
355 if ((include = line.match(/^\s*include\s+(\S+)/))) {
356 includeOpts = utils.shallowCopy({}, self.opts);
357 includeSrc = includeSource(include[1], includeOpts);
358 includeSrc = ';(function(){' + includeSrc + '})();';
359 self.source += includeSrc;
369 this.parseTemplateText = function () {
370 var str = this.templateText
372 , result = pat.exec(str)
378 firstPos = result.index;
379 lastPos = pat.lastIndex;
381 if (firstPos !== 0) {
382 arr.push(str.substring(0, firstPos));
383 str = str.slice(firstPos);
387 str = str.slice(result[0].length);
388 result = pat.exec(str);
398 this.scanLine = function (line) {
400 , d = this.opts.delimiter
403 function _addOutput() {
405 line = line.replace('\n', '');
408 // Preserve literal slashes
409 line = line.replace(/\\/g, '\\\\');
411 // Convert linebreaks
412 line = line.replace(/\n/g, '\\n');
413 line = line.replace(/\r/g, '\\r');
415 // Escape double-quotes
416 // - this will be the delimiter during execution
417 line = line.replace(/"/g, '\\"');
418 self.source += ';__output.push("' + line + '");';
421 newLineCount = (line.split('\n').length - 1);
425 this.mode = Template.modes.EVAL;
428 this.mode = Template.modes.ESCAPED;
431 this.mode = Template.modes.RAW;
434 this.mode = Template.modes.COMMENT;
437 this.mode = Template.modes.LITERAL;
438 this.source += ';__output.push("' + line.replace('<' + d + d, '<' + d) + '");';
442 if (this.mode == Template.modes.LITERAL) {
447 this.truncate = line.indexOf('-') === 0;
450 // In script mode, depends on type of tag
452 // If '//' is found without a line break, add a line break.
454 case Template.modes.EVAL:
455 case Template.modes.ESCAPED:
456 case Template.modes.RAW:
457 if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
462 // Just executing code
463 case Template.modes.EVAL:
464 this.source += ';' + line;
466 // Exec, esc, and output
467 case Template.modes.ESCAPED:
468 // Add the exec'd, escaped result to the output
469 // Have to prevent the string-coercion of `undefined` and `null`
470 // in the `escape` function -- making a `join` call like below unnecessary
471 this.source += ';__output.push(escape(' +
472 line.replace(_TRAILING_SEMCOL, '').trim() + '))';
475 case Template.modes.RAW:
476 // Add the exec'd result to the output
477 // Using `join` here prevents string-coercion of `undefined` and `null`
478 // without filtering out falsey values like zero
479 this.source += ';__output.push(' +
480 line.replace(_TRAILING_SEMCOL, '').trim() + ')';
482 case Template.modes.COMMENT:
485 // Literal <%% mode, append as raw output
486 case Template.modes.LITERAL:
491 // In string mode, just add the output
497 if (self.opts.compileDebug && newLineCount) {
498 this.currentLine += newLineCount;
499 this.source += ';__line = ' + this.currentLine + ';';
505 exports.__express = exports.renderFile;
507 // Add require support
508 /* istanbul ignore else */
509 if (require.extensions) {
510 require.extensions['.ejs'] = function (module, filename) {
511 filename = filename || /* istanbul ignore next */ module.filename;
516 , template = fs.readFileSync(filename).toString().trim()
517 , fn = compile(template, options);
518 module._compile('module.exports = ' + fn.toString() + ';', filename);
522 exports.VERSION = _VERSION_STRING;
524 /* istanbul ignore if */
525 if (typeof window != 'undefined') {
526 window.ejs = exports;
529 }).call(this,require('_process'))
530 },{"../package.json":6,"./utils":2,"_process":5,"fs":3,"path":4}],2:[function(require,module,exports){
532 * EJS Embedded JavaScript templates
533 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
535 * Licensed under the Apache License, Version 2.0 (the "License");
536 * you may not use this file except in compliance with the License.
537 * You may obtain a copy of the License at
539 * http://www.apache.org/licenses/LICENSE-2.0
541 * Unless required by applicable law or agreed to in writing, software
542 * distributed under the License is distributed on an "AS IS" BASIS,
543 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
544 * See the License for the specific language governing permissions and
545 * limitations under the License.
551 var regExpChars = /[|\\{}()[\]^$+*?.]/g;
553 exports.escapeRegExpChars = function (string) {
554 // istanbul ignore if
558 return String(string).replace(regExpChars, '\\$&');
561 var encodeHTMLRules = {
568 , matchHTML = /[&<>\'"]/g;
570 exports.escapeFuncStr =
571 'var encodeHTMLRules = {'
578 + ', matchHTML = /[&<>\'"]/g;';
580 exports.escapeXML = function (markup) {
581 return markup == undefined
584 .replace(matchHTML, function(m) {
585 return encodeHTMLRules[m] || m;
589 exports.shallowCopy = function (to, from) {
590 for (var p in from) {
597 },{}],3:[function(require,module,exports){
599 },{}],4:[function(require,module,exports){
601 // Copyright Joyent, Inc. and other Node contributors.
603 // Permission is hereby granted, free of charge, to any person obtaining a
604 // copy of this software and associated documentation files (the
605 // "Software"), to deal in the Software without restriction, including
606 // without limitation the rights to use, copy, modify, merge, publish,
607 // distribute, sublicense, and/or sell copies of the Software, and to permit
608 // persons to whom the Software is furnished to do so, subject to the
609 // following conditions:
611 // The above copyright notice and this permission notice shall be included
612 // in all copies or substantial portions of the Software.
614 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
615 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
616 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
617 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
618 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
619 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
620 // USE OR OTHER DEALINGS IN THE SOFTWARE.
622 // resolves . and .. elements in a path array with directory names there
623 // must be no slashes, empty elements, or device names (c:\) in the array
624 // (so also no leading and trailing slashes - it does not distinguish
625 // relative and absolute paths)
626 function normalizeArray(parts, allowAboveRoot) {
627 // if the path tries to go above the root, `up` ends up > 0
629 for (var i = parts.length - 1; i >= 0; i--) {
633 } else if (last === '..') {
642 // if the path is allowed to go above the root, restore leading ..s
643 if (allowAboveRoot) {
652 // Split a filename into [root, dir, basename, ext], unix version
653 // 'root' is just a slash, or nothing.
655 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
656 var splitPath = function(filename) {
657 return splitPathRe.exec(filename).slice(1);
660 // path.resolve([from ...], to)
662 exports.resolve = function() {
663 var resolvedPath = '',
664 resolvedAbsolute = false;
666 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
667 var path = (i >= 0) ? arguments[i] : process.cwd();
669 // Skip empty and invalid entries
670 if (typeof path !== 'string') {
671 throw new TypeError('Arguments to path.resolve must be strings');
676 resolvedPath = path + '/' + resolvedPath;
677 resolvedAbsolute = path.charAt(0) === '/';
680 // At this point the path should be resolved to a full absolute path, but
681 // handle relative paths to be safe (might happen when process.cwd() fails)
683 // Normalize the path
684 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
686 }), !resolvedAbsolute).join('/');
688 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
691 // path.normalize(path)
693 exports.normalize = function(path) {
694 var isAbsolute = exports.isAbsolute(path),
695 trailingSlash = substr(path, -1) === '/';
697 // Normalize the path
698 path = normalizeArray(filter(path.split('/'), function(p) {
700 }), !isAbsolute).join('/');
702 if (!path && !isAbsolute) {
705 if (path && trailingSlash) {
709 return (isAbsolute ? '/' : '') + path;
713 exports.isAbsolute = function(path) {
714 return path.charAt(0) === '/';
718 exports.join = function() {
719 var paths = Array.prototype.slice.call(arguments, 0);
720 return exports.normalize(filter(paths, function(p, index) {
721 if (typeof p !== 'string') {
722 throw new TypeError('Arguments to path.join must be strings');
729 // path.relative(from, to)
731 exports.relative = function(from, to) {
732 from = exports.resolve(from).substr(1);
733 to = exports.resolve(to).substr(1);
737 for (; start < arr.length; start++) {
738 if (arr[start] !== '') break;
741 var end = arr.length - 1;
742 for (; end >= 0; end--) {
743 if (arr[end] !== '') break;
746 if (start > end) return [];
747 return arr.slice(start, end - start + 1);
750 var fromParts = trim(from.split('/'));
751 var toParts = trim(to.split('/'));
753 var length = Math.min(fromParts.length, toParts.length);
754 var samePartsLength = length;
755 for (var i = 0; i < length; i++) {
756 if (fromParts[i] !== toParts[i]) {
762 var outputParts = [];
763 for (var i = samePartsLength; i < fromParts.length; i++) {
764 outputParts.push('..');
767 outputParts = outputParts.concat(toParts.slice(samePartsLength));
769 return outputParts.join('/');
773 exports.delimiter = ':';
775 exports.dirname = function(path) {
776 var result = splitPath(path),
781 // No dirname whatsoever
786 // It has a dirname, strip trailing slash
787 dir = dir.substr(0, dir.length - 1);
794 exports.basename = function(path, ext) {
795 var f = splitPath(path)[2];
796 // TODO: make this comparison case-insensitive on windows?
797 if (ext && f.substr(-1 * ext.length) === ext) {
798 f = f.substr(0, f.length - ext.length);
804 exports.extname = function(path) {
805 return splitPath(path)[3];
808 function filter (xs, f) {
809 if (xs.filter) return xs.filter(f);
811 for (var i = 0; i < xs.length; i++) {
812 if (f(xs[i], i, xs)) res.push(xs[i]);
817 // String.prototype.substr - negative index don't work in IE8
818 var substr = 'ab'.substr(-1) === 'b'
819 ? function (str, start, len) { return str.substr(start, len) }
820 : function (str, start, len) {
821 if (start < 0) start = str.length + start;
822 return str.substr(start, len);
826 }).call(this,require('_process'))
827 },{"_process":5}],5:[function(require,module,exports){
828 // shim for using process in browser
830 var process = module.exports = {};
832 var draining = false;
834 function drainQueue() {
840 var len = queue.length;
842 currentQueue = queue;
852 process.nextTick = function (fun) {
855 setTimeout(drainQueue, 0);
859 process.title = 'browser';
860 process.browser = true;
863 process.version = ''; // empty string to avoid regexp issues
868 process.addListener = noop;
871 process.removeListener = noop;
872 process.removeAllListeners = noop;
875 process.binding = function (name) {
876 throw new Error('process.binding is not supported');
880 process.cwd = function () { return '/' };
881 process.chdir = function (dir) {
882 throw new Error('process.chdir is not supported');
884 process.umask = function() { return 0; };
886 },{}],6:[function(require,module,exports){
889 "description": "Embedded JavaScript templates",
896 "author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
898 "Timothy Gu <timothygu99@gmail.com> (https://timothygu.github.io)"
900 "license": "Apache-2.0",
901 "main": "./lib/ejs.js",
904 "url": "git://github.com/mde/ejs.git"
906 "bugs": "https://github.com/mde/ejs/issues",
907 "homepage": "https://github.com/mde/ejs",
910 "browserify": "^8.0.3",
911 "uglify-js": "^2.4.16",
921 "coverage": "istanbul cover node_modules/mocha/bin/_mocha"