ejs.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /*
  3. * EJS Embedded JavaScript templates
  4. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. 'use strict';
  20. /**
  21. * @file Embedded JavaScript templating engine. {@link http://ejs.co}
  22. * @author Matthew Eernisse <mde@fleegix.org>
  23. * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
  24. * @project EJS
  25. * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
  26. */
  27. /**
  28. * EJS internal functions.
  29. *
  30. * Technically this "module" lies in the same file as {@link module:ejs}, for
  31. * the sake of organization all the private functions re grouped into this
  32. * module.
  33. *
  34. * @module ejs-internal
  35. * @private
  36. */
  37. /**
  38. * Embedded JavaScript templating engine.
  39. *
  40. * @module ejs
  41. * @public
  42. */
  43. var fs = require('fs');
  44. var path = require('path');
  45. var utils = require('./utils');
  46. var scopeOptionWarned = false;
  47. /** @type {string} */
  48. var _VERSION_STRING = require('../package.json').version;
  49. var _DEFAULT_OPEN_DELIMITER = '<';
  50. var _DEFAULT_CLOSE_DELIMITER = '>';
  51. var _DEFAULT_DELIMITER = '%';
  52. var _DEFAULT_LOCALS_NAME = 'locals';
  53. var _NAME = 'ejs';
  54. var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
  55. var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
  56. 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
  57. // We don't allow 'cache' option to be passed in the data obj for
  58. // the normal `render` call, but this is where Express 2 & 3 put it
  59. // so we make an exception for `renderFile`
  60. var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
  61. var _BOM = /^\uFEFF/;
  62. var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
  63. /**
  64. * EJS template function cache. This can be a LRU object from lru-cache NPM
  65. * module. By default, it is {@link module:utils.cache}, a simple in-process
  66. * cache that grows continuously.
  67. *
  68. * @type {Cache}
  69. */
  70. exports.cache = utils.cache;
  71. /**
  72. * Custom file loader. Useful for template preprocessing or restricting access
  73. * to a certain part of the filesystem.
  74. *
  75. * @type {fileLoader}
  76. */
  77. exports.fileLoader = fs.readFileSync;
  78. /**
  79. * Name of the object containing the locals.
  80. *
  81. * This variable is overridden by {@link Options}`.localsName` if it is not
  82. * `undefined`.
  83. *
  84. * @type {String}
  85. * @public
  86. */
  87. exports.localsName = _DEFAULT_LOCALS_NAME;
  88. /**
  89. * Promise implementation -- defaults to the native implementation if available
  90. * This is mostly just for testability
  91. *
  92. * @type {PromiseConstructorLike}
  93. * @public
  94. */
  95. exports.promiseImpl = (new Function('return this;'))().Promise;
  96. /**
  97. * Get the path to the included file from the parent file path and the
  98. * specified path.
  99. *
  100. * @param {String} name specified path
  101. * @param {String} filename parent file path
  102. * @param {Boolean} [isDir=false] whether the parent file path is a directory
  103. * @return {String}
  104. */
  105. exports.resolveInclude = function(name, filename, isDir) {
  106. var dirname = path.dirname;
  107. var extname = path.extname;
  108. var resolve = path.resolve;
  109. var includePath = resolve(isDir ? filename : dirname(filename), name);
  110. var ext = extname(name);
  111. if (!ext) {
  112. includePath += '.ejs';
  113. }
  114. return includePath;
  115. };
  116. /**
  117. * Try to resolve file path on multiple directories
  118. *
  119. * @param {String} name specified path
  120. * @param {Array<String>} paths list of possible parent directory paths
  121. * @return {String}
  122. */
  123. function resolvePaths(name, paths) {
  124. var filePath;
  125. if (paths.some(function (v) {
  126. filePath = exports.resolveInclude(name, v, true);
  127. return fs.existsSync(filePath);
  128. })) {
  129. return filePath;
  130. }
  131. }
  132. /**
  133. * Get the path to the included file by Options
  134. *
  135. * @param {String} path specified path
  136. * @param {Options} options compilation options
  137. * @return {String}
  138. */
  139. function getIncludePath(path, options) {
  140. var includePath;
  141. var filePath;
  142. var views = options.views;
  143. var match = /^[A-Za-z]+:\\|^\//.exec(path);
  144. // Abs path
  145. if (match && match.length) {
  146. path = path.replace(/^\/*/, '');
  147. if (Array.isArray(options.root)) {
  148. includePath = resolvePaths(path, options.root);
  149. } else {
  150. includePath = exports.resolveInclude(path, options.root || '/', true);
  151. }
  152. }
  153. // Relative paths
  154. else {
  155. // Look relative to a passed filename first
  156. if (options.filename) {
  157. filePath = exports.resolveInclude(path, options.filename);
  158. if (fs.existsSync(filePath)) {
  159. includePath = filePath;
  160. }
  161. }
  162. // Then look in any views directories
  163. if (!includePath && Array.isArray(views)) {
  164. includePath = resolvePaths(path, views);
  165. }
  166. if (!includePath && typeof options.includer !== 'function') {
  167. throw new Error('Could not find the include file "' +
  168. options.escapeFunction(path) + '"');
  169. }
  170. }
  171. return includePath;
  172. }
  173. /**
  174. * Get the template from a string or a file, either compiled on-the-fly or
  175. * read from cache (if enabled), and cache the template if needed.
  176. *
  177. * If `template` is not set, the file specified in `options.filename` will be
  178. * read.
  179. *
  180. * If `options.cache` is true, this function reads the file from
  181. * `options.filename` so it must be set prior to calling this function.
  182. *
  183. * @memberof module:ejs-internal
  184. * @param {Options} options compilation options
  185. * @param {String} [template] template source
  186. * @return {(TemplateFunction|ClientFunction)}
  187. * Depending on the value of `options.client`, either type might be returned.
  188. * @static
  189. */
  190. function handleCache(options, template) {
  191. var func;
  192. var filename = options.filename;
  193. var hasTemplate = arguments.length > 1;
  194. if (options.cache) {
  195. if (!filename) {
  196. throw new Error('cache option requires a filename');
  197. }
  198. func = exports.cache.get(filename);
  199. if (func) {
  200. return func;
  201. }
  202. if (!hasTemplate) {
  203. template = fileLoader(filename).toString().replace(_BOM, '');
  204. }
  205. }
  206. else if (!hasTemplate) {
  207. // istanbul ignore if: should not happen at all
  208. if (!filename) {
  209. throw new Error('Internal EJS error: no file name or template '
  210. + 'provided');
  211. }
  212. template = fileLoader(filename).toString().replace(_BOM, '');
  213. }
  214. func = exports.compile(template, options);
  215. if (options.cache) {
  216. exports.cache.set(filename, func);
  217. }
  218. return func;
  219. }
  220. /**
  221. * Try calling handleCache with the given options and data and call the
  222. * callback with the result. If an error occurs, call the callback with
  223. * the error. Used by renderFile().
  224. *
  225. * @memberof module:ejs-internal
  226. * @param {Options} options compilation options
  227. * @param {Object} data template data
  228. * @param {RenderFileCallback} cb callback
  229. * @static
  230. */
  231. function tryHandleCache(options, data, cb) {
  232. var result;
  233. if (!cb) {
  234. if (typeof exports.promiseImpl == 'function') {
  235. return new exports.promiseImpl(function (resolve, reject) {
  236. try {
  237. result = handleCache(options)(data);
  238. resolve(result);
  239. }
  240. catch (err) {
  241. reject(err);
  242. }
  243. });
  244. }
  245. else {
  246. throw new Error('Please provide a callback function');
  247. }
  248. }
  249. else {
  250. try {
  251. result = handleCache(options)(data);
  252. }
  253. catch (err) {
  254. return cb(err);
  255. }
  256. cb(null, result);
  257. }
  258. }
  259. /**
  260. * fileLoader is independent
  261. *
  262. * @param {String} filePath ejs file path.
  263. * @return {String} The contents of the specified file.
  264. * @static
  265. */
  266. function fileLoader(filePath){
  267. return exports.fileLoader(filePath);
  268. }
  269. /**
  270. * Get the template function.
  271. *
  272. * If `options.cache` is `true`, then the template is cached.
  273. *
  274. * @memberof module:ejs-internal
  275. * @param {String} path path for the specified file
  276. * @param {Options} options compilation options
  277. * @return {(TemplateFunction|ClientFunction)}
  278. * Depending on the value of `options.client`, either type might be returned
  279. * @static
  280. */
  281. function includeFile(path, options) {
  282. var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
  283. opts.filename = getIncludePath(path, opts);
  284. if (typeof options.includer === 'function') {
  285. var includerResult = options.includer(path, opts.filename);
  286. if (includerResult) {
  287. if (includerResult.filename) {
  288. opts.filename = includerResult.filename;
  289. }
  290. if (includerResult.template) {
  291. return handleCache(opts, includerResult.template);
  292. }
  293. }
  294. }
  295. return handleCache(opts);
  296. }
  297. /**
  298. * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
  299. * `lineno`.
  300. *
  301. * @implements {RethrowCallback}
  302. * @memberof module:ejs-internal
  303. * @param {Error} err Error object
  304. * @param {String} str EJS source
  305. * @param {String} flnm file name of the EJS file
  306. * @param {Number} lineno line number of the error
  307. * @param {EscapeCallback} esc
  308. * @static
  309. */
  310. function rethrow(err, str, flnm, lineno, esc) {
  311. var lines = str.split('\n');
  312. var start = Math.max(lineno - 3, 0);
  313. var end = Math.min(lines.length, lineno + 3);
  314. var filename = esc(flnm);
  315. // Error context
  316. var context = lines.slice(start, end).map(function (line, i){
  317. var curr = i + start + 1;
  318. return (curr == lineno ? ' >> ' : ' ')
  319. + curr
  320. + '| '
  321. + line;
  322. }).join('\n');
  323. // Alter exception message
  324. err.path = filename;
  325. err.message = (filename || 'ejs') + ':'
  326. + lineno + '\n'
  327. + context + '\n\n'
  328. + err.message;
  329. throw err;
  330. }
  331. function stripSemi(str){
  332. return str.replace(/;(\s*$)/, '$1');
  333. }
  334. /**
  335. * Compile the given `str` of ejs into a template function.
  336. *
  337. * @param {String} template EJS template
  338. *
  339. * @param {Options} [opts] compilation options
  340. *
  341. * @return {(TemplateFunction|ClientFunction)}
  342. * Depending on the value of `opts.client`, either type might be returned.
  343. * Note that the return type of the function also depends on the value of `opts.async`.
  344. * @public
  345. */
  346. exports.compile = function compile(template, opts) {
  347. var templ;
  348. // v1 compat
  349. // 'scope' is 'context'
  350. // FIXME: Remove this in a future version
  351. if (opts && opts.scope) {
  352. if (!scopeOptionWarned){
  353. console.warn('`scope` option is deprecated and will be removed in EJS 3');
  354. scopeOptionWarned = true;
  355. }
  356. if (!opts.context) {
  357. opts.context = opts.scope;
  358. }
  359. delete opts.scope;
  360. }
  361. templ = new Template(template, opts);
  362. return templ.compile();
  363. };
  364. /**
  365. * Render the given `template` of ejs.
  366. *
  367. * If you would like to include options but not data, you need to explicitly
  368. * call this function with `data` being an empty object or `null`.
  369. *
  370. * @param {String} template EJS template
  371. * @param {Object} [data={}] template data
  372. * @param {Options} [opts={}] compilation and rendering options
  373. * @return {(String|Promise<String>)}
  374. * Return value type depends on `opts.async`.
  375. * @public
  376. */
  377. exports.render = function (template, d, o) {
  378. var data = d || utils.createNullProtoObjWherePossible();
  379. var opts = o || utils.createNullProtoObjWherePossible();
  380. // No options object -- if there are optiony names
  381. // in the data, copy them to options
  382. if (arguments.length == 2) {
  383. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
  384. }
  385. return handleCache(opts, template)(data);
  386. };
  387. /**
  388. * Render an EJS file at the given `path` and callback `cb(err, str)`.
  389. *
  390. * If you would like to include options but not data, you need to explicitly
  391. * call this function with `data` being an empty object or `null`.
  392. *
  393. * @param {String} path path to the EJS file
  394. * @param {Object} [data={}] template data
  395. * @param {Options} [opts={}] compilation and rendering options
  396. * @param {RenderFileCallback} cb callback
  397. * @public
  398. */
  399. exports.renderFile = function () {
  400. var args = Array.prototype.slice.call(arguments);
  401. var filename = args.shift();
  402. var cb;
  403. var opts = {filename: filename};
  404. var data;
  405. var viewOpts;
  406. // Do we have a callback?
  407. if (typeof arguments[arguments.length - 1] == 'function') {
  408. cb = args.pop();
  409. }
  410. // Do we have data/opts?
  411. if (args.length) {
  412. // Should always have data obj
  413. data = args.shift();
  414. // Normal passed opts (data obj + opts obj)
  415. if (args.length) {
  416. // Use shallowCopy so we don't pollute passed in opts obj with new vals
  417. utils.shallowCopy(opts, args.pop());
  418. }
  419. // Special casing for Express (settings + opts-in-data)
  420. else {
  421. // Express 3 and 4
  422. if (data.settings) {
  423. // Pull a few things from known locations
  424. if (data.settings.views) {
  425. opts.views = data.settings.views;
  426. }
  427. if (data.settings['view cache']) {
  428. opts.cache = true;
  429. }
  430. // Undocumented after Express 2, but still usable, esp. for
  431. // items that are unsafe to be passed along with data, like `root`
  432. viewOpts = data.settings['view options'];
  433. if (viewOpts) {
  434. utils.shallowCopy(opts, viewOpts);
  435. }
  436. }
  437. // Express 2 and lower, values set in app.locals, or people who just
  438. // want to pass options in their data. NOTE: These values will override
  439. // anything previously set in settings or settings['view options']
  440. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
  441. }
  442. opts.filename = filename;
  443. }
  444. else {
  445. data = utils.createNullProtoObjWherePossible();
  446. }
  447. return tryHandleCache(opts, data, cb);
  448. };
  449. /**
  450. * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
  451. * @public
  452. */
  453. /**
  454. * EJS template class
  455. * @public
  456. */
  457. exports.Template = Template;
  458. exports.clearCache = function () {
  459. exports.cache.reset();
  460. };
  461. function Template(text, optsParam) {
  462. var opts = utils.hasOwnOnlyObject(optsParam);
  463. var options = utils.createNullProtoObjWherePossible();
  464. this.templateText = text;
  465. /** @type {string | null} */
  466. this.mode = null;
  467. this.truncate = false;
  468. this.currentLine = 1;
  469. this.source = '';
  470. options.client = opts.client || false;
  471. options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
  472. options.compileDebug = opts.compileDebug !== false;
  473. options.debug = !!opts.debug;
  474. options.filename = opts.filename;
  475. options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
  476. options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
  477. options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
  478. options.strict = opts.strict || false;
  479. options.context = opts.context;
  480. options.cache = opts.cache || false;
  481. options.rmWhitespace = opts.rmWhitespace;
  482. options.root = opts.root;
  483. options.includer = opts.includer;
  484. options.outputFunctionName = opts.outputFunctionName;
  485. options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
  486. options.views = opts.views;
  487. options.async = opts.async;
  488. options.destructuredLocals = opts.destructuredLocals;
  489. options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
  490. if (options.strict) {
  491. options._with = false;
  492. }
  493. else {
  494. options._with = typeof opts._with != 'undefined' ? opts._with : true;
  495. }
  496. this.opts = options;
  497. this.regex = this.createRegex();
  498. }
  499. Template.modes = {
  500. EVAL: 'eval',
  501. ESCAPED: 'escaped',
  502. RAW: 'raw',
  503. COMMENT: 'comment',
  504. LITERAL: 'literal'
  505. };
  506. Template.prototype = {
  507. createRegex: function () {
  508. var str = _REGEX_STRING;
  509. var delim = utils.escapeRegExpChars(this.opts.delimiter);
  510. var open = utils.escapeRegExpChars(this.opts.openDelimiter);
  511. var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
  512. str = str.replace(/%/g, delim)
  513. .replace(/</g, open)
  514. .replace(/>/g, close);
  515. return new RegExp(str);
  516. },
  517. compile: function () {
  518. /** @type {string} */
  519. var src;
  520. /** @type {ClientFunction} */
  521. var fn;
  522. var opts = this.opts;
  523. var prepended = '';
  524. var appended = '';
  525. /** @type {EscapeCallback} */
  526. var escapeFn = opts.escapeFunction;
  527. /** @type {FunctionConstructor} */
  528. var ctor;
  529. /** @type {string} */
  530. var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
  531. if (!this.source) {
  532. this.generateSource();
  533. prepended +=
  534. ' var __output = "";\n' +
  535. ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
  536. if (opts.outputFunctionName) {
  537. if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
  538. throw new Error('outputFunctionName is not a valid JS identifier.');
  539. }
  540. prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
  541. }
  542. if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
  543. throw new Error('localsName is not a valid JS identifier.');
  544. }
  545. if (opts.destructuredLocals && opts.destructuredLocals.length) {
  546. var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
  547. for (var i = 0; i < opts.destructuredLocals.length; i++) {
  548. var name = opts.destructuredLocals[i];
  549. if (!_JS_IDENTIFIER.test(name)) {
  550. throw new Error('destructuredLocals[' + i + '] is not a valid JS identifier.');
  551. }
  552. if (i > 0) {
  553. destructuring += ',\n ';
  554. }
  555. destructuring += name + ' = __locals.' + name;
  556. }
  557. prepended += destructuring + ';\n';
  558. }
  559. if (opts._with !== false) {
  560. prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
  561. appended += ' }' + '\n';
  562. }
  563. appended += ' return __output;' + '\n';
  564. this.source = prepended + this.source + appended;
  565. }
  566. if (opts.compileDebug) {
  567. src = 'var __line = 1' + '\n'
  568. + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
  569. + ' , __filename = ' + sanitizedFilename + ';' + '\n'
  570. + 'try {' + '\n'
  571. + this.source
  572. + '} catch (e) {' + '\n'
  573. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  574. + '}' + '\n';
  575. }
  576. else {
  577. src = this.source;
  578. }
  579. if (opts.client) {
  580. src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
  581. if (opts.compileDebug) {
  582. src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
  583. }
  584. }
  585. if (opts.strict) {
  586. src = '"use strict";\n' + src;
  587. }
  588. if (opts.debug) {
  589. console.log(src);
  590. }
  591. if (opts.compileDebug && opts.filename) {
  592. src = src + '\n'
  593. + '//# sourceURL=' + sanitizedFilename + '\n';
  594. }
  595. try {
  596. if (opts.async) {
  597. // Have to use generated function for this, since in envs without support,
  598. // it breaks in parsing
  599. try {
  600. ctor = (new Function('return (async function(){}).constructor;'))();
  601. }
  602. catch(e) {
  603. if (e instanceof SyntaxError) {
  604. throw new Error('This environment does not support async/await');
  605. }
  606. else {
  607. throw e;
  608. }
  609. }
  610. }
  611. else {
  612. ctor = Function;
  613. }
  614. fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
  615. }
  616. catch(e) {
  617. // istanbul ignore else
  618. if (e instanceof SyntaxError) {
  619. if (opts.filename) {
  620. e.message += ' in ' + opts.filename;
  621. }
  622. e.message += ' while compiling ejs\n\n';
  623. e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
  624. e.message += 'https://github.com/RyanZim/EJS-Lint';
  625. if (!opts.async) {
  626. e.message += '\n';
  627. e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
  628. }
  629. }
  630. throw e;
  631. }
  632. // Return a callable function which will execute the function
  633. // created by the source-code, with the passed data as locals
  634. // Adds a local `include` function which allows full recursive include
  635. var returnedFn = opts.client ? fn : function anonymous(data) {
  636. var include = function (path, includeData) {
  637. var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
  638. if (includeData) {
  639. d = utils.shallowCopy(d, includeData);
  640. }
  641. return includeFile(path, opts)(d);
  642. };
  643. return fn.apply(opts.context,
  644. [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]);
  645. };
  646. if (opts.filename && typeof Object.defineProperty === 'function') {
  647. var filename = opts.filename;
  648. var basename = path.basename(filename, path.extname(filename));
  649. try {
  650. Object.defineProperty(returnedFn, 'name', {
  651. value: basename,
  652. writable: false,
  653. enumerable: false,
  654. configurable: true
  655. });
  656. } catch (e) {/* ignore */}
  657. }
  658. return returnedFn;
  659. },
  660. generateSource: function () {
  661. var opts = this.opts;
  662. if (opts.rmWhitespace) {
  663. // Have to use two separate replace here as `^` and `$` operators don't
  664. // work well with `\r` and empty lines don't work well with the `m` flag.
  665. this.templateText =
  666. this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
  667. }
  668. // Slurp spaces and tabs before <%_ and after _%>
  669. this.templateText =
  670. this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
  671. var self = this;
  672. var matches = this.parseTemplateText();
  673. var d = this.opts.delimiter;
  674. var o = this.opts.openDelimiter;
  675. var c = this.opts.closeDelimiter;
  676. if (matches && matches.length) {
  677. matches.forEach(function (line, index) {
  678. var closing;
  679. // If this is an opening tag, check for closing tags
  680. // FIXME: May end up with some false positives here
  681. // Better to store modes as k/v with openDelimiter + delimiter as key
  682. // Then this can simply check against the map
  683. if ( line.indexOf(o + d) === 0 // If it is a tag
  684. && line.indexOf(o + d + d) !== 0) { // and is not escaped
  685. closing = matches[index + 2];
  686. if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
  687. throw new Error('Could not find matching close tag for "' + line + '".');
  688. }
  689. }
  690. self.scanLine(line);
  691. });
  692. }
  693. },
  694. parseTemplateText: function () {
  695. var str = this.templateText;
  696. var pat = this.regex;
  697. var result = pat.exec(str);
  698. var arr = [];
  699. var firstPos;
  700. while (result) {
  701. firstPos = result.index;
  702. if (firstPos !== 0) {
  703. arr.push(str.substring(0, firstPos));
  704. str = str.slice(firstPos);
  705. }
  706. arr.push(result[0]);
  707. str = str.slice(result[0].length);
  708. result = pat.exec(str);
  709. }
  710. if (str) {
  711. arr.push(str);
  712. }
  713. return arr;
  714. },
  715. _addOutput: function (line) {
  716. if (this.truncate) {
  717. // Only replace single leading linebreak in the line after
  718. // -%> tag -- this is the single, trailing linebreak
  719. // after the tag that the truncation mode replaces
  720. // Handle Win / Unix / old Mac linebreaks -- do the \r\n
  721. // combo first in the regex-or
  722. line = line.replace(/^(?:\r\n|\r|\n)/, '');
  723. this.truncate = false;
  724. }
  725. if (!line) {
  726. return line;
  727. }
  728. // Preserve literal slashes
  729. line = line.replace(/\\/g, '\\\\');
  730. // Convert linebreaks
  731. line = line.replace(/\n/g, '\\n');
  732. line = line.replace(/\r/g, '\\r');
  733. // Escape double-quotes
  734. // - this will be the delimiter during execution
  735. line = line.replace(/"/g, '\\"');
  736. this.source += ' ; __append("' + line + '")' + '\n';
  737. },
  738. scanLine: function (line) {
  739. var self = this;
  740. var d = this.opts.delimiter;
  741. var o = this.opts.openDelimiter;
  742. var c = this.opts.closeDelimiter;
  743. var newLineCount = 0;
  744. newLineCount = (line.split('\n').length - 1);
  745. switch (line) {
  746. case o + d:
  747. case o + d + '_':
  748. this.mode = Template.modes.EVAL;
  749. break;
  750. case o + d + '=':
  751. this.mode = Template.modes.ESCAPED;
  752. break;
  753. case o + d + '-':
  754. this.mode = Template.modes.RAW;
  755. break;
  756. case o + d + '#':
  757. this.mode = Template.modes.COMMENT;
  758. break;
  759. case o + d + d:
  760. this.mode = Template.modes.LITERAL;
  761. this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
  762. break;
  763. case d + d + c:
  764. this.mode = Template.modes.LITERAL;
  765. this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
  766. break;
  767. case d + c:
  768. case '-' + d + c:
  769. case '_' + d + c:
  770. if (this.mode == Template.modes.LITERAL) {
  771. this._addOutput(line);
  772. }
  773. this.mode = null;
  774. this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
  775. break;
  776. default:
  777. // In script mode, depends on type of tag
  778. if (this.mode) {
  779. // If '//' is found without a line break, add a line break.
  780. switch (this.mode) {
  781. case Template.modes.EVAL:
  782. case Template.modes.ESCAPED:
  783. case Template.modes.RAW:
  784. if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
  785. line += '\n';
  786. }
  787. }
  788. switch (this.mode) {
  789. // Just executing code
  790. case Template.modes.EVAL:
  791. this.source += ' ; ' + line + '\n';
  792. break;
  793. // Exec, esc, and output
  794. case Template.modes.ESCAPED:
  795. this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
  796. break;
  797. // Exec and output
  798. case Template.modes.RAW:
  799. this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
  800. break;
  801. case Template.modes.COMMENT:
  802. // Do nothing
  803. break;
  804. // Literal <%% mode, append as raw output
  805. case Template.modes.LITERAL:
  806. this._addOutput(line);
  807. break;
  808. }
  809. }
  810. // In string mode, just add the output
  811. else {
  812. this._addOutput(line);
  813. }
  814. }
  815. if (self.opts.compileDebug && newLineCount) {
  816. this.currentLine += newLineCount;
  817. this.source += ' ; __line = ' + this.currentLine + '\n';
  818. }
  819. }
  820. };
  821. /**
  822. * Escape characters reserved in XML.
  823. *
  824. * This is simply an export of {@link module:utils.escapeXML}.
  825. *
  826. * If `markup` is `undefined` or `null`, the empty string is returned.
  827. *
  828. * @param {String} markup Input string
  829. * @return {String} Escaped string
  830. * @public
  831. * @func
  832. * */
  833. exports.escapeXML = utils.escapeXML;
  834. /**
  835. * Express.js support.
  836. *
  837. * This is an alias for {@link module:ejs.renderFile}, in order to support
  838. * Express.js out-of-the-box.
  839. *
  840. * @func
  841. */
  842. exports.__express = exports.renderFile;
  843. /**
  844. * Version of EJS.
  845. *
  846. * @readonly
  847. * @type {String}
  848. * @public
  849. */
  850. exports.VERSION = _VERSION_STRING;
  851. /**
  852. * Name for detection of EJS.
  853. *
  854. * @readonly
  855. * @type {String}
  856. * @public
  857. */
  858. exports.name = _NAME;
  859. /* istanbul ignore if */
  860. if (typeof window != 'undefined') {
  861. window.ejs = exports;
  862. }
  863. },{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){
  864. /*
  865. * EJS Embedded JavaScript templates
  866. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  867. *
  868. * Licensed under the Apache License, Version 2.0 (the "License");
  869. * you may not use this file except in compliance with the License.
  870. * You may obtain a copy of the License at
  871. *
  872. * http://www.apache.org/licenses/LICENSE-2.0
  873. *
  874. * Unless required by applicable law or agreed to in writing, software
  875. * distributed under the License is distributed on an "AS IS" BASIS,
  876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  877. * See the License for the specific language governing permissions and
  878. * limitations under the License.
  879. *
  880. */
  881. /**
  882. * Private utility functions
  883. * @module utils
  884. * @private
  885. */
  886. 'use strict';
  887. var regExpChars = /[|\\{}()[\]^$+*?.]/g;
  888. var hasOwnProperty = Object.prototype.hasOwnProperty;
  889. var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); };
  890. /**
  891. * Escape characters reserved in regular expressions.
  892. *
  893. * If `string` is `undefined` or `null`, the empty string is returned.
  894. *
  895. * @param {String} string Input string
  896. * @return {String} Escaped string
  897. * @static
  898. * @private
  899. */
  900. exports.escapeRegExpChars = function (string) {
  901. // istanbul ignore if
  902. if (!string) {
  903. return '';
  904. }
  905. return String(string).replace(regExpChars, '\\$&');
  906. };
  907. var _ENCODE_HTML_RULES = {
  908. '&': '&amp;',
  909. '<': '&lt;',
  910. '>': '&gt;',
  911. '"': '&#34;',
  912. "'": '&#39;'
  913. };
  914. var _MATCH_HTML = /[&<>'"]/g;
  915. function encode_char(c) {
  916. return _ENCODE_HTML_RULES[c] || c;
  917. }
  918. /**
  919. * Stringified version of constants used by {@link module:utils.escapeXML}.
  920. *
  921. * It is used in the process of generating {@link ClientFunction}s.
  922. *
  923. * @readonly
  924. * @type {String}
  925. */
  926. var escapeFuncStr =
  927. 'var _ENCODE_HTML_RULES = {\n'
  928. + ' "&": "&amp;"\n'
  929. + ' , "<": "&lt;"\n'
  930. + ' , ">": "&gt;"\n'
  931. + ' , \'"\': "&#34;"\n'
  932. + ' , "\'": "&#39;"\n'
  933. + ' }\n'
  934. + ' , _MATCH_HTML = /[&<>\'"]/g;\n'
  935. + 'function encode_char(c) {\n'
  936. + ' return _ENCODE_HTML_RULES[c] || c;\n'
  937. + '};\n';
  938. /**
  939. * Escape characters reserved in XML.
  940. *
  941. * If `markup` is `undefined` or `null`, the empty string is returned.
  942. *
  943. * @implements {EscapeCallback}
  944. * @param {String} markup Input string
  945. * @return {String} Escaped string
  946. * @static
  947. * @private
  948. */
  949. exports.escapeXML = function (markup) {
  950. return markup == undefined
  951. ? ''
  952. : String(markup)
  953. .replace(_MATCH_HTML, encode_char);
  954. };
  955. function escapeXMLToString() {
  956. return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
  957. }
  958. try {
  959. if (typeof Object.defineProperty === 'function') {
  960. // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property
  961. // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict
  962. // mode, attempting that will be silently ignored.
  963. // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object.
  964. Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString });
  965. } else {
  966. // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator.
  967. exports.escapeXML.toString = escapeXMLToString;
  968. }
  969. } catch (err) {
  970. console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)');
  971. }
  972. /**
  973. * Naive copy of properties from one object to another.
  974. * Does not recurse into non-scalar properties
  975. * Does not check to see if the property has a value before copying
  976. *
  977. * @param {Object} to Destination object
  978. * @param {Object} from Source object
  979. * @return {Object} Destination object
  980. * @static
  981. * @private
  982. */
  983. exports.shallowCopy = function (to, from) {
  984. from = from || {};
  985. if ((to !== null) && (to !== undefined)) {
  986. for (var p in from) {
  987. if (!hasOwn(from, p)) {
  988. continue;
  989. }
  990. if (p === '__proto__' || p === 'constructor') {
  991. continue;
  992. }
  993. to[p] = from[p];
  994. }
  995. }
  996. return to;
  997. };
  998. /**
  999. * Naive copy of a list of key names, from one object to another.
  1000. * Only copies property if it is actually defined
  1001. * Does not recurse into non-scalar properties
  1002. *
  1003. * @param {Object} to Destination object
  1004. * @param {Object} from Source object
  1005. * @param {Array} list List of properties to copy
  1006. * @return {Object} Destination object
  1007. * @static
  1008. * @private
  1009. */
  1010. exports.shallowCopyFromList = function (to, from, list) {
  1011. list = list || [];
  1012. from = from || {};
  1013. if ((to !== null) && (to !== undefined)) {
  1014. for (var i = 0; i < list.length; i++) {
  1015. var p = list[i];
  1016. if (typeof from[p] != 'undefined') {
  1017. if (!hasOwn(from, p)) {
  1018. continue;
  1019. }
  1020. if (p === '__proto__' || p === 'constructor') {
  1021. continue;
  1022. }
  1023. to[p] = from[p];
  1024. }
  1025. }
  1026. }
  1027. return to;
  1028. };
  1029. /**
  1030. * Simple in-process cache implementation. Does not implement limits of any
  1031. * sort.
  1032. *
  1033. * @implements {Cache}
  1034. * @static
  1035. * @private
  1036. */
  1037. exports.cache = {
  1038. _data: {},
  1039. set: function (key, val) {
  1040. this._data[key] = val;
  1041. },
  1042. get: function (key) {
  1043. return this._data[key];
  1044. },
  1045. remove: function (key) {
  1046. delete this._data[key];
  1047. },
  1048. reset: function () {
  1049. this._data = {};
  1050. }
  1051. };
  1052. /**
  1053. * Transforms hyphen case variable into camel case.
  1054. *
  1055. * @param {String} string Hyphen case string
  1056. * @return {String} Camel case string
  1057. * @static
  1058. * @private
  1059. */
  1060. exports.hyphenToCamel = function (str) {
  1061. return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
  1062. };
  1063. /**
  1064. * Returns a null-prototype object in runtimes that support it
  1065. *
  1066. * @return {Object} Object, prototype will be set to null where possible
  1067. * @static
  1068. * @private
  1069. */
  1070. exports.createNullProtoObjWherePossible = (function () {
  1071. if (typeof Object.create == 'function') {
  1072. return function () {
  1073. return Object.create(null);
  1074. };
  1075. }
  1076. if (!({__proto__: null} instanceof Object)) {
  1077. return function () {
  1078. return {__proto__: null};
  1079. };
  1080. }
  1081. // Not possible, just pass through
  1082. return function () {
  1083. return {};
  1084. };
  1085. })();
  1086. exports.hasOwnOnlyObject = function (obj) {
  1087. var o = exports.createNullProtoObjWherePossible();
  1088. for (var p in obj) {
  1089. if (hasOwn(obj, p)) {
  1090. o[p] = obj[p];
  1091. }
  1092. }
  1093. return o;
  1094. };
  1095. },{}],3:[function(require,module,exports){
  1096. },{}],4:[function(require,module,exports){
  1097. (function (process){
  1098. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  1099. // backported and transplited with Babel, with backwards-compat fixes
  1100. // Copyright Joyent, Inc. and other Node contributors.
  1101. //
  1102. // Permission is hereby granted, free of charge, to any person obtaining a
  1103. // copy of this software and associated documentation files (the
  1104. // "Software"), to deal in the Software without restriction, including
  1105. // without limitation the rights to use, copy, modify, merge, publish,
  1106. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1107. // persons to whom the Software is furnished to do so, subject to the
  1108. // following conditions:
  1109. //
  1110. // The above copyright notice and this permission notice shall be included
  1111. // in all copies or substantial portions of the Software.
  1112. //
  1113. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1114. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1115. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1116. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1117. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1118. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1119. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1120. // resolves . and .. elements in a path array with directory names there
  1121. // must be no slashes, empty elements, or device names (c:\) in the array
  1122. // (so also no leading and trailing slashes - it does not distinguish
  1123. // relative and absolute paths)
  1124. function normalizeArray(parts, allowAboveRoot) {
  1125. // if the path tries to go above the root, `up` ends up > 0
  1126. var up = 0;
  1127. for (var i = parts.length - 1; i >= 0; i--) {
  1128. var last = parts[i];
  1129. if (last === '.') {
  1130. parts.splice(i, 1);
  1131. } else if (last === '..') {
  1132. parts.splice(i, 1);
  1133. up++;
  1134. } else if (up) {
  1135. parts.splice(i, 1);
  1136. up--;
  1137. }
  1138. }
  1139. // if the path is allowed to go above the root, restore leading ..s
  1140. if (allowAboveRoot) {
  1141. for (; up--; up) {
  1142. parts.unshift('..');
  1143. }
  1144. }
  1145. return parts;
  1146. }
  1147. // path.resolve([from ...], to)
  1148. // posix version
  1149. exports.resolve = function() {
  1150. var resolvedPath = '',
  1151. resolvedAbsolute = false;
  1152. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1153. var path = (i >= 0) ? arguments[i] : process.cwd();
  1154. // Skip empty and invalid entries
  1155. if (typeof path !== 'string') {
  1156. throw new TypeError('Arguments to path.resolve must be strings');
  1157. } else if (!path) {
  1158. continue;
  1159. }
  1160. resolvedPath = path + '/' + resolvedPath;
  1161. resolvedAbsolute = path.charAt(0) === '/';
  1162. }
  1163. // At this point the path should be resolved to a full absolute path, but
  1164. // handle relative paths to be safe (might happen when process.cwd() fails)
  1165. // Normalize the path
  1166. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  1167. return !!p;
  1168. }), !resolvedAbsolute).join('/');
  1169. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1170. };
  1171. // path.normalize(path)
  1172. // posix version
  1173. exports.normalize = function(path) {
  1174. var isAbsolute = exports.isAbsolute(path),
  1175. trailingSlash = substr(path, -1) === '/';
  1176. // Normalize the path
  1177. path = normalizeArray(filter(path.split('/'), function(p) {
  1178. return !!p;
  1179. }), !isAbsolute).join('/');
  1180. if (!path && !isAbsolute) {
  1181. path = '.';
  1182. }
  1183. if (path && trailingSlash) {
  1184. path += '/';
  1185. }
  1186. return (isAbsolute ? '/' : '') + path;
  1187. };
  1188. // posix version
  1189. exports.isAbsolute = function(path) {
  1190. return path.charAt(0) === '/';
  1191. };
  1192. // posix version
  1193. exports.join = function() {
  1194. var paths = Array.prototype.slice.call(arguments, 0);
  1195. return exports.normalize(filter(paths, function(p, index) {
  1196. if (typeof p !== 'string') {
  1197. throw new TypeError('Arguments to path.join must be strings');
  1198. }
  1199. return p;
  1200. }).join('/'));
  1201. };
  1202. // path.relative(from, to)
  1203. // posix version
  1204. exports.relative = function(from, to) {
  1205. from = exports.resolve(from).substr(1);
  1206. to = exports.resolve(to).substr(1);
  1207. function trim(arr) {
  1208. var start = 0;
  1209. for (; start < arr.length; start++) {
  1210. if (arr[start] !== '') break;
  1211. }
  1212. var end = arr.length - 1;
  1213. for (; end >= 0; end--) {
  1214. if (arr[end] !== '') break;
  1215. }
  1216. if (start > end) return [];
  1217. return arr.slice(start, end - start + 1);
  1218. }
  1219. var fromParts = trim(from.split('/'));
  1220. var toParts = trim(to.split('/'));
  1221. var length = Math.min(fromParts.length, toParts.length);
  1222. var samePartsLength = length;
  1223. for (var i = 0; i < length; i++) {
  1224. if (fromParts[i] !== toParts[i]) {
  1225. samePartsLength = i;
  1226. break;
  1227. }
  1228. }
  1229. var outputParts = [];
  1230. for (var i = samePartsLength; i < fromParts.length; i++) {
  1231. outputParts.push('..');
  1232. }
  1233. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1234. return outputParts.join('/');
  1235. };
  1236. exports.sep = '/';
  1237. exports.delimiter = ':';
  1238. exports.dirname = function (path) {
  1239. if (typeof path !== 'string') path = path + '';
  1240. if (path.length === 0) return '.';
  1241. var code = path.charCodeAt(0);
  1242. var hasRoot = code === 47 /*/*/;
  1243. var end = -1;
  1244. var matchedSlash = true;
  1245. for (var i = path.length - 1; i >= 1; --i) {
  1246. code = path.charCodeAt(i);
  1247. if (code === 47 /*/*/) {
  1248. if (!matchedSlash) {
  1249. end = i;
  1250. break;
  1251. }
  1252. } else {
  1253. // We saw the first non-path separator
  1254. matchedSlash = false;
  1255. }
  1256. }
  1257. if (end === -1) return hasRoot ? '/' : '.';
  1258. if (hasRoot && end === 1) {
  1259. // return '//';
  1260. // Backwards-compat fix:
  1261. return '/';
  1262. }
  1263. return path.slice(0, end);
  1264. };
  1265. function basename(path) {
  1266. if (typeof path !== 'string') path = path + '';
  1267. var start = 0;
  1268. var end = -1;
  1269. var matchedSlash = true;
  1270. var i;
  1271. for (i = path.length - 1; i >= 0; --i) {
  1272. if (path.charCodeAt(i) === 47 /*/*/) {
  1273. // If we reached a path separator that was not part of a set of path
  1274. // separators at the end of the string, stop now
  1275. if (!matchedSlash) {
  1276. start = i + 1;
  1277. break;
  1278. }
  1279. } else if (end === -1) {
  1280. // We saw the first non-path separator, mark this as the end of our
  1281. // path component
  1282. matchedSlash = false;
  1283. end = i + 1;
  1284. }
  1285. }
  1286. if (end === -1) return '';
  1287. return path.slice(start, end);
  1288. }
  1289. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  1290. // in new Node.js versions, so only basename() above is backported here
  1291. exports.basename = function (path, ext) {
  1292. var f = basename(path);
  1293. if (ext && f.substr(-1 * ext.length) === ext) {
  1294. f = f.substr(0, f.length - ext.length);
  1295. }
  1296. return f;
  1297. };
  1298. exports.extname = function (path) {
  1299. if (typeof path !== 'string') path = path + '';
  1300. var startDot = -1;
  1301. var startPart = 0;
  1302. var end = -1;
  1303. var matchedSlash = true;
  1304. // Track the state of characters (if any) we see before our first dot and
  1305. // after any path separator we find
  1306. var preDotState = 0;
  1307. for (var i = path.length - 1; i >= 0; --i) {
  1308. var code = path.charCodeAt(i);
  1309. if (code === 47 /*/*/) {
  1310. // If we reached a path separator that was not part of a set of path
  1311. // separators at the end of the string, stop now
  1312. if (!matchedSlash) {
  1313. startPart = i + 1;
  1314. break;
  1315. }
  1316. continue;
  1317. }
  1318. if (end === -1) {
  1319. // We saw the first non-path separator, mark this as the end of our
  1320. // extension
  1321. matchedSlash = false;
  1322. end = i + 1;
  1323. }
  1324. if (code === 46 /*.*/) {
  1325. // If this is our first dot, mark it as the start of our extension
  1326. if (startDot === -1)
  1327. startDot = i;
  1328. else if (preDotState !== 1)
  1329. preDotState = 1;
  1330. } else if (startDot !== -1) {
  1331. // We saw a non-dot and non-path separator before our dot, so we should
  1332. // have a good chance at having a non-empty extension
  1333. preDotState = -1;
  1334. }
  1335. }
  1336. if (startDot === -1 || end === -1 ||
  1337. // We saw a non-dot character immediately before the dot
  1338. preDotState === 0 ||
  1339. // The (right-most) trimmed path component is exactly '..'
  1340. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  1341. return '';
  1342. }
  1343. return path.slice(startDot, end);
  1344. };
  1345. function filter (xs, f) {
  1346. if (xs.filter) return xs.filter(f);
  1347. var res = [];
  1348. for (var i = 0; i < xs.length; i++) {
  1349. if (f(xs[i], i, xs)) res.push(xs[i]);
  1350. }
  1351. return res;
  1352. }
  1353. // String.prototype.substr - negative index don't work in IE8
  1354. var substr = 'ab'.substr(-1) === 'b'
  1355. ? function (str, start, len) { return str.substr(start, len) }
  1356. : function (str, start, len) {
  1357. if (start < 0) start = str.length + start;
  1358. return str.substr(start, len);
  1359. }
  1360. ;
  1361. }).call(this,require('_process'))
  1362. },{"_process":5}],5:[function(require,module,exports){
  1363. // shim for using process in browser
  1364. var process = module.exports = {};
  1365. // cached from whatever global is present so that test runners that stub it
  1366. // don't break things. But we need to wrap it in a try catch in case it is
  1367. // wrapped in strict mode code which doesn't define any globals. It's inside a
  1368. // function because try/catches deoptimize in certain engines.
  1369. var cachedSetTimeout;
  1370. var cachedClearTimeout;
  1371. function defaultSetTimout() {
  1372. throw new Error('setTimeout has not been defined');
  1373. }
  1374. function defaultClearTimeout () {
  1375. throw new Error('clearTimeout has not been defined');
  1376. }
  1377. (function () {
  1378. try {
  1379. if (typeof setTimeout === 'function') {
  1380. cachedSetTimeout = setTimeout;
  1381. } else {
  1382. cachedSetTimeout = defaultSetTimout;
  1383. }
  1384. } catch (e) {
  1385. cachedSetTimeout = defaultSetTimout;
  1386. }
  1387. try {
  1388. if (typeof clearTimeout === 'function') {
  1389. cachedClearTimeout = clearTimeout;
  1390. } else {
  1391. cachedClearTimeout = defaultClearTimeout;
  1392. }
  1393. } catch (e) {
  1394. cachedClearTimeout = defaultClearTimeout;
  1395. }
  1396. } ())
  1397. function runTimeout(fun) {
  1398. if (cachedSetTimeout === setTimeout) {
  1399. //normal enviroments in sane situations
  1400. return setTimeout(fun, 0);
  1401. }
  1402. // if setTimeout wasn't available but was latter defined
  1403. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1404. cachedSetTimeout = setTimeout;
  1405. return setTimeout(fun, 0);
  1406. }
  1407. try {
  1408. // when when somebody has screwed with setTimeout but no I.E. maddness
  1409. return cachedSetTimeout(fun, 0);
  1410. } catch(e){
  1411. try {
  1412. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1413. return cachedSetTimeout.call(null, fun, 0);
  1414. } catch(e){
  1415. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  1416. return cachedSetTimeout.call(this, fun, 0);
  1417. }
  1418. }
  1419. }
  1420. function runClearTimeout(marker) {
  1421. if (cachedClearTimeout === clearTimeout) {
  1422. //normal enviroments in sane situations
  1423. return clearTimeout(marker);
  1424. }
  1425. // if clearTimeout wasn't available but was latter defined
  1426. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1427. cachedClearTimeout = clearTimeout;
  1428. return clearTimeout(marker);
  1429. }
  1430. try {
  1431. // when when somebody has screwed with setTimeout but no I.E. maddness
  1432. return cachedClearTimeout(marker);
  1433. } catch (e){
  1434. try {
  1435. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1436. return cachedClearTimeout.call(null, marker);
  1437. } catch (e){
  1438. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  1439. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  1440. return cachedClearTimeout.call(this, marker);
  1441. }
  1442. }
  1443. }
  1444. var queue = [];
  1445. var draining = false;
  1446. var currentQueue;
  1447. var queueIndex = -1;
  1448. function cleanUpNextTick() {
  1449. if (!draining || !currentQueue) {
  1450. return;
  1451. }
  1452. draining = false;
  1453. if (currentQueue.length) {
  1454. queue = currentQueue.concat(queue);
  1455. } else {
  1456. queueIndex = -1;
  1457. }
  1458. if (queue.length) {
  1459. drainQueue();
  1460. }
  1461. }
  1462. function drainQueue() {
  1463. if (draining) {
  1464. return;
  1465. }
  1466. var timeout = runTimeout(cleanUpNextTick);
  1467. draining = true;
  1468. var len = queue.length;
  1469. while(len) {
  1470. currentQueue = queue;
  1471. queue = [];
  1472. while (++queueIndex < len) {
  1473. if (currentQueue) {
  1474. currentQueue[queueIndex].run();
  1475. }
  1476. }
  1477. queueIndex = -1;
  1478. len = queue.length;
  1479. }
  1480. currentQueue = null;
  1481. draining = false;
  1482. runClearTimeout(timeout);
  1483. }
  1484. process.nextTick = function (fun) {
  1485. var args = new Array(arguments.length - 1);
  1486. if (arguments.length > 1) {
  1487. for (var i = 1; i < arguments.length; i++) {
  1488. args[i - 1] = arguments[i];
  1489. }
  1490. }
  1491. queue.push(new Item(fun, args));
  1492. if (queue.length === 1 && !draining) {
  1493. runTimeout(drainQueue);
  1494. }
  1495. };
  1496. // v8 likes predictible objects
  1497. function Item(fun, array) {
  1498. this.fun = fun;
  1499. this.array = array;
  1500. }
  1501. Item.prototype.run = function () {
  1502. this.fun.apply(null, this.array);
  1503. };
  1504. process.title = 'browser';
  1505. process.browser = true;
  1506. process.env = {};
  1507. process.argv = [];
  1508. process.version = ''; // empty string to avoid regexp issues
  1509. process.versions = {};
  1510. function noop() {}
  1511. process.on = noop;
  1512. process.addListener = noop;
  1513. process.once = noop;
  1514. process.off = noop;
  1515. process.removeListener = noop;
  1516. process.removeAllListeners = noop;
  1517. process.emit = noop;
  1518. process.prependListener = noop;
  1519. process.prependOnceListener = noop;
  1520. process.listeners = function (name) { return [] }
  1521. process.binding = function (name) {
  1522. throw new Error('process.binding is not supported');
  1523. };
  1524. process.cwd = function () { return '/' };
  1525. process.chdir = function (dir) {
  1526. throw new Error('process.chdir is not supported');
  1527. };
  1528. process.umask = function() { return 0; };
  1529. },{}],6:[function(require,module,exports){
  1530. module.exports={
  1531. "name": "ejs",
  1532. "description": "Embedded JavaScript templates",
  1533. "keywords": [
  1534. "template",
  1535. "engine",
  1536. "ejs"
  1537. ],
  1538. "version": "3.1.9",
  1539. "author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
  1540. "license": "Apache-2.0",
  1541. "bin": {
  1542. "ejs": "./bin/cli.js"
  1543. },
  1544. "main": "./lib/ejs.js",
  1545. "jsdelivr": "ejs.min.js",
  1546. "unpkg": "ejs.min.js",
  1547. "repository": {
  1548. "type": "git",
  1549. "url": "git://github.com/mde/ejs.git"
  1550. },
  1551. "bugs": "https://github.com/mde/ejs/issues",
  1552. "homepage": "https://github.com/mde/ejs",
  1553. "dependencies": {
  1554. "jake": "^10.8.5"
  1555. },
  1556. "devDependencies": {
  1557. "browserify": "^16.5.1",
  1558. "eslint": "^6.8.0",
  1559. "git-directory-deploy": "^1.5.1",
  1560. "jsdoc": "^4.0.2",
  1561. "lru-cache": "^4.0.1",
  1562. "mocha": "^10.2.0",
  1563. "uglify-js": "^3.3.16"
  1564. },
  1565. "engines": {
  1566. "node": ">=0.10.0"
  1567. },
  1568. "scripts": {
  1569. "test": "npx jake test"
  1570. }
  1571. }
  1572. },{}]},{},[1])(1)
  1573. });