Shared.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. var parseRange = require("range-parser");
  2. var pathIsAbsolute = require("path-is-absolute");
  3. var MemoryFileSystem = require("memory-fs");
  4. var HASH_REGEXP = /[0-9a-f]{10,}/;
  5. module.exports = function Shared(context) {
  6. var share = {
  7. setOptions: function(options) {
  8. if(!options) options = {};
  9. if(typeof options.watchOptions === "undefined") options.watchOptions = {};
  10. if(typeof options.reporter !== "function") options.reporter = share.defaultReporter;
  11. if(typeof options.log !== "function") options.log = console.log.bind(console);
  12. if(typeof options.warn !== "function") options.warn = console.warn.bind(console);
  13. if(typeof options.error !== "function") options.error = console.error.bind(console);
  14. if(typeof options.watchDelay !== "undefined") {
  15. // TODO remove this in next major version
  16. options.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
  17. options.watchOptions.aggregateTimeout = options.watchDelay;
  18. }
  19. if(typeof options.watchOptions.aggregateTimeout === "undefined") options.watchOptions.aggregateTimeout = 200;
  20. if(typeof options.stats === "undefined") options.stats = {};
  21. if(!options.stats.context) options.stats.context = process.cwd();
  22. if(options.lazy) {
  23. if(typeof options.filename === "string") {
  24. var str = options.filename
  25. .replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
  26. .replace(/\\\[[a-z]+\\\]/ig, ".+");
  27. options.filename = new RegExp("^[\/]{0,1}" + str + "$");
  28. }
  29. }
  30. context.options = options;
  31. },
  32. defaultReporter: function(reporterOptions) {
  33. var state = reporterOptions.state;
  34. var stats = reporterOptions.stats;
  35. var options = reporterOptions.options;
  36. if(state) {
  37. var displayStats = (!options.quiet && options.stats !== false);
  38. if(displayStats && !(stats.hasErrors() || stats.hasWarnings()) &&
  39. options.noInfo)
  40. displayStats = false;
  41. if(displayStats) {
  42. options.log(stats.toString(options.stats));
  43. }
  44. if(!options.noInfo && !options.quiet) {
  45. var msg = "Compiled successfully.";
  46. if(stats.hasErrors()) {
  47. msg = "Failed to compile.";
  48. } else if(stats.hasWarnings()) {
  49. msg = "Compiled with warnings.";
  50. }
  51. options.log("webpack: " + msg);
  52. }
  53. } else {
  54. options.log("webpack: Compiling...");
  55. }
  56. },
  57. handleRangeHeaders: function handleRangeHeaders(content, req, res) {
  58. //assumes express API. For other servers, need to add logic to access alternative header APIs
  59. res.setHeader("Accept-Ranges", "bytes");
  60. if(req.headers.range) {
  61. var ranges = parseRange(content.length, req.headers.range);
  62. // unsatisfiable
  63. if(-1 == ranges) {
  64. res.setHeader("Content-Range", "bytes */" + content.length);
  65. res.statusCode = 416;
  66. }
  67. // valid (syntactically invalid/multiple ranges are treated as a regular response)
  68. if(-2 != ranges && ranges.length === 1) {
  69. // Content-Range
  70. res.statusCode = 206;
  71. var length = content.length;
  72. res.setHeader(
  73. "Content-Range",
  74. "bytes " + ranges[0].start + "-" + ranges[0].end + "/" + length
  75. );
  76. content = content.slice(ranges[0].start, ranges[0].end + 1);
  77. }
  78. }
  79. return content;
  80. },
  81. setFs: function(compiler) {
  82. if(typeof compiler.outputPath === "string" && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
  83. throw new Error("`output.path` needs to be an absolute path or `/`.");
  84. }
  85. // store our files in memory
  86. var fs;
  87. var isMemoryFs = !compiler.compilers && compiler.outputFileSystem instanceof MemoryFileSystem;
  88. if(isMemoryFs) {
  89. fs = compiler.outputFileSystem;
  90. } else {
  91. fs = compiler.outputFileSystem = new MemoryFileSystem();
  92. }
  93. context.fs = fs;
  94. },
  95. compilerDone: function(stats) {
  96. // We are now on valid state
  97. context.state = true;
  98. context.webpackStats = stats;
  99. // Do the stuff in nextTick, because bundle may be invalidated
  100. // if a change happened while compiling
  101. process.nextTick(function() {
  102. // check if still in valid state
  103. if(!context.state) return;
  104. // print webpack output
  105. context.options.reporter({
  106. state: true,
  107. stats: stats,
  108. options: context.options
  109. });
  110. // execute callback that are delayed
  111. var cbs = context.callbacks;
  112. context.callbacks = [];
  113. cbs.forEach(function continueBecauseBundleAvailable(cb) {
  114. cb(stats);
  115. });
  116. });
  117. // In lazy mode, we may issue another rebuild
  118. if(context.forceRebuild) {
  119. context.forceRebuild = false;
  120. share.rebuild();
  121. }
  122. },
  123. compilerInvalid: function() {
  124. if(context.state && (!context.options.noInfo && !context.options.quiet))
  125. context.options.reporter({
  126. state: false,
  127. options: context.options
  128. });
  129. // We are now in invalid state
  130. context.state = false;
  131. //resolve async
  132. if(arguments.length === 2 && typeof arguments[1] === "function") {
  133. var callback = arguments[1];
  134. callback();
  135. }
  136. },
  137. ready: function ready(fn, req) {
  138. var options = context.options;
  139. if(context.state) return fn(context.webpackStats);
  140. if(!options.noInfo && !options.quiet)
  141. options.log("webpack: wait until bundle finished: " + (req.url || fn.name));
  142. context.callbacks.push(fn);
  143. },
  144. startWatch: function() {
  145. var options = context.options;
  146. var compiler = context.compiler;
  147. // start watching
  148. if(!options.lazy) {
  149. var watching = compiler.watch(options.watchOptions, share.handleCompilerCallback);
  150. context.watching = watching;
  151. } else {
  152. context.state = true;
  153. }
  154. },
  155. rebuild: function rebuild() {
  156. if(context.state) {
  157. context.state = false;
  158. context.compiler.run(share.handleCompilerCallback);
  159. } else {
  160. context.forceRebuild = true;
  161. }
  162. },
  163. handleCompilerCallback: function(err) {
  164. if(err) {
  165. context.options.error(err.stack || err);
  166. if(err.details) context.options.error(err.details);
  167. }
  168. },
  169. handleRequest: function(filename, processRequest, req) {
  170. // in lazy mode, rebuild on bundle request
  171. if(context.options.lazy && (!context.options.filename || context.options.filename.test(filename)))
  172. share.rebuild();
  173. if(HASH_REGEXP.test(filename)) {
  174. try {
  175. if(context.fs.statSync(filename).isFile()) {
  176. processRequest();
  177. return;
  178. }
  179. } catch(e) {
  180. }
  181. }
  182. share.ready(processRequest, req);
  183. },
  184. waitUntilValid: function(callback) {
  185. callback = callback || function() {};
  186. share.ready(callback, {});
  187. },
  188. invalidate: function(callback) {
  189. callback = callback || function() {};
  190. if(context.watching) {
  191. share.ready(callback, {});
  192. context.watching.invalidate();
  193. } else {
  194. callback();
  195. }
  196. },
  197. close: function(callback) {
  198. callback = callback || function() {};
  199. if(context.watching) context.watching.close(callback);
  200. else callback();
  201. }
  202. };
  203. share.setOptions(context.options);
  204. share.setFs(context.compiler);
  205. context.compiler.plugin("done", share.compilerDone);
  206. context.compiler.plugin("invalid", share.compilerInvalid);
  207. context.compiler.plugin("watch-run", share.compilerInvalid);
  208. context.compiler.plugin("run", share.compilerInvalid);
  209. share.startWatch();
  210. return share;
  211. };