index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. 'use strict';
  2. /*!
  3. * Pug
  4. * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var fs = require('fs');
  11. var path = require('path');
  12. var lex = require('pug-lexer');
  13. var stripComments = require('pug-strip-comments');
  14. var parse = require('pug-parser');
  15. var load = require('pug-load');
  16. var filters = require('pug-filters');
  17. var link = require('pug-linker');
  18. var generateCode = require('pug-code-gen');
  19. var runtime = require('pug-runtime');
  20. var runtimeWrap = require('pug-runtime/wrap');
  21. /**
  22. * Name for detection
  23. */
  24. exports.name = 'Pug';
  25. /**
  26. * Pug runtime helpers.
  27. */
  28. exports.runtime = runtime;
  29. /**
  30. * Template function cache.
  31. */
  32. exports.cache = {};
  33. function applyPlugins(value, options, plugins, name) {
  34. return plugins.reduce(function (value, plugin) {
  35. return (
  36. plugin[name]
  37. ? plugin[name](value, options)
  38. : value
  39. );
  40. }, value);
  41. }
  42. function findReplacementFunc(plugins, name) {
  43. var eligiblePlugins = plugins.filter(function (plugin) {
  44. return plugin[name];
  45. });
  46. if (eligiblePlugins.length > 1) {
  47. throw new Error('Two or more plugins all implement ' + name + ' method.');
  48. } else if (eligiblePlugins.length) {
  49. return eligiblePlugins[0][name].bind(eligiblePlugins[0]);
  50. }
  51. return null;
  52. }
  53. /**
  54. * Object for global custom filters. Note that you can also just pass a `filters`
  55. * option to any other method.
  56. */
  57. exports.filters = {};
  58. /**
  59. * Compile the given `str` of pug and return a function body.
  60. *
  61. * @param {String} str
  62. * @param {Object} options
  63. * @return {Object}
  64. * @api private
  65. */
  66. function compileBody(str, options){
  67. var debug_sources = {};
  68. debug_sources[options.filename] = str;
  69. var dependencies = [];
  70. var plugins = options.plugins || [];
  71. var ast = load.string(str, {
  72. filename: options.filename,
  73. basedir: options.basedir,
  74. lex: function (str, options) {
  75. var lexOptions = {};
  76. Object.keys(options).forEach(function (key) {
  77. lexOptions[key] = options[key];
  78. });
  79. lexOptions.plugins = plugins.filter(function (plugin) {
  80. return !!plugin.lex;
  81. }).map(function (plugin) {
  82. return plugin.lex;
  83. });
  84. var contents = applyPlugins(str, {filename: options.filename}, plugins, 'preLex');
  85. return applyPlugins(lex(contents, lexOptions), options, plugins, 'postLex');
  86. },
  87. parse: function (tokens, options) {
  88. tokens = tokens.map(function (token) {
  89. if (token.type === 'path' && path.extname(token.val) === '') {
  90. return {
  91. type: 'path',
  92. loc: token.loc,
  93. val: token.val + '.pug'
  94. };
  95. }
  96. return token;
  97. });
  98. tokens = stripComments(tokens, options);
  99. tokens = applyPlugins(tokens, options, plugins, 'preParse');
  100. var parseOptions = {};
  101. Object.keys(options).forEach(function (key) {
  102. parseOptions[key] = options[key];
  103. });
  104. parseOptions.plugins = plugins.filter(function (plugin) {
  105. return !!plugin.parse;
  106. }).map(function (plugin) {
  107. return plugin.parse;
  108. });
  109. return applyPlugins(
  110. applyPlugins(parse(tokens, parseOptions), options, plugins, 'postParse'),
  111. options, plugins, 'preLoad'
  112. );
  113. },
  114. resolve: function (filename, source, loadOptions) {
  115. var replacementFunc = findReplacementFunc(plugins, 'resolve');
  116. if (replacementFunc) {
  117. return replacementFunc(filename, source, options);
  118. }
  119. return load.resolve(filename, source, loadOptions);
  120. },
  121. read: function (filename, loadOptions) {
  122. dependencies.push(filename);
  123. var contents;
  124. var replacementFunc = findReplacementFunc(plugins, 'read');
  125. if (replacementFunc) {
  126. contents = replacementFunc(filename, options);
  127. } else {
  128. contents = load.read(filename, loadOptions);
  129. }
  130. debug_sources[filename] = contents;
  131. return contents;
  132. }
  133. });
  134. ast = applyPlugins(ast, options, plugins, 'postLoad');
  135. ast = applyPlugins(ast, options, plugins, 'preFilters');
  136. var filtersSet = {};
  137. Object.keys(exports.filters).forEach(function (key) {
  138. filtersSet[key] = exports.filters[key];
  139. });
  140. if (options.filters) {
  141. Object.keys(options.filters).forEach(function (key) {
  142. filtersSet[key] = options.filters[key];
  143. });
  144. }
  145. ast = filters.handleFilters(ast, filtersSet, options.filterOptions, options.filterAliases);
  146. ast = applyPlugins(ast, options, plugins, 'postFilters');
  147. ast = applyPlugins(ast, options, plugins, 'preLink');
  148. ast = link(ast);
  149. ast = applyPlugins(ast, options, plugins, 'postLink');
  150. // Compile
  151. ast = applyPlugins(ast, options, plugins, 'preCodeGen');
  152. var js = generateCode(ast, {
  153. pretty: options.pretty,
  154. compileDebug: options.compileDebug,
  155. doctype: options.doctype,
  156. inlineRuntimeFunctions: options.inlineRuntimeFunctions,
  157. globals: options.globals,
  158. self: options.self,
  159. includeSources: options.includeSources ? debug_sources : false,
  160. templateName: options.templateName
  161. });
  162. js = applyPlugins(js, options, plugins, 'postCodeGen');
  163. // Debug compiler
  164. if (options.debug) {
  165. console.error('\nCompiled Function:\n\n\u001b[90m%s\u001b[0m', js.replace(/^/gm, ' '));
  166. }
  167. return {body: js, dependencies: dependencies};
  168. }
  169. /**
  170. * Get the template from a string or a file, either compiled on-the-fly or
  171. * read from cache (if enabled), and cache the template if needed.
  172. *
  173. * If `str` is not set, the file specified in `options.filename` will be read.
  174. *
  175. * If `options.cache` is true, this function reads the file from
  176. * `options.filename` so it must be set prior to calling this function.
  177. *
  178. * @param {Object} options
  179. * @param {String=} str
  180. * @return {Function}
  181. * @api private
  182. */
  183. function handleTemplateCache (options, str) {
  184. var key = options.filename;
  185. if (options.cache && exports.cache[key]) {
  186. return exports.cache[key];
  187. } else {
  188. if (str === undefined) str = fs.readFileSync(options.filename, 'utf8');
  189. var templ = exports.compile(str, options);
  190. if (options.cache) exports.cache[key] = templ;
  191. return templ;
  192. }
  193. }
  194. /**
  195. * Compile a `Function` representation of the given pug `str`.
  196. *
  197. * Options:
  198. *
  199. * - `compileDebug` when `false` debugging code is stripped from the compiled
  200. template, when it is explicitly `true`, the source code is included in
  201. the compiled template for better accuracy.
  202. * - `filename` used to improve errors when `compileDebug` is not `false` and to resolve imports/extends
  203. *
  204. * @param {String} str
  205. * @param {Options} options
  206. * @return {Function}
  207. * @api public
  208. */
  209. exports.compile = function(str, options){
  210. var options = options || {}
  211. str = String(str);
  212. var parsed = compileBody(str, {
  213. compileDebug: options.compileDebug !== false,
  214. filename: options.filename,
  215. basedir: options.basedir,
  216. pretty: options.pretty,
  217. doctype: options.doctype,
  218. inlineRuntimeFunctions: options.inlineRuntimeFunctions,
  219. globals: options.globals,
  220. self: options.self,
  221. includeSources: options.compileDebug === true,
  222. debug: options.debug,
  223. templateName: 'template',
  224. filters: options.filters,
  225. filterOptions: options.filterOptions,
  226. filterAliases: options.filterAliases,
  227. plugins: options.plugins,
  228. });
  229. var res = options.inlineRuntimeFunctions
  230. ? new Function('', parsed.body + ';return template;')()
  231. : runtimeWrap(parsed.body);
  232. res.dependencies = parsed.dependencies;
  233. return res;
  234. };
  235. /**
  236. * Compile a JavaScript source representation of the given pug `str`.
  237. *
  238. * Options:
  239. *
  240. * - `compileDebug` When it is `true`, the source code is included in
  241. * the compiled template for better error messages.
  242. * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends
  243. * - `name` the name of the resulting function (defaults to "template")
  244. * - `module` when it is explicitly `true`, the source code include export module syntax
  245. *
  246. * @param {String} str
  247. * @param {Options} options
  248. * @return {Object}
  249. * @api public
  250. */
  251. exports.compileClientWithDependenciesTracked = function(str, options){
  252. var options = options || {};
  253. str = String(str);
  254. var parsed = compileBody(str, {
  255. compileDebug: options.compileDebug,
  256. filename: options.filename,
  257. basedir: options.basedir,
  258. pretty: options.pretty,
  259. doctype: options.doctype,
  260. inlineRuntimeFunctions: options.inlineRuntimeFunctions !== false,
  261. globals: options.globals,
  262. self: options.self,
  263. includeSources: options.compileDebug,
  264. debug: options.debug,
  265. templateName: options.name || 'template',
  266. filters: options.filters,
  267. filterOptions: options.filterOptions,
  268. filterAliases: options.filterAliases,
  269. plugins: options.plugins
  270. });
  271. var body = parsed.body;
  272. if(options.module) {
  273. if(options.inlineRuntimeFunctions === false) {
  274. body = 'var pug = require("pug-runtime");' + body;
  275. }
  276. body += ' module.exports = ' + (options.name || 'template') + ';';
  277. }
  278. return {body: body, dependencies: parsed.dependencies};
  279. };
  280. /**
  281. * Compile a JavaScript source representation of the given pug `str`.
  282. *
  283. * Options:
  284. *
  285. * - `compileDebug` When it is `true`, the source code is included in
  286. * the compiled template for better error messages.
  287. * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends
  288. * - `name` the name of the resulting function (defaults to "template")
  289. *
  290. * @param {String} str
  291. * @param {Options} options
  292. * @return {String}
  293. * @api public
  294. */
  295. exports.compileClient = function (str, options) {
  296. return exports.compileClientWithDependenciesTracked(str, options).body;
  297. };
  298. /**
  299. * Compile a `Function` representation of the given pug file.
  300. *
  301. * Options:
  302. *
  303. * - `compileDebug` when `false` debugging code is stripped from the compiled
  304. template, when it is explicitly `true`, the source code is included in
  305. the compiled template for better accuracy.
  306. *
  307. * @param {String} path
  308. * @param {Options} options
  309. * @return {Function}
  310. * @api public
  311. */
  312. exports.compileFile = function (path, options) {
  313. options = options || {};
  314. options.filename = path;
  315. return handleTemplateCache(options);
  316. };
  317. /**
  318. * Render the given `str` of pug.
  319. *
  320. * Options:
  321. *
  322. * - `cache` enable template caching
  323. * - `filename` filename required for `include` / `extends` and caching
  324. *
  325. * @param {String} str
  326. * @param {Object|Function} options or fn
  327. * @param {Function|undefined} fn
  328. * @returns {String}
  329. * @api public
  330. */
  331. exports.render = function(str, options, fn){
  332. // support callback API
  333. if ('function' == typeof options) {
  334. fn = options, options = undefined;
  335. }
  336. if (typeof fn === 'function') {
  337. var res;
  338. try {
  339. res = exports.render(str, options);
  340. } catch (ex) {
  341. return fn(ex);
  342. }
  343. return fn(null, res);
  344. }
  345. options = options || {};
  346. // cache requires .filename
  347. if (options.cache && !options.filename) {
  348. throw new Error('the "filename" option is required for caching');
  349. }
  350. return handleTemplateCache(options, str)(options);
  351. };
  352. /**
  353. * Render a Pug file at the given `path`.
  354. *
  355. * @param {String} path
  356. * @param {Object|Function} options or callback
  357. * @param {Function|undefined} fn
  358. * @returns {String}
  359. * @api public
  360. */
  361. exports.renderFile = function(path, options, fn){
  362. // support callback API
  363. if ('function' == typeof options) {
  364. fn = options, options = undefined;
  365. }
  366. if (typeof fn === 'function') {
  367. var res;
  368. try {
  369. res = exports.renderFile(path, options);
  370. } catch (ex) {
  371. return fn(ex);
  372. }
  373. return fn(null, res);
  374. }
  375. options = options || {};
  376. options.filename = path;
  377. return handleTemplateCache(options)(options);
  378. };
  379. /**
  380. * Compile a Pug file at the given `path` for use on the client.
  381. *
  382. * @param {String} path
  383. * @param {Object} options
  384. * @returns {String}
  385. * @api public
  386. */
  387. exports.compileFileClient = function(path, options){
  388. var key = path + ':client';
  389. options = options || {};
  390. options.filename = path;
  391. if (options.cache && exports.cache[key]) {
  392. return exports.cache[key];
  393. }
  394. var str = fs.readFileSync(options.filename, 'utf8');
  395. var out = exports.compileClient(str, options);
  396. if (options.cache) exports.cache[key] = out;
  397. return out;
  398. };
  399. /**
  400. * Express support.
  401. */
  402. exports.__express = function(path, options, fn) {
  403. if(options.compileDebug == undefined && process.env.NODE_ENV === 'production') {
  404. options.compileDebug = false;
  405. }
  406. exports.renderFile(path, options, fn);
  407. }