-
Notifications
You must be signed in to change notification settings - Fork 70
/
plugin.js
254 lines (218 loc) · 7.83 KB
/
plugin.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
const { spawn } = require('child_process')
const fs = require('fs')
const path = require('path')
const commandExistsSync = require('command-exists').sync
const chalk = require('chalk')
const Watchpack = require('watchpack')
const which = require('which')
const { homedir } = require('os')
const error = (msg) => console.error(chalk.bold.red(msg))
let info = (msg) => console.log(chalk.bold.blue(msg))
function findWasmPack() {
// https://github.com/wasm-tool/wasm-pack-plugin/issues/58
if (process.env['WASM_PACK_PATH'] !== undefined) {
return process.env['WASM_PACK_PATH']
}
const inPath = which.sync('wasm-pack', { nothrow: true })
if (inPath) {
return inPath
}
const inCargo = path.join(homedir(), '.cargo', 'bin', 'wasm-pack')
if (fs.existsSync(inCargo)) {
return inCargo
}
}
class WasmPackPlugin {
constructor(options) {
/**
* In some cases Webpack will require the pkg entrypoint before it actually
* exists. To mitigate that we are forcing a first compilation.
*
* See https://github.com/wasm-tool/wasm-pack-plugin/issues/15
*/
this._ranInitialCompilation = false
this.crateDirectory = options.crateDirectory
this.forceWatch = options.forceWatch
this.forceMode = options.forceMode
this.args = (options.args || '--verbose')
.trim()
.split(' ')
.filter((x) => x)
this.extraArgs = (options.extraArgs || '')
.trim()
.split(' ')
.filter((x) => x)
this.outDir = options.outDir || 'pkg'
this.outName = options.outName || 'index'
this.watchDirectories = (options.watchDirectories || []).concat(
path.resolve(this.crateDirectory, 'src')
)
this.watchFiles = [path.resolve(this.crateDirectory, 'Cargo.toml')]
if (options.pluginLogLevel && options.pluginLogLevel !== 'info') {
// The default value for pluginLogLevel is 'info'. If specified and it's
// not 'info', don't log informational messages. If unspecified or 'info',
// log as per usual.
info = () => {}
}
this.wp = new Watchpack()
this.isDebug = true
this.error = null
}
apply(compiler) {
this.isDebug = this.forceMode
? this.forceMode === 'development'
: compiler.options.mode === 'development'
// This fixes an error in Webpack where it cannot find
// the `pkg/index.js` file if Rust compilation errors.
this._makeEmpty()
// force first compilation
compiler.hooks.beforeCompile.tapPromise('WasmPackPlugin', () => {
if (this._ranInitialCompilation === true) {
return Promise.resolve()
}
this._ranInitialCompilation = true
return this._checkWasmPack().then(() => {
const shouldWatch =
this.forceWatch ||
(this.forceWatch === undefined && compiler.watchMode)
if (shouldWatch) {
this.wp.watch({
files: this.watchFiles,
directories: this.watchDirectories,
startTime: Date.now() - 10000,
})
this.wp.on('aggregated', () => {
this._compile(true)
})
}
return this._compile(false)
})
})
let first = true
compiler.hooks.thisCompilation.tap('WasmPackPlugin', (compilation) => {
// Super hacky, needed to workaround a bug in Webpack which causes
// thisCompilation to be triggered twice on the first compilation.
if (first) {
first = false
} else {
// This is needed in order to gracefully handle errors in Webpack,
// since Webpack has its own custom error system.
if (this.error != null) {
compilation.errors.push(this.error)
}
}
})
}
_makeEmpty() {
try {
fs.mkdirSync(this.outDir, {recursive: true})
} catch (e) {
if (e.code !== 'EEXIST') {
throw e
}
}
fs.writeFileSync(path.join(this.outDir, this.outName + '.js'), '')
}
async _checkWasmPack() {
info('🧐 Checking for wasm-pack...\n')
const bin = findWasmPack()
if (bin) {
info('✅ wasm-pack is installed at ' + bin + '. \n')
return true
}
info('ℹ️ Installing wasm-pack \n')
if (commandExistsSync('npm')) {
return runProcess('npm', ['install', '-g', 'wasm-pack'], {stdio: ['ignore', 'inherit', 'inherit']}).catch(e => {
error(
'⚠️ could not install wasm-pack globally when using npm, you must have permission to do this'
)
throw e
})
} else if (commandExistsSync('yarn')) {
return runProcess('yarn', ['global', 'add', 'wasm-pack'], {stdio: ['ignore', 'inherit', 'inherit']}).catch(e => {
error(
'⚠️ could not install wasm-pack globally when using yarn, you must have permission to do this'
)
throw e
})
} else {
error(
'⚠️ could not install wasm-pack, you must have yarn or npm installed'
)
}
return false
}
_compile(watching) {
info(
`ℹ️ Compiling your crate in ${
this.isDebug ? 'development' : 'release'
} mode...\n`
)
return fs.promises
.stat(this.crateDirectory)
.then((stats) => {
if (!stats.isDirectory()) {
throw new Error(`${this.crateDirectory} is not a directory`)
}
})
.then(() => {
return spawnWasmPack({
outDir: this.outDir,
outName: this.outName,
isDebug: this.isDebug,
cwd: this.crateDirectory,
args: this.args,
extraArgs: this.extraArgs,
})
})
.then((detail) => {
// This clears out the error when the compilation succeeds.
this.error = null
if (detail) {
info(detail)
}
info('✅ Your crate has been correctly compiled\n')
})
.catch((e) => {
// Webpack has a custom error system, so we cannot return an
// error directly, instead we need to trigger it later.
this.error = e
if (watching) {
// This is to trigger a recompilation so it displays the error message
this._makeEmpty()
}
})
}
}
function spawnWasmPack({ outDir, outName, isDebug, cwd, args, extraArgs }) {
const bin = findWasmPack()
const allArgs = [
...args,
'build',
'--out-dir',
outDir,
'--out-name',
outName,
...(isDebug ? ['--dev'] : []),
...extraArgs,
]
const options = {
cwd,
stdio: 'inherit',
}
return runProcess(bin, allArgs, options)
}
function runProcess(bin, args, options) {
return new Promise((resolve, reject) => {
const p = spawn(bin, args, options)
p.on('close', (code) => {
if (code === 0) {
resolve()
} else {
reject(new Error('Rust compilation.'))
}
})
p.on('error', reject)
})
}
module.exports = WasmPackPlugin