-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
210 lines (163 loc) · 6.12 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
const path = require('path');
const fs = require('fs').promises;
const elmCompiler = require('node-elm-compiler');
const commandExists_ = require('command-exists');
const namespace = 'elm';
const fileFilter = /\.elm$/;
const PURE_FUNCS = [ 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']
// Like command-exists' function but returns undefined when the command is missing,
// instead of throwing an error.
const commandExists = path =>
commandExists_(path).catch(_ => undefined);
const getPathToElm = async () => {
const commands = [path.resolve('./node_modules/.bin/elm'), 'elm'];
const CMD_NOT_FOUND_ERR = 'Could not find `elm` executable. You can install it with `yarn add elm` or `npm install elm`';
const foundCommands = await Promise.all(commands.map(commandExists));
const elmCommand = foundCommands.find(cmd => cmd !== undefined);
if (elmCommand) {
return elmCommand;
} else {
throw new Error(CMD_NOT_FOUND_ERR);
}
}
// Cached version of `fs.stat`.
// Cache is cleared on each build.
const readFileModificationTime = async (fileCache, filePath) => {
const cached = fileCache.get(filePath);
if (cached !== undefined) {
return cached;
}
const stat = await fs.stat(filePath);
const fileContents = stat.mtimeMs;
fileCache.set(filePath, fileContents);
return fileContents;
};
const toBuildError = error => ({ text: error.message });
// Checks whether all deps for a "main" elm file are unchanged.
// These only include source deps (might need to reset the dev server if you add an extra dep).
// If not, we need to recompile the file importing them.
const validateDependencies = async (fileCache, depsMap) => {
const depStatus = await Promise.all([...depsMap].map(async ([depPath, cachedDep]) => {
const newInput = await readFileModificationTime(fileCache, depPath);
if (cachedDep.input === newInput) {
return true;
}
cachedDep.input = newInput;
return false;
}));
return depStatus.every(isReady => isReady);
};
// Cached version of `elmCompiler.compileToStringSync`
// Cache is persisted across builds
const checkCache = async (fileCache, cache, mainFilePath, compileOptions) => {
const cached = cache.get(mainFilePath);
const newInput = await readFileModificationTime(fileCache, mainFilePath);
const depsUnchanged = await validateDependencies(fileCache, cached.dependencies);
if (depsUnchanged && cached.input === newInput) {
return cached.output;
}
// Can't use the async version:
// https://github.com/phenax/esbuild-plugin-elm/issues/2
const contents = elmCompiler.compileToStringSync([mainFilePath], compileOptions);
const output = { contents };
cache.set(mainFilePath, {
input: newInput,
output,
dependencies: cached.dependencies,
});
return output;
};
// Recompute dependencies but keep cached artifacts if we had them
const updateDependencies = (cache, resolvedPath, dependencyPaths) => {
let cached = cache.get(resolvedPath)
|| { input: undefined, output: undefined, dependencies: new Map() };
const newValue = depPath => cached.dependencies.get(depPath) || { input: undefined };
const dependencies = new Map(dependencyPaths.map(depPath => [depPath, newValue(depPath)]));
cache.set(resolvedPath, {
...cached,
dependencies,
});
};
const cachedElmCompiler = () => {
const cache = new Map();
const compileToStringSync = async (fileCache, inputPath, compileOptions) => {
try {
const output = await checkCache(fileCache, cache, inputPath, compileOptions);
return output;
} catch (e) {
return { errors: [toBuildError(e)] };
}
};
return { cache, compileToStringSync };
};
const fileExists = (file) => {
return fs.stat(file).then(stat => stat.isFile()).catch(_ => false);
};
// Attempts to resolve a file path by joining to each load path, and returns the
// resolved path if that file exists.
// If no load paths are provided, or none resolve, the file path is assumed to
// be relative to `resolveDir`.
const resolvePath = async (resolveDir, filePath, loadPaths = []) => {
for (const loadPath of loadPaths) {
const joinedPath = path.join(loadPath, filePath);
if (await fileExists(joinedPath)) {
return joinedPath;
}
}
return path.join(resolveDir, filePath);
};
const getLoadPaths = async (cwd = '.') => {
const readFile = await fs.readFile(path.join(cwd, 'elm.json'), 'utf8');
const elmPackage = JSON.parse(readFile);
const paths = elmPackage['source-directories'].map((dir) => {
return path.join(cwd, dir);
});
return paths;
}
module.exports = (config = {}) => ({
name: 'elm',
async setup(build) {
const isProd = process.env.NODE_ENV === 'production';
const { optimize = isProd, cwd, debug, verbose, clearOnWatch } = config
const pathToElm = config.pathToElm || await getPathToElm();
const options = build.initialOptions
if (options.minify) {
Object.assign(options, {
pure: [ ...(options.pure || []), ...PURE_FUNCS ],
})
}
const compileOptions = {
pathToElm,
optimize,
processOpts: { stdout: 'pipe' },
cwd,
debug,
verbose,
};
const { cache, compileToStringSync } = cachedElmCompiler();
const fileCache = new Map();
build.onStart(() => {
fileCache.clear();
});
const loadPaths = await getLoadPaths(cwd);
build.onResolve({ filter: fileFilter }, async (args) => {
const resolvedPath = await resolvePath(args.resolveDir, args.path, loadPaths);
const resolvedDependencies = await elmCompiler.findAllDependencies(resolvedPath);
// I think we need to update deps on each resolve because you might
// change your imports on every build
updateDependencies(cache, resolvedPath, resolvedDependencies);
return ({
path: resolvedPath,
namespace,
watchFiles: [resolvedPath, ...resolvedDependencies],
});
});
build.onLoad({ filter: /.*/, namespace }, async (args) => {
if (clearOnWatch) {
// eslint-disable-next-line no-console
console.clear();
}
return compileToStringSync(fileCache, args.path, compileOptions);
});
},
});