@pwrdrvr/microapps-publish 0.0.19 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/bin/run +5 -0
  2. package/dist/commands/nextjs-docker-auto.d.ts +38 -0
  3. package/dist/commands/nextjs-docker-auto.d.ts.map +1 -0
  4. package/dist/commands/nextjs-docker-auto.js +415 -0
  5. package/dist/commands/nextjs-docker-auto.js.map +1 -0
  6. package/dist/commands/nextjs-version-restore.d.ts +14 -0
  7. package/dist/commands/nextjs-version-restore.d.ts.map +1 -0
  8. package/dist/commands/nextjs-version-restore.js +57 -0
  9. package/dist/commands/nextjs-version-restore.js.map +1 -0
  10. package/dist/commands/nextjs-version.d.ts +16 -0
  11. package/dist/commands/nextjs-version.d.ts.map +1 -0
  12. package/dist/commands/nextjs-version.js +93 -0
  13. package/dist/commands/nextjs-version.js.map +1 -0
  14. package/dist/commands/preflight.d.ts +15 -0
  15. package/dist/commands/preflight.d.ts.map +1 -0
  16. package/dist/commands/preflight.js +111 -0
  17. package/dist/commands/preflight.js.map +1 -0
  18. package/dist/commands/publish.d.ts +23 -0
  19. package/dist/commands/publish.d.ts.map +1 -0
  20. package/dist/commands/publish.js +300 -0
  21. package/dist/commands/publish.js.map +1 -0
  22. package/dist/config/Config.d.ts +0 -2
  23. package/dist/config/Config.d.ts.map +1 -1
  24. package/dist/config/Config.js +0 -5
  25. package/dist/config/Config.js.map +1 -1
  26. package/dist/index.d.ts +1 -30
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +3 -448
  29. package/dist/index.js.map +1 -1
  30. package/dist/lib/DeployClient.d.ts +34 -0
  31. package/dist/lib/DeployClient.d.ts.map +1 -0
  32. package/dist/{DeployClient.js → lib/DeployClient.js} +24 -5
  33. package/dist/lib/DeployClient.js.map +1 -0
  34. package/dist/{S3TransferUtility.d.ts → lib/S3TransferUtility.d.ts} +9 -1
  35. package/dist/lib/S3TransferUtility.d.ts.map +1 -0
  36. package/dist/{S3TransferUtility.js → lib/S3TransferUtility.js} +8 -0
  37. package/dist/lib/S3TransferUtility.js.map +1 -0
  38. package/dist/{S3Uploader.d.ts → lib/S3Uploader.d.ts} +3 -2
  39. package/dist/lib/S3Uploader.d.ts.map +1 -0
  40. package/dist/{S3Uploader.js → lib/S3Uploader.js} +11 -10
  41. package/dist/lib/S3Uploader.js.map +1 -0
  42. package/dist/lib/Versions.d.ts +27 -0
  43. package/dist/lib/Versions.d.ts.map +1 -0
  44. package/dist/lib/Versions.js +76 -0
  45. package/dist/lib/Versions.js.map +1 -0
  46. package/package.json +11 -3
  47. package/src/commands/nextjs-docker-auto.ts +499 -0
  48. package/src/commands/nextjs-version-restore.ts +74 -0
  49. package/src/commands/nextjs-version.ts +114 -0
  50. package/src/commands/preflight.ts +122 -0
  51. package/src/commands/publish.ts +359 -0
  52. package/src/config/Config.ts +0 -4
  53. package/src/index.ts +1 -553
  54. package/src/{DeployClient.ts → lib/DeployClient.ts} +34 -10
  55. package/src/{S3TransferUtility.ts → lib/S3TransferUtility.ts} +9 -1
  56. package/src/{S3Uploader.ts → lib/S3Uploader.ts} +5 -4
  57. package/src/lib/Versions.ts +95 -0
  58. package/dist/DeployClient.d.ts +0 -15
  59. package/dist/DeployClient.d.ts.map +0 -1
  60. package/dist/DeployClient.js.map +0 -1
  61. package/dist/S3TransferUtility.d.ts.map +0 -1
  62. package/dist/S3TransferUtility.js.map +0 -1
  63. package/dist/S3Uploader.d.ts.map +0 -1
  64. package/dist/S3Uploader.js.map +0 -1
  65. package/dist/config/FileStore.d.ts +0 -7
  66. package/dist/config/FileStore.d.ts.map +0 -1
  67. package/dist/config/FileStore.js +0 -17
  68. package/dist/config/FileStore.js.map +0 -1
  69. package/src/config/FileStore.ts +0 -14
