-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.js
296 lines (250 loc) · 9.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
'use strict';
var spawn = require("cross-spawn");
var _ = require("lodash");
var compilerBinaryName = "elm-make";
var fs = require("fs");
var path = require("path");
var temp = require("temp").track();
var firstline = require("firstline");
var defaultOptions = {
emitWarning: console.warn,
spawn: spawn,
cwd: undefined,
pathToMake: undefined,
yes: undefined,
help: undefined,
output: undefined,
report: undefined,
warn: undefined,
debug: undefined,
verbose: false,
processOpts: undefined,
};
var supportedOptions = _.keys(defaultOptions);
function compile(sources, options) {
if (typeof sources === "string") {
sources = [sources];
}
if (!(sources instanceof Array)) {
throw "compile() received neither an Array nor a String for its sources argument."
}
options = _.defaults({}, options, defaultOptions);
if (typeof options.spawn !== "function") {
throw "options.spawn was a(n) " + (typeof options.spawn) + " instead of a function."
}
var compilerArgs = compilerArgsFromOptions(options, options.emitWarning);
var processArgs = sources ? sources.concat(compilerArgs) : compilerArgs;
var env = _.merge({LANG: 'en_US.UTF-8'}, process.env);
var processOpts = _.merge({ env: env, stdio: "inherit", cwd: options.cwd }, options.processOpts);
var pathToMake = options.pathToMake || compilerBinaryName;
var verbose = options.verbose;
try {
if (verbose) {
console.log(["Running", pathToMake].concat(processArgs || []).join(" "));
}
return options.spawn(pathToMake, processArgs, processOpts)
.on('error', function(err) {
handleError(pathToMake, err);
process.exit(1)
});
} catch (err) {
if ((typeof err === "object") && (typeof err.code === "string")) {
handleError(pathToMake, err);
} else {
console.error("Exception thrown when attempting to run Elm compiler " + JSON.stringify(pathToMake) + ":\n" + err);
}
process.exit(1)
}
}
function getBaseDir(file) {
return firstline(file).then(function(line) {
return new Promise(function(resolve, reject) {
var matches = line.match(/^(?:port\s+)?module\s+([^\s]+)/);
if (matches) {
// e.g. Css.Declarations
var moduleName = matches[1];
// e.g. Css/Declarations
var dependencyLogicalName = moduleName.replace(/\./g, "/");
// e.g. ../..
var backedOut = dependencyLogicalName.replace(/[^/]+/g, "..");
// e.g. /..
var trimmedBackedOut = backedOut.replace(/^../, "");
return resolve(path.normalize(path.dirname(file) + trimmedBackedOut));
} else if (!line.match(/^(?:port\s+)?module\s/)) {
// Technically you're allowed to omit the module declaration for
// beginner applications where it'd just be `module Main exposing (..)`
// If there is no module declaration, we'll assume we have one of these,
// and succeed with the file's directory itself.
//
// See https://github.com/rtfeldman/node-elm-compiler/pull/36
return resolve(path.dirname(file));
}
return reject(file + " is not a syntactically valid Elm module. Try running elm-make on it manually to figure out what the problem is.");
});
});
}
// Returns a Promise that returns a flat list of all the Elm files the given
// Elm file depends on, based on the modules it loads via `import`.
function findAllDependencies(file, knownDependencies, baseDir) {
if (!knownDependencies) {
knownDependencies = [];
}
if (baseDir) {
return findAllDependenciesHelp(file, knownDependencies, baseDir);
} else {
return getBaseDir(file).then(function(newBaseDir) {
return findAllDependenciesHelp(file, knownDependencies, newBaseDir);
});
}
}
function findAllDependenciesHelp(file, knownDependencies, baseDir) {
return new Promise(function(resolve, reject) {
fs.readFile(file, {encoding: "utf8"}, function(err, lines) {
if (err) {
reject(err);
} else {
// Turn e.g. ~/code/elm-css/src/Css.elm
// into just ~/code/elm-css/src/
var newImports = _.compact(lines.split("\n").map(function(line) {
var matches = line.match(/^import\s+([^\s]+)/);
if (matches) {
// e.g. Css.Declarations
var moduleName = matches[1];
// e.g. Css/Declarations
var dependencyLogicalName = moduleName.replace(/\./g, "/");
// e.g. ~/code/elm-css/src/Css/Declarations.elm
var result = path.join(baseDir, dependencyLogicalName)
return _.includes(knownDependencies, result) ? null : result;
} else {
return null;
}
}));
var promises = newImports.map(function(newImport) {
var elmFile = newImport + ".elm";
return new Promise(function(resolve, reject) {
return checkIsFile(newImport + ".elm").then(resolve).catch(function(firstErr) {
if (firstErr.code === "ENOENT") {
// If we couldn't find the import as a .elm file, try as .js
checkIsFile(newImport + ".js").then(resolve).catch(function(secondErr) {
if (secondErr.code === "ENOENT") {
// If we don't find the dependency in our filesystem, assume it's because
// it comes in through a third-party package rather than our sources.
resolve([]);
} else {
reject(secondErr);
}
})
} else {
reject(firstErr);
}
});
});
});
Promise.all(promises).then(function(nestedValidDependencies) {
var validDependencies = _.flatten(nestedValidDependencies);
var newDependencies = knownDependencies.concat(validDependencies);
var recursePromises = _.compact(validDependencies.map(function(dependency) {
return path.extname(dependency) === ".elm" ?
findAllDependenciesHelp(dependency, newDependencies, baseDir) : null;
}));
Promise.all(recursePromises).then(function(extraDependencies) {
resolve(_.uniq(_.flatten(newDependencies.concat(extraDependencies))));
}).catch(reject);
}).catch(reject);
}
});
});
}
// write compiled Elm to a string output
// returns a Promise which will contain a Buffer of the text
// If you want html instead of js, use options object to set
// output to a html file instead
// creates a temp file and deletes it after reading
function compileToString(sources, options){
if (typeof options.output === "undefined"){
options.output = '.js';
}
return new Promise(function(resolve, reject){
temp.open({ suffix: options.output }, function(err, info){
if (err){
return reject(err);
}
options.output = info.path;
options.processOpts = { stdio: 'pipe' }
var compiler = compile(sources, options);
compiler.stdout.setEncoding("utf8");
compiler.stderr.setEncoding("utf8");
var output = '';
compiler.stdout.on('data', function(chunk) {
output += chunk;
});
compiler.stderr.on('data', function(chunk) {
output += chunk;
});
compiler.on("close", function(exitCode) {
if (exitCode !== 0) {
return reject(new Error('Compilation failed\n' + output));
} else if (options.verbose) {
console.log(output);
}
fs.readFile(info.path, {encoding: "utf8"}, function(err, data){
return err ? reject(err) : resolve(data);
});
});
});
});
}
function checkIsFile(file) {
return new Promise(function(resolve, reject) {
fs.stat(file, function(err, stats) {
if (err) {
reject(err);
} else if (stats.isFile()) {
resolve([file]);
} else {
resolve([]);
}
});
});
}
function handleError(pathToMake, err) {
if (err.code === "ENOENT") {
console.error("Could not find Elm compiler \"" + pathToMake + "\". Is it installed?")
} else if (err.code === "EACCES") {
console.error("Elm compiler \"" + pathToMake + "\" did not have permission to run. Do you need to give it executable permissions?");
} else {
console.error("Error attempting to run Elm compiler \"" + pathToMake + "\":\n" + err);
}
}
function escapePath(pathStr) {
return pathStr.replace(/ /g, "\\ ");
}
// Converts an object of key/value pairs to an array of arguments suitable
// to be passed to child_process.spawn for elm-make.
function compilerArgsFromOptions(options, emitWarning) {
return _.flatten(_.map(options, function(value, opt) {
if (value) {
switch(opt) {
case "yes": return ["--yes"];
case "help": return ["--help"];
case "output": return ["--output", escapePath(value)];
case "report": return ["--report", value];
case "warn": return ["--warn"];
case "debug": return ["--debug"];
default:
if (supportedOptions.indexOf(opt) === -1) {
emitWarning('Unknown Elm compiler option: ' + opt);
}
return [];
}
} else {
return [];
}
}));
}
module.exports = {
compile: compile,
compileWorker: require("./worker.js")(compile),
compileToString: compileToString,
findAllDependencies: findAllDependencies
};