-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
398 lines (350 loc) · 12.4 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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/* eslint-disable max-len */
const chalk = require('chalk')
const semver = require('semver')
const fs = require('fs')
const fsp = require('fs').promises
const path = require('path')
const { EOL } = require('os')
const { bundleAmazon } = require('./bundler/amazon/index')
const { bundleGoogle } = require('./bundler/google/index')
const { getNamedExportKeys } = require('./discoverer/index')
const { deployAmazon } = require('./deployer/amazon/index')
const { publishAmazon } = require('./publisher/amazon/index')
const { spinnies, log, logdev } = require('./printers/index')
const { zip } = require('./zipper/index')
const { deployGoogle, publishGoogle } = require('./deployer/google/index')
const { transpile } = require('./transpiler/index')
const packagejson = require('./package.json')
const { createCopy } = require('./copier/index')
const { zipDir } = require('./zipper/google/index')
const { kindle } = require('./kindler/index')
const { amazonSchema, googleSchema } = require('./schemas/index')
/**
*
* @param {string} fpath Path to .js file
*/
async function bundleTranspileZipAmazon(fpath) {
// Bundle
let amazonBundledCode
try {
amazonBundledCode = await bundleAmazon(fpath)
} catch (e) {
log(`Errored bundling ${fpath} for Amazon: ${e}`)
return // just skip that file
}
// Transpile
const amazonTranspiledCode = transpile(amazonBundledCode)
// Zip
try {
const amazonZipPath = await zip({
'index.js': amazonTranspiledCode,
})
return amazonZipPath
} catch (e) {
// probably underlying issue with the zipping library or OS
// skip that file
log(`Errored zipping ${fpath} for Amazon: ${e}`)
}
}
// TODO those are basically the same now
// but for later it may be good to have them separate
// in case they start to diverge
// /**
// *
// * @param {string} fpath Path to .js file
// * @param {string} dir
// */
// async function bundleTranspileZipGoogle(fpath, dir) {
// // Bundle (omits any npm packages)
// let googleBundledCode
// try {
// googleBundledCode = await bundleGoogle(fpath)
// } catch (e) {
// log(`Errored bundling ${fpath} for Google: ${e}`)
// return // just skip that file
// }
// // Transpile
// const googleTranspiledCode = transpile(googleBundledCode)
// // Try to locate a package.json
// // Needed so google installs the npm packages
// const packageJsonPath = path.join(dir, 'package.json')
// let packageJsonContent
// if (fs.existsSync(packageJsonPath)) {
// packageJsonContent = fs.readFileSync(packageJsonPath, { encoding: 'utf-8' })
// } else {
// // warn
// log(`No package.json found in this directory.
// On Google, therefore no dependencies will be included`)
// }
// // Zip code and package.json
// try {
// const googleZipPath = await zip({
// 'index.js': googleTranspiledCode,
// 'package.json': packageJsonContent || undefined,
// })
// return googleZipPath
// } catch (e) {
// // probably underlying issue with the zipping library or OS
// throw new Error(`Errored zipping ${fpath} for Google: ${e}`)
// }
// }
async function bundleTranspileZipGoogle(fpath, dir, exps) {
// warn if package.json does not exist
// (Google won't install npm dependencies then)
if (fs.existsSync(path.join(dir, 'package.json')) === false) {
log(`No package.json found in this directory.
On Google, therefore no dependencies will be included`)
}
// copy whole dir to /tmp so we can tinker with it
const googlecopyDir = await createCopy(
dir,
['node_modules', '.git', '.github', 'hyperform.json'],
)
const indexJsPath = path.join(googlecopyDir, 'index.js')
let indexJsAppendix = ''
// add import-export appendix
indexJsAppendix = kindle(indexJsAppendix, dir, [
{
p: fpath,
exps: exps,
},
])
// add platform appendix
indexJsAppendix = transpile(indexJsAppendix)
// write or append to index.js in our tinker folder
if (fs.existsSync(indexJsPath) === false) {
await fsp.writeFile(indexJsPath, indexJsAppendix, { encoding: 'utf-8' })
} else {
await fsp.appendFile(indexJsPath, indexJsAppendix, { encoding: 'utf-8' })
}
// zip tinker folder
const googleZipPath = await zipDir(
googlecopyDir,
['node_modules', '.git', '.github', 'hyperform.json'], // superfluous we didnt copy them in the first place
)
return googleZipPath
}
/**
* @description Deploys a given code .zip to AWS Lambda, and gives it a HTTP endpoint via API Gateway
* @param {string} name
* @param {string} region
* @param {string} zipPath
* @param {boolean} isPublic whether to publish
* @returns {string?} If isPublic was true, URL of the endpoint of the Lambda
*/
async function deployPublishAmazon(name, region, zipPath, isPublic) {
const amazonSpinnieName = `amazon-main-${name}`
try {
spinnies.add(amazonSpinnieName, { text: `Deploying ${name} to AWS Lambda` })
// Deploy it
const amazonDeployOptions = {
name: name,
region: region,
}
const amazonArn = await deployAmazon(zipPath, amazonDeployOptions)
let amazonUrl
// Publish it if isPpublic
if (isPublic === true) {
amazonUrl = await publishAmazon(amazonArn, region)
}
spinnies.succ(amazonSpinnieName, { text: `🟢 Deployed ${name} to AWS Lambda ${amazonUrl || ''}` })
// (return url)
return amazonUrl
} catch (e) {
spinnies.f(amazonSpinnieName, {
text: `Error deploying ${name} to AWS Lambda: ${e.stack}`,
})
logdev(e, e.stack)
return null
}
}
// TODO probieren
// TODO tests anpassen
// TODO testen
// TODO tests schreiben, refactoren
/**
* @description Deploys and publishes a give code .zip to Google Cloud Functions
* @param {string} name
* @param {string} region
* @param {string} project
* @param {string} zipPath
* @param {boolean} isPublic whether to publish
* @returns {string?} If isPublic was true, URL of the Google Cloud Function
*/
async function deployPublishGoogle(name, region, project, zipPath, isPublic) {
const googleSpinnieName = `google-main-${name}`
try {
spinnies.add(googleSpinnieName, { text: `Deploying ${name} to Google Cloud Functions` })
const googleOptions = {
name: name,
project: project, // process.env.GC_PROJECT,
region: region, // TODO get from parsedhyperfromjson
runtime: 'nodejs12',
}
const googleUrl = await deployGoogle(zipPath, googleOptions)
if (isPublic === true) {
// enables anyone with the URL to call the function
await publishGoogle(name, project, region)
}
spinnies.succ(googleSpinnieName, { text: `🟢 Deployed ${name} to Google Cloud Functions ${googleUrl || ''}` })
console.log('Google takes another 1 - 2m for changes to take effect')
// return url
return googleUrl
} catch (e) {
spinnies.f(googleSpinnieName, {
text: `${chalk.rgb(255, 255, 255).bgWhite(' Google ')} ${name}: ${e.stack}`,
})
logdev(e, e.stack)
return null
}
}
/**
* @param {string} dir
* @param {Regex} fpath the path to the .js file whose exports should be deployed
* @param {amazon|google} platform
* @param {boolean?} _isPublic
* @param {{amazon: {aws_access_key_id:string, aws_secret_access_key: string, aws_region: string}}} parsedHyperformJson
*/
async function main(dir, fpath, platform, parsedHyperformJson, _isPublic) {
// Check node version (again)
const version = packagejson.engines.node
if (semver.satisfies(process.version, version) !== true) {
console.log(`Hyperform needs node ${version} or newer, but version is ${process.version}.`);
process.exit(1);
}
// verify parsedHyperformJson (again)
let schema
if (platform === 'amazon') schema = amazonSchema
if (platform === 'google') schema = googleSchema
const { error, value } = schema.validate(parsedHyperformJson)
if (error) {
throw new Error(`${error} ${value}`)
}
const absfpath = path.resolve(dir, fpath)
// determine named exports
const exps = getNamedExportKeys(absfpath)
if (exps.length === 0) {
log(`No named CommonJS exports found in ${absfpath}. ${EOL}Named exports have the form 'module.exports = { ... }' or 'exports.... = ...' `)
return [] // no endpoint URLs created
}
const isToAmazon = platform === 'amazon'
const isToGoogle = platform === 'google'
let amazonZipPath
let googleZipPath
if (isToAmazon === true) {
amazonZipPath = await bundleTranspileZipAmazon(absfpath)
}
if (isToGoogle === true) {
googleZipPath = await bundleTranspileZipGoogle(absfpath, dir, exps)
}
/// ///////////////////////////////////////////////////
/// Each export, deploy as function & publish. Obtain URL.
/// ///////////////////////////////////////////////////
const isPublic = _isPublic || false
let endpoints = await Promise.all(
// For each export
exps.map(async (exp) => {
/// //////////////////////////////////////////////////////////
/// Deploy to Amazon
/// //////////////////////////////////////////////////////////
let amazonUrl
if (isToAmazon === true) {
amazonUrl = await deployPublishAmazon(
exp,
parsedHyperformJson.amazon.aws_region,
amazonZipPath,
isPublic,
)
}
/// //////////////////////////////////////////////////////////
/// Deploy to Google
/// //////////////////////////////////////////////////////////
let googleUrl
if (isToGoogle === true) {
googleUrl = await deployPublishGoogle(
exp,
// TODO lol
parsedHyperformJson.google.gc_region,
parsedHyperformJson.google.gc_project, // TODO
googleZipPath,
isPublic,
)
}
return amazonUrl || googleUrl // for tests etc
}),
)
endpoints = endpoints.filter((el) => el)
return { urls: endpoints }
/// //////////////////////////////////////////////////////////
// Bundle and zip for Google (once) //
/// //////////////////////////////////////////////////////////
// TODO
// NOTE that google and amazon now work fundamentally different
// Google - 1 deployment package
// For each file
// bundle
// transpile
// // Amazon
// // zip
// // deployAmazon
// // publishAmazon
// // Later instead of N times, just create 1 deployment package for all functions
// const endpoints = await Promise.all(
// // For each file
// infos.map(async (info) => {
// const toAmazon = parsedHyperformJson.amazon != null
// const toGoogle = parsedHyperformJson.google != null
// /// //////////////////////////////////////////////////////////
// // Bundle and zip for Amazon //
// /// //////////////////////////////////////////////////////////
// let amazonZipPath
// if (toAmazon === true) {
// amazonZipPath = await bundleTranspileZipAmazon(info.p)
// }
// /// //////////////////////////////////////////////////////////
// // Bundle and zip for Google //
// // NOW DONE ABOVE
// /// //////////////////////////////////////////////////////////
// // let googleZipPath
// // if (toGoogle === true) {
// // googleZipPath = await bundleTranspileZipGoogle(info.p)
// // }
// // For each matching export
// const endpts = await Promise.all(
// info.exps.map(async (exp, idx) => {
// /// //////////////////////////////////////////////////////////
// /// Deploy to Amazon
// /// //////////////////////////////////////////////////////////
// let amazonUrl
// if (toAmazon === true) {
// amazonUrl = await deployPublishAmazon(
// exp,
// parsedHyperformJson.amazon.aws_region,
// amazonZipPath,
// isPublic,
// )
// }
// /// //////////////////////////////////////////////////////////
// /// Deploy to Google
// /// //////////////////////////////////////////////////////////
// let googleUrl
// if (toGoogle === true) {
// googleUrl = await deployPublishGoogle(
// exp,
// 'us-central1',
// 'hyperform-7fd42', // TODO
// googleZipPath,
// isPublic,
// )
// }
// return [amazonUrl, googleUrl].filter((el) => el) // for tests etc
// }),
// )
// return [].concat(...endpts)
// }),
// )
// return { urls: endpoints }
}
module.exports = {
main,
}