package/src/index.ts CHANGED
@@ -1,553 +1 @@
1
- #!/usr/bin/env node
2
- /* eslint-disable no-console */
3
-
4
- import 'source-map-support/register';
5
- // Used by ts-convict
6
- import 'reflect-metadata';
7
- import { exec } from 'child_process';
8
- import * as util from 'util';
9
- import * as lambda from '@aws-sdk/client-lambda';
10
- import * as s3 from '@aws-sdk/client-s3';
11
- import * as sts from '@aws-sdk/client-sts';
12
- import { Command, flags as flagsParser } from '@oclif/command';
13
- import { IConfig as OCLIFIConfig } from '@oclif/config';
14
- import { handle as errorHandler } from '@oclif/errors';
15
- import chalk from 'chalk';
16
- import path from 'path';
17
- import { promises as fs, pathExists, createReadStream } from 'fs-extra';
18
- import { Listr, ListrErrorTypes, ListrTask, ListrTaskObject } from 'listr2';
19
- import { Config, IConfig } from './config/Config';
20
- import DeployClient, { IDeployVersionPreflightResult } from './DeployClient';
21
- import S3Uploader from './S3Uploader';
22
- import S3TransferUtility from './S3TransferUtility';
23
- import { Upload } from '@aws-sdk/lib-storage';
24
- import { contentType } from 'mime-types';
25
- const asyncSetTimeout = util.promisify(setTimeout);
26
- const asyncExec = util.promisify(exec);
27
-
28
- const RUNNING_TEXT = ' RUNS ';
29
- const RUNNING = chalk.reset.inverse.yellow.bold(RUNNING_TEXT) + ' ';
30
-
31
- const lambdaClient = new lambda.LambdaClient({
32
- maxAttempts: 8,
33
- });
34
-
35
- interface IVersions {
36
- version: string;
37
- alias?: string;
38
- }
39
-
40
- interface IContext {
41
- preflightResult: IDeployVersionPreflightResult;
42
- files: string[];
43
- }
44
-
45
- class PublishTool extends Command {
46
- static flags = {
47
- version: flagsParser.version({
48
- char: 'v',
49
- }),
50
- help: flagsParser.help(),
51
- deployerLambdaName: flagsParser.string({
52
- char: 'd',
53
- multiple: false,
54
- required: true,
55
- description: 'Name of the deployer lambda function',
56
- }),
57
- newVersion: flagsParser.string({
58
- char: 'n',
59
- multiple: false,
60
- required: true,
61
- description: 'New semantic version to apply',
62
- }),
63
- repoName: flagsParser.string({
64
- char: 'r',
65
- multiple: false,
66
- required: true,
67
- description: 'Name (not URI) of the Docker repo for the app',
68
- }),
69
- leaveCopy: flagsParser.boolean({
70
- char: 'l',
71
- default: false,
72
- required: false,
73
- description: 'Leave a copy of the modifed files as .modified',
74
- }),
75
- };
76
-
77
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
78
- private static escapeRegExp(value: string): string {
79
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
80
- }
81
-
82
- private VersionAndAlias: IVersions;
83
- private IMAGE_TAG = '';
84
- private IMAGE_URI = '';
85
- private FILES_TO_MODIFY: {
86
- path: string;
87
- versions: IVersions;
88
- }[];
89
- private _restoreFilesStarted = false;
90
-
91
- constructor(argv: string[], config: OCLIFIConfig) {
92
- super(argv, config);
93
- this.restoreFiles = this.restoreFiles.bind(this);
94
- }
95
-
96
- async run(): Promise<void> {
97
- const { flags: parsedFlags } = this.parse(PublishTool);
98
- const version = parsedFlags.newVersion;
99
- const leaveFiles = parsedFlags.leaveCopy;
100
- const lambdaName = parsedFlags.deployerLambdaName;
101
- const ecrRepo = parsedFlags.repoName;
102
-
103
- // Override the config value
104
- const config = Config.instance;
105
- config.deployer.lambdaName = lambdaName;
106
- config.app.semVer = version;
107
-
108
- // Get the account ID and region from STS
109
- // TODO: Move this to the right place
110
- if (config.app.awsAccountID === 0 || config.app.awsRegion === '') {
111
- const stsClient = new sts.STSClient({
112
- maxAttempts: 8,
113
- });
114
- const stsResponse = await stsClient.send(new sts.GetCallerIdentityCommand({}));
115
- if (config.app.awsAccountID === 0) {
116
- config.app.awsAccountID = parseInt(stsResponse.Account, 10);
117
- }
118
- if (config.app.awsRegion === '') {
119
- config.app.awsRegion = stsClient.config.region as string;
120
- }
121
- }
122
- if (config.app.ecrHost === '') {
123
- config.app.ecrHost = `${config.app.awsAccountID}.dkr.ecr.${config.app.awsRegion}.amazonaws.com`;
124
- }
125
- if (ecrRepo) {
126
- config.app.ecrRepoName = ecrRepo;
127
- } else if (config.app.ecrRepoName === '') {
128
- config.app.ecrRepoName = `microapps-app-${config.app.name}${Config.envLevel}-repo`;
129
- }
130
-
131
- this.VersionAndAlias = this.createVersions(version);
132
- const versionOnly = { version: this.VersionAndAlias.version };
133
-
134
- this.FILES_TO_MODIFY = [
135
- { path: 'package.json', versions: versionOnly },
136
- // { path: 'deploy.json', versions: this.VersionAndAlias },
137
- { path: 'next.config.js', versions: versionOnly },
138
- ] as { path: string; versions: IVersions }[];
139
-
140
- // Install handler to ensure that we restore files
141
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
142
- process.on('SIGINT', async () => {
143
- if (this._restoreFilesStarted) {
144
- return;
145
- } else {
146
- this._restoreFilesStarted = true;
147
- }
148
- this.log('Caught Ctrl-C, restoring files');
149
- await S3Uploader.removeTempDirIfExists();
150
- await this.restoreFiles();
151
- });
152
-
153
- if (config === undefined) {
154
- this.error('Failed to load the config file');
155
- }
156
- if (config.app.staticAssetsPath === undefined) {
157
- this.error('StaticAssetsPath must be specified in the config file');
158
- }
159
-
160
- //
161
- // Setup Tasks
162
- //
163
-
164
- const tasks = new Listr<IContext>(
165
- [
166
- {
167
- title: 'Logging into ECR',
168
- task: async (ctx, task) => {
169
- const origTitle = task.title;
170
- task.title = RUNNING + origTitle;
171
-
172
- await this.loginToECR(config);
173
-
174
- task.title = origTitle;
175
- },
176
- },
177
- {
178
- title: 'Modifying Config Files',
179
- task: async (ctx, task) => {
180
- const origTitle = task.title;
181
- task.title = RUNNING + origTitle;
182
-
183
- // Modify the existing files with the new version
184
- for (const fileToModify of this.FILES_TO_MODIFY) {
185
- task.output = `Patching version (${this.VersionAndAlias.version}) into ${fileToModify.path}`;
186
- if (
187
- !(await this.writeNewVersions(fileToModify.path, fileToModify.versions, leaveFiles))
188
- ) {
189
- task.output = `Failed modifying file: ${fileToModify.path}`;
190
- }
191
- }
192
-
193
- task.title = origTitle;
194
- },
195
- },
196
- {
197
- title: 'Preflight Version Check',
198
- task: async (ctx, task) => {
199
- const origTitle = task.title;
200
- task.title = RUNNING + origTitle;
201
-
202
- // Confirm the Version Does Not Exist in Published State
203
- task.output = `Checking if deployed app/version already exists for ${config.app.name}/${version}`;
204
- ctx.preflightResult = await DeployClient.DeployVersionPreflight(config);
205
- if (ctx.preflightResult.exists) {
206
- task.output = `Warning: App/Version already exists: ${config.app.name}/${config.app.semVer}`;
207
- }
208
-
209
- task.title = origTitle;
210
- },
211
- },
212
- {
213
- title: 'Serverless Next.js Build',
214
- task: async (ctx, task) => {
215
- const origTitle = task.title;
216
- task.title = RUNNING + origTitle;
217
-
218
- task.output = `Invoking serverless next.js build for ${config.app.name}/${version}`;
219
-
220
- // Run the serverless next.js build
221
- await asyncExec('serverless');
222
-
223
- if (config.app.serverlessNextRouterPath !== undefined) {
224
- task.output = 'Copying Serverless Next.js router to build output directory';
225
- await fs.copyFile(
226
- config.app.serverlessNextRouterPath,
227
- './.serverless_nextjs/index.js',
228
- );
229
- }
230
-
231
- task.title = origTitle;
232
- },
233
- },
234
- {
235
- title: 'Publish to ECR',
236
- task: async (ctx, task) => {
237
- const origTitle = task.title;
238
- task.title = RUNNING + origTitle;
239
-
240
- // Docker, build, tag, push to ECR
241
- // Note: Need to already have AWS env vars set
242
- await this.publishToECR(config);
243
-
244
- task.title = origTitle;
245
- },
246
- },
247
- {
248
- title: 'Deploy to Lambda',
249
- task: async (ctx, task) => {
250
- const origTitle = task.title;
251
- task.title = RUNNING + origTitle;
252
-
253
- // Update the Lambda function
254
- await this.deployToLambda(config, this.VersionAndAlias);
255
-
256
- task.title = origTitle;
257
- },
258
- },
259
- {
260
- title: 'Confirm Static Assets Folder Exists',
261
- task: async (ctx, task) => {
262
- const origTitle = task.title;
263
- task.title = RUNNING + origTitle;
264
-
265
- // Check that Static Assets Folder exists
266
- if (!(await pathExists(config.app.staticAssetsPath))) {
267
- this.error(`Static asset path does not exist: ${config.app.staticAssetsPath}`);
268
- }
269
-
270
- task.title = origTitle;
271
- },
272
- },
273
- {
274
- title: 'Copy Static Files to Local Upload Dir',
275
- task: async (ctx, task) => {
276
- const origTitle = task.title;
277
- task.title = RUNNING + origTitle;
278
-
279
- // Copy files to local dir to be uploaded
280
- await S3Uploader.CopyToUploadDir(config, ctx.preflightResult.response.s3UploadUrl);
281
-
282
- task.title = origTitle;
283
- },
284
- },
285
- // {
286
- // title: 'Upload Files to S3 Staging AppName/Version Prefix',
287
- // task: async (ctx, task) => {
288
- // const origTitle = task.title;
289
- // task.title = RUNNING + origTitle;
290
-
291
- // const { destinationPrefix, bucketName } = S3Uploader.ParseUploadPath(
292
- // ctx.preflightResult.response.s3UploadUrl,
293
- // );
294
-
295
- // // Upload Files to S3 Staging AppName/Version Prefix
296
- // await S3TransferUtility.UploadDir(
297
- // S3Uploader.TempDir,
298
- // destinationPrefix,
299
- // bucketName,
300
- // ctx.preflightResult.response,
301
- // );
302
-
303
- // task.title = origTitle;
304
- // },
305
- // },
306
- {
307
- title: 'Enumerate Files to Upload to S3',
308
- task: async (ctx, task) => {
309
- const origTitle = task.title;
310
- task.title = RUNNING + origTitle;
311
-
312
- ctx.files = (await S3TransferUtility.GetFiles(S3Uploader.TempDir)) as string[];
313
-
314
- task.title = origTitle;
315
- },
316
- },
317
- {
318
- title: 'Upload Static Files to S3',
319
- task: (ctx, task) => {
320
- const origTitle = task.title;
321
- task.title = RUNNING + origTitle;
322
-
323
- const { bucketName } = S3Uploader.ParseUploadPath(
324
- ctx.preflightResult.response.s3UploadUrl,
325
- );
326
-
327
- // Use temp credentials for S3
328
- const s3Client = new s3.S3Client({
329
- maxAttempts: 16,
330
- credentials: {
331
- accessKeyId: ctx.preflightResult.response.awsCredentials.accessKeyId,
332
- secretAccessKey: ctx.preflightResult.response.awsCredentials.secretAccessKey,
333
- sessionToken: ctx.preflightResult.response.awsCredentials.sessionToken,
334
- },
335
- });
336
-
337
- const tasks: ListrTask<IContext>[] = ctx.files.map((filePath) => ({
338
- task: async (ctx: IContext, subtask) => {
339
- const origTitle = subtask.title;
340
- subtask.title = RUNNING + origTitle;
341
-
342
- const upload = new Upload({
343
- client: s3Client,
344
- leavePartsOnError: false,
345
- params: {
346
- Bucket: bucketName,
347
- Key: path.relative(S3Uploader.TempDir, filePath),
348
- Body: createReadStream(filePath),
349
- ContentType: contentType(path.basename(filePath)) || 'application/octet-stream',
350
- CacheControl: 'max-age=86400; public',
351
- },
352
- });
353
- await upload.done();
354
-
355
- subtask.title = origTitle;
356
- },
357
- }));
358
-
359
- task.title = origTitle;
360
-
361
- return task.newListr(tasks, {
362
- concurrent: 8,
363
- rendererOptions: {
364
- clearOutput: false,
365
- showErrorMessage: true,
366
- showTimer: true,
367
- },
368
- });
369
- },
370
- },
371
- {
372
- title: `Creating MicroApp Application: ${config.app.name}`,
373
- task: async (ctx, task) => {
374
- const origTitle = task.title;
375
- task.title = RUNNING + origTitle;
376
-
377
- // Call Deployer to Create App if Not Exists
378
- await DeployClient.CreateApp(config);
379
-
380
- task.title = origTitle;
381
- },
382
- },
383
- {
384
- title: `Creating MicroApp Version: ${config.app.semVer}`,
385
- task: async (ctx, task) => {
386
- const origTitle = task.title;
387
- task.title = RUNNING + origTitle;
388
-
389
- // Call Deployer to Deploy AppName/Version
390
- await DeployClient.DeployVersion(config);
391
-
392
- task.title = origTitle;
393
- },
394
- },
395
- ],
396
- {
397
- rendererOptions: {
398
- showTimer: true,
399
- },
400
- },
401
- );
402
-
403
- try {
404
- await tasks.run();
405
- this.log(`Published: ${config.app.name}/${config.app.semVer}`);
406
- } catch (error) {
407
- this.log(`Caught exception: ${error.message}`);
408
- } finally {
409
- await this.restoreFiles();
410
- }
411
- }
412
-
413
- public async restoreFiles(): Promise<void> {
414
- // Put the old files back when succeeded or failed
415
- for (const fileToModify of this.FILES_TO_MODIFY) {
416
- try {
417
- const stats = await fs.stat(`${fileToModify.path}.original`);
418
- if (stats.isFile()) {
419
- // Remove the possibly modified file
420
- await fs.unlink(fileToModify.path);
421
-
422
- // Move the original file back
423
- await fs.rename(`${fileToModify.path}.original`, fileToModify.path);
424
- }
425
- } catch {
426
- // don't care... if the file doesn't exist we can't do anything
427
- }
428
- }
429
- }
430
-
431
- private createVersions(version: string): IVersions {
432
- return { version, alias: `v${version.replace(/\./g, '_')}` };
433
- }
434
-
435
- private async writeNewVersions(
436
- path: string,
437
- requiredVersions: IVersions,
438
- leaveFiles: boolean,
439
- ): Promise<boolean> {
440
- const stats = await fs.stat(path);
441
- if (!stats.isFile) {
442
- return false;
443
- }
444
-
445
- // Make a backup of the file
446
- await fs.copyFile(path, `${path}.original`);
447
-
448
- // File exists, check that it has the required version strings
449
- let fileText = await fs.readFile(path, 'utf8');
450
-
451
- for (const key of Object.keys(requiredVersions)) {
452
- const placeHolder = key === 'version' ? '0.0.0' : 'v0_0_0';
453
- if (fileText.indexOf(placeHolder) === -1) {
454
- // The required placeholder is missing
455
- return false;
456
- } else {
457
- const regExp = new RegExp(PublishTool.escapeRegExp(placeHolder), 'g');
458
- fileText = fileText.replace(
459
- regExp,
460
- key === 'version' ? requiredVersions.version : (requiredVersions.alias as string),
461
- );
462
- }
463
- }
464
-
465
- // Write the updated file contents
466
- await fs.writeFile(path, fileText, 'utf8');
467
-
468
- // Leave a copy of the modified file if requested
469
- if (leaveFiles) {
470
- // This copy will overwrite an existing file
471
- await fs.copyFile(path, `${path}.modified`);
472
- }
473
-
474
- return true;
475
- }
476
-
477
- private async loginToECR(config: IConfig): Promise<boolean> {
478
- this.IMAGE_TAG = `${config.app.ecrRepoName}:${this.VersionAndAlias.version}`;
479
- this.IMAGE_URI = `${config.app.ecrHost}/${this.IMAGE_TAG}`;
480
-
481
- try {
482
- await asyncExec(
483
- `aws ecr get-login-password --region ${config.app.awsRegion} | docker login --username AWS --password-stdin ${config.app.ecrHost}`,
484
- );
485
- } catch (error) {
486
- throw new Error(`ECR Login Failed: ${error.message}`);
487
- }
488
-
489
- return true;
490
- }
491
-
492
- private async publishToECR(config: IConfig): Promise<void> {
493
- // console.log('Starting Docker build');
494
- await asyncExec(`docker build -f Dockerfile -t ${this.IMAGE_TAG} .`);
495
- await asyncExec(`docker tag ${this.IMAGE_TAG} ${config.app.ecrHost}/${this.IMAGE_TAG}`);
496
- // console.log('Starting Docker push to ECR');
497
- await asyncExec(`docker push ${config.app.ecrHost}/${this.IMAGE_TAG}`);
498
- }
499
-
500
- private async deployToLambda(config: IConfig, versions: IVersions): Promise<void> {
501
- // Create Lambda version
502
- // console.log('Updating Lambda code to point to new Docker image');
503
- const resultUpdate = await lambdaClient.send(
504
- new lambda.UpdateFunctionCodeCommand({
505
- FunctionName: config.app.lambdaName,
506
- ImageUri: this.IMAGE_URI,
507
- Publish: true,
508
- }),
509
- );
510
- const lambdaVersion = resultUpdate.Version;
511
- // console.log('Lambda version created: ', resultUpdate.Version);
512
-
513
- let lastUpdateStatus = resultUpdate.LastUpdateStatus;
514
- for (let i = 0; i < 5; i++) {
515
- // When the function is created the status will be "Pending"
516
- // and we have to wait until it's done creating
517
- // before we can point an alias to it
518
- if (lastUpdateStatus === 'Successful') {
519
- // console.log(`Lambda function updated, version: ${lambdaVersion}`);
520
- break;
521
- }
522
-
523
- // If it didn't work, wait and try again
524
- await asyncSetTimeout(1000 * i);
525
-
526
- const resultGet = await lambdaClient.send(
527
- new lambda.GetFunctionCommand({
528
- FunctionName: config.app.lambdaName,
529
- Qualifier: lambdaVersion,
530
- }),
531
- );
532
-
533
- // Save the last update status so we can check on re-loop
534
- lastUpdateStatus = resultGet?.Configuration?.LastUpdateStatus;
535
- }
536
-
537
- // Create Lambda alias point
538
- // console.log(`Creating the lambda alias for the new version: ${lambdaVersion}`);
539
- const resultLambdaAlias = await lambdaClient.send(
540
- new lambda.CreateAliasCommand({
541
- FunctionName: config.app.lambdaName,
542
- Name: versions.alias,
543
- FunctionVersion: lambdaVersion,
544
- }),
545
- );
546
- // console.log(`Lambda alias created, name: ${resultLambdaAlias.Name}`);
547
- }
548
- }
549
-
550
- // @ts-expect-error catch is actually defined
551
- PublishTool.run().catch(errorHandler);
552
-
553
- export default PublishTool;
1
+ export { run } from '@oclif/command';
@@ -1,13 +1,12 @@
1
1
  import * as lambda from '@aws-sdk/client-lambda';
2
-
3
2
  import {
4
3
  IDeployVersionPreflightRequest,
5
4
  IDeployVersionPreflightResponse,
6
5
  ICreateApplicationRequest,
7
6
  IDeployerResponse,
8
7
  IDeployVersionRequest,
9
- } from '@pwrdrvr/microapps-deployer';
10
- import { IConfig } from './config/Config';
8
+ } from '@pwrdrvr/microapps-deployer-lib';
9
+ import { IConfig } from '../config/Config';
11
10
 
12
11
  export interface IDeployVersionPreflightResult {
13
12
  exists: boolean;
@@ -45,13 +44,25 @@ export default class DeployClient {
45
44
  }
46
45
  }
47
46
 
48
- public static async DeployVersionPreflight(
49
- config: IConfig,
50
- ): Promise<IDeployVersionPreflightResult> {
47
+ /**
48
+ * Check if version exists.
49
+ * Optionally get S3 creds for static asset upload.
50
+ * @param config
51
+ * @param output
52
+ * @returns
53
+ */
54
+ public static async DeployVersionPreflight(opts: {
55
+ config: IConfig;
56
+ needS3Creds?: boolean;
57
+ output: (message: string) => void;
58
+ }): Promise<IDeployVersionPreflightResult> {
59
+ const { config, needS3Creds = true, output } = opts;
60
+
51
61
  const request = {
52
62
  type: 'deployVersionPreflight',
53
63
  appName: config.app.name,
54
64
  semVer: config.app.semVer,
65
+ needS3Creds,
55
66
  } as IDeployVersionPreflightRequest;
56
67
  const response = await this._client.send(
57
68
  new lambda.InvokeCommand({
@@ -65,9 +76,10 @@ export default class DeployClient {
65
76
  Buffer.from(response.Payload).toString('utf-8'),
66
77
  ) as IDeployVersionPreflightResponse;
67
78
  if (dResponse.statusCode === 404) {
68
- console.log(`App/Version do not exist: ${config.app.name}/${config.app.semVer}`);
79
+ output(`App/Version does not exist: ${config.app.name}/${config.app.semVer}`);
69
80
  return { exists: false, response: dResponse };
70
81
  } else {
82
+ output(`App/Version exists: ${config.app.name}/${config.app.semVer}`);
71
83
  return { exists: true, response: dResponse };
72
84
  }
73
85
  } else {
@@ -75,7 +87,18 @@ export default class DeployClient {
75
87
  }
76
88
  }
77
89
 
78
- public static async DeployVersion(config: IConfig): Promise<void> {
90
+ /**
91
+ * Copy S3 static assets from staging to live bucket.
92
+ * Create API Gateway Integration for app (if needed).
93
+ * Give API Gateway permission to call the Lambda.
94
+ * Create API Gateway routes for this specific version.
95
+ * @param config
96
+ * @param task
97
+ */
98
+ public static async DeployVersion(
99
+ config: IConfig,
100
+ output: (message: string) => void,
101
+ ): Promise<void> {
79
102
  const request = {
80
103
  type: 'deployVersion',
81
104
  appName: config.app.name,
@@ -95,9 +118,10 @@ export default class DeployClient {
95
118
  Buffer.from(response.Payload).toString('utf-8'),
96
119
  ) as IDeployerResponse;
97
120
  if (dResponse.statusCode === 201) {
98
- console.log(`Deploy succeeded: ${config.app.name}/${config.app.semVer}`);
121
+ output(`Deploy succeeded: ${config.app.name}/${config.app.semVer}`);
99
122
  } else {
100
- console.log(`Deploy failed with: ${dResponse.statusCode}`);
123
+ output(`Deploy failed with: ${dResponse.statusCode}`);
124
+ throw new Error(`Lambda call to DeployVersionfailed with: ${dResponse.statusCode}`);
101
125
  }
102
126
  } else {
103
127
  throw new Error(`Lambda call to DeployVersion failed: ${JSON.stringify(response)}`);
@@ -6,11 +6,19 @@ import { promises as fs, createReadStream } from 'fs';
6
6
  import * as path from 'path';
7
7
  import * as s3 from '@aws-sdk/client-s3';
8
8
  import { Upload } from '@aws-sdk/lib-storage';
9
- import { IDeployVersionPreflightResponse } from '@pwrdrvr/microapps-deployer';
9
+ import { IDeployVersionPreflightResponse } from '@pwrdrvr/microapps-deployer-lib';
10
10
  import { contentType } from 'mime-types';
11
11
  import pMap from 'p-map';
12
12
 
13
13
  export default class S3TransferUtility {
14
+ /**
15
+ * @deprecated 2021-11-27
16
+ *
17
+ * @param s3Path
18
+ * @param destPrefixPath
19
+ * @param bucketName
20
+ * @param preflightResponse
21
+ */
14
22
  public static async UploadDir(
15
23
  s3Path: string,
16
24
  destPrefixPath: string,
@@ -1,7 +1,7 @@
1
- import path from 'path';
2
- import { IDeployVersionPreflightResponse } from '@pwrdrvr/microapps-deployer';
3
- import fs from 'fs-extra';
4
- import { IConfig } from './config/Config';
1
+ import * as path from 'path';
2
+ import { IDeployVersionPreflightResponse } from '@pwrdrvr/microapps-deployer-lib';
3
+ import * as fs from 'fs-extra';
4
+ import { IConfig } from '../config/Config';
5
5
  import S3TransferUtility from './S3TransferUtility';
6
6
 
7
7
  export default class S3Uploader {
@@ -38,6 +38,7 @@ export default class S3Uploader {
38
38
 
39
39
  /**
40
40
  * Upload files to S3
41
+ * @deprecated 2021-11-27
41
42
  * @param config
42
43
  * @param s3UploadPath
43
44
  * @param preflightResponse