-
Notifications
You must be signed in to change notification settings - Fork 125
/
s3_plugin.js
373 lines (303 loc) · 9.59 KB
/
s3_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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import http from 'http'
import https from 'https'
import fs from 'fs'
import path from 'path'
import ProgressBar from 'progress'
import cdnizer from 'cdnizer'
import _ from 'lodash'
import mime from 'mime/lite'
import {CloudFront} from '@aws-sdk/client-cloudfront'
import {S3} from '@aws-sdk/client-s3'
import {Upload} from '@aws-sdk/lib-storage'
import packageJson from '../package.json'
import {
addSeperatorToPath,
addTrailingS3Sep,
getDirectoryFilesRecursive,
testRule,
UPLOAD_IGNORES,
DEFAULT_UPLOAD_OPTIONS,
REQUIRED_S3_UP_OPTS,
PATH_SEP,
DEFAULT_TRANSFORM,
} from './helpers'
http.globalAgent.maxSockets = https.globalAgent.maxSockets = 50
const compileError = (compilation, error) => {
compilation.errors.push(new Error(error))
}
module.exports = class S3Plugin {
constructor(options = {}) {
var {
include,
exclude,
progress,
basePath,
directory,
htmlFiles,
basePathTransform = DEFAULT_TRANSFORM,
s3Options = {},
cdnizerOptions = {},
s3UploadOptions = {},
cloudfrontInvalidateOptions = {},
priority,
} = options
this.uploadOptions = s3UploadOptions
this.cloudfrontInvalidateOptions = cloudfrontInvalidateOptions
this.isConnected = false
this.cdnizerOptions = cdnizerOptions
this.urlMappings = []
this.uploadTotal = 0
this.uploadProgress = 0
this.basePathTransform = basePathTransform
basePath = basePath ? addTrailingS3Sep(basePath) : ''
this.options = {
directory,
include,
exclude,
basePath,
priority,
htmlFiles: typeof htmlFiles === 'string' ? [htmlFiles] : htmlFiles,
progress: _.isBoolean(progress) ? progress : true,
}
this.clientConfig = {
s3Options,
maxAsyncS3: 50,
}
this.noCdnizer = !Object.keys(this.cdnizerOptions).length
if (!this.noCdnizer && !this.cdnizerOptions.files)
this.cdnizerOptions.files = []
}
apply(compiler) {
this.connect()
const isDirectoryUpload = !!this.options.directory,
hasRequiredUploadOpts = _.every(
REQUIRED_S3_UP_OPTS,
(type) => this.uploadOptions[type]
)
// Set directory to output dir or custom
this.options.directory =
this.options.directory ||
compiler.options.output.path ||
compiler.options.output.context ||
'.'
compiler.hooks.done.tapPromise(
packageJson.name,
async({compilation}) => {
let error
if (!hasRequiredUploadOpts)
error = `S3Plugin-RequiredS3UploadOpts: ${REQUIRED_S3_UP_OPTS.join(
', '
)}`
if (error) return compileError(compilation, error)
if (isDirectoryUpload) {
const dPath = addSeperatorToPath(this.options.directory)
return this.getAllFilesRecursive(dPath)
.then((files) => this.handleFiles(files))
.catch((e) => this.handleErrors(e, compilation))
} else {
return this.getAssetFiles(compilation)
.then((files) => this.handleFiles(files))
.catch((e) => this.handleErrors(e, compilation))
}
}
)
}
handleFiles(files) {
return this.changeUrls(files)
.then((files) => this.filterAllowedFiles(files))
.then((files) => this.uploadFiles(files))
.then(() => this.invalidateCloudfront())
}
async handleErrors(error, compilation) {
compileError(compilation, `S3Plugin: ${error}`)
throw error
}
getAllFilesRecursive(fPath) {
return getDirectoryFilesRecursive(fPath)
}
addPathToFiles(files, fPath) {
return files.map((file) => ({
name: file,
path: path.resolve(fPath, file),
}))
}
getFileName(file = '') {
if (_.includes(file, PATH_SEP))
return file.substring(_.lastIndexOf(file, PATH_SEP) + 1)
else return file
}
getAssetFiles({assets, outputOptions}) {
const files = _.map(assets, (value, name) => ({
name,
path: `${outputOptions.path}/${name}`,
}))
return Promise.resolve(files)
}
cdnizeHtml(file) {
return new Promise((resolve, reject) => {
fs.readFile(file.path, (err, data) => {
if (err) return reject(err)
fs.writeFile(file.path, this.cdnizer(data.toString()), (err) => {
if (err) return reject(err)
resolve(file)
})
})
})
}
changeUrls(files = []) {
if (this.noCdnizer) return Promise.resolve(files)
var allHtml
const {directory, htmlFiles = []} = this.options
if (htmlFiles.length)
allHtml = this.addPathToFiles(htmlFiles, directory).concat(files)
else allHtml = files
this.cdnizerOptions.files = allHtml.map(({name}) => `{/,}*${name}*`)
this.cdnizer = cdnizer(this.cdnizerOptions)
const [cdnizeFiles, otherFiles] = _(allHtml)
.uniq('name')
.partition((file) => /\.(html|css)/.test(file.name))
.value()
return Promise.all(
cdnizeFiles.map((file) => this.cdnizeHtml(file)).concat(otherFiles)
)
}
filterAllowedFiles(files) {
return files.reduce((res, file) => {
if (
this.isIncludeAndNotExclude(file.name) &&
!this.isIgnoredFile(file.name)
)
res.push(file)
return res
}, [])
}
isIgnoredFile(file) {
return _.some(UPLOAD_IGNORES, (ignore) => new RegExp(ignore).test(file))
}
isIncludeAndNotExclude(file) {
var isExclude,
isInclude,
{include, exclude} = this.options
isInclude = include ? testRule(include, file) : true
isExclude = exclude ? testRule(exclude, file) : false
return isInclude && !isExclude
}
connect() {
if (this.isConnected) return
this.client = new S3(this.clientConfig.s3Options)
this.isConnected = true
}
transformBasePath() {
return Promise.resolve(this.basePathTransform(this.options.basePath))
.then(addTrailingS3Sep)
.then((nPath) => (this.options.basePath = nPath))
}
setupProgressBar(uploadFiles) {
const progressTotal = uploadFiles.reduce((acc, {upload}) => upload.totalBytes + acc, 0)
const progressBar = new ProgressBar('Uploading [:bar] :percent :etas', {
complete: '>',
incomplete: '∆',
total: progressTotal,
})
var progressValue = 0
uploadFiles.forEach(({upload}) => {
upload.on('httpUploadProgress', ({loaded}) => {
progressValue += loaded
progressBar.update(progressValue / progressTotal)
})
})
}
prioritizeFiles(files) {
const remainingFiles = [...files]
const prioritizedFiles = this.options.priority.map((reg) =>
_.remove(remainingFiles, (file) => reg.test(file.name))
)
return [remainingFiles, ...prioritizedFiles]
}
uploadPriorityChunk(priorityChunk) {
const uploadFiles = priorityChunk.map((file) =>
this.uploadFile(file.name, file.path)
)
return Promise.all(uploadFiles.map(({promise}) => promise))
}
uploadInPriorityOrder(files) {
const priorityChunks = this.prioritizeFiles(files)
const uploadFunctions = priorityChunks.map((priorityChunk) => () =>
this.uploadPriorityChunk(priorityChunk)
)
return uploadFunctions.reduce(
(promise, uploadFn) => promise.then(uploadFn),
Promise.resolve()
)
}
uploadFiles(files = []) {
return this.transformBasePath().then(() => {
if (this.options.priority) {
return this.uploadInPriorityOrder(files)
} else {
const uploadFiles = files.map((file) =>
this.uploadFile(file.name, file.path)
)
if (this.options.progress) {
this.setupProgressBar(uploadFiles)
}
return Promise.all(uploadFiles.map(({promise}) => promise))
}
})
}
uploadFile(fileName, file) {
let Key = this.options.basePath + fileName
const s3Params = _.mapValues(this.uploadOptions, (optionConfig) => {
return _.isFunction(optionConfig) ? optionConfig(fileName, file) : optionConfig
})
// avoid noname folders in bucket
if (Key[0] === '/') Key = Key.substr(1)
if (s3Params.ContentType === undefined)
s3Params.ContentType = mime.getType(fileName)
const Body = fs.createReadStream(file)
const params = _.merge({Key, Body}, DEFAULT_UPLOAD_OPTIONS, s3Params)
const upload = new Upload({client: this.client, params})
if (!this.noCdnizer) this.cdnizerOptions.files.push(`*${fileName}*`)
return {upload, promise: upload.done()}
}
invalidateCloudfront() {
const {clientConfig, cloudfrontInvalidateOptions} = this
if (cloudfrontInvalidateOptions.DistributionId) {
const {
accessKeyId,
secretAccessKey,
sessionToken,
} = clientConfig.s3Options
const cloudfront = new CloudFront({
accessKeyId,
secretAccessKey,
sessionToken,
})
if (!_.isArray(cloudfrontInvalidateOptions.DistributionId))
cloudfrontInvalidateOptions.DistributionId = [
cloudfrontInvalidateOptions.DistributionId
]
const cloudfrontInvalidations = cloudfrontInvalidateOptions.DistributionId.map(
(DistributionId) =>
new Promise((resolve, reject) => {
cloudfront.createInvalidation({
DistributionId,
InvalidationBatch: {
CallerReference: Date.now().toString(),
Paths: {
Quantity: cloudfrontInvalidateOptions.Items.length,
Items: cloudfrontInvalidateOptions.Items,
},
},
}, (err, res) => {
if (err) reject(err)
else resolve(res.Id)
})
})
)
return Promise.all(cloudfrontInvalidations)
} else {
return Promise.resolve(null)
}
}
}