ejs.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. /*
  2. * EJS Embedded JavaScript templates
  3. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. 'use strict';
  19. /**
  20. * @file Embedded JavaScript templating engine. {@link http://ejs.co}
  21. * @author Matthew Eernisse <mde@fleegix.org>
  22. * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
  23. * @project EJS
  24. * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
  25. */
  26. /**
  27. * EJS internal functions.
  28. *
  29. * Technically this "module" lies in the same file as {@link module:ejs}, for
  30. * the sake of organization all the private functions re grouped into this
  31. * module.
  32. *
  33. * @module ejs-internal
  34. * @private
  35. */
  36. /**
  37. * Embedded JavaScript templating engine.
  38. *
  39. * @module ejs
  40. * @public
  41. */
  42. var fs = require('fs');
  43. var path = require('path');
  44. var utils = require('./utils');
  45. var scopeOptionWarned = false;
  46. var _VERSION_STRING = require('../package.json').version;
  47. var _DEFAULT_OPEN_DELIMITER = '<';
  48. var _DEFAULT_CLOSE_DELIMITER = '>';
  49. var _DEFAULT_DELIMITER = '%';
  50. var _DEFAULT_LOCALS_NAME = 'locals';
  51. var _NAME = 'ejs';
  52. var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
  53. var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
  54. 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
  55. // We don't allow 'cache' option to be passed in the data obj for
  56. // the normal `render` call, but this is where Express 2 & 3 put it
  57. // so we make an exception for `renderFile`
  58. var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
  59. var _BOM = /^\uFEFF/;
  60. /**
  61. * EJS template function cache. This can be a LRU object from lru-cache NPM
  62. * module. By default, it is {@link module:utils.cache}, a simple in-process
  63. * cache that grows continuously.
  64. *
  65. * @type {Cache}
  66. */
  67. exports.cache = utils.cache;
  68. /**
  69. * Custom file loader. Useful for template preprocessing or restricting access
  70. * to a certain part of the filesystem.
  71. *
  72. * @type {fileLoader}
  73. */
  74. exports.fileLoader = fs.readFileSync;
  75. /**
  76. * Name of the object containing the locals.
  77. *
  78. * This variable is overridden by {@link Options}`.localsName` if it is not
  79. * `undefined`.
  80. *
  81. * @type {String}
  82. * @public
  83. */
  84. exports.localsName = _DEFAULT_LOCALS_NAME;
  85. /**
  86. * Promise implementation -- defaults to the native implementation if available
  87. * This is mostly just for testability
  88. *
  89. * @type {Function}
  90. * @public
  91. */
  92. exports.promiseImpl = (new Function('return this;'))().Promise;
  93. /**
  94. * Get the path to the included file from the parent file path and the
  95. * specified path.
  96. *
  97. * @param {String} name specified path
  98. * @param {String} filename parent file path
  99. * @param {Boolean} isDir parent file path whether is directory
  100. * @return {String}
  101. */
  102. exports.resolveInclude = function(name, filename, isDir) {
  103. var dirname = path.dirname;
  104. var extname = path.extname;
  105. var resolve = path.resolve;
  106. var includePath = resolve(isDir ? filename : dirname(filename), name);
  107. var ext = extname(name);
  108. if (!ext) {
  109. includePath += '.ejs';
  110. }
  111. return includePath;
  112. };
  113. /**
  114. * Get the path to the included file by Options
  115. *
  116. * @param {String} path specified path
  117. * @param {Options} options compilation options
  118. * @return {String}
  119. */
  120. function getIncludePath(path, options) {
  121. var includePath;
  122. var filePath;
  123. var views = options.views;
  124. var match = /^[A-Za-z]+:\\|^\//.exec(path);
  125. // Abs path
  126. if (match && match.length) {
  127. includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true);
  128. }
  129. // Relative paths
  130. else {
  131. // Look relative to a passed filename first
  132. if (options.filename) {
  133. filePath = exports.resolveInclude(path, options.filename);
  134. if (fs.existsSync(filePath)) {
  135. includePath = filePath;
  136. }
  137. }
  138. // Then look in any views directories
  139. if (!includePath) {
  140. if (Array.isArray(views) && views.some(function (v) {
  141. filePath = exports.resolveInclude(path, v, true);
  142. return fs.existsSync(filePath);
  143. })) {
  144. includePath = filePath;
  145. }
  146. }
  147. if (!includePath) {
  148. throw new Error('Could not find the include file "' +
  149. options.escapeFunction(path) + '"');
  150. }
  151. }
  152. return includePath;
  153. }
  154. /**
  155. * Get the template from a string or a file, either compiled on-the-fly or
  156. * read from cache (if enabled), and cache the template if needed.
  157. *
  158. * If `template` is not set, the file specified in `options.filename` will be
  159. * read.
  160. *
  161. * If `options.cache` is true, this function reads the file from
  162. * `options.filename` so it must be set prior to calling this function.
  163. *
  164. * @memberof module:ejs-internal
  165. * @param {Options} options compilation options
  166. * @param {String} [template] template source
  167. * @return {(TemplateFunction|ClientFunction)}
  168. * Depending on the value of `options.client`, either type might be returned.
  169. * @static
  170. */
  171. function handleCache(options, template) {
  172. var func;
  173. var filename = options.filename;
  174. var hasTemplate = arguments.length > 1;
  175. if (options.cache) {
  176. if (!filename) {
  177. throw new Error('cache option requires a filename');
  178. }
  179. func = exports.cache.get(filename);
  180. if (func) {
  181. return func;
  182. }
  183. if (!hasTemplate) {
  184. template = fileLoader(filename).toString().replace(_BOM, '');
  185. }
  186. }
  187. else if (!hasTemplate) {
  188. // istanbul ignore if: should not happen at all
  189. if (!filename) {
  190. throw new Error('Internal EJS error: no file name or template '
  191. + 'provided');
  192. }
  193. template = fileLoader(filename).toString().replace(_BOM, '');
  194. }
  195. func = exports.compile(template, options);
  196. if (options.cache) {
  197. exports.cache.set(filename, func);
  198. }
  199. return func;
  200. }
  201. /**
  202. * Try calling handleCache with the given options and data and call the
  203. * callback with the result. If an error occurs, call the callback with
  204. * the error. Used by renderFile().
  205. *
  206. * @memberof module:ejs-internal
  207. * @param {Options} options compilation options
  208. * @param {Object} data template data
  209. * @param {RenderFileCallback} cb callback
  210. * @static
  211. */
  212. function tryHandleCache(options, data, cb) {
  213. var result;
  214. if (!cb) {
  215. if (typeof exports.promiseImpl == 'function') {
  216. return new exports.promiseImpl(function (resolve, reject) {
  217. try {
  218. result = handleCache(options)(data);
  219. resolve(result);
  220. }
  221. catch (err) {
  222. reject(err);
  223. }
  224. });
  225. }
  226. else {
  227. throw new Error('Please provide a callback function');
  228. }
  229. }
  230. else {
  231. try {
  232. result = handleCache(options)(data);
  233. }
  234. catch (err) {
  235. return cb(err);
  236. }
  237. cb(null, result);
  238. }
  239. }
  240. /**
  241. * fileLoader is independent
  242. *
  243. * @param {String} filePath ejs file path.
  244. * @return {String} The contents of the specified file.
  245. * @static
  246. */
  247. function fileLoader(filePath){
  248. return exports.fileLoader(filePath);
  249. }
  250. /**
  251. * Get the template function.
  252. *
  253. * If `options.cache` is `true`, then the template is cached.
  254. *
  255. * @memberof module:ejs-internal
  256. * @param {String} path path for the specified file
  257. * @param {Options} options compilation options
  258. * @return {(TemplateFunction|ClientFunction)}
  259. * Depending on the value of `options.client`, either type might be returned
  260. * @static
  261. */
  262. function includeFile(path, options) {
  263. var opts = utils.shallowCopy({}, options);
  264. opts.filename = getIncludePath(path, opts);
  265. return handleCache(opts);
  266. }
  267. /**
  268. * Get the JavaScript source of an included file.
  269. *
  270. * @memberof module:ejs-internal
  271. * @param {String} path path for the specified file
  272. * @param {Options} options compilation options
  273. * @return {Object}
  274. * @static
  275. */
  276. function includeSource(path, options) {
  277. var opts = utils.shallowCopy({}, options);
  278. var includePath;
  279. var template;
  280. includePath = getIncludePath(path, opts);
  281. template = fileLoader(includePath).toString().replace(_BOM, '');
  282. opts.filename = includePath;
  283. var templ = new Template(template, opts);
  284. templ.generateSource();
  285. return {
  286. source: templ.source,
  287. filename: includePath,
  288. template: template
  289. };
  290. }
  291. /**
  292. * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
  293. * `lineno`.
  294. *
  295. * @implements RethrowCallback
  296. * @memberof module:ejs-internal
  297. * @param {Error} err Error object
  298. * @param {String} str EJS source
  299. * @param {String} filename file name of the EJS file
  300. * @param {String} lineno line number of the error
  301. * @static
  302. */
  303. function rethrow(err, str, flnm, lineno, esc){
  304. var lines = str.split('\n');
  305. var start = Math.max(lineno - 3, 0);
  306. var end = Math.min(lines.length, lineno + 3);
  307. var filename = esc(flnm); // eslint-disable-line
  308. // Error context
  309. var context = lines.slice(start, end).map(function (line, i){
  310. var curr = i + start + 1;
  311. return (curr == lineno ? ' >> ' : ' ')
  312. + curr
  313. + '| '
  314. + line;
  315. }).join('\n');
  316. // Alter exception message
  317. err.path = filename;
  318. err.message = (filename || 'ejs') + ':'
  319. + lineno + '\n'
  320. + context + '\n\n'
  321. + err.message;
  322. throw err;
  323. }
  324. function stripSemi(str){
  325. return str.replace(/;(\s*$)/, '$1');
  326. }
  327. /**
  328. * Compile the given `str` of ejs into a template function.
  329. *
  330. * @param {String} template EJS template
  331. *
  332. * @param {Options} opts compilation options
  333. *
  334. * @return {(TemplateFunction|ClientFunction)}
  335. * Depending on the value of `opts.client`, either type might be returned.
  336. * Note that the return type of the function also depends on the value of `opts.async`.
  337. * @public
  338. */
  339. exports.compile = function compile(template, opts) {
  340. var templ;
  341. // v1 compat
  342. // 'scope' is 'context'
  343. // FIXME: Remove this in a future version
  344. if (opts && opts.scope) {
  345. if (!scopeOptionWarned){
  346. console.warn('`scope` option is deprecated and will be removed in EJS 3');
  347. scopeOptionWarned = true;
  348. }
  349. if (!opts.context) {
  350. opts.context = opts.scope;
  351. }
  352. delete opts.scope;
  353. }
  354. templ = new Template(template, opts);
  355. return templ.compile();
  356. };
  357. /**
  358. * Render the given `template` of ejs.
  359. *
  360. * If you would like to include options but not data, you need to explicitly
  361. * call this function with `data` being an empty object or `null`.
  362. *
  363. * @param {String} template EJS template
  364. * @param {Object} [data={}] template data
  365. * @param {Options} [opts={}] compilation and rendering options
  366. * @return {(String|Promise<String>)}
  367. * Return value type depends on `opts.async`.
  368. * @public
  369. */
  370. exports.render = function (template, d, o) {
  371. var data = d || {};
  372. var opts = o || {};
  373. // No options object -- if there are optiony names
  374. // in the data, copy them to options
  375. if (arguments.length == 2) {
  376. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
  377. }
  378. return handleCache(opts, template)(data);
  379. };
  380. /**
  381. * Render an EJS file at the given `path` and callback `cb(err, str)`.
  382. *
  383. * If you would like to include options but not data, you need to explicitly
  384. * call this function with `data` being an empty object or `null`.
  385. *
  386. * @param {String} path path to the EJS file
  387. * @param {Object} [data={}] template data
  388. * @param {Options} [opts={}] compilation and rendering options
  389. * @param {RenderFileCallback} cb callback
  390. * @public
  391. */
  392. exports.renderFile = function () {
  393. var args = Array.prototype.slice.call(arguments);
  394. var filename = args.shift();
  395. var cb;
  396. var opts = {filename: filename};
  397. var data;
  398. var viewOpts;
  399. // Do we have a callback?
  400. if (typeof arguments[arguments.length - 1] == 'function') {
  401. cb = args.pop();
  402. }
  403. // Do we have data/opts?
  404. if (args.length) {
  405. // Should always have data obj
  406. data = args.shift();
  407. // Normal passed opts (data obj + opts obj)
  408. if (args.length) {
  409. // Use shallowCopy so we don't pollute passed in opts obj with new vals
  410. utils.shallowCopy(opts, args.pop());
  411. }
  412. // Special casing for Express (settings + opts-in-data)
  413. else {
  414. // Express 3 and 4
  415. if (data.settings) {
  416. // Pull a few things from known locations
  417. if (data.settings.views) {
  418. opts.views = data.settings.views;
  419. }
  420. if (data.settings['view cache']) {
  421. opts.cache = true;
  422. }
  423. // Undocumented after Express 2, but still usable, esp. for
  424. // items that are unsafe to be passed along with data, like `root`
  425. viewOpts = data.settings['view options'];
  426. if (viewOpts) {
  427. utils.shallowCopy(opts, viewOpts);
  428. }
  429. }
  430. // Express 2 and lower, values set in app.locals, or people who just
  431. // want to pass options in their data. NOTE: These values will override
  432. // anything previously set in settings or settings['view options']
  433. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
  434. }
  435. opts.filename = filename;
  436. }
  437. else {
  438. data = {};
  439. }
  440. return tryHandleCache(opts, data, cb);
  441. };
  442. /**
  443. * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
  444. * @public
  445. */
  446. /**
  447. * EJS template class
  448. * @public
  449. */
  450. exports.Template = Template;
  451. exports.clearCache = function () {
  452. exports.cache.reset();
  453. };
  454. function Template(text, opts) {
  455. opts = opts || {};
  456. var options = {};
  457. this.templateText = text;
  458. this.mode = null;
  459. this.truncate = false;
  460. this.currentLine = 1;
  461. this.source = '';
  462. this.dependencies = [];
  463. options.client = opts.client || false;
  464. options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
  465. options.compileDebug = opts.compileDebug !== false;
  466. options.debug = !!opts.debug;
  467. options.filename = opts.filename;
  468. options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
  469. options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
  470. options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
  471. options.strict = opts.strict || false;
  472. options.context = opts.context;
  473. options.cache = opts.cache || false;
  474. options.rmWhitespace = opts.rmWhitespace;
  475. options.root = opts.root;
  476. options.outputFunctionName = opts.outputFunctionName;
  477. options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
  478. options.views = opts.views;
  479. options.async = opts.async;
  480. options.destructuredLocals = opts.destructuredLocals;
  481. options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
  482. if (options.strict) {
  483. options._with = false;
  484. }
  485. else {
  486. options._with = typeof opts._with != 'undefined' ? opts._with : true;
  487. }
  488. this.opts = options;
  489. this.regex = this.createRegex();
  490. }
  491. Template.modes = {
  492. EVAL: 'eval',
  493. ESCAPED: 'escaped',
  494. RAW: 'raw',
  495. COMMENT: 'comment',
  496. LITERAL: 'literal'
  497. };
  498. Template.prototype = {
  499. createRegex: function () {
  500. var str = _REGEX_STRING;
  501. var delim = utils.escapeRegExpChars(this.opts.delimiter);
  502. var open = utils.escapeRegExpChars(this.opts.openDelimiter);
  503. var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
  504. str = str.replace(/%/g, delim)
  505. .replace(/</g, open)
  506. .replace(/>/g, close);
  507. return new RegExp(str);
  508. },
  509. compile: function () {
  510. var src;
  511. var fn;
  512. var opts = this.opts;
  513. var prepended = '';
  514. var appended = '';
  515. var escapeFn = opts.escapeFunction;
  516. var ctor;
  517. if (!this.source) {
  518. this.generateSource();
  519. prepended +=
  520. ' var __output = "";\n' +
  521. ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
  522. if (opts.outputFunctionName) {
  523. prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
  524. }
  525. if (opts.destructuredLocals && opts.destructuredLocals.length) {
  526. var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
  527. for (var i = 0; i < opts.destructuredLocals.length; i++) {
  528. var name = opts.destructuredLocals[i];
  529. if (i > 0) {
  530. destructuring += ',\n ';
  531. }
  532. destructuring += name + ' = __locals.' + name;
  533. }
  534. prepended += destructuring + ';\n';
  535. }
  536. if (opts._with !== false) {
  537. prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
  538. appended += ' }' + '\n';
  539. }
  540. appended += ' return __output;' + '\n';
  541. this.source = prepended + this.source + appended;
  542. }
  543. if (opts.compileDebug) {
  544. src = 'var __line = 1' + '\n'
  545. + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
  546. + ' , __filename = ' + (opts.filename ?
  547. JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
  548. + 'try {' + '\n'
  549. + this.source
  550. + '} catch (e) {' + '\n'
  551. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  552. + '}' + '\n';
  553. }
  554. else {
  555. src = this.source;
  556. }
  557. if (opts.client) {
  558. src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
  559. if (opts.compileDebug) {
  560. src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
  561. }
  562. }
  563. if (opts.strict) {
  564. src = '"use strict";\n' + src;
  565. }
  566. if (opts.debug) {
  567. console.log(src);
  568. }
  569. if (opts.compileDebug && opts.filename) {
  570. src = src + '\n'
  571. + '//# sourceURL=' + opts.filename + '\n';
  572. }
  573. try {
  574. if (opts.async) {
  575. // Have to use generated function for this, since in envs without support,
  576. // it breaks in parsing
  577. try {
  578. ctor = (new Function('return (async function(){}).constructor;'))();
  579. }
  580. catch(e) {
  581. if (e instanceof SyntaxError) {
  582. throw new Error('This environment does not support async/await');
  583. }
  584. else {
  585. throw e;
  586. }
  587. }
  588. }
  589. else {
  590. ctor = Function;
  591. }
  592. fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
  593. }
  594. catch(e) {
  595. // istanbul ignore else
  596. if (e instanceof SyntaxError) {
  597. if (opts.filename) {
  598. e.message += ' in ' + opts.filename;
  599. }
  600. e.message += ' while compiling ejs\n\n';
  601. e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
  602. e.message += 'https://github.com/RyanZim/EJS-Lint';
  603. if (!opts.async) {
  604. e.message += '\n';
  605. e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
  606. }
  607. }
  608. throw e;
  609. }
  610. // Return a callable function which will execute the function
  611. // created by the source-code, with the passed data as locals
  612. // Adds a local `include` function which allows full recursive include
  613. var returnedFn = opts.client ? fn : function anonymous(data) {
  614. var include = function (path, includeData) {
  615. var d = utils.shallowCopy({}, data);
  616. if (includeData) {
  617. d = utils.shallowCopy(d, includeData);
  618. }
  619. return includeFile(path, opts)(d);
  620. };
  621. return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
  622. };
  623. returnedFn.dependencies = this.dependencies;
  624. if (opts.filename && typeof Object.defineProperty === 'function') {
  625. var filename = opts.filename;
  626. var basename = path.basename(filename, path.extname(filename));
  627. try {
  628. Object.defineProperty(returnedFn, 'name', {
  629. value: basename,
  630. writable: false,
  631. enumerable: false,
  632. configurable: true
  633. });
  634. } catch (e) {/* ignore */}
  635. }
  636. return returnedFn;
  637. },
  638. generateSource: function () {
  639. var opts = this.opts;
  640. if (opts.rmWhitespace) {
  641. // Have to use two separate replace here as `^` and `$` operators don't
  642. // work well with `\r` and empty lines don't work well with the `m` flag.
  643. this.templateText =
  644. this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
  645. }
  646. // Slurp spaces and tabs before <%_ and after _%>
  647. this.templateText =
  648. this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
  649. var self = this;
  650. var matches = this.parseTemplateText();
  651. var d = this.opts.delimiter;
  652. var o = this.opts.openDelimiter;
  653. var c = this.opts.closeDelimiter;
  654. if (matches && matches.length) {
  655. matches.forEach(function (line, index) {
  656. var opening;
  657. var closing;
  658. var include;
  659. var includeOpts;
  660. var includeObj;
  661. var includeSrc;
  662. // If this is an opening tag, check for closing tags
  663. // FIXME: May end up with some false positives here
  664. // Better to store modes as k/v with openDelimiter + delimiter as key
  665. // Then this can simply check against the map
  666. if ( line.indexOf(o + d) === 0 // If it is a tag
  667. && line.indexOf(o + d + d) !== 0) { // and is not escaped
  668. closing = matches[index + 2];
  669. if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
  670. throw new Error('Could not find matching close tag for "' + line + '".');
  671. }
  672. }
  673. // HACK: backward-compat `include` preprocessor directives
  674. if (opts.legacyInclude && (include = line.match(/^\s*include\s+(\S+)/))) {
  675. opening = matches[index - 1];
  676. // Must be in EVAL or RAW mode
  677. if (opening && (opening == o + d || opening == o + d + '-' || opening == o + d + '_')) {
  678. includeOpts = utils.shallowCopy({}, self.opts);
  679. includeObj = includeSource(include[1], includeOpts);
  680. if (self.opts.compileDebug) {
  681. includeSrc =
  682. ' ; (function(){' + '\n'
  683. + ' var __line = 1' + '\n'
  684. + ' , __lines = ' + JSON.stringify(includeObj.template) + '\n'
  685. + ' , __filename = ' + JSON.stringify(includeObj.filename) + ';' + '\n'
  686. + ' try {' + '\n'
  687. + includeObj.source
  688. + ' } catch (e) {' + '\n'
  689. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  690. + ' }' + '\n'
  691. + ' ; }).call(this)' + '\n';
  692. }else{
  693. includeSrc = ' ; (function(){' + '\n' + includeObj.source +
  694. ' ; }).call(this)' + '\n';
  695. }
  696. self.source += includeSrc;
  697. self.dependencies.push(exports.resolveInclude(include[1],
  698. includeOpts.filename));
  699. return;
  700. }
  701. }
  702. self.scanLine(line);
  703. });
  704. }
  705. },
  706. parseTemplateText: function () {
  707. var str = this.templateText;
  708. var pat = this.regex;
  709. var result = pat.exec(str);
  710. var arr = [];
  711. var firstPos;
  712. while (result) {
  713. firstPos = result.index;
  714. if (firstPos !== 0) {
  715. arr.push(str.substring(0, firstPos));
  716. str = str.slice(firstPos);
  717. }
  718. arr.push(result[0]);
  719. str = str.slice(result[0].length);
  720. result = pat.exec(str);
  721. }
  722. if (str) {
  723. arr.push(str);
  724. }
  725. return arr;
  726. },
  727. _addOutput: function (line) {
  728. if (this.truncate) {
  729. // Only replace single leading linebreak in the line after
  730. // -%> tag -- this is the single, trailing linebreak
  731. // after the tag that the truncation mode replaces
  732. // Handle Win / Unix / old Mac linebreaks -- do the \r\n
  733. // combo first in the regex-or
  734. line = line.replace(/^(?:\r\n|\r|\n)/, '');
  735. this.truncate = false;
  736. }
  737. if (!line) {
  738. return line;
  739. }
  740. // Preserve literal slashes
  741. line = line.replace(/\\/g, '\\\\');
  742. // Convert linebreaks
  743. line = line.replace(/\n/g, '\\n');
  744. line = line.replace(/\r/g, '\\r');
  745. // Escape double-quotes
  746. // - this will be the delimiter during execution
  747. line = line.replace(/"/g, '\\"');
  748. this.source += ' ; __append("' + line + '")' + '\n';
  749. },
  750. scanLine: function (line) {
  751. var self = this;
  752. var d = this.opts.delimiter;
  753. var o = this.opts.openDelimiter;
  754. var c = this.opts.closeDelimiter;
  755. var newLineCount = 0;
  756. newLineCount = (line.split('\n').length - 1);
  757. switch (line) {
  758. case o + d:
  759. case o + d + '_':
  760. this.mode = Template.modes.EVAL;
  761. break;
  762. case o + d + '=':
  763. this.mode = Template.modes.ESCAPED;
  764. break;
  765. case o + d + '-':
  766. this.mode = Template.modes.RAW;
  767. break;
  768. case o + d + '#':
  769. this.mode = Template.modes.COMMENT;
  770. break;
  771. case o + d + d:
  772. this.mode = Template.modes.LITERAL;
  773. this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
  774. break;
  775. case d + d + c:
  776. this.mode = Template.modes.LITERAL;
  777. this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
  778. break;
  779. case d + c:
  780. case '-' + d + c:
  781. case '_' + d + c:
  782. if (this.mode == Template.modes.LITERAL) {
  783. this._addOutput(line);
  784. }
  785. this.mode = null;
  786. this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
  787. break;
  788. default:
  789. // In script mode, depends on type of tag
  790. if (this.mode) {
  791. // If '//' is found without a line break, add a line break.
  792. switch (this.mode) {
  793. case Template.modes.EVAL:
  794. case Template.modes.ESCAPED:
  795. case Template.modes.RAW:
  796. if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
  797. line += '\n';
  798. }
  799. }
  800. switch (this.mode) {
  801. // Just executing code
  802. case Template.modes.EVAL:
  803. this.source += ' ; ' + line + '\n';
  804. break;
  805. // Exec, esc, and output
  806. case Template.modes.ESCAPED:
  807. this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
  808. break;
  809. // Exec and output
  810. case Template.modes.RAW:
  811. this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
  812. break;
  813. case Template.modes.COMMENT:
  814. // Do nothing
  815. break;
  816. // Literal <%% mode, append as raw output
  817. case Template.modes.LITERAL:
  818. this._addOutput(line);
  819. break;
  820. }
  821. }
  822. // In string mode, just add the output
  823. else {
  824. this._addOutput(line);
  825. }
  826. }
  827. if (self.opts.compileDebug && newLineCount) {
  828. this.currentLine += newLineCount;
  829. this.source += ' ; __line = ' + this.currentLine + '\n';
  830. }
  831. }
  832. };
  833. /**
  834. * Escape characters reserved in XML.
  835. *
  836. * This is simply an export of {@link module:utils.escapeXML}.
  837. *
  838. * If `markup` is `undefined` or `null`, the empty string is returned.
  839. *
  840. * @param {String} markup Input string
  841. * @return {String} Escaped string
  842. * @public
  843. * @func
  844. * */
  845. exports.escapeXML = utils.escapeXML;
  846. /**
  847. * Express.js support.
  848. *
  849. * This is an alias for {@link module:ejs.renderFile}, in order to support
  850. * Express.js out-of-the-box.
  851. *
  852. * @func
  853. */
  854. exports.__express = exports.renderFile;
  855. // Add require support
  856. /* istanbul ignore else */
  857. if (require.extensions) {
  858. require.extensions['.ejs'] = function (module, flnm) {
  859. console.log('Deprecated: this API will go away in EJS v2.8');
  860. var filename = flnm || /* istanbul ignore next */ module.filename;
  861. var options = {
  862. filename: filename,
  863. client: true
  864. };
  865. var template = fileLoader(filename).toString();
  866. var fn = exports.compile(template, options);
  867. module._compile('module.exports = ' + fn.toString() + ';', filename);
  868. };
  869. }
  870. /**
  871. * Version of EJS.
  872. *
  873. * @readonly
  874. * @type {String}
  875. * @public
  876. */
  877. exports.VERSION = _VERSION_STRING;
  878. /**
  879. * Name for detection of EJS.
  880. *
  881. * @readonly
  882. * @type {String}
  883. * @public
  884. */
  885. exports.name = _NAME;
  886. /* istanbul ignore if */
  887. if (typeof window != 'undefined') {
  888. window.ejs = exports;
  889. }