-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
558 lines (433 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
import createBearerToken from './utils/promises/createBearerToken.js';
import createGliaFunction from './utils/create-gf.js';
import createGfVersion from './utils/create-gf-version.js'
import listGliaFunctions from './utils/list-gfs.js'
import fetchVersion from './utils/fetch-version.js';
import fetchVersions from './utils/fetch-versions.js';
import fetchGf from './utils/fetch-function.js';
import fetchGfLogs from './utils/fetch-logs.js';
import deployGf from './utils/deploy-gf.js'
import invokeGf from './utils/invoke-gf.js'
import * as fs from 'fs';
import { execSync } from 'child_process';
import { input, select, confirm, editor } from '@inquirer/prompts';
import chalk from 'chalk';
import dotenv from 'dotenv';
dotenv.config();
const separator = '============================='
const CLIIntro = () => {
console.log(chalk.hex('#7C19DE').bold(` ##### #######
# # # # ## # # # # # #### ##### # #### # # ####
# # # # # # # # ## # # # # # # # ## # #
# #### # # # # ##### # # # # # # # # # # # # # ####
# # # # ###### # # # # # # # # # # # # # # #
# # # # # # # # # # ## # # # # # # # ## # #
##### ###### # # # # #### # # #### # # #### # # #### `))
console.log(chalk.italic('v0.1.0'))
console.log(separator)
}
const CLIMainMenu = async () => {
let choices = [
{
name: 'Setup project',
value: 'setup',
description: 'Setup the environment for further requests and generate a bearer token',
}
]
if (process.env.GLIA_SITE_ID) {
choices.push({
name: 'Authenticate CLI',
value: 'auth',
description: '(Re)Generate a new bearer token',
})
}
if (process.env.GLIA_BEARER_TOKEN) {
choices.push({
name: 'Manage & build functions',
value: 'build',
description: 'Build or update a function',
})
}
choices.push({
name: '(Exit)',
value: 'exit'
})
select({
message: 'Select action:',
choices
})
.then(answer => {
switch(answer) {
case 'setup': CLISetup(); return false;
case 'auth': CLIAuth(); return false;
case 'build': CLIBuildMenu(); return false;
case 'exit': return false;
}
})
}
const CLISetup = async () => {
const APIKey = await input({
name: 'APIKey',
message: 'API key:'
});
const APISecret = await input({
name: 'APISecret',
message: 'API secret:'
});
const SiteID = await input({
type: 'input',
name: 'SiteID',
message: 'Site ID:'
});
const Environment = await select({
message: 'Choose environment:',
choices: [{
name: 'Production',
value: 'production'
}, {
name: 'Beta',
value: 'beta'
}]
});
const confirmDetails = await (confirm({ message: 'Do you want to proceed with the above details? This will overwrite your current settings.' }))
if (confirmDetails) {
let env = ``;
const url = Environment === 'beta' ? 'https://api.beta.glia.com' : 'https://api.glia.com';
env += `GLIA_KEY_ID = ${APIKey}\n`;
env += `GLIA_KEY_SECRET = ${APISecret}\n`;
env += `GLIA_SITE_ID = ${SiteID}\n`;
env += `GLIA_API_URL = ${url}\n`;
const token = await createBearerToken(APIKey, APISecret, url);
env += `GLIA_BEARER_TOKEN = ${token}\n`;
await fs.writeFileSync('.env', env);
console.log('>', chalk.green('Done.'))
console.log('> Settings written to .env file.')
CLIMainMenu();
return false;
}
};
const CLIAuth = async () => {
const envBuffer = await fs.readFileSync('.env');
let env = '' + envBuffer;
const token = await createBearerToken(process.env.GLIA_KEY_ID, process.env.GLIA_KEY_SECRET, process.env.GLIA_API_URL);
env = env.replace(/GLIA_BEARER_TOKEN = (.*)\n/g, `GLIA_BEARER_TOKEN = ${token}\n`)
await fs.writeFileSync('.env', env);
console.log('> New bearer token written to .env file.');
console.log('>', chalk.green('Done.'));
return false;
};
const CLIBuildMenu = async () => {
select({
message: 'Select action:',
choices: [
{
name: 'Create new function',
value: 'CLINewFunction',
description: 'Create a new Glia Function from scratch.',
},
{
name: 'Manage existing functions',
value: 'CLIListFunctions',
description: 'Build and deploy function versions, access function logs, see usage statistics.',
},
{
name: '(Back)',
value: 'back'
}
]
})
.then(answer => {
switch(answer) {
case 'CLINewFunction': CLINewFunction(); return false;
case 'CLIListFunctions': CLIListFunctions(); return false;
case 'back': CLIMainMenu(); return false;
}
})
}
const CLINewFunction = async () => {
const functionName = await input({
name: 'functionName',
message: 'Function name:'
});
const functionDescription = await input({
name: 'functionDescription',
message: 'Function description:'
});
const confirmDetails = await (confirm({ message: 'Proceed with above details?' }));
if (confirmDetails) {
try {
const newGliaFunction = await createGliaFunction(process.env.GLIA_SITE_ID, functionName, functionDescription);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log('> New Glia Function successfully created.');
console.log('>', chalk.green('Done.'));
}
else {
console.log('> Canceled.');
CLIBuildMenu();
return false;
}
}
const CLINewVersion = async (functionSelect) => {
const fileSelect = await input({
name: 'fileSelect',
message: 'Relative path to input file:',
default: './function.js'
});
const compatibilityDate = await input({
name: 'compatibilityDate',
message: 'Compatibility date (YYYY-MM-DD format):',
default: 'latest'
});
const passEnvVariables = await confirm({
message: 'Add custom environment variables?',
default: false
})
let environmentVariables = false;
if (passEnvVariables) {
environmentVariables = await editor({
message: 'Enter environment variables as JSON:',
default: '{\n\n}',
postfix: '.js'
});
try {
console.log(JSON.parse(environmentVariables))
console.log('> Appending environment variables.');
} catch(err) {
console.log(chalk.red('> Invalid JSON format.'));
console.log('> Canceled.');
CLIFunctionDetailsMenu(functionSelect);
return false;
}
}
const confirmDetails = await (confirm({ message: 'Proceed with above details?' }));
if (confirmDetails) {
execSync('npm run build ' + fileSelect);
console.log('> File bundled.');
try {
const gfVersion = await createGfVersion(
functionSelect, './function-out.js',
compatibilityDate === 'latest' ? false : compatibilityDate,
!environmentVariables ? false : JSON.parse(environmentVariables)
);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log('> Function version creation tasked enqueued.');
console.log('>', chalk.green('Done.'));
}
else {
console.log('> Canceled.');
CLIFunctionDetailsMenu(functionSelect);
return false;
}
}
const CLIDeployFunction = async (functionSelect, versionSelect) => {
try {
const gfDeployment = await deployGf(functionSelect, versionSelect);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log('> Deploying function version.');
console.log('> Writing audit logs.');
console.log('>', chalk.green('Done.'));
}
const CLIFunctionLogs = async (functionSelect) => {
console.log(separator)
console.log(chalk.bold('Function logs:'));
try {
const logs = await fetchGfLogs(functionSelect);
process.stdout.write(JSON.stringify(logs, null, 2));
} catch(error) {
console.log(chalk.red('> Network error.'));
console.log(error)
return false;
}
CLIFunctionDetailsMenu(functionSelect);
return false;
}
const CLIFunctionVersion = async (functionSelect, versionSelect) => {
console.log(separator)
console.log(chalk.bold('Function version details:'));
let version;
try {
version = await fetchVersion(functionSelect, versionSelect);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log(version);
console.log(separator)
select({
message: 'Select action:',
choices: [
{
name: 'Deploy function version',
value: 'deployFunction',
description: 'Mark this function version as main.',
},
{
name: '(Back)',
value: 'back'
}
]
})
.then(answer => {
switch(answer) {
case 'deployFunction': CLIDeployFunction(functionSelect, versionSelect); return false;
case 'back': CLIFunctionDetailsMenu(functionSelect); return false;
}
})
}
const CLIFunctionVersions = async (functionSelect, current_version) => {
let versions;
try {
versions = await fetchVersions(functionSelect);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
let choices = []
for (let item of versions.function_versions) {
choices.push({
name: `${current_version && current_version.id === item.id ? '(current)' : ''} ${item.id} (created at ${item.created_at})`,
value: item.id,
})
}
const versionSelect = await select({
message: 'Function versions:',
choices: [
...choices,
{
name: '(Back)',
value: 'back',
}
]
})
if (versionSelect === 'back') {
CLIFunctionDetailsMenu(functionSelect);
return false;
}
CLIFunctionVersion(functionSelect, versionSelect)
}
const CLIFunctionInvoke = async (functionSelect, invocationUri) => {
const passPayload = await confirm({
message: 'Add custom payload?'
})
let payload;
if (passPayload) {
payload = await editor({
message: 'Enter payload:',
});
try {
console.log(JSON.parse(payload))
console.log('> Appending custom payload.');
} catch(err) {
console.log(chalk.red('> Invalid JSON format.'));
console.log('> Canceled.');
CLIFunctionDetailsMenu(functionSelect);
return false;
}
}
console.log('> Invoking function.');
let response;
try {
response = await invokeGf(invocationUri, payload);
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log(separator);
console.log(chalk.bold('Function response:'));
console.log(response);
CLIFunctionDetailsMenu(functionSelect);
return false;
}
const CLIFunctionDetailsMenu = async (functionSelect) => {
console.log(separator)
console.log(chalk.bold('Function details:'))
let functionDetails;
try {
functionDetails = await fetchGf(functionSelect)
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
console.log(functionDetails)
console.log(separator)
select({
message: 'Select action:',
choices: [
{
name: 'Create new function version',
value: 'newVersion',
description: 'Bundle and create a new function version or update env. variables.',
},
{
name: 'Manage existing function versions',
value: 'functionVersions',
description: 'Retrieve function versions.',
},
{
name: 'Invoke function',
value: 'functionInvoke',
description: 'Manually invoke a function.'
},
{
name: 'Fetch logs',
value: 'functionLogs',
description: 'Retrieve runtime logs for this function.',
},
{
name: '(Back)',
value: 'back'
}
]
})
.then(answer => {
switch(answer) {
case 'functionLogs': CLIFunctionLogs(functionSelect); return false;
case 'newVersion': CLINewVersion(functionSelect); return false;
case 'functionVersions': CLIFunctionVersions(functionSelect, functionDetails.current_version); return false;
case 'functionInvoke': CLIFunctionInvoke(functionSelect, functionDetails.invocation_uri); return false;
case 'back': CLIBuildMenu(); return false; // alternative CLIListFunctions()
}
})
}
const CLIListFunctions = async () => {
let list;
try {
list = await listGliaFunctions();
} catch(error) {
console.log(chalk.red('> Network error.'));
return false;
}
let choices = []
for (let item of list.functions) {
choices.push({
name: item.name,
value: item.id,
})
}
const functionSelect = await select({
message: 'Select function:',
choices: [
...choices,
{
name: '(Back)',
value: 'back',
}
]
})
if (functionSelect === 'back') {
CLIBuildMenu();
return false;
}
CLIFunctionDetailsMenu(functionSelect)
}
CLIIntro();
CLIMainMenu();