UNPKG

2.3 kBJavaScriptView Raw
1var COFFEE_CACHE_DIR, COFFEE_NO_CACHE, Coffeescript, child_process, coffeeBinary, fs, md5, origFork, path, register, serveCached;
2
3Coffeescript = require('coffee-script');
4
5child_process = require('child_process');
6
7fs = require('fs-jetpack');
8
9path = require('path');
10
11md5 = require('md5');
12
13COFFEE_CACHE_DIR = process.env.COFFEE_CACHE_DIR ? path.resolve(process.env.COFFEE_CACHE_DIR) : path.join(__dirname, '..', '.cache');
14
15COFFEE_NO_CACHE = process.env.COFFEE_NO_CACHE;
16
17serveCached = !COFFEE_NO_CACHE;
18
19register = function(extensions) {
20 var cachedFiles, extension, i, len, loadFile, targetExtensions;
21 targetExtensions = [].concat(extensions, '.coffee');
22 fs.dir(COFFEE_CACHE_DIR);
23 cachedFiles = fs.list(COFFEE_CACHE_DIR).filter(function(file) {
24 return file.slice(-3) === '.js';
25 });
26 loadFile = function(module, filename) {
27 var cachedFile, cachedFilePath, compiledContent, content, hash;
28 content = fs.read(filename);
29 hash = md5(content);
30 cachedFile = hash + ".js";
31 cachedFilePath = path.join(COFFEE_CACHE_DIR, cachedFile);
32 if (serveCached && cachedFiles.indexOf(cachedFile) !== -1) {
33 compiledContent = fs.read(cachedFilePath);
34 } else {
35 compiledContent = Coffeescript.compile(content, {
36 filename: filename,
37 bare: true,
38 inlineMap: true
39 });
40 fs.write(cachedFilePath, compiledContent);
41 }
42 return module._compile(compiledContent, filename);
43 };
44 for (i = 0, len = targetExtensions.length; i < len; i++) {
45 extension = targetExtensions[i];
46 if (extension) {
47 require.extensions[extension] = loadFile;
48 }
49 }
50 return register;
51};
52
53if (child_process) {
54 origFork = child_process.fork;
55 coffeeBinary = path.resolve('./node_modules/coffee-script/bin/coffee');
56 child_process.fork = function(filePath, args, options) {
57 if (path.extname(filePath) === '.coffee') {
58 if (!Array.isArray(args)) {
59 options = args || {};
60 args = [];
61 }
62 args = [filePath].concat(args);
63 filePath = coffeeBinary;
64 }
65 return origFork(filePath, args, options);
66 };
67}
68
69
70/* istanbul ignore next */
71
72if (process.env.SOURCE_MAPS || process.env.SOURCE_MAP) {
73 require('@danielkalen/source-map-support').install({
74 hookRequire: true
75 });
76}
77
78module.exports = register();