forked from multiplegeorges/vue-cli-plugin-s3-deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3deploy.js
207 lines (177 loc) · 5.88 KB
/
s3deploy.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
const { info, error, logWithSpinner, stopSpinner } = require('@vue/cli-shared-utils')
const path = require('path')
const fs = require('fs')
const mime = require('mime-types')
const AWS = require('aws-sdk')
const PromisePool = require('es6-promise-pool')
module.exports = async (options, api) => {
info(`Options: ${JSON.stringify(options)}`)
AWS.config.update({
region: options.region,
httpOptions: {
connectTimeout: 10 * 1000,
timeout: 10 * 1000
}
})
let s3 = new AWS.S3()
if (await bucketExists(options.bucket)) {
let cwd = process.cwd()
let cwdPrefix = new RegExp(`^${cwd}/${options.assetPath}/`)
let fileList = getAllFiles(`${cwd}/${options.assetPath}`)
let uploadCount = 0
let uploadTotal = fileList.length
info(`Deploying ${fileList.length} assets from ./${options.assetPath}/ to s3://${options.bucket}/`)
let nextFile = () => {
if (fileList.length === 0) return null
let filename = fileList.pop()
let fileStream = fs.readFileSync(filename)
let fileKey = filename.replace(cwdPrefix, '')
let promise = new Promise((resolve, reject) => {
uploadFile(options.bucket, fileKey, fileStream)
.then(() => {
uploadCount++
info(`(${uploadCount}/${uploadTotal}) Uploaded ${fileKey}`)
resolve()
})
.catch((e) => {
error(`Upload failed: ${fileKey}`)
error(e.toString())
reject(e)
})
})
return promise
}
let uploadPool = new PromisePool(nextFile, parseInt(options.uploadConcurrency, 10))
var poolPromise = uploadPool.start()
// Wait for the pool to settle.
poolPromise.then(() => {
info('Deploy complete.')
handlePWAFiles(options)
invalidateDistribution(options.cloudfrontId, options.cloudfrontMatchers)
}, (err) => {
error(err.toString())
})
} else {
error(`Bucket ${options.bucket} does not exist.`)
return
}
async function handlePWAFiles (options) {
// Handle the cache setting serially for now.
if (options.pwa) {
let pwaFiles = options.pwaFiles.split(',')
for(let i = 0; i < pwaFiles.length; i++) {
let fileKey = pwaFiles[i]
try {
logWithSpinner(`Setting Cache-Control (${i+1}/${pwaFiles.length}): ${fileKey}`)
await setCacheControl(options.bucket, fileKey)
stopSpinner()
} catch (e) {
error(`Setting Cache-Control failed: ${fileKey}`)
error(e.toString())
stopSpinner()
return
}
}
}
}
function contentTypeFor(filename) {
return mime.lookup(filename) || 'application/octet-stream'
}
async function setCacheControl(bucket, fileKey) {
// Copies in-place while updating the metadata.
let params = {
CopySource: `${bucket}/${fileKey}`,
Bucket: bucket,
Key: fileKey,
CacheControl: 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
ContentType: contentTypeFor(fileKey),
MetadataDirective: 'REPLACE'
}
return new Promise((resolve, reject) => {
s3.copyObject(params, function(err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
async function uploadFile (bucket, fileKey, fileStream) {
let params = {
Bucket: bucket,
Key: fileKey,
Body: fileStream,
ContentType: contentTypeFor(fileKey)
}
let options = { partSize: 5 * 1024 * 1024, queueSize: 4 }
return new Promise((resolve, reject) => {
s3.upload(params, options, function(err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
async function bucketExists (bucketName) {
return new Promise((resolve, reject) => {
s3.listBuckets((err, data) => {
if (err) {
reject(err)
} else {
let names = data['Buckets'].map(b => b['Name'])
resolve(names.includes(bucketName))
}
})
})
}
function getAllFiles (dir) {
return fs.readdirSync(dir).reduce((files, file) => {
const name = path.join(dir, file)
const isDirectory = fs.statSync(name).isDirectory()
return isDirectory ? [...files, ...getAllFiles(name)] : [...files, name]
}, [])
}
function isCloudfrontEnabled () {
// When this option is overridden in a .env file, the option comes through as a string, not a boolean.
// So, we need to check for the string version as well.
return options.enableCloudfront === true || options.enableCloudfront.toString().toLowerCase() === 'true'
}
function invalidateDistribution (id, matcher) {
if (!isCloudfrontEnabled()) { return }
let cloudfront = new AWS.CloudFront()
return new Promise((resolve, reject) => {
let invalidationItems = options.cloudfrontMatchers.split(',')
let params = {
DistributionId: id,
InvalidationBatch: {
CallerReference: `vue-cli-plugin-s3-deploy-${Date.now().toString()}`,
Paths: {
Quantity: invalidationItems.length,
Items: invalidationItems
}
}
}
logWithSpinner(`Invalidating CloudFront distribution: ${ id }`)
cloudfront.createInvalidation(params, (err, data) => {
if (err) {
error('Cloudfront Error!')
error(`Code: ${err.code}`)
error(`Message: ${err.message}`)
error(`AWS Request ID: ${err.requestId}`)
stopSpinner()
reject(err)
} else {
info(`Invalidation ID: ${data['Invalidation']['Id']}`)
info(`Status: ${data['Invalidation']['Status']}`)
info(`Call Reference: ${data['Invalidation']['InvalidationBatch']['CallerReference']}`)
info(`See your AWS console for on-going status on this invalidation.`)
stopSpinner()
resolve()
}
})
})
}
}