-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
277 lines (233 loc) · 7.82 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
'use strict'
const _ = require('lodash')
const Path = require('path')
const LoaderUtils = require('loader-utils')
const Fs = require('fs')
const Spawn = require('child_process').spawn
const Globby = require('globby')
const TempFile = require('temp')
const CreateSolution = options => {
return new Promise((resolve, reject) => {
const relativeToProject = path => {
return Path.join(Path.dirname(options.projectFile), path)
}
const elmJsonDir = relativeToProject(options.project['elm-json-dir'])
Fs.readFile(Path.join(elmJsonDir, 'elm.json'), (err, contents) => {
if (err) {
return reject(err)
}
return resolve({
'project-file': options.projectFile,
'elm-json-dir': elmJsonDir,
'main-modules': _.map(options.project['main-modules'], relativeToProject),
'elm-json': JSON.parse(contents),
'cache-dependency-resolve': (options.project['cache-dependency-resolve'] || 'false').toString() === 'true',
'query-params': options.params,
})
})
})
}
const ExtractImports = importRegex => {
return fileName => {
return new Promise((resolve, reject) => {
Fs.readFile(fileName, (err, contents) => {
if (err) {
return reject(err)
}
const lines = contents.toString().split('\n')
const modules = _.chain(lines)
.map(m => m.match(importRegex))
.compact()
.map(x => x[1])
.value()
return resolve(modules)
})
})
}
}
const CheckIfElmFileExists = (basePath, cache) => {
return relativePath => {
const fullPath = Path.join(basePath, relativePath + '.elm')
if (cache[fullPath]) {
return Promise.resolve(cache[fullPath])
}
return new Promise(resolve => {
Fs.access(fullPath, Fs.R_OK, err => {
cache[fullPath] = err ? false : fullPath
resolve(cache[fullPath])
})
})
}
}
const RunFileTests = (tests, pathPart) => {
return _.reduce(
tests,
(promiseChain, test) => {
return promiseChain.then(res => {
if (res) {
return res
}
return test(pathPart)
})
},
Promise.resolve(false)
)
}
const importRegex = /^import\s+([^\s]+)/
const _CrawlDependencies = (paths, fileTests, dependencies, remainingPossibleFiles, cache) => {
if (_.isEmpty(paths) || _.isEmpty(remainingPossibleFiles)) {
return Promise.resolve(_.sortBy(dependencies, _.identity))
}
const unvisitedPaths = _.filter(paths, p => !cache[p])
const newCache = _.merge(cache, _.keyBy(unvisitedPaths, _.identity))
const parseTasks = _.map(unvisitedPaths, ExtractImports(importRegex))
return Promise.all(parseTasks)
.then(x => _.uniq(_.flatten(x)))
.then(modules => _.map(modules, m => m.replace(/\.+/g, '/')))
.then(modulePaths => {
return Promise.all(
_.map(modulePaths, modulePath => {
return RunFileTests(fileTests, modulePath)
})
).then(x => _.compact(_.flatten(x)))
})
.then(newDependencies => {
return _CrawlDependencies(
newDependencies,
fileTests,
_.uniq(dependencies.concat(newDependencies)),
_.difference(remainingPossibleFiles, newDependencies),
newCache
)
})
}
const CrawlDependencies = solution => {
const elmPackageDir = solution['elm-json-dir']
const sourceDirs = solution['elm-json']['source-directories']
const checkCache = {}
const searchDirs = _.map(sourceDirs, d => Path.join(elmPackageDir, d))
const fileTests = _.map(searchDirs, d => {
return CheckIfElmFileExists(d, checkCache)
})
return Promise.all(
_.map(searchDirs, p => {
return Globby('**/*.elm',{
gitignore: true,
cwd: p,
})
.then(res => _.filter(res, r => /elm$/i.test(r)))
})
)
.then(results => _.uniq(_.flatten(results)))
.then(allPossibleFiles => {
return _CrawlDependencies(
solution['main-modules'],
fileTests,
solution['main-modules'],
_.difference(allPossibleFiles, solution['main-modules']), {}
)
})
}
const Compile = solution => {
const collectOutput = stream => {
let output = ''
stream.on('data', d => (output += d))
return {
data: () => output,
}
}
return new Promise((resolve, reject) => {
TempFile.open({
prefix: 'elm-project',
suffix: '.js',
},
(err, info) => {
if (err) return reject(err)
const debug = solution['query-params']['debug'] ? '--debug' : ''
const optimize = solution['query-params']['optimize'] ? '--optimize' : ''
const elmArgs = _.compact(['make', debug, optimize, '--output', info.path].concat(solution['main-modules']))
const elmMakeProc = Spawn('elm', elmArgs, {
cwd: solution['elm-json-dir'],
})
let stdOut = collectOutput(elmMakeProc.stdout)
let stdErr = collectOutput(elmMakeProc.stderr)
elmMakeProc.on('close', code => {
if (code !== 0) {
return reject(stdOut.data() + '\n' + stdErr.data())
}
Fs.readFile(info.path, (err, compiledOutput) => {
if (err) return reject(err)
Fs.unlink(info.path, () => {
/* Ignore error with unlink */
})
return resolve(compiledOutput)
})
})
}
)
})
.then(output => {
return {
output,
err: null,
}
})
.catch(err => {
return {
output: null,
err,
}
})
}
const dependencyCache = {}
const ElmProjectLoader = solution => {
const getDependencies = () => {
if (solution['cache-dependency-resolve'] && dependencyCache[solution['project-file']]) {
return Promise.resolve(dependencyCache[solution['project-file']])
}
return CrawlDependencies(solution).then(deps => {
dependencyCache[solution['project-file']] = deps
return deps
})
}
return Promise.all([Compile(solution), getDependencies()]).then(results => {
return {
result: results[0],
dependencies: results[1],
solution: solution,
}
})
}
module.exports = function (source) {
const callback = this.async()
if (!callback) {
throw new Error('elm-webpack-project-loader only supports async mode.')
}
return Promise.resolve()
.then(() => {
return {
params: LoaderUtils.getOptions(this) || {},
project: JSON.parse(source),
projectFile: LoaderUtils.getRemainingRequest(this),
}
})
.then(options => {
return CreateSolution(options).then(solution => {
solution['cache-dependency-resolve'] && this.cacheable()
if (solution['cache-dependency-resolve'] && dependencyCache[solution['project-file']]) {
_.map(dependencyCache[solution['project-file']], d => this.addDependency(d))
}
return ElmProjectLoader(solution).then(loaded => {
_.map(loaded.dependencies, d => this.addDependency(d))
if (loaded.result.err) {
throw loaded.result.err
}
callback(null, loaded.result.output)
})
})
})
.catch(e => {
this.emitError(e)
callback(e)
})
}