ejs.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. if (options.strict) {
  481. options._with = false;
  482. }
  483. else {
  484. options._with = typeof opts._with != 'undefined' ? opts._with : true;
  485. }
  486. this.opts = options;
  487. this.regex = this.createRegex();
  488. }
  489. Template.modes = {
  490. EVAL: 'eval',
  491. ESCAPED: 'escaped',
  492. RAW: 'raw',
  493. COMMENT: 'comment',
  494. LITERAL: 'literal'
  495. };
  496. Template.prototype = {
  497. createRegex: function () {
  498. var str = _REGEX_STRING;
  499. var delim = utils.escapeRegExpChars(this.opts.delimiter);
  500. var open = utils.escapeRegExpChars(this.opts.openDelimiter);
  501. var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
  502. str = str.replace(/%/g, delim)
  503. .replace(/</g, open)
  504. .replace(/>/g, close);
  505. return new RegExp(str);
  506. },
  507. compile: function () {
  508. var src;
  509. var fn;
  510. var opts = this.opts;
  511. var prepended = '';
  512. var appended = '';
  513. var escapeFn = opts.escapeFunction;
  514. var ctor;
  515. if (!this.source) {
  516. this.generateSource();
  517. prepended += ' var __output = [], __append = __output.push.bind(__output);' + '\n';
  518. if (opts.outputFunctionName) {
  519. prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
  520. }
  521. if (opts._with !== false) {
  522. prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
  523. appended += ' }' + '\n';
  524. }
  525. appended += ' return __output.join("");' + '\n';
  526. this.source = prepended + this.source + appended;
  527. }
  528. if (opts.compileDebug) {
  529. src = 'var __line = 1' + '\n'
  530. + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
  531. + ' , __filename = ' + (opts.filename ?
  532. JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
  533. + 'try {' + '\n'
  534. + this.source
  535. + '} catch (e) {' + '\n'
  536. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  537. + '}' + '\n';
  538. }
  539. else {
  540. src = this.source;
  541. }
  542. if (opts.client) {
  543. src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
  544. if (opts.compileDebug) {
  545. src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
  546. }
  547. }
  548. if (opts.strict) {
  549. src = '"use strict";\n' + src;
  550. }
  551. if (opts.debug) {
  552. console.log(src);
  553. }
  554. try {
  555. if (opts.async) {
  556. // Have to use generated function for this, since in envs without support,
  557. // it breaks in parsing
  558. try {
  559. ctor = (new Function('return (async function(){}).constructor;'))();
  560. }
  561. catch(e) {
  562. if (e instanceof SyntaxError) {
  563. throw new Error('This environment does not support async/await');
  564. }
  565. else {
  566. throw e;
  567. }
  568. }
  569. }
  570. else {
  571. ctor = Function;
  572. }
  573. fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
  574. }
  575. catch(e) {
  576. // istanbul ignore else
  577. if (e instanceof SyntaxError) {
  578. if (opts.filename) {
  579. e.message += ' in ' + opts.filename;
  580. }
  581. e.message += ' while compiling ejs\n\n';
  582. e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
  583. e.message += 'https://github.com/RyanZim/EJS-Lint';
  584. if (!e.async) {
  585. e.message += '\n';
  586. e.message += 'Or, if you meant to create an async function, pass async: true as an option.';
  587. }
  588. }
  589. throw e;
  590. }
  591. if (opts.client) {
  592. fn.dependencies = this.dependencies;
  593. return fn;
  594. }
  595. // Return a callable function which will execute the function
  596. // created by the source-code, with the passed data as locals
  597. // Adds a local `include` function which allows full recursive include
  598. var returnedFn = function (data) {
  599. var include = function (path, includeData) {
  600. var d = utils.shallowCopy({}, data);
  601. if (includeData) {
  602. d = utils.shallowCopy(d, includeData);
  603. }
  604. return includeFile(path, opts)(d);
  605. };
  606. return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
  607. };
  608. returnedFn.dependencies = this.dependencies;
  609. return returnedFn;
  610. },
  611. generateSource: function () {
  612. var opts = this.opts;
  613. if (opts.rmWhitespace) {
  614. // Have to use two separate replace here as `^` and `$` operators don't
  615. // work well with `\r` and empty lines don't work well with the `m` flag.
  616. this.templateText =
  617. this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
  618. }
  619. // Slurp spaces and tabs before <%_ and after _%>
  620. this.templateText =
  621. this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
  622. var self = this;
  623. var matches = this.parseTemplateText();
  624. var d = this.opts.delimiter;
  625. var o = this.opts.openDelimiter;
  626. var c = this.opts.closeDelimiter;
  627. if (matches && matches.length) {
  628. matches.forEach(function (line, index) {
  629. var opening;
  630. var closing;
  631. var include;
  632. var includeOpts;
  633. var includeObj;
  634. var includeSrc;
  635. // If this is an opening tag, check for closing tags
  636. // FIXME: May end up with some false positives here
  637. // Better to store modes as k/v with openDelimiter + delimiter as key
  638. // Then this can simply check against the map
  639. if ( line.indexOf(o + d) === 0 // If it is a tag
  640. && line.indexOf(o + d + d) !== 0) { // and is not escaped
  641. closing = matches[index + 2];
  642. if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
  643. throw new Error('Could not find matching close tag for "' + line + '".');
  644. }
  645. }
  646. // HACK: backward-compat `include` preprocessor directives
  647. if ((include = line.match(/^\s*include\s+(\S+)/))) {
  648. opening = matches[index - 1];
  649. // Must be in EVAL or RAW mode
  650. if (opening && (opening == o + d || opening == o + d + '-' || opening == o + d + '_')) {
  651. includeOpts = utils.shallowCopy({}, self.opts);
  652. includeObj = includeSource(include[1], includeOpts);
  653. if (self.opts.compileDebug) {
  654. includeSrc =
  655. ' ; (function(){' + '\n'
  656. + ' var __line = 1' + '\n'
  657. + ' , __lines = ' + JSON.stringify(includeObj.template) + '\n'
  658. + ' , __filename = ' + JSON.stringify(includeObj.filename) + ';' + '\n'
  659. + ' try {' + '\n'
  660. + includeObj.source
  661. + ' } catch (e) {' + '\n'
  662. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  663. + ' }' + '\n'
  664. + ' ; }).call(this)' + '\n';
  665. }else{
  666. includeSrc = ' ; (function(){' + '\n' + includeObj.source +
  667. ' ; }).call(this)' + '\n';
  668. }
  669. self.source += includeSrc;
  670. self.dependencies.push(exports.resolveInclude(include[1],
  671. includeOpts.filename));
  672. return;
  673. }
  674. }
  675. self.scanLine(line);
  676. });
  677. }
  678. },
  679. parseTemplateText: function () {
  680. var str = this.templateText;
  681. var pat = this.regex;
  682. var result = pat.exec(str);
  683. var arr = [];
  684. var firstPos;
  685. while (result) {
  686. firstPos = result.index;
  687. if (firstPos !== 0) {
  688. arr.push(str.substring(0, firstPos));
  689. str = str.slice(firstPos);
  690. }
  691. arr.push(result[0]);
  692. str = str.slice(result[0].length);
  693. result = pat.exec(str);
  694. }
  695. if (str) {
  696. arr.push(str);
  697. }
  698. return arr;
  699. },
  700. _addOutput: function (line) {
  701. if (this.truncate) {
  702. // Only replace single leading linebreak in the line after
  703. // -%> tag -- this is the single, trailing linebreak
  704. // after the tag that the truncation mode replaces
  705. // Handle Win / Unix / old Mac linebreaks -- do the \r\n
  706. // combo first in the regex-or
  707. line = line.replace(/^(?:\r\n|\r|\n)/, '');
  708. this.truncate = false;
  709. }
  710. if (!line) {
  711. return line;
  712. }
  713. // Preserve literal slashes
  714. line = line.replace(/\\/g, '\\\\');
  715. // Convert linebreaks
  716. line = line.replace(/\n/g, '\\n');
  717. line = line.replace(/\r/g, '\\r');
  718. // Escape double-quotes
  719. // - this will be the delimiter during execution
  720. line = line.replace(/"/g, '\\"');
  721. this.source += ' ; __append("' + line + '")' + '\n';
  722. },
  723. scanLine: function (line) {
  724. var self = this;
  725. var d = this.opts.delimiter;
  726. var o = this.opts.openDelimiter;
  727. var c = this.opts.closeDelimiter;
  728. var newLineCount = 0;
  729. newLineCount = (line.split('\n').length - 1);
  730. switch (line) {
  731. case o + d:
  732. case o + d + '_':
  733. this.mode = Template.modes.EVAL;
  734. break;
  735. case o + d + '=':
  736. this.mode = Template.modes.ESCAPED;
  737. break;
  738. case o + d + '-':
  739. this.mode = Template.modes.RAW;
  740. break;
  741. case o + d + '#':
  742. this.mode = Template.modes.COMMENT;
  743. break;
  744. case o + d + d:
  745. this.mode = Template.modes.LITERAL;
  746. this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
  747. break;
  748. case d + d + c:
  749. this.mode = Template.modes.LITERAL;
  750. this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
  751. break;
  752. case d + c:
  753. case '-' + d + c:
  754. case '_' + d + c:
  755. if (this.mode == Template.modes.LITERAL) {
  756. this._addOutput(line);
  757. }
  758. this.mode = null;
  759. this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
  760. break;
  761. default:
  762. // In script mode, depends on type of tag
  763. if (this.mode) {
  764. // If '//' is found without a line break, add a line break.
  765. switch (this.mode) {
  766. case Template.modes.EVAL:
  767. case Template.modes.ESCAPED:
  768. case Template.modes.RAW:
  769. if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
  770. line += '\n';
  771. }
  772. }
  773. switch (this.mode) {
  774. // Just executing code
  775. case Template.modes.EVAL:
  776. this.source += ' ; ' + line + '\n';
  777. break;
  778. // Exec, esc, and output
  779. case Template.modes.ESCAPED:
  780. this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
  781. break;
  782. // Exec and output
  783. case Template.modes.RAW:
  784. this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
  785. break;
  786. case Template.modes.COMMENT:
  787. // Do nothing
  788. break;
  789. // Literal <%% mode, append as raw output
  790. case Template.modes.LITERAL:
  791. this._addOutput(line);
  792. break;
  793. }
  794. }
  795. // In string mode, just add the output
  796. else {
  797. this._addOutput(line);
  798. }
  799. }
  800. if (self.opts.compileDebug && newLineCount) {
  801. this.currentLine += newLineCount;
  802. this.source += ' ; __line = ' + this.currentLine + '\n';
  803. }
  804. }
  805. };
  806. /**
  807. * Escape characters reserved in XML.
  808. *
  809. * This is simply an export of {@link module:utils.escapeXML}.
  810. *
  811. * If `markup` is `undefined` or `null`, the empty string is returned.
  812. *
  813. * @param {String} markup Input string
  814. * @return {String} Escaped string
  815. * @public
  816. * @func
  817. * */
  818. exports.escapeXML = utils.escapeXML;
  819. /**
  820. * Express.js support.
  821. *
  822. * This is an alias for {@link module:ejs.renderFile}, in order to support
  823. * Express.js out-of-the-box.
  824. *
  825. * @func
  826. */
  827. exports.__express = exports.renderFile;
  828. // Add require support
  829. /* istanbul ignore else */
  830. if (require.extensions) {
  831. require.extensions['.ejs'] = function (module, flnm) {
  832. var filename = flnm || /* istanbul ignore next */ module.filename;
  833. var options = {
  834. filename: filename,
  835. client: true
  836. };
  837. var template = fileLoader(filename).toString();
  838. var fn = exports.compile(template, options);
  839. module._compile('module.exports = ' + fn.toString() + ';', filename);
  840. };
  841. }
  842. /**
  843. * Version of EJS.
  844. *
  845. * @readonly
  846. * @type {String}
  847. * @public
  848. */
  849. exports.VERSION = _VERSION_STRING;
  850. /**
  851. * Name for detection of EJS.
  852. *
  853. * @readonly
  854. * @type {String}
  855. * @public
  856. */
  857. exports.name = _NAME;
  858. /* istanbul ignore if */
  859. if (typeof window != 'undefined') {
  860. window.ejs = exports;
  861. }