server.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* server.coffee */
  2. (function() {
  3. var Config, ContentPlugin, ContentTree, Stream, async, buildLookupMap, chalk, chokidar, colorCode, enableDestroy, http, keyForValue, loadContent, lookupCharset, mime, minimatch, normalizeUrl, pump, ref, renderView, replaceInArray, run, runGenerator, setup, sleep, url, urlEqual;
  4. async = require('async');
  5. chokidar = require('chokidar');
  6. chalk = require('chalk');
  7. http = require('http');
  8. mime = require('mime');
  9. url = require('url');
  10. minimatch = require('minimatch');
  11. enableDestroy = require('server-destroy');
  12. Stream = require('stream').Stream;
  13. Config = require('./config').Config;
  14. ref = require('./content'), ContentTree = ref.ContentTree, ContentPlugin = ref.ContentPlugin, loadContent = ref.loadContent;
  15. pump = require('./utils').pump;
  16. renderView = require('./renderer').renderView;
  17. runGenerator = require('./generator').runGenerator;
  18. colorCode = function(code) {
  19. switch (Math.floor(code / 100)) {
  20. case 2:
  21. return chalk.green(code);
  22. case 4:
  23. return chalk.yellow(code);
  24. case 5:
  25. return chalk.red(code);
  26. default:
  27. return code.toString();
  28. }
  29. };
  30. sleep = function(callback) {
  31. return setTimeout(callback, 50);
  32. };
  33. normalizeUrl = function(anUrl) {
  34. if (anUrl[anUrl.length - 1] === '/') {
  35. anUrl += 'index.html';
  36. }
  37. if (anUrl.match(/^([^.]*[^\/])$/)) {
  38. anUrl += '/index.html';
  39. }
  40. anUrl = decodeURI(anUrl);
  41. return anUrl;
  42. };
  43. urlEqual = function(urlA, urlB) {
  44. return normalizeUrl(urlA) === normalizeUrl(urlB);
  45. };
  46. keyForValue = function(object, value) {
  47. var key;
  48. for (key in object) {
  49. if (object[key] === value) {
  50. return key;
  51. }
  52. }
  53. return null;
  54. };
  55. replaceInArray = function(array, oldItem, newItem) {
  56. var idx;
  57. idx = array.indexOf(oldItem);
  58. if (idx === -1) {
  59. return false;
  60. }
  61. array[idx] = newItem;
  62. return true;
  63. };
  64. buildLookupMap = function(contents) {
  65. var i, item, len, map, ref1;
  66. map = {};
  67. ref1 = ContentTree.flatten(contents);
  68. for (i = 0, len = ref1.length; i < len; i++) {
  69. item = ref1[i];
  70. map[normalizeUrl(item.url)] = item;
  71. }
  72. return map;
  73. };
  74. lookupCharset = function(mimeType) {
  75. if (/^text\/|^application\/(javascript|json)/.test(mimeType)) {
  76. return 'UTF-8';
  77. } else {
  78. return null;
  79. }
  80. };
  81. setup = function(env) {
  82. /* Create a preview request handler. */
  83. var block, changeHandler, contentHandler, contentWatcher, contents, isReady, loadContents, loadLocals, loadTemplates, loadViews, locals, logop, lookup, requestHandler, templateWatcher, templates, viewsWatcher;
  84. contents = null;
  85. templates = null;
  86. locals = null;
  87. lookup = {};
  88. block = {
  89. contentsLoad: false,
  90. templatesLoad: false,
  91. viewsLoad: false,
  92. localsLoad: false
  93. };
  94. isReady = function() {
  95. /* Returns true if we have no running tasks */
  96. var k, v;
  97. for (k in block) {
  98. v = block[k];
  99. if (v === true) {
  100. return false;
  101. }
  102. }
  103. return true;
  104. };
  105. logop = function(error) {
  106. if (error != null) {
  107. return env.logger.error(error.message, error);
  108. }
  109. };
  110. changeHandler = function(error, path) {
  111. /* Emits a change event if called without error */
  112. if (error == null) {
  113. env.emit('change', path, false);
  114. }
  115. return logop(error);
  116. };
  117. loadContents = function(callback) {
  118. if (callback == null) {
  119. callback = logop;
  120. }
  121. block.contentsLoad = true;
  122. lookup = {};
  123. contents = null;
  124. return ContentTree.fromDirectory(env, env.contentsPath, function(error, result) {
  125. if (error == null) {
  126. contents = result;
  127. lookup = buildLookupMap(result);
  128. }
  129. block.contentsLoad = false;
  130. return callback(error);
  131. });
  132. };
  133. loadTemplates = function(callback) {
  134. if (callback == null) {
  135. callback = logop;
  136. }
  137. block.templatesLoad = true;
  138. templates = null;
  139. return env.getTemplates(function(error, result) {
  140. if (error == null) {
  141. templates = result;
  142. }
  143. block.templatesLoad = false;
  144. return callback(error);
  145. });
  146. };
  147. loadViews = function(callback) {
  148. if (callback == null) {
  149. callback = logop;
  150. }
  151. block.viewsLoad = true;
  152. return env.loadViews(function(error) {
  153. block.viewsLoad = false;
  154. return callback(error);
  155. });
  156. };
  157. loadLocals = function(callback) {
  158. if (callback == null) {
  159. callback = logop;
  160. }
  161. block.localsLoad = true;
  162. locals = null;
  163. return env.getLocals(function(error, result) {
  164. if (error == null) {
  165. locals = result;
  166. }
  167. block.localsLoad = false;
  168. return callback(error);
  169. });
  170. };
  171. contentWatcher = chokidar.watch(env.contentsPath, {
  172. ignoreInitial: true
  173. });
  174. contentWatcher.on('all', function(type, filename) {
  175. var i, len, pattern, ref1, relpath;
  176. if (block.contentsLoad) {
  177. return;
  178. }
  179. relpath = env.relativeContentsPath(filename);
  180. ref1 = env.config.ignore;
  181. for (i = 0, len = ref1.length; i < len; i++) {
  182. pattern = ref1[i];
  183. if (minimatch(relpath, pattern)) {
  184. env.emit('change', relpath, true);
  185. return;
  186. }
  187. }
  188. return loadContents(function(error) {
  189. var content, contentFilename, j, len1, ref2;
  190. contentFilename = null;
  191. if ((error == null) && (filename != null)) {
  192. ref2 = ContentTree.flatten(contents);
  193. for (j = 0, len1 = ref2.length; j < len1; j++) {
  194. content = ref2[j];
  195. if (content.__filename === filename) {
  196. contentFilename = content.filename;
  197. break;
  198. }
  199. }
  200. }
  201. return changeHandler(error, contentFilename);
  202. });
  203. });
  204. templateWatcher = chokidar.watch(env.templatesPath, {
  205. ignoreInitial: true
  206. });
  207. templateWatcher.on('all', function(event, path) {
  208. if (!block.templatesLoad) {
  209. return loadTemplates(changeHandler);
  210. }
  211. });
  212. if (env.config.views != null) {
  213. viewsWatcher = chokidar.watch(env.resolvePath(env.config.views), {
  214. ignoreInitial: true
  215. });
  216. viewsWatcher.on('all', function(event, path) {
  217. if (!block.viewsLoad) {
  218. delete require.cache[path];
  219. return loadViews(changeHandler);
  220. }
  221. });
  222. }
  223. contentHandler = function(request, response, callback) {
  224. var uri;
  225. uri = normalizeUrl(url.parse(request.url).pathname);
  226. env.logger.verbose("contentHandler - " + uri);
  227. return async.waterfall([
  228. function(callback) {
  229. return async.mapSeries(env.generators, function(generator, callback) {
  230. return runGenerator(env, contents, generator, callback);
  231. }, callback);
  232. }, function(generated, callback) {
  233. var error, gentree, i, len, map, tree;
  234. if (generated.length > 0) {
  235. try {
  236. tree = new ContentTree('', env.getContentGroups());
  237. for (i = 0, len = generated.length; i < len; i++) {
  238. gentree = generated[i];
  239. ContentTree.merge(tree, gentree);
  240. }
  241. map = buildLookupMap(generated);
  242. ContentTree.merge(tree, contents);
  243. } catch (error1) {
  244. error = error1;
  245. return callback(error);
  246. }
  247. return callback(null, tree, map);
  248. } else {
  249. return callback(null, contents, {});
  250. }
  251. }, function(tree, generatorLookup, callback) {
  252. var content, pluginName;
  253. content = generatorLookup[uri] || lookup[uri];
  254. if (content != null) {
  255. pluginName = content.constructor.name;
  256. return renderView(env, content, locals, tree, templates, function(error, result) {
  257. var charset, contentType, mimeType, ref1;
  258. if (error) {
  259. return callback(error, 500, pluginName);
  260. } else if (result != null) {
  261. mimeType = (ref1 = mime.getType(content.filename)) != null ? ref1 : mime.getType(uri);
  262. charset = lookupCharset(mimeType);
  263. if (charset) {
  264. contentType = mimeType + "; charset=" + charset;
  265. } else {
  266. contentType = mimeType;
  267. }
  268. if (result instanceof Stream) {
  269. response.writeHead(200, {
  270. 'Content-Type': contentType
  271. });
  272. return pump(result, response, function(error) {
  273. return callback(error, 200, pluginName);
  274. });
  275. } else if (result instanceof Buffer) {
  276. response.writeHead(200, {
  277. 'Content-Type': contentType
  278. });
  279. response.write(result);
  280. response.end();
  281. return callback(null, 200, pluginName);
  282. } else {
  283. return callback(new Error("View for content '" + content.filename + "' returned invalid response. Expected Buffer or Stream."));
  284. }
  285. } else {
  286. response.writeHead(404, {
  287. 'Content-Type': 'text/plain'
  288. });
  289. response.end('404 Not Found\n');
  290. return callback(null, 404, pluginName);
  291. }
  292. });
  293. } else {
  294. return callback();
  295. }
  296. }
  297. ], callback);
  298. };
  299. requestHandler = function(request, response) {
  300. var start, uri;
  301. start = Date.now();
  302. uri = url.parse(request.url).pathname;
  303. return async.waterfall([
  304. function(callback) {
  305. if (!block.contentsLoad && (contents == null)) {
  306. return loadContents(callback);
  307. } else {
  308. return callback();
  309. }
  310. }, function(callback) {
  311. if (!block.templatesLoad && (templates == null)) {
  312. return loadTemplates(callback);
  313. } else {
  314. return callback();
  315. }
  316. }, function(callback) {
  317. return async.until(isReady, sleep, callback);
  318. }, function(callback) {
  319. return contentHandler(request, response, callback);
  320. }
  321. ], function(error, responseCode, pluginName) {
  322. var delta, logstr;
  323. if ((error != null) || (responseCode == null)) {
  324. responseCode = error != null ? 500 : 404;
  325. response.writeHead(responseCode, {
  326. 'Content-Type': 'text/plain'
  327. });
  328. response.end(error != null ? error.message : '404 Not Found\n');
  329. }
  330. delta = Date.now() - start;
  331. logstr = (colorCode(responseCode)) + " " + (chalk.bold(uri));
  332. if (pluginName != null) {
  333. logstr += " " + (chalk.grey(pluginName));
  334. }
  335. logstr += chalk.grey(" " + delta + "ms");
  336. env.logger.info(logstr);
  337. if (error) {
  338. return env.logger.error(error.message, error);
  339. }
  340. });
  341. };
  342. loadContents();
  343. loadTemplates();
  344. loadViews();
  345. loadLocals();
  346. requestHandler.destroy = function() {
  347. contentWatcher.close();
  348. templateWatcher.close();
  349. return viewsWatcher != null ? viewsWatcher.close() : void 0;
  350. };
  351. return requestHandler;
  352. };
  353. run = function(env, callback) {
  354. var configWatcher, handler, restart, server, start, stop;
  355. server = null;
  356. handler = null;
  357. if (env.config._restartOnConfChange && (env.config.__filename != null)) {
  358. env.logger.verbose("watching config file " + env.config.__filename + " for changes");
  359. configWatcher = chokidar.watch(env.config.__filename);
  360. configWatcher.on('change', function() {
  361. var cliopts, config, error, key, value;
  362. try {
  363. config = Config.fromFileSync(env.config.__filename);
  364. } catch (error1) {
  365. error = error1;
  366. env.logger.error("Error reloading config: " + error.message, error);
  367. }
  368. if (config != null) {
  369. if (cliopts = env.config._cliopts) {
  370. config._cliopts = {};
  371. for (key in cliopts) {
  372. value = cliopts[key];
  373. config[key] = config._cliopts[key] = value;
  374. }
  375. }
  376. env.setConfig(config);
  377. return restart(function(error) {
  378. if (error) {
  379. throw error;
  380. }
  381. env.logger.verbose('config file change detected, server reloaded');
  382. return env.emit('change');
  383. });
  384. }
  385. });
  386. }
  387. restart = function(callback) {
  388. env.logger.info('restarting server');
  389. return async.waterfall([stop, start], callback);
  390. };
  391. stop = function(callback) {
  392. if (server != null) {
  393. return server.destroy(function(error) {
  394. handler.destroy();
  395. env.reset();
  396. return callback(error);
  397. });
  398. } else {
  399. return callback();
  400. }
  401. };
  402. start = function(callback) {
  403. return async.series([
  404. function(callback) {
  405. return env.loadPlugins(callback);
  406. }, function(callback) {
  407. handler = setup(env);
  408. server = http.createServer(handler);
  409. enableDestroy(server);
  410. server.on('error', function(error) {
  411. if (typeof callback === "function") {
  412. callback(error);
  413. }
  414. return callback = null;
  415. });
  416. server.on('listening', function() {
  417. if (typeof callback === "function") {
  418. callback(null, server);
  419. }
  420. return callback = null;
  421. });
  422. return server.listen(env.config.port, env.config.hostname);
  423. }
  424. ], callback);
  425. };
  426. process.on('uncaughtException', function(error) {
  427. env.logger.error(error.message, error);
  428. return process.exit(1);
  429. });
  430. env.logger.verbose('starting preview server');
  431. return start(function(error, server) {
  432. var host, serverUrl;
  433. if (error == null) {
  434. host = env.config.hostname || 'localhost';
  435. serverUrl = "http://" + host + ":" + env.config.port + env.config.baseUrl;
  436. env.logger.info("server running on: " + (chalk.bold(serverUrl)));
  437. }
  438. return callback(error, server);
  439. });
  440. };
  441. module.exports = {
  442. run: run,
  443. setup: setup
  444. };
  445. }).call(this);