-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
268 lines (240 loc) · 6.79 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
const path = require('path')
const { promisify } = require('util')
const WebSocket = require('ws')
const compileTemplate = require('./utils/compile-template')
const WebpackFileEntry = require('./utils/webpack-file-entry')
const manifestUtils = require('./manifest-utils')
const vendors = require('./vendors.json')
class WebextensionPlugin {
constructor ({
port = 35729,
host = '127.0.0.1',
reconnectTime = 3000,
autoreload = true,
vendor = 'chrome',
manifestDefaults = {},
quiet = false
} = {}) {
// Apply Settings
this.port = port
this.host = host
this.autoreload = autoreload
this.reconnectTime = reconnectTime
this.vendor = vendor
this.manifestDefaults = manifestDefaults
this.quiet = quiet
// Set some defaults
this.server = null
this.isWatching = false
this.startTime = Date.now()
this.prevFileTimestamps = new Map()
}
/**
* Install plugin (install hooks)
*
* @param {Object} compiler
*/
apply (compiler) {
const { name } = this.constructor
compiler.hooks.watchRun.tapPromise(name, this.watchRun.bind(this))
compiler.hooks.emit.tapPromise(name, this.emit.bind(this))
compiler.hooks.afterCompile.tap(name, this.afterCompile.bind(this))
compiler.hooks.done.tap(name, this.done.bind(this))
}
/**
* Webpack watchRun hook
*
* @param {Boolean} watching
*/
watchRun (watching) {
this.isWatching = true
return this.startServer()
}
/**
* Webpack emit hook
*
* @param {Object} compilation
*/
emit (compilation) {
const { inputFileSystem } = compilation
this.readFile = promisify(inputFileSystem.readFile.bind(inputFileSystem))
return Promise.all([
this.addClient(compilation),
this.addManifest(compilation)
])
}
/**
* Webpack afteCompile hook
*
* @param {Object} compilation
*/
afterCompile (compilation) {
return this.watchManifest(compilation)
}
/**
* Add manifest to the filesDependencies
*
* @param {Object} compilation
*/
watchManifest (compilation) {
compilation.fileDependencies.add(
path.join(compilation.options.context, 'manifest.json')
)
}
/**
* Webpack done hook
*
* @param {Object} stats
*/
done (stats) {
this.reloadExtensions(stats)
}
/**
* Start websocket server
* on watch mode
*/
startServer () {
return new Promise((resolve, reject) => {
if (!this.autoreload || !this.isWatching || this.server) return resolve()
const { host, port } = this
this.server = new WebSocket.Server({ port }, () => {
this.log(`listens on ws://${host}:${port}`)
resolve()
})
this.server.on('error', reject)
this.nofiyExtension = data => {
this.server.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data))
}
})
}
})
}
/**
* Namespaced logger
*
* @param {*} args
*/
log (...args) {
if (!this.quiet) {
console.log('webpack-webextension-plugin', ...args)
}
}
/**
* Add the client script to assets
* when autoreload enabled and is watching
*
* @param {Object} compilation
*/
async addClient (compilation) {
if (this.autoreload && this.isWatching) {
await this.compileClient(compilation)
// Add client to extension. We will includes this
// as a background script in the manifest.json later.
compilation.assets['webextension-toolbox/client.js'] = this.client
}
}
/**
* Compile the client only once
* and add it to the assets output
*
* @param {Object} compilation
*/
async compileClient ({ inputFileSystem }) {
// Only compile client once
if (this.client) return this.client
// Get the client as string
const clientPath = path.resolve(__dirname, 'client.js')
const clientBuffer = await this.readFile(clientPath)
// Inject settings
const client = compileTemplate(clientBuffer.toString(), {
port: this.port,
host: this.host,
reconnectTime: this.reconnectTime
})
// Create webpack file entry
this.client = new WebpackFileEntry(client)
}
/**
* Compile manifest and add it
* to the asset ouput
*
* @param {Object} compilation
*/
async addManifest (compilation) {
// Load manifest
const manifestPath = path.join(compilation.options.context, 'manifest.json')
const manifestBuffer = await this.readFile(manifestPath)
let manifest
// Convert to JSON
try {
manifest = JSON.parse(manifestBuffer)
} catch (error) {
throw new Error('Could not parse manifest.json')
}
manifest = {
...this.manifestDefaults,
...manifest
}
// Tranform __chrome__key -> key
manifest = manifestUtils.transformVendorKeys(manifest, this.vendor)
// Validate
await manifestUtils.validate(manifest)
// Add client
if (this.autoreload && this.isWatching) {
let result = await manifestUtils.addBackgroundscript(manifest, 'webextension-toolbox/client.js', compilation.options.context)
manifest = result.manifest
if (result.backgroundPagePath) {
compilation.assets[result.backgroundPagePath] = new WebpackFileEntry(result.backgroundPageStr)
}
}
// Create webpack file entry
const manifestStr = JSON.stringify(manifest, null, 2)
compilation.assets['manifest.json'] = new WebpackFileEntry(manifestStr)
}
/**
* Send message to extensions with
* changed files
*
* @param {Object} stats
*/
reloadExtensions (stats) {
// Skip in normal mode
if (!this.server || !this.isWatching) return
// Get changed files since last compile
const changedFiles = this.extractChangedFiles(stats.compilation)
if (changedFiles.length) {
this.log('reloading extension...')
this.nofiyExtension({
action: 'reload',
changedFiles
})
}
}
/**
* Get the changed files since
* last compilation
*
* @param {Object} compilation
*/
extractChangedFiles ({ fileTimestamps, options }) {
const changedFiles = new Map()
// Compare file timestamps with last compilation
for (const [watchfile, timestamp] of fileTimestamps.entries()) {
const isFile = Boolean(path.extname(watchfile))
if (isFile && (this.prevFileTimestamps.get(watchfile) || this.startTime) < (fileTimestamps.get(watchfile) || Infinity)) {
changedFiles.set(watchfile, timestamp)
}
}
this.prevFileTimestamps = fileTimestamps
// Remove context path
const contextRegex = new RegExp('^' + options.context.replace('/', '\\/') + '\\/')
return Array
.from(changedFiles.keys())
.map(filePath => filePath.replace(contextRegex, ''))
}
}
// Expose the vendors
WebextensionPlugin.vendors = vendors
module.exports = WebextensionPlugin