carlin 3.2.1 → 4.0.0
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.
- package/dist/defineConfig.d.mts +11 -15
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +781 -618
- package/package.json +32 -32
package/dist/index.mjs
CHANGED
|
@@ -1,35 +1,36 @@
|
|
|
1
1
|
import { builtinModules, createRequire } from "node:module";
|
|
2
|
-
import * as path$2 from "node:path";
|
|
3
|
-
import path from "node:path";
|
|
2
|
+
import path, * as path$2 from "node:path";
|
|
4
3
|
import * as fs$3 from "node:fs";
|
|
5
4
|
import fs, { chmodSync, createReadStream, existsSync, statSync } from "node:fs";
|
|
6
|
-
import
|
|
5
|
+
import { CORE_SCHEMA, defineScalarTag, defineSequenceTag, dump, load, mergeTag } from "js-yaml";
|
|
7
6
|
import * as esbuild from "esbuild";
|
|
8
|
-
import AWS from "aws-sdk";
|
|
9
7
|
import { camelCase, constantCase, kebabCase, pascalCase } from "change-case";
|
|
10
8
|
import deepEqual from "deep-equal";
|
|
11
|
-
import
|
|
9
|
+
import deepmerge from "deepmerge";
|
|
12
10
|
import dotenv from "dotenv";
|
|
13
11
|
import findUpSync from "findup-sync";
|
|
14
12
|
import yargs from "yargs";
|
|
15
13
|
import { hideBin } from "yargs/helpers";
|
|
16
|
-
import
|
|
14
|
+
import { InvokeCommand, LambdaClient } from "@aws-sdk/client-lambda";
|
|
15
|
+
import { format, styleText } from "node:util";
|
|
16
|
+
import { BatchGetBuildsCommand, CodeBuildClient, StartBuildCommand } from "@aws-sdk/client-codebuild";
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
17
18
|
import "uglify-js";
|
|
18
19
|
import "prettier";
|
|
19
|
-
import
|
|
20
|
-
import
|
|
21
|
-
import fs$1 from "fs";
|
|
22
|
-
import { CloudFormationClient, CreateStackCommand, DeleteStackCommand, DescribeStackEventsCommand, DescribeStackResourceCommand, DescribeStacksCommand, UpdateStackCommand, UpdateTerminationProtectionCommand, ValidateTemplateCommand } from "@aws-sdk/client-cloudformation";
|
|
20
|
+
import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
|
|
21
|
+
import { simpleGit } from "simple-git";
|
|
22
|
+
import fs$1, * as fs$2 from "fs";
|
|
23
|
+
import { CloudFormationClient, CreateStackCommand, DeleteStackCommand, DescribeStackEventsCommand, DescribeStackResourceCommand, DescribeStacksCommand, ListStackResourcesCommand, UpdateStackCommand, UpdateTerminationProtectionCommand, ValidateTemplateCommand, waitUntilStackCreateComplete, waitUntilStackDeleteComplete, waitUntilStackUpdateComplete } from "@aws-sdk/client-cloudformation";
|
|
23
24
|
import { CopyObjectCommand, DeleteObjectsCommand, HeadObjectCommand, ListObjectVersionsCommand, ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
|
|
24
25
|
import { Upload } from "@aws-sdk/lib-storage";
|
|
25
26
|
import { glob } from "glob";
|
|
26
27
|
import mime from "mime-types";
|
|
27
|
-
import * as path$1 from "path";
|
|
28
28
|
import { typescriptConfig } from "@ttoss/config";
|
|
29
29
|
import AdmZip from "adm-zip";
|
|
30
|
-
import
|
|
30
|
+
import * as path$1 from "path";
|
|
31
|
+
import { CloudFrontClient, CreateInvalidationCommand } from "@aws-sdk/client-cloudfront";
|
|
31
32
|
//#region \0rolldown/runtime.js
|
|
32
|
-
var __require = /*
|
|
33
|
+
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
33
34
|
//#endregion
|
|
34
35
|
//#region ../read-config-file/src/loadConfig.ts
|
|
35
36
|
const nodeRequire = createRequire(import.meta.url);
|
|
@@ -73,7 +74,7 @@ const readConfigFileSync = ({ configFilePath, options }) => {
|
|
|
73
74
|
const extension = configFilePath.split(".").pop();
|
|
74
75
|
if (extension === "yaml" || extension === "yml") {
|
|
75
76
|
const file = fs.readFileSync(configFilePath, "utf8");
|
|
76
|
-
return
|
|
77
|
+
return load(file, { schema: CORE_SCHEMA.withTags(mergeTag) });
|
|
77
78
|
}
|
|
78
79
|
if (extension === "json") {
|
|
79
80
|
const file = fs.readFileSync(configFilePath, "utf8");
|
|
@@ -113,6 +114,94 @@ const CLOUDFRONT_REGION = "us-east-1";
|
|
|
113
114
|
*/
|
|
114
115
|
const DEFAULT_NODE_RUNTIME = `nodejs24.x`;
|
|
115
116
|
//#endregion
|
|
117
|
+
//#region src/utils/environmentVariables.ts
|
|
118
|
+
const cache = /* @__PURE__ */ new Map();
|
|
119
|
+
const getEnvVar = (key) => {
|
|
120
|
+
return cache.has(key) && cache.get(key) ? cache.get(key) : void 0;
|
|
121
|
+
};
|
|
122
|
+
const setEnvVar = (key, value) => {
|
|
123
|
+
if (!value) return cache.delete(key);
|
|
124
|
+
return cache.set(key, value);
|
|
125
|
+
};
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region src/utils/log.ts
|
|
128
|
+
const levels = {
|
|
129
|
+
info: {
|
|
130
|
+
label: "info",
|
|
131
|
+
color: "green"
|
|
132
|
+
},
|
|
133
|
+
warn: {
|
|
134
|
+
label: "WARN",
|
|
135
|
+
color: "yellow"
|
|
136
|
+
},
|
|
137
|
+
error: {
|
|
138
|
+
label: "ERR!",
|
|
139
|
+
color: "red"
|
|
140
|
+
},
|
|
141
|
+
event: {
|
|
142
|
+
label: "event",
|
|
143
|
+
color: "yellow"
|
|
144
|
+
},
|
|
145
|
+
output: {
|
|
146
|
+
label: "output",
|
|
147
|
+
color: "blue"
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Color only when stderr supports it, honoring `NO_COLOR` and `FORCE_COLOR`.
|
|
152
|
+
*/
|
|
153
|
+
const paint = ({ color, text }) => {
|
|
154
|
+
return styleText(color, text, { stream: process.stderr });
|
|
155
|
+
};
|
|
156
|
+
const write = ({ level, prefix, args }) => {
|
|
157
|
+
const { label, color } = levels[level];
|
|
158
|
+
const header = [paint({
|
|
159
|
+
color,
|
|
160
|
+
text: label
|
|
161
|
+
}), prefix ? paint({
|
|
162
|
+
color: "magenta",
|
|
163
|
+
text: String(prefix)
|
|
164
|
+
}) : ""].filter(Boolean).join(" ");
|
|
165
|
+
/**
|
|
166
|
+
* Every line of a multi-line message carries the level and the prefix, so
|
|
167
|
+
* interleaved output stays attributable.
|
|
168
|
+
*/
|
|
169
|
+
const lines = format(...args).split("\n").map((line) => {
|
|
170
|
+
return line ? `${header} ${line}` : header;
|
|
171
|
+
});
|
|
172
|
+
/**
|
|
173
|
+
* Logs go to stderr so stdout stays clean for command output.
|
|
174
|
+
*/
|
|
175
|
+
console.error(lines.join("\n"));
|
|
176
|
+
};
|
|
177
|
+
const createLevel = (level) => {
|
|
178
|
+
return (prefix, ...args) => {
|
|
179
|
+
write({
|
|
180
|
+
level,
|
|
181
|
+
prefix,
|
|
182
|
+
args
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* Minimal logger with the `log.<level>(prefix, message, ...args)` signature.
|
|
188
|
+
* Messages are formatted with `util.format` and written to stderr as
|
|
189
|
+
* `<level> <prefix> <message>`.
|
|
190
|
+
*/
|
|
191
|
+
const log = {
|
|
192
|
+
info: createLevel("info"),
|
|
193
|
+
warn: createLevel("warn"),
|
|
194
|
+
error: createLevel("error"),
|
|
195
|
+
/**
|
|
196
|
+
* CloudFormation stack events.
|
|
197
|
+
*/
|
|
198
|
+
event: createLevel("event"),
|
|
199
|
+
/**
|
|
200
|
+
* CloudFormation stack outputs.
|
|
201
|
+
*/
|
|
202
|
+
output: createLevel("output")
|
|
203
|
+
};
|
|
204
|
+
//#endregion
|
|
116
205
|
//#region src/deploy/cicd/ecsTaskReportCommand.ts
|
|
117
206
|
const logPrefix$20 = "cicd-ecs-task-report";
|
|
118
207
|
/**
|
|
@@ -125,14 +214,19 @@ const sendEcsTaskReport = async ({ status }) => {
|
|
|
125
214
|
log.info(logPrefix$20, "ECS_TASK_REPORT_HANDLER_NAME not defined.");
|
|
126
215
|
return;
|
|
127
216
|
}
|
|
128
|
-
const lambda = new
|
|
217
|
+
const lambda = new LambdaClient({ region: getEnvVar("REGION") });
|
|
129
218
|
const payload = { status };
|
|
130
219
|
if (process.env.ECS_TASK_ARN) payload.ecsTaskArn = process.env.ECS_TASK_ARN;
|
|
131
220
|
if (process.env.PIPELINE_NAME) payload.pipelineName = process.env.PIPELINE_NAME;
|
|
132
|
-
|
|
221
|
+
/**
|
|
222
|
+
* `Event` invokes the function asynchronously, replacing the deprecated
|
|
223
|
+
* InvokeAsync API.
|
|
224
|
+
*/
|
|
225
|
+
await lambda.send(new InvokeCommand({
|
|
133
226
|
FunctionName: process.env.ECS_TASK_REPORT_HANDLER_NAME,
|
|
134
|
-
|
|
135
|
-
|
|
227
|
+
InvocationType: "Event",
|
|
228
|
+
Payload: JSON.stringify(payload)
|
|
229
|
+
}));
|
|
136
230
|
log.info(logPrefix$20, "Report sent.");
|
|
137
231
|
};
|
|
138
232
|
const options$7 = { status: {
|
|
@@ -154,7 +248,7 @@ const ecsTaskReportCommand = {
|
|
|
154
248
|
return yargs.options(options$7);
|
|
155
249
|
},
|
|
156
250
|
handler: async (args) => {
|
|
157
|
-
return sendEcsTaskReport(args);
|
|
251
|
+
return sendEcsTaskReport({ status: args.status });
|
|
158
252
|
}
|
|
159
253
|
};
|
|
160
254
|
//#endregion
|
|
@@ -168,15 +262,18 @@ const addGroupToOptions = (options, group) => {
|
|
|
168
262
|
//#endregion
|
|
169
263
|
//#region src/utils/codeBuild.ts
|
|
170
264
|
const logPrefix$19 = "codebuild";
|
|
171
|
-
const WAIT_TIME =
|
|
265
|
+
const WAIT_TIME = 1e4;
|
|
266
|
+
const codeBuild = () => {
|
|
267
|
+
return new CodeBuildClient({ region: getEnvVar("REGION") });
|
|
268
|
+
};
|
|
172
269
|
/**
|
|
173
270
|
* @param param.name name used to identify the build.
|
|
174
271
|
*/
|
|
175
272
|
const waitCodeBuildFinish = async ({ buildId, name }) => {
|
|
176
|
-
const
|
|
273
|
+
const client = codeBuild();
|
|
177
274
|
let result;
|
|
178
275
|
const checkIfBuildIsFinished = async () => {
|
|
179
|
-
const { builds } = await
|
|
276
|
+
const { builds } = await client.send(new BatchGetBuildsCommand({ ids: [buildId] }));
|
|
180
277
|
return new Promise((resolve, reject) => {
|
|
181
278
|
setTimeout(() => {
|
|
182
279
|
const executedBuild = builds?.find(({ id }) => {
|
|
@@ -195,27 +292,14 @@ const waitCodeBuildFinish = async ({ buildId, name }) => {
|
|
|
195
292
|
return result;
|
|
196
293
|
};
|
|
197
294
|
const startCodeBuildBuild = async ({ projectName }) => {
|
|
198
|
-
const { build } = await
|
|
295
|
+
const { build } = await codeBuild().send(new StartBuildCommand({ projectName }));
|
|
199
296
|
if (!build) throw new Error(`Cannot start ${projectName} build`);
|
|
200
297
|
return build;
|
|
201
298
|
};
|
|
202
299
|
//#endregion
|
|
203
|
-
//#region src/utils/environmentVariables.ts
|
|
204
|
-
const cache = /* @__PURE__ */ new Map();
|
|
205
|
-
const getEnvVar = (key) => {
|
|
206
|
-
return cache.has(key) && cache.get(key) ? cache.get(key) : void 0;
|
|
207
|
-
};
|
|
208
|
-
const setEnvVar = (key, value) => {
|
|
209
|
-
if (!value) return cache.delete(key);
|
|
210
|
-
return cache.set(key, value);
|
|
211
|
-
};
|
|
212
|
-
//#endregion
|
|
213
|
-
//#region src/utils/exec.ts
|
|
214
|
-
log.heading = "exec";
|
|
215
|
-
//#endregion
|
|
216
300
|
//#region src/utils/getAwsAccountId.ts
|
|
217
301
|
const getAwsAccountId = async () => {
|
|
218
|
-
const { Account } = await new
|
|
302
|
+
const { Account } = await new STSClient({ region: getEnvVar("REGION") }).send(new GetCallerIdentityCommand({}));
|
|
219
303
|
return Account;
|
|
220
304
|
};
|
|
221
305
|
/**
|
|
@@ -234,9 +318,9 @@ const getAwsAccountId = async () => {
|
|
|
234
318
|
const getCurrentBranch = async () => {
|
|
235
319
|
try {
|
|
236
320
|
if (getEnvVar("BRANCH")) return getEnvVar("BRANCH");
|
|
237
|
-
const { current } = await
|
|
321
|
+
const { current } = await simpleGit().branch();
|
|
238
322
|
return current || "";
|
|
239
|
-
} catch
|
|
323
|
+
} catch {
|
|
240
324
|
return "";
|
|
241
325
|
}
|
|
242
326
|
};
|
|
@@ -294,9 +378,6 @@ const getProjectName = () => {
|
|
|
294
378
|
}
|
|
295
379
|
};
|
|
296
380
|
//#endregion
|
|
297
|
-
//#region src/utils/spawn.ts
|
|
298
|
-
log.heading = "exec";
|
|
299
|
-
//#endregion
|
|
300
381
|
//#region src/deploy/addDefaults.cloudformation.ts
|
|
301
382
|
const addDefaultsParametersAndTagsToParams = async (params) => {
|
|
302
383
|
const branchName = await getCurrentBranch();
|
|
@@ -503,14 +584,6 @@ const getBaseStackResource = async (resource) => {
|
|
|
503
584
|
return resources[resource];
|
|
504
585
|
};
|
|
505
586
|
//#endregion
|
|
506
|
-
//#region src/deploy/config.ts
|
|
507
|
-
/**
|
|
508
|
-
* Besides saving the deploy information in the `$STACK_NAME.json` file,
|
|
509
|
-
* we also save in a "latest-deploy.json" file to be used by tests and other
|
|
510
|
-
* packages that need to know the latest deploy information.
|
|
511
|
-
*/
|
|
512
|
-
const LATEST_DEPLOY_OUTPUTS_FILENAME = "latest-deploy.json";
|
|
513
|
-
//#endregion
|
|
514
587
|
//#region src/deploy/s3.ts
|
|
515
588
|
const logPrefix$18 = "s3";
|
|
516
589
|
/**
|
|
@@ -689,9 +762,10 @@ const emptyS3Directory = async ({ bucket, directory = "" }) => {
|
|
|
689
762
|
*/
|
|
690
763
|
const BATCH_SIZE = 1e3;
|
|
691
764
|
for (let i = 0; i < objectsWithVersionsIds.length; i += BATCH_SIZE) {
|
|
765
|
+
const batch = objectsWithVersionsIds.slice(i, i + BATCH_SIZE);
|
|
692
766
|
const deleteCommand = new DeleteObjectsCommand({
|
|
693
767
|
Bucket: bucket,
|
|
694
|
-
Delete: { Objects:
|
|
768
|
+
Delete: { Objects: batch }
|
|
695
769
|
});
|
|
696
770
|
const result = await s3().send(deleteCommand);
|
|
697
771
|
if (result.Errors && result.Errors.length > 0) {
|
|
@@ -752,9 +826,10 @@ const deleteOldS3Files = async ({ bucket, continuationToken, directory = "", ret
|
|
|
752
826
|
*/
|
|
753
827
|
const BATCH_SIZE = 1e3;
|
|
754
828
|
for (let i = 0; i < oldFiles.length; i += BATCH_SIZE) {
|
|
829
|
+
const batch = oldFiles.slice(i, i + BATCH_SIZE);
|
|
755
830
|
const deleteCommand = new DeleteObjectsCommand({
|
|
756
831
|
Bucket: bucket,
|
|
757
|
-
Delete: { Objects:
|
|
832
|
+
Delete: { Objects: batch.map((Key) => {
|
|
758
833
|
return { Key };
|
|
759
834
|
}) }
|
|
760
835
|
});
|
|
@@ -787,10 +862,39 @@ const deleteOldS3Files = async ({ bucket, continuationToken, directory = "", ret
|
|
|
787
862
|
}
|
|
788
863
|
};
|
|
789
864
|
//#endregion
|
|
865
|
+
//#region src/deploy/config.ts
|
|
866
|
+
/**
|
|
867
|
+
* Besides saving the deploy information in the `$STACK_NAME.json` file,
|
|
868
|
+
* we also save in a "latest-deploy.json" file to be used by tests and other
|
|
869
|
+
* packages that need to know the latest deploy information.
|
|
870
|
+
*/
|
|
871
|
+
const LATEST_DEPLOY_OUTPUTS_FILENAME = "latest-deploy.json";
|
|
872
|
+
//#endregion
|
|
873
|
+
//#region src/deploy/saveEnvironmentOutput.ts
|
|
874
|
+
const saveEnvironmentOutput = async ({ outputs, stackName }) => {
|
|
875
|
+
const envFile = {
|
|
876
|
+
stackName,
|
|
877
|
+
environment: getEnvironment(),
|
|
878
|
+
projectName: getProjectName(),
|
|
879
|
+
packageName: getPackageName()
|
|
880
|
+
};
|
|
881
|
+
envFile.outputs = outputs.reduce((acc, output) => {
|
|
882
|
+
if (!output.OutputKey || !output) return acc;
|
|
883
|
+
return {
|
|
884
|
+
...acc,
|
|
885
|
+
[output.OutputKey]: output
|
|
886
|
+
};
|
|
887
|
+
}, {});
|
|
888
|
+
const dotCarlinFolderPath = path$2.join(process.cwd(), ".carlin");
|
|
889
|
+
if (!fs$3.existsSync(dotCarlinFolderPath)) await fs$3.promises.mkdir(dotCarlinFolderPath);
|
|
890
|
+
const filePath = path$2.join(dotCarlinFolderPath, `${stackName}.json`);
|
|
891
|
+
await fs$3.promises.writeFile(filePath, JSON.stringify(envFile, null, 2));
|
|
892
|
+
const latestFilePath = path$2.join(dotCarlinFolderPath, LATEST_DEPLOY_OUTPUTS_FILENAME);
|
|
893
|
+
await fs$3.promises.writeFile(latestFilePath, JSON.stringify(envFile, null, 2));
|
|
894
|
+
};
|
|
895
|
+
//#endregion
|
|
790
896
|
//#region src/deploy/cloudformation.core.ts
|
|
791
897
|
const logPrefix$17 = "cloudformation";
|
|
792
|
-
log.addLevel("event", 1e4, { fg: "yellow" });
|
|
793
|
-
log.addLevel("output", 1e4, { fg: "blue" });
|
|
794
898
|
/**
|
|
795
899
|
* https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html
|
|
796
900
|
*/
|
|
@@ -804,8 +908,9 @@ const isTemplateBodyGreaterThanMaxSize = (template) => {
|
|
|
804
908
|
* @param input.template: CloudFormation template.
|
|
805
909
|
*/
|
|
806
910
|
const uploadTemplateToBaseStackBucket = async ({ stackName, template }) => {
|
|
911
|
+
const bucketName = await getBaseStackResource("BASE_STACK_BUCKET_LOGICAL_NAME");
|
|
807
912
|
const { url } = await uploadFileToS3({
|
|
808
|
-
bucket:
|
|
913
|
+
bucket: bucketName,
|
|
809
914
|
contentType: "application/json",
|
|
810
915
|
key: `${BASE_STACK_BUCKET_TEMPLATES_FOLDER}/${stackName}.json`,
|
|
811
916
|
file: Buffer.from(JSON.stringify(template, null, 2))
|
|
@@ -829,8 +934,16 @@ const cloudformation = () => {
|
|
|
829
934
|
});
|
|
830
935
|
return cloudFormationClients[key];
|
|
831
936
|
};
|
|
832
|
-
|
|
833
|
-
|
|
937
|
+
/**
|
|
938
|
+
* Stack waiters poll every 30 seconds by default. One hour matches the
|
|
939
|
+
* timeout of the AWS SDK v2 waiters carlin used before.
|
|
940
|
+
*/
|
|
941
|
+
const STACK_WAITER_MAX_WAIT_TIME_IN_SECONDS = 3600;
|
|
942
|
+
const getStackWaiterParams = () => {
|
|
943
|
+
return {
|
|
944
|
+
client: cloudformation(),
|
|
945
|
+
maxWaitTime: STACK_WAITER_MAX_WAIT_TIME_IN_SECONDS
|
|
946
|
+
};
|
|
834
947
|
};
|
|
835
948
|
const describeStacks = async ({ stackName } = {}) => {
|
|
836
949
|
const { Stacks } = await cloudformation().send(new DescribeStacksCommand({ StackName: stackName }));
|
|
@@ -857,7 +970,7 @@ const describeStackEvents = async ({ stackName }) => {
|
|
|
857
970
|
log.error(logPrefix$17, "Stack events:");
|
|
858
971
|
const { StackEvents } = await cloudformation().send(new DescribeStackEventsCommand({ StackName: stackName }));
|
|
859
972
|
const events = (StackEvents || []).filter(({ Timestamp }) => {
|
|
860
|
-
return Date.now() - Number(Timestamp) <
|
|
973
|
+
return Date.now() - Number(Timestamp) < 6e5;
|
|
861
974
|
}).filter(({ ResourceStatusReason }) => {
|
|
862
975
|
return ResourceStatusReason;
|
|
863
976
|
}).reverse();
|
|
@@ -877,27 +990,6 @@ const getStackOutput = async ({ stackName, outputKey }) => {
|
|
|
877
990
|
if (!output) throw new Error(`Output ${outputKey} doesn't exist on ${stackName} stack`);
|
|
878
991
|
return output;
|
|
879
992
|
};
|
|
880
|
-
const saveEnvironmentOutput = async ({ outputs, stackName }) => {
|
|
881
|
-
const envFile = {
|
|
882
|
-
stackName,
|
|
883
|
-
environment: getEnvironment(),
|
|
884
|
-
projectName: getProjectName(),
|
|
885
|
-
packageName: getPackageName()
|
|
886
|
-
};
|
|
887
|
-
envFile.outputs = outputs.reduce((acc, output) => {
|
|
888
|
-
if (!output.OutputKey || !output) return acc;
|
|
889
|
-
return {
|
|
890
|
-
...acc,
|
|
891
|
-
[output.OutputKey]: output
|
|
892
|
-
};
|
|
893
|
-
}, {});
|
|
894
|
-
const dotCarlinFolderPath = path$2.join(process.cwd(), ".carlin");
|
|
895
|
-
if (!fs$3.existsSync(dotCarlinFolderPath)) await fs$3.promises.mkdir(dotCarlinFolderPath);
|
|
896
|
-
const filePath = path$2.join(dotCarlinFolderPath, `${stackName}.json`);
|
|
897
|
-
await fs$3.promises.writeFile(filePath, JSON.stringify(envFile, null, 2));
|
|
898
|
-
const latestFilePath = path$2.join(dotCarlinFolderPath, LATEST_DEPLOY_OUTPUTS_FILENAME);
|
|
899
|
-
await fs$3.promises.writeFile(latestFilePath, JSON.stringify(envFile, null, 2));
|
|
900
|
-
};
|
|
901
993
|
/**
|
|
902
994
|
* After deployment, Carlin prints the outputs defined in your CloudFormation
|
|
903
995
|
* template and saves them in two files:
|
|
@@ -934,7 +1026,7 @@ const deleteStack = async ({ stackName }) => {
|
|
|
934
1026
|
log.info(logPrefix$17, `Deleting stack ${stackName}...`);
|
|
935
1027
|
await cloudformation().send(new DeleteStackCommand({ StackName: stackName }));
|
|
936
1028
|
try {
|
|
937
|
-
await
|
|
1029
|
+
await waitUntilStackDeleteComplete(getStackWaiterParams(), { StackName: stackName });
|
|
938
1030
|
} catch (error) {
|
|
939
1031
|
log.error(logPrefix$17, `An error occurred when deleting stack ${stackName}.`);
|
|
940
1032
|
await describeStackEvents({ stackName });
|
|
@@ -947,7 +1039,7 @@ const createStack = async ({ params }) => {
|
|
|
947
1039
|
log.info(logPrefix$17, `Creating stack ${stackName}...`);
|
|
948
1040
|
await cloudformation().send(new CreateStackCommand(params));
|
|
949
1041
|
try {
|
|
950
|
-
await
|
|
1042
|
+
await waitUntilStackCreateComplete(getStackWaiterParams(), { StackName: stackName });
|
|
951
1043
|
} catch (error) {
|
|
952
1044
|
log.error(logPrefix$17, `An error occurred when creating stack ${stackName}.`);
|
|
953
1045
|
await describeStackEvents({ stackName });
|
|
@@ -961,7 +1053,7 @@ const updateStack = async ({ params }) => {
|
|
|
961
1053
|
log.info(logPrefix$17, `Updating stack ${stackName}...`);
|
|
962
1054
|
try {
|
|
963
1055
|
await cloudformation().send(new UpdateStackCommand(params));
|
|
964
|
-
await
|
|
1056
|
+
await waitUntilStackUpdateComplete(getStackWaiterParams(), { StackName: stackName });
|
|
965
1057
|
} catch (error) {
|
|
966
1058
|
if (error.message === "No updates are to be performed.") {
|
|
967
1059
|
log.info(logPrefix$17, error.message);
|
|
@@ -1034,6 +1126,48 @@ const canDestroyStack = async ({ stackName }) => {
|
|
|
1034
1126
|
if (EnableTerminationProtection) return false;
|
|
1035
1127
|
return true;
|
|
1036
1128
|
};
|
|
1129
|
+
const emptyStackBuckets = async ({ stackName }) => {
|
|
1130
|
+
const buckets = [];
|
|
1131
|
+
await (async ({ nextToken }) => {
|
|
1132
|
+
const { NextToken, StackResourceSummaries } = await cloudformation().send(new ListStackResourcesCommand({
|
|
1133
|
+
StackName: stackName,
|
|
1134
|
+
NextToken: nextToken
|
|
1135
|
+
}));
|
|
1136
|
+
if (NextToken) {}
|
|
1137
|
+
for (const { ResourceType, PhysicalResourceId } of StackResourceSummaries || []) if (ResourceType === "AWS::S3::Bucket" && PhysicalResourceId) buckets.push(PhysicalResourceId);
|
|
1138
|
+
})({});
|
|
1139
|
+
return Promise.all(buckets.map((bucket) => {
|
|
1140
|
+
return emptyS3Directory({ bucket });
|
|
1141
|
+
}));
|
|
1142
|
+
};
|
|
1143
|
+
/**
|
|
1144
|
+
* 1. Check if `environment` is defined. If defined, return. It doesn't destroy
|
|
1145
|
+
* stacks with defined `environment`.
|
|
1146
|
+
* 1. Check if termination protection is disabled.
|
|
1147
|
+
* 1. If the stack deployed buckets, empty all buckets.
|
|
1148
|
+
* 1. Delete the stack.
|
|
1149
|
+
*/
|
|
1150
|
+
const destroy = async ({ stackName }) => {
|
|
1151
|
+
const environment = getEnvironment();
|
|
1152
|
+
if (environment) {
|
|
1153
|
+
log.info(logPrefix$17, `Cannot destroy stack when environment (${environment}) is defined.`);
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
if (!await doesStackExist({ stackName })) {
|
|
1157
|
+
log.info(logPrefix$17, `Stack ${stackName} doesn't exist.`);
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
if (!await canDestroyStack({ stackName })) {
|
|
1161
|
+
const message = `Stack ${stackName} cannot be destroyed while TerminationProtection is enabled.`;
|
|
1162
|
+
throw new Error(message);
|
|
1163
|
+
}
|
|
1164
|
+
try {
|
|
1165
|
+
await emptyStackBuckets({ stackName });
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
log.warn(logPrefix$17, `Failed to empty buckets for stack ${stackName}: ${error?.message || error}. Proceeding with stack deletion.`);
|
|
1168
|
+
}
|
|
1169
|
+
await deleteStack({ stackName });
|
|
1170
|
+
};
|
|
1037
1171
|
const validateTemplate = async ({ stackName, template }) => {
|
|
1038
1172
|
const validateTemplateCommandInput = {};
|
|
1039
1173
|
if (isTemplateBodyGreaterThanMaxSize(template)) {
|
|
@@ -1117,12 +1251,13 @@ const getStackName = async () => {
|
|
|
1117
1251
|
getEnvironment(),
|
|
1118
1252
|
getPackageName()
|
|
1119
1253
|
]);
|
|
1120
|
-
|
|
1254
|
+
const name = [packageName ? pascalCase(packageName) : `Stack-${Math.round(Math.random() * 1e5)}`, (() => {
|
|
1121
1255
|
if (environment) return environment;
|
|
1122
1256
|
if (currentBranch) return kebabCase(currentBranch);
|
|
1123
1257
|
})()].filter((word) => {
|
|
1124
1258
|
return !!word;
|
|
1125
|
-
}).join("-")
|
|
1259
|
+
}).join("-");
|
|
1260
|
+
return limitStackName(sanitizeStackName(name));
|
|
1126
1261
|
};
|
|
1127
1262
|
//#endregion
|
|
1128
1263
|
//#region src/deploy/utils.ts
|
|
@@ -1315,7 +1450,7 @@ const getLambdaImageBuilderTemplate = () => {
|
|
|
1315
1450
|
} },
|
|
1316
1451
|
ServiceRole: { "Fn::GetAtt": [CODE_BUILD_PROJECT_SERVICE_ROLE_LOGICAL_ID, "Arn"] },
|
|
1317
1452
|
Source: {
|
|
1318
|
-
BuildSpec:
|
|
1453
|
+
BuildSpec: dump({
|
|
1319
1454
|
version: "0.2",
|
|
1320
1455
|
phases: {
|
|
1321
1456
|
install: { commands: [
|
|
@@ -1581,7 +1716,7 @@ const getVpcTemplate = () => {
|
|
|
1581
1716
|
//#endregion
|
|
1582
1717
|
//#region src/deploy/baseStack/deployBaseStack.ts
|
|
1583
1718
|
const logPrefix$16 = "base-stack";
|
|
1584
|
-
const baseStackTemplate =
|
|
1719
|
+
const baseStackTemplate = deepmerge.all([
|
|
1585
1720
|
getBucketTemplate(),
|
|
1586
1721
|
getCloudFrontTemplate$1(),
|
|
1587
1722
|
getLambdaImageBuilderTemplate(),
|
|
@@ -1709,60 +1844,330 @@ const getCicdConfig = () => {
|
|
|
1709
1844
|
}, {});
|
|
1710
1845
|
};
|
|
1711
1846
|
//#endregion
|
|
1712
|
-
//#region src/deploy/
|
|
1847
|
+
//#region src/deploy/lambda/buildLambdaCode.ts
|
|
1848
|
+
const logPrefix$15 = "lambda";
|
|
1713
1849
|
/**
|
|
1714
|
-
*
|
|
1715
|
-
* will
|
|
1850
|
+
* Carlin builds the Lambda code using esbuild. It can build the code as ESM or
|
|
1851
|
+
* CJS format. When building as ESM, it will split the code into multiple files,
|
|
1852
|
+
* which reduces the payload size when deploying the Lambda function. The file
|
|
1853
|
+
* extension of the output files will be `.mjs` for ESM and `.cjs` for CJS.
|
|
1716
1854
|
*/
|
|
1717
|
-
const
|
|
1718
|
-
|
|
1855
|
+
const buildLambdaCode = async ({ lambdaEntryPoints, lambdaEntryPointsBaseDir = ".", lambdaExternal = [], lambdaFormat = "esm", lambdaOutdir, lambdaSourceMaps = false }) => {
|
|
1856
|
+
log.info(logPrefix$15, "Building Lambda single file...");
|
|
1857
|
+
/**
|
|
1858
|
+
* Remove the output directory if it exists to not mix old files with the
|
|
1859
|
+
* new ones.
|
|
1860
|
+
*/
|
|
1861
|
+
if (fs.existsSync(lambdaOutdir)) fs.rmSync(lambdaOutdir, { recursive: true });
|
|
1862
|
+
const entryPoints = lambdaEntryPoints.map((entryPoint) => {
|
|
1863
|
+
return path.resolve(process.cwd(), lambdaEntryPointsBaseDir, entryPoint);
|
|
1864
|
+
});
|
|
1865
|
+
const { errors } = esbuild.buildSync({
|
|
1866
|
+
banner: { js: "// Powered by carlin (https://ttoss.dev/docs/carlin/)" },
|
|
1867
|
+
bundle: true,
|
|
1868
|
+
entryPoints,
|
|
1869
|
+
external: [
|
|
1870
|
+
"@aws-sdk/*",
|
|
1871
|
+
...builtinModules,
|
|
1872
|
+
...lambdaExternal
|
|
1873
|
+
],
|
|
1874
|
+
/**
|
|
1875
|
+
* Some packages as `graphql` are not compatible with ESM yet.
|
|
1876
|
+
* https://github.com/graphql/graphql-js/issues/3603
|
|
1877
|
+
*/
|
|
1878
|
+
format: lambdaFormat,
|
|
1879
|
+
/**
|
|
1880
|
+
* https://esbuild.github.io/api/#minify
|
|
1881
|
+
*/
|
|
1882
|
+
minifySyntax: true,
|
|
1883
|
+
platform: "node",
|
|
1884
|
+
/**
|
|
1885
|
+
* Node applies the map only with `--enable-source-maps`, which
|
|
1886
|
+
* `addSourceMapsNodeOptions` sets on every function. Without
|
|
1887
|
+
* `sourcesContent`: Node maps a frame from names and lines alone, and the
|
|
1888
|
+
* source text would only grow the zip.
|
|
1889
|
+
*/
|
|
1890
|
+
...lambdaSourceMaps ? {
|
|
1891
|
+
sourcemap: "linked",
|
|
1892
|
+
sourcesContent: false
|
|
1893
|
+
} : {},
|
|
1894
|
+
splitting: lambdaFormat === "esm",
|
|
1895
|
+
outbase: path.join(process.cwd(), lambdaEntryPointsBaseDir),
|
|
1896
|
+
outdir: path.join(process.cwd(), lambdaOutdir),
|
|
1897
|
+
outExtension: { ".js": lambdaFormat === "esm" ? ".mjs" : ".cjs" },
|
|
1898
|
+
target: typescriptConfig.target,
|
|
1899
|
+
treeShaking: true
|
|
1900
|
+
});
|
|
1901
|
+
if (errors.length > 0) throw errors;
|
|
1719
1902
|
};
|
|
1720
1903
|
//#endregion
|
|
1721
|
-
//#region src/deploy/
|
|
1722
|
-
const
|
|
1723
|
-
const
|
|
1724
|
-
const
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
const
|
|
1736
|
-
const
|
|
1737
|
-
|
|
1738
|
-
const
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1904
|
+
//#region src/deploy/lambdaLayer/getPackageLambdaLayerStackName.ts
|
|
1905
|
+
const lambdaLayerStackNamePrefix = `LambdaLayer`;
|
|
1906
|
+
const getPackageLambdaLayerStackName = (packageName) => {
|
|
1907
|
+
const [scopedName, version] = packageName.split("@").filter((part) => {
|
|
1908
|
+
return !!part;
|
|
1909
|
+
});
|
|
1910
|
+
return [
|
|
1911
|
+
lambdaLayerStackNamePrefix,
|
|
1912
|
+
pascalCase(scopedName),
|
|
1913
|
+
version.replace(/[^0-9.]/g, "").replace(/\./g, "-")
|
|
1914
|
+
].join("-");
|
|
1915
|
+
};
|
|
1916
|
+
//#endregion
|
|
1917
|
+
//#region src/deploy/lambdaLayer/deployLambdaLayer.ts
|
|
1918
|
+
const logPrefix$14 = "lambda-layer";
|
|
1919
|
+
const createLambdaLayerZipFile = async ({ codeBuildProjectName, packageName }) => {
|
|
1920
|
+
log.info(logPrefix$14, `Creating zip file for package ${packageName}...`);
|
|
1921
|
+
const { build } = await codeBuild().send(new StartBuildCommand({
|
|
1922
|
+
environmentVariablesOverride: [{
|
|
1923
|
+
name: "PACKAGE_NAME",
|
|
1924
|
+
value: packageName
|
|
1925
|
+
}],
|
|
1926
|
+
projectName: codeBuildProjectName
|
|
1927
|
+
}));
|
|
1928
|
+
if (!build?.id) throw new Error("Cannot start build.");
|
|
1929
|
+
const result = await waitCodeBuildFinish({
|
|
1930
|
+
buildId: build.id,
|
|
1931
|
+
name: packageName
|
|
1932
|
+
});
|
|
1933
|
+
if (result.artifacts?.location) {
|
|
1934
|
+
const location = result.artifacts.location.split("/");
|
|
1935
|
+
const bucket = location.shift()?.replace("arn:aws:s3:::", "");
|
|
1936
|
+
if (!bucket) throw new Error("Cannot retrieve bucket name.");
|
|
1937
|
+
return {
|
|
1938
|
+
bucket,
|
|
1939
|
+
key: location.join("/")
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
throw new Error(`Cannot get artifact location for package ${packageName}`);
|
|
1943
|
+
};
|
|
1944
|
+
/**
|
|
1945
|
+
* The CloudFormation template created to deploy a Lambda Layer.
|
|
1946
|
+
*
|
|
1947
|
+
* - The Layer name is the same as the Stack name.
|
|
1948
|
+
*/
|
|
1949
|
+
const getLambdaLayerTemplate = ({ bucket, key, packageName, runtime }) => {
|
|
1950
|
+
const description = packageName.substring(0, 256);
|
|
1951
|
+
return {
|
|
1952
|
+
AWSTemplateFormatVersion: "2010-09-09",
|
|
1953
|
+
Resources: { LambdaLayer: {
|
|
1954
|
+
Type: "AWS::Lambda::LayerVersion",
|
|
1955
|
+
Properties: {
|
|
1956
|
+
CompatibleRuntimes: [runtime || DEFAULT_NODE_RUNTIME],
|
|
1957
|
+
Content: {
|
|
1958
|
+
S3Bucket: bucket,
|
|
1959
|
+
S3Key: key
|
|
1960
|
+
},
|
|
1961
|
+
Description: description,
|
|
1962
|
+
LayerName: { Ref: "AWS::StackName" }
|
|
1963
|
+
}
|
|
1964
|
+
} },
|
|
1965
|
+
Outputs: { LambdaLayerVersion: {
|
|
1966
|
+
Description: description,
|
|
1967
|
+
Value: { Ref: "LambdaLayer" },
|
|
1968
|
+
Export: { Name: { Ref: "AWS::StackName" } }
|
|
1969
|
+
} }
|
|
1970
|
+
};
|
|
1971
|
+
};
|
|
1972
|
+
const getPackagesThatAreNotDeployed = async ({ packages }) => {
|
|
1973
|
+
return (await Promise.all(packages.map(async (packageName) => {
|
|
1974
|
+
const stackName = getPackageLambdaLayerStackName(packageName);
|
|
1975
|
+
return await doesStackExist({ stackName }) ? "" : packageName;
|
|
1976
|
+
}))).filter((packageName) => {
|
|
1977
|
+
return !!packageName;
|
|
1978
|
+
});
|
|
1979
|
+
};
|
|
1980
|
+
const deployLambdaLayer = async ({ packages, deployIfExists = true, runtime }) => {
|
|
1981
|
+
try {
|
|
1982
|
+
const packagesToBeDeployed = deployIfExists ? packages : await getPackagesThatAreNotDeployed({ packages });
|
|
1983
|
+
if (packagesToBeDeployed.length === 0) return;
|
|
1984
|
+
const codeBuildProjectName = await getBaseStackResource("BASE_STACK_LAMBDA_LAYER_BUILDER_LOGICAL_NAME");
|
|
1985
|
+
if (!codeBuildProjectName) throw new Error("Cannot deploy lambda-layer because AWS CodeBuild project doesn't exist.");
|
|
1986
|
+
const deployLambdaLayerSinglePackage = async (packageName) => {
|
|
1987
|
+
try {
|
|
1988
|
+
const { bucket, key } = await createLambdaLayerZipFile({
|
|
1989
|
+
codeBuildProjectName,
|
|
1990
|
+
packageName
|
|
1991
|
+
});
|
|
1992
|
+
const lambdaLayerTemplate = getLambdaLayerTemplate({
|
|
1993
|
+
packageName,
|
|
1994
|
+
bucket,
|
|
1995
|
+
key,
|
|
1996
|
+
runtime
|
|
1997
|
+
});
|
|
1998
|
+
await deploy({
|
|
1999
|
+
template: lambdaLayerTemplate,
|
|
2000
|
+
terminationProtection: true,
|
|
2001
|
+
params: { StackName: getPackageLambdaLayerStackName(packageName) }
|
|
2002
|
+
});
|
|
2003
|
+
} catch (error) {
|
|
2004
|
+
handleDeployError({
|
|
2005
|
+
error,
|
|
2006
|
+
logPrefix: logPrefix$14
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
2009
|
+
};
|
|
2010
|
+
await Promise.all(packagesToBeDeployed.map((packageName) => {
|
|
2011
|
+
return deployLambdaLayerSinglePackage(packageName);
|
|
2012
|
+
}));
|
|
2013
|
+
} catch (error) {
|
|
2014
|
+
handleDeployError({
|
|
2015
|
+
error,
|
|
2016
|
+
logPrefix: logPrefix$14
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
//#endregion
|
|
2021
|
+
//#region src/deploy/lambda/deployLambdaLayers.ts
|
|
2022
|
+
const logPrefix$13 = "lambda";
|
|
2023
|
+
const deployLambdaLayers = async ({ lambdaExternal = [] }) => {
|
|
2024
|
+
if (lambdaExternal.length === 0) return;
|
|
2025
|
+
log.info(logPrefix$13, `--lambda-externals [${lambdaExternal.join(", ")}] was found. Creating other layers...`);
|
|
2026
|
+
const { dependencies = {} } = (() => {
|
|
2027
|
+
try {
|
|
2028
|
+
return JSON.parse(fs$3.readFileSync(path$2.resolve(process.cwd(), "package.json"), "utf8"));
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
log.error(logPrefix$13, "Cannot read package.json. Error message: %j", error.message);
|
|
2031
|
+
return {};
|
|
2032
|
+
}
|
|
2033
|
+
})();
|
|
2034
|
+
const packages = lambdaExternal.map((external) => {
|
|
2035
|
+
try {
|
|
2036
|
+
return `${external}@${dependencies[external].replace(/(~|\^)/g, "")}`;
|
|
2037
|
+
} catch {
|
|
2038
|
+
throw new Error(`Cannot find ${external} on package.json dependencies.`);
|
|
2039
|
+
}
|
|
2040
|
+
});
|
|
2041
|
+
await deployLambdaLayer({
|
|
2042
|
+
packages,
|
|
2043
|
+
deployIfExists: false
|
|
2044
|
+
});
|
|
2045
|
+
};
|
|
2046
|
+
//#endregion
|
|
2047
|
+
//#region src/deploy/lambda/uploadCodeToECR.ts
|
|
2048
|
+
new CodeBuildClient({ region: AWS_DEFAULT_REGION });
|
|
2049
|
+
const uploadCodeToECR = async ({ bucket, key, lambdaExternal, lambdaDockerfile }) => {
|
|
2050
|
+
throw new Error("uploadCodeToECR not finished yet.");
|
|
2051
|
+
};
|
|
2052
|
+
//#endregion
|
|
2053
|
+
//#region src/deploy/lambda/uploadCodeToS3.ts
|
|
2054
|
+
const logPrefix$12 = "lambda";
|
|
2055
|
+
const zipFileName = "lambda.zip";
|
|
2056
|
+
const uploadCodeToS3 = async ({ stackName, lambdaOutdir }) => {
|
|
2057
|
+
log.info(logPrefix$12, `Uploading code to S3...`);
|
|
2058
|
+
const zip = new AdmZip();
|
|
2059
|
+
const zipFile = `${lambdaOutdir}/${zipFileName}`;
|
|
2060
|
+
/**
|
|
2061
|
+
* Check if the zip file already exists and delete it before creating a new.
|
|
2062
|
+
*/
|
|
2063
|
+
if (fs.existsSync(zipFile)) await fs.promises.rm(zipFile);
|
|
2064
|
+
/**
|
|
2065
|
+
* Zip entire directory.
|
|
2066
|
+
*/
|
|
2067
|
+
zip.addLocalFolder(lambdaOutdir);
|
|
2068
|
+
zip.writeZip(`${lambdaOutdir}/${zipFileName}`);
|
|
2069
|
+
const bucketName = await getBaseStackResource("BASE_STACK_BUCKET_LOGICAL_NAME");
|
|
2070
|
+
return uploadFileToS3({
|
|
2071
|
+
bucket: bucketName,
|
|
2072
|
+
contentType: "application/zip",
|
|
2073
|
+
key: `lambdas/${stackName}/${zipFileName}`,
|
|
2074
|
+
file: zip.toBuffer()
|
|
2075
|
+
});
|
|
2076
|
+
};
|
|
2077
|
+
//#endregion
|
|
2078
|
+
//#region src/deploy/lambda/deployLambdaCode.ts
|
|
2079
|
+
const logPrefix$11 = "lambda";
|
|
2080
|
+
const deployLambdaCode = async ({ lambdaDockerfile, lambdaExternal = [], lambdaImage, lambdaEntryPoints, lambdaEntryPointsBaseDir = "src", lambdaFormat, lambdaOutdir = "out", lambdaSourceMaps, stackName }) => {
|
|
2081
|
+
if (!lambdaEntryPoints.length) return {};
|
|
2082
|
+
log.info(logPrefix$11, "Deploying Lambda code...");
|
|
2083
|
+
for (const entryPoint of lambdaEntryPoints) {
|
|
2084
|
+
const entryPointPath = path.resolve(lambdaEntryPointsBaseDir, entryPoint);
|
|
2085
|
+
if (!fs.existsSync(entryPointPath)) throw new Error(`Entry point ${entryPointPath} does not exist.`);
|
|
2086
|
+
}
|
|
2087
|
+
await buildLambdaCode({
|
|
2088
|
+
lambdaExternal,
|
|
2089
|
+
lambdaEntryPoints,
|
|
2090
|
+
lambdaEntryPointsBaseDir,
|
|
2091
|
+
lambdaFormat,
|
|
2092
|
+
lambdaOutdir,
|
|
2093
|
+
lambdaSourceMaps
|
|
2094
|
+
});
|
|
2095
|
+
const { bucket, key, versionId } = await uploadCodeToS3({
|
|
2096
|
+
stackName,
|
|
2097
|
+
lambdaOutdir
|
|
2098
|
+
});
|
|
2099
|
+
if (!lambdaImage) {
|
|
2100
|
+
await deployLambdaLayers({ lambdaExternal });
|
|
2101
|
+
return {
|
|
2102
|
+
bucket,
|
|
2103
|
+
key,
|
|
2104
|
+
versionId
|
|
2105
|
+
};
|
|
2106
|
+
}
|
|
2107
|
+
const { imageUri } = await uploadCodeToECR({
|
|
2108
|
+
bucket,
|
|
2109
|
+
key,
|
|
2110
|
+
versionId,
|
|
2111
|
+
lambdaDockerfile,
|
|
2112
|
+
lambdaExternal
|
|
2113
|
+
});
|
|
2114
|
+
return { imageUri };
|
|
2115
|
+
};
|
|
2116
|
+
//#endregion
|
|
2117
|
+
//#region src/deploy/cicd/getTriggerPipelineObjectKey.ts
|
|
2118
|
+
/**
|
|
2119
|
+
* The file with this key inside the source S3 key of main and tag pipelines
|
|
2120
|
+
* will trigger those pipelines.
|
|
2121
|
+
*/
|
|
2122
|
+
const getTriggerPipelinesObjectKey = ({ prefix, pipeline }) => {
|
|
2123
|
+
return `${prefix}/${pipeline}.zip`;
|
|
2124
|
+
};
|
|
2125
|
+
//#endregion
|
|
2126
|
+
//#region src/deploy/cicd/cicd.template.ts
|
|
2127
|
+
const API_LOGICAL_ID = "ApiV1ServerlessApi";
|
|
2128
|
+
const CODE_BUILD_PROJECT_LOGS_LOGICAL_ID = "RepositoryImageCodeBuildProjectLogsLogGroup";
|
|
2129
|
+
const CODE_BUILD_PROJECT_SERVICE_ROLE_LOGICAL_ID = "RepositoryImageCodeBuildProjectIAMRole";
|
|
2130
|
+
const ECR_REPOSITORY_LOGICAL_ID = "RepositoryECRRepository";
|
|
2131
|
+
const FUNCTION_IAM_ROLE_LOGICAL_ID = "ApiV1ServerlessFunctionIAMRole";
|
|
2132
|
+
const ECS_TASK_REPORT_HANDLER_LAMBDA_FUNCTION_LOGICAL_ID = "EcsTaskReportHandler";
|
|
2133
|
+
const PROCESS_ENV_REPOSITORY_IMAGE_CODE_BUILD_PROJECT_NAME = "REPOSITORY_IMAGE_CODE_BUILD_PROJECT_NAME";
|
|
2134
|
+
const REPOSITORY_ECS_TASK_CONTAINER_NAME = "RepositoryECSTaskContainerName";
|
|
2135
|
+
const REPOSITORY_ECS_TASK_DEFINITION_LOGICAL_ID = "RepositoryECSTaskDefinition";
|
|
2136
|
+
const REPOSITORY_IMAGE_CODE_BUILD_PROJECT_LOGICAL_ID = "RepositoryImageCodeBuildProject";
|
|
2137
|
+
const REPOSITORY_TASKS_ECS_CLUSTER_LOGICAL_ID = "RepositoryTasksECSCluster";
|
|
2138
|
+
const REPOSITORY_TASKS_ECS_CLUSTER_LOGS_LOG_GROUP_LOGICAL_ID = "RepositoryTasksECSClusterLogsLogGroup";
|
|
2139
|
+
const REPOSITORY_TASKS_ECS_TASK_DEFINITION_EXECUTION_ROLE_LOGICAL_ID = "RepositoryTasksECSTaskDefinitionExecutionRoleIAMRole";
|
|
2140
|
+
const REPOSITORY_TASKS_ECS_TASK_DEFINITION_TASK_ROLE_LOGICAL_ID = "RepositoryTasksECSTaskDefinitionTaskRoleIAMRole";
|
|
2141
|
+
const PIPELINES_ARTIFACT_STORE_S3_BUCKET_LOGICAL_ID = "PipelinesArtifactStoreS3Bucket";
|
|
2142
|
+
const PIPELINES_ROLE_LOGICAL_ID = "PipelinesMainIAMRole";
|
|
2143
|
+
const PIPELINES_MAIN_LOGICAL_ID = "PipelinesMainCodePipeline";
|
|
2144
|
+
const PIPELINES_TAG_LOGICAL_ID = "PipelinesTagCodePipeline";
|
|
2145
|
+
const PIPELINES_HANDLER_LAMBDA_FUNCTION_LOGICAL_ID = "PipelinesHandlerLambdaFunction";
|
|
2146
|
+
const IMAGE_UPDATER_SCHEDULE_SERVERLESS_FUNCTION_LOGICAL_ID = "ImageUpdaterScheduleServerlessFunction";
|
|
2147
|
+
/**
|
|
2148
|
+
* An [AWS CodeBuild](https://aws.amazon.com/codebuild/) project is created
|
|
2149
|
+
* to build (create and update) repository images. It uses a
|
|
2150
|
+
* [BUILD\_GENERAL1\_SMALL environment compute type](https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html)
|
|
2151
|
+
* with Linux as operational system to build the image.
|
|
2152
|
+
*/
|
|
2153
|
+
const getRepositoryImageBuilder = () => {
|
|
2154
|
+
return {
|
|
2155
|
+
Type: "AWS::CodeBuild::Project",
|
|
2156
|
+
Properties: {
|
|
2157
|
+
Artifacts: { Type: "NO_ARTIFACTS" },
|
|
2158
|
+
Cache: {
|
|
2159
|
+
Location: "LOCAL",
|
|
2160
|
+
Modes: ["LOCAL_DOCKER_LAYER_CACHE"],
|
|
2161
|
+
Type: "LOCAL"
|
|
2162
|
+
},
|
|
2163
|
+
Description: "Create repository image.",
|
|
2164
|
+
Environment: {
|
|
2165
|
+
ComputeType: "BUILD_GENERAL1_SMALL",
|
|
2166
|
+
EnvironmentVariables: [
|
|
2167
|
+
{
|
|
2168
|
+
Name: "AWS_ACCOUNT_ID",
|
|
2169
|
+
Value: { Ref: "AWS::AccountId" }
|
|
2170
|
+
},
|
|
1766
2171
|
{
|
|
1767
2172
|
Name: "AWS_REGION",
|
|
1768
2173
|
Value: { Ref: "AWS::Region" }
|
|
@@ -1831,7 +2236,7 @@ const getRepositoryImageBuilder = () => {
|
|
|
1831
2236
|
} },
|
|
1832
2237
|
ServiceRole: { "Fn::GetAtt": [CODE_BUILD_PROJECT_SERVICE_ROLE_LOGICAL_ID, "Arn"] },
|
|
1833
2238
|
Source: {
|
|
1834
|
-
BuildSpec:
|
|
2239
|
+
BuildSpec: dump({
|
|
1835
2240
|
version: "0.2",
|
|
1836
2241
|
phases: {
|
|
1837
2242
|
install: { commands: [
|
|
@@ -2297,388 +2702,124 @@ const getCicdTemplate = ({ pipelines = [], cpu = ECS_TASK_DEFAULT_CPU, memory =
|
|
|
2297
2702
|
}
|
|
2298
2703
|
]
|
|
2299
2704
|
}
|
|
2300
|
-
}]
|
|
2301
|
-
}
|
|
2302
|
-
};
|
|
2303
|
-
const getCodePipelinePipeline = (pipeline) => {
|
|
2304
|
-
const pipelinePascalCase = pascalCase(pipeline);
|
|
2305
|
-
const pipelineS3SourceOutputName = `Pipeline${pipelinePascalCase}S3SourceOutput`;
|
|
2306
|
-
return {
|
|
2307
|
-
Type: "AWS::CodePipeline::Pipeline",
|
|
2308
|
-
Properties: {
|
|
2309
|
-
ArtifactStore: {
|
|
2310
|
-
Location: { Ref: PIPELINES_ARTIFACT_STORE_S3_BUCKET_LOGICAL_ID },
|
|
2311
|
-
Type: "S3"
|
|
2312
|
-
},
|
|
2313
|
-
RestartExecutionOnUpdate: false,
|
|
2314
|
-
RoleArn: { "Fn::GetAtt": [PIPELINES_ROLE_LOGICAL_ID, "Arn"] },
|
|
2315
|
-
Stages: [{
|
|
2316
|
-
Actions: [{
|
|
2317
|
-
ActionTypeId: {
|
|
2318
|
-
Category: "Source",
|
|
2319
|
-
Owner: "AWS",
|
|
2320
|
-
Provider: "S3",
|
|
2321
|
-
Version: 1
|
|
2322
|
-
},
|
|
2323
|
-
Configuration: {
|
|
2324
|
-
S3Bucket: { "Fn::ImportValue": BASE_STACK_BUCKET_NAME_EXPORTED_NAME },
|
|
2325
|
-
S3ObjectKey: getTriggerPipelinesObjectKey({
|
|
2326
|
-
prefix: triggerPipelinesObjectKeyPrefix,
|
|
2327
|
-
pipeline
|
|
2328
|
-
})
|
|
2329
|
-
},
|
|
2330
|
-
Name: `Pipeline${pipelinePascalCase}S3SourceAction`,
|
|
2331
|
-
OutputArtifacts: [{ Name: pipelineS3SourceOutputName }]
|
|
2332
|
-
}],
|
|
2333
|
-
Name: `Pipeline${pipelinePascalCase}S3SourceStage`
|
|
2334
|
-
}, {
|
|
2335
|
-
Actions: [{
|
|
2336
|
-
ActionTypeId: {
|
|
2337
|
-
Category: "Invoke",
|
|
2338
|
-
Owner: "AWS",
|
|
2339
|
-
Provider: "Lambda",
|
|
2340
|
-
Version: 1
|
|
2341
|
-
},
|
|
2342
|
-
Configuration: {
|
|
2343
|
-
FunctionName: { Ref: PIPELINES_HANDLER_LAMBDA_FUNCTION_LOGICAL_ID },
|
|
2344
|
-
UserParameters: (() => {
|
|
2345
|
-
return pipeline;
|
|
2346
|
-
})()
|
|
2347
|
-
},
|
|
2348
|
-
InputArtifacts: [{ Name: pipelineS3SourceOutputName }],
|
|
2349
|
-
Name: `Pipeline${pipelinePascalCase}RunECSTasksAction`
|
|
2350
|
-
}, {
|
|
2351
|
-
ActionTypeId: {
|
|
2352
|
-
Category: "Approval",
|
|
2353
|
-
Owner: "AWS",
|
|
2354
|
-
Provider: "Manual",
|
|
2355
|
-
Version: 1
|
|
2356
|
-
},
|
|
2357
|
-
Name: PIPELINE_ECS_TASK_EXECUTION_MANUAL_APPROVAL_ACTION_NAME
|
|
2358
|
-
}],
|
|
2359
|
-
Name: PIPELINE_ECS_TASK_EXECUTION_STAGE_NAME
|
|
2360
|
-
}]
|
|
2361
|
-
}
|
|
2362
|
-
};
|
|
2363
|
-
};
|
|
2364
|
-
if (pipelines.includes("main")) resources[PIPELINES_MAIN_LOGICAL_ID] = getCodePipelinePipeline("main");
|
|
2365
|
-
if (pipelines.includes("tag")) resources[PIPELINES_TAG_LOGICAL_ID] = getCodePipelinePipeline("tag");
|
|
2366
|
-
}
|
|
2367
|
-
return {
|
|
2368
|
-
AWSTemplateFormatVersion: "2010-09-09",
|
|
2369
|
-
Transform: "AWS::Serverless-2016-10-31",
|
|
2370
|
-
Resources: resources,
|
|
2371
|
-
Parameters: {
|
|
2372
|
-
SSHKey: {
|
|
2373
|
-
NoEcho: true,
|
|
2374
|
-
Type: "String"
|
|
2375
|
-
},
|
|
2376
|
-
SSHUrl: { Type: "String" }
|
|
2377
|
-
},
|
|
2378
|
-
Outputs: {
|
|
2379
|
-
[REPOSITORY_IMAGE_CODE_BUILD_PROJECT_LOGICAL_ID]: { Value: { Ref: REPOSITORY_IMAGE_CODE_BUILD_PROJECT_LOGICAL_ID } },
|
|
2380
|
-
ApiV1Endpoint: {
|
|
2381
|
-
Description: "CICD API v1 stage endpoint.",
|
|
2382
|
-
Value: { "Fn::Sub": `https://\${${API_LOGICAL_ID}}.execute-api.\${AWS::Region}.amazonaws.com/v1/` }
|
|
2383
|
-
}
|
|
2384
|
-
}
|
|
2385
|
-
};
|
|
2386
|
-
};
|
|
2387
|
-
//#endregion
|
|
2388
|
-
//#region src/deploy/lambda/buildLambdaCode.ts
|
|
2389
|
-
const logPrefix$15 = "lambda";
|
|
2390
|
-
/**
|
|
2391
|
-
* Carlin builds the Lambda code using esbuild. It can build the code as ESM or
|
|
2392
|
-
* CJS format. When building as ESM, it will split the code into multiple files,
|
|
2393
|
-
* which reduces the payload size when deploying the Lambda function. The file
|
|
2394
|
-
* extension of the output files will be `.mjs` for ESM and `.cjs` for CJS.
|
|
2395
|
-
*/
|
|
2396
|
-
const buildLambdaCode = async ({ lambdaEntryPoints, lambdaEntryPointsBaseDir = ".", lambdaExternal = [], lambdaFormat = "esm", lambdaOutdir, lambdaSourceMaps = false }) => {
|
|
2397
|
-
log.info(logPrefix$15, "Building Lambda single file...");
|
|
2398
|
-
/**
|
|
2399
|
-
* Remove the output directory if it exists to not mix old files with the
|
|
2400
|
-
* new ones.
|
|
2401
|
-
*/
|
|
2402
|
-
if (fs.existsSync(lambdaOutdir)) fs.rmSync(lambdaOutdir, { recursive: true });
|
|
2403
|
-
const entryPoints = lambdaEntryPoints.map((entryPoint) => {
|
|
2404
|
-
return path.resolve(process.cwd(), lambdaEntryPointsBaseDir, entryPoint);
|
|
2405
|
-
});
|
|
2406
|
-
const { errors } = esbuild.buildSync({
|
|
2407
|
-
banner: { js: "// Powered by carlin (https://ttoss.dev/docs/carlin/)" },
|
|
2408
|
-
bundle: true,
|
|
2409
|
-
entryPoints,
|
|
2410
|
-
external: [
|
|
2411
|
-
"@aws-sdk/*",
|
|
2412
|
-
...builtinModules,
|
|
2413
|
-
...lambdaExternal
|
|
2414
|
-
],
|
|
2415
|
-
/**
|
|
2416
|
-
* Some packages as `graphql` are not compatible with ESM yet.
|
|
2417
|
-
* https://github.com/graphql/graphql-js/issues/3603
|
|
2418
|
-
*/
|
|
2419
|
-
format: lambdaFormat,
|
|
2420
|
-
/**
|
|
2421
|
-
* https://esbuild.github.io/api/#minify
|
|
2422
|
-
*/
|
|
2423
|
-
minifySyntax: true,
|
|
2424
|
-
platform: "node",
|
|
2425
|
-
/**
|
|
2426
|
-
* Node applies the map only with `--enable-source-maps`, which
|
|
2427
|
-
* `addSourceMapsNodeOptions` sets on every function. Without
|
|
2428
|
-
* `sourcesContent`: Node maps a frame from names and lines alone, and the
|
|
2429
|
-
* source text would only grow the zip.
|
|
2430
|
-
*/
|
|
2431
|
-
...lambdaSourceMaps ? {
|
|
2432
|
-
sourcemap: "linked",
|
|
2433
|
-
sourcesContent: false
|
|
2434
|
-
} : {},
|
|
2435
|
-
splitting: lambdaFormat === "esm",
|
|
2436
|
-
outbase: path.join(process.cwd(), lambdaEntryPointsBaseDir),
|
|
2437
|
-
outdir: path.join(process.cwd(), lambdaOutdir),
|
|
2438
|
-
outExtension: { ".js": lambdaFormat === "esm" ? ".mjs" : ".cjs" },
|
|
2439
|
-
target: typescriptConfig.target,
|
|
2440
|
-
treeShaking: true
|
|
2441
|
-
});
|
|
2442
|
-
if (errors.length > 0) throw errors;
|
|
2443
|
-
};
|
|
2444
|
-
//#endregion
|
|
2445
|
-
//#region src/deploy/lambdaLayer/getPackageLambdaLayerStackName.ts
|
|
2446
|
-
const lambdaLayerStackNamePrefix = `LambdaLayer`;
|
|
2447
|
-
const getPackageLambdaLayerStackName = (packageName) => {
|
|
2448
|
-
const [scopedName, version] = packageName.split("@").filter((part) => {
|
|
2449
|
-
return !!part;
|
|
2450
|
-
});
|
|
2451
|
-
return [
|
|
2452
|
-
lambdaLayerStackNamePrefix,
|
|
2453
|
-
pascalCase(scopedName),
|
|
2454
|
-
version.replace(/[^0-9.]/g, "").replace(/\./g, "-")
|
|
2455
|
-
].join("-");
|
|
2456
|
-
};
|
|
2457
|
-
//#endregion
|
|
2458
|
-
//#region src/deploy/lambdaLayer/deployLambdaLayer.ts
|
|
2459
|
-
const logPrefix$14 = "lambda-layer";
|
|
2460
|
-
const createLambdaLayerZipFile = async ({ codeBuildProjectName, packageName }) => {
|
|
2461
|
-
log.info(logPrefix$14, `Creating zip file for package ${packageName}...`);
|
|
2462
|
-
const { build } = await new AWS.CodeBuild().startBuild({
|
|
2463
|
-
environmentVariablesOverride: [{
|
|
2464
|
-
name: "PACKAGE_NAME",
|
|
2465
|
-
value: packageName
|
|
2466
|
-
}],
|
|
2467
|
-
projectName: codeBuildProjectName
|
|
2468
|
-
}).promise();
|
|
2469
|
-
if (!build?.id) throw new Error("Cannot start build.");
|
|
2470
|
-
const result = await waitCodeBuildFinish({
|
|
2471
|
-
buildId: build.id,
|
|
2472
|
-
name: packageName
|
|
2473
|
-
});
|
|
2474
|
-
if (result.artifacts?.location) {
|
|
2475
|
-
const location = result.artifacts.location.split("/");
|
|
2476
|
-
const bucket = location.shift()?.replace("arn:aws:s3:::", "");
|
|
2477
|
-
if (!bucket) throw new Error("Cannot retrieve bucket name.");
|
|
2478
|
-
return {
|
|
2479
|
-
bucket,
|
|
2480
|
-
key: location.join("/")
|
|
2481
|
-
};
|
|
2482
|
-
}
|
|
2483
|
-
throw new Error(`Cannot get artifact location for package ${packageName}`);
|
|
2484
|
-
};
|
|
2485
|
-
/**
|
|
2486
|
-
* The CloudFormation template created to deploy a Lambda Layer.
|
|
2487
|
-
*
|
|
2488
|
-
* - The Layer name is the same as the Stack name.
|
|
2489
|
-
*/
|
|
2490
|
-
const getLambdaLayerTemplate = ({ bucket, key, packageName, runtime }) => {
|
|
2491
|
-
const description = packageName.substring(0, 256);
|
|
2492
|
-
return {
|
|
2493
|
-
AWSTemplateFormatVersion: "2010-09-09",
|
|
2494
|
-
Resources: { LambdaLayer: {
|
|
2495
|
-
Type: "AWS::Lambda::LayerVersion",
|
|
2496
|
-
Properties: {
|
|
2497
|
-
CompatibleRuntimes: [runtime || DEFAULT_NODE_RUNTIME],
|
|
2498
|
-
Content: {
|
|
2499
|
-
S3Bucket: bucket,
|
|
2500
|
-
S3Key: key
|
|
2501
|
-
},
|
|
2502
|
-
Description: description,
|
|
2503
|
-
LayerName: { Ref: "AWS::StackName" }
|
|
2504
|
-
}
|
|
2505
|
-
} },
|
|
2506
|
-
Outputs: { LambdaLayerVersion: {
|
|
2507
|
-
Description: description,
|
|
2508
|
-
Value: { Ref: "LambdaLayer" },
|
|
2509
|
-
Export: { Name: { Ref: "AWS::StackName" } }
|
|
2510
|
-
} }
|
|
2511
|
-
};
|
|
2512
|
-
};
|
|
2513
|
-
const getPackagesThatAreNotDeployed = async ({ packages }) => {
|
|
2514
|
-
return (await Promise.all(packages.map(async (packageName) => {
|
|
2515
|
-
return await doesStackExist({ stackName: getPackageLambdaLayerStackName(packageName) }) ? "" : packageName;
|
|
2516
|
-
}))).filter((packageName) => {
|
|
2517
|
-
return !!packageName;
|
|
2518
|
-
});
|
|
2519
|
-
};
|
|
2520
|
-
const deployLambdaLayer = async ({ packages, deployIfExists = true, runtime }) => {
|
|
2521
|
-
try {
|
|
2522
|
-
const packagesToBeDeployed = deployIfExists ? packages : await getPackagesThatAreNotDeployed({ packages });
|
|
2523
|
-
if (packagesToBeDeployed.length === 0) return;
|
|
2524
|
-
const codeBuildProjectName = await getBaseStackResource("BASE_STACK_LAMBDA_LAYER_BUILDER_LOGICAL_NAME");
|
|
2525
|
-
if (!codeBuildProjectName) throw new Error("Cannot deploy lambda-layer because AWS CodeBuild project doesn't exist.");
|
|
2526
|
-
const deployLambdaLayerSinglePackage = async (packageName) => {
|
|
2527
|
-
try {
|
|
2528
|
-
const { bucket, key } = await createLambdaLayerZipFile({
|
|
2529
|
-
codeBuildProjectName,
|
|
2530
|
-
packageName
|
|
2531
|
-
});
|
|
2532
|
-
await deploy({
|
|
2533
|
-
template: getLambdaLayerTemplate({
|
|
2534
|
-
packageName,
|
|
2535
|
-
bucket,
|
|
2536
|
-
key,
|
|
2537
|
-
runtime
|
|
2538
|
-
}),
|
|
2539
|
-
terminationProtection: true,
|
|
2540
|
-
params: { StackName: getPackageLambdaLayerStackName(packageName) }
|
|
2541
|
-
});
|
|
2542
|
-
} catch (error) {
|
|
2543
|
-
handleDeployError({
|
|
2544
|
-
error,
|
|
2545
|
-
logPrefix: logPrefix$14
|
|
2546
|
-
});
|
|
2547
|
-
}
|
|
2548
|
-
};
|
|
2549
|
-
await Promise.all(packagesToBeDeployed.map((packageName) => {
|
|
2550
|
-
return deployLambdaLayerSinglePackage(packageName);
|
|
2551
|
-
}));
|
|
2552
|
-
} catch (error) {
|
|
2553
|
-
handleDeployError({
|
|
2554
|
-
error,
|
|
2555
|
-
logPrefix: logPrefix$14
|
|
2556
|
-
});
|
|
2557
|
-
}
|
|
2558
|
-
};
|
|
2559
|
-
//#endregion
|
|
2560
|
-
//#region src/deploy/lambda/deployLambdaLayers.ts
|
|
2561
|
-
const logPrefix$13 = "lambda";
|
|
2562
|
-
const deployLambdaLayers = async ({ lambdaExternal = [] }) => {
|
|
2563
|
-
if (lambdaExternal.length === 0) return;
|
|
2564
|
-
log.info(logPrefix$13, `--lambda-externals [${lambdaExternal.join(", ")}] was found. Creating other layers...`);
|
|
2565
|
-
const { dependencies = {} } = (() => {
|
|
2566
|
-
try {
|
|
2567
|
-
return JSON.parse(fs$2.readFileSync(path$1.resolve(process.cwd(), "package.json"), "utf8"));
|
|
2568
|
-
} catch (err) {
|
|
2569
|
-
log.error(logPrefix$13, "Cannot read package.json. Error message: %j", err.message);
|
|
2570
|
-
return {};
|
|
2571
|
-
}
|
|
2572
|
-
})();
|
|
2573
|
-
await deployLambdaLayer({
|
|
2574
|
-
packages: lambdaExternal.map((external) => {
|
|
2575
|
-
try {
|
|
2576
|
-
return `${external}@${dependencies[external].replace(/(~|\^)/g, "")}`;
|
|
2577
|
-
} catch {
|
|
2578
|
-
throw new Error(`Cannot find ${external} on package.json dependencies.`);
|
|
2705
|
+
}]
|
|
2579
2706
|
}
|
|
2580
|
-
}),
|
|
2581
|
-
deployIfExists: false
|
|
2582
|
-
});
|
|
2583
|
-
};
|
|
2584
|
-
//#endregion
|
|
2585
|
-
//#region src/deploy/lambda/uploadCodeToECR.ts
|
|
2586
|
-
new AWS.CodeBuild({ region: AWS_DEFAULT_REGION });
|
|
2587
|
-
const uploadCodeToECR = async ({ bucket, key, lambdaExternal, lambdaDockerfile }) => {
|
|
2588
|
-
throw new Error("uploadCodeToECR not finished yet.");
|
|
2589
|
-
};
|
|
2590
|
-
//#endregion
|
|
2591
|
-
//#region src/deploy/lambda/uploadCodeToS3.ts
|
|
2592
|
-
const logPrefix$12 = "lambda";
|
|
2593
|
-
const zipFileName = "lambda.zip";
|
|
2594
|
-
const uploadCodeToS3 = async ({ stackName, lambdaOutdir }) => {
|
|
2595
|
-
log.info(logPrefix$12, `Uploading code to S3...`);
|
|
2596
|
-
const zip = new AdmZip();
|
|
2597
|
-
const zipFile = `${lambdaOutdir}/${zipFileName}`;
|
|
2598
|
-
/**
|
|
2599
|
-
* Check if the zip file already exists and delete it before creating a new.
|
|
2600
|
-
*/
|
|
2601
|
-
if (fs.existsSync(zipFile)) await fs.promises.rm(zipFile);
|
|
2602
|
-
/**
|
|
2603
|
-
* Zip entire directory.
|
|
2604
|
-
*/
|
|
2605
|
-
zip.addLocalFolder(lambdaOutdir);
|
|
2606
|
-
zip.writeZip(`${lambdaOutdir}/${zipFileName}`);
|
|
2607
|
-
return uploadFileToS3({
|
|
2608
|
-
bucket: await getBaseStackResource("BASE_STACK_BUCKET_LOGICAL_NAME"),
|
|
2609
|
-
contentType: "application/zip",
|
|
2610
|
-
key: `lambdas/${stackName}/${zipFileName}`,
|
|
2611
|
-
file: zip.toBuffer()
|
|
2612
|
-
});
|
|
2613
|
-
};
|
|
2614
|
-
//#endregion
|
|
2615
|
-
//#region src/deploy/lambda/deployLambdaCode.ts
|
|
2616
|
-
const logPrefix$11 = "lambda";
|
|
2617
|
-
const deployLambdaCode = async ({ lambdaDockerfile, lambdaExternal = [], lambdaImage, lambdaEntryPoints, lambdaEntryPointsBaseDir = "src", lambdaFormat, lambdaOutdir = "out", lambdaSourceMaps, stackName }) => {
|
|
2618
|
-
if (!lambdaEntryPoints.length) return {};
|
|
2619
|
-
log.info(logPrefix$11, "Deploying Lambda code...");
|
|
2620
|
-
for (const entryPoint of lambdaEntryPoints) {
|
|
2621
|
-
const entryPointPath = path.resolve(lambdaEntryPointsBaseDir, entryPoint);
|
|
2622
|
-
if (!fs.existsSync(entryPointPath)) throw new Error(`Entry point ${entryPointPath} does not exist.`);
|
|
2623
|
-
}
|
|
2624
|
-
await buildLambdaCode({
|
|
2625
|
-
lambdaExternal,
|
|
2626
|
-
lambdaEntryPoints,
|
|
2627
|
-
lambdaEntryPointsBaseDir,
|
|
2628
|
-
lambdaFormat,
|
|
2629
|
-
lambdaOutdir,
|
|
2630
|
-
lambdaSourceMaps
|
|
2631
|
-
});
|
|
2632
|
-
const { bucket, key, versionId } = await uploadCodeToS3({
|
|
2633
|
-
stackName,
|
|
2634
|
-
lambdaOutdir
|
|
2635
|
-
});
|
|
2636
|
-
if (!lambdaImage) {
|
|
2637
|
-
await deployLambdaLayers({ lambdaExternal });
|
|
2638
|
-
return {
|
|
2639
|
-
bucket,
|
|
2640
|
-
key,
|
|
2641
|
-
versionId
|
|
2642
2707
|
};
|
|
2708
|
+
const getCodePipelinePipeline = (pipeline) => {
|
|
2709
|
+
const pipelinePascalCase = pascalCase(pipeline);
|
|
2710
|
+
const pipelineS3SourceOutputName = `Pipeline${pipelinePascalCase}S3SourceOutput`;
|
|
2711
|
+
return {
|
|
2712
|
+
Type: "AWS::CodePipeline::Pipeline",
|
|
2713
|
+
Properties: {
|
|
2714
|
+
ArtifactStore: {
|
|
2715
|
+
Location: { Ref: PIPELINES_ARTIFACT_STORE_S3_BUCKET_LOGICAL_ID },
|
|
2716
|
+
Type: "S3"
|
|
2717
|
+
},
|
|
2718
|
+
RestartExecutionOnUpdate: false,
|
|
2719
|
+
RoleArn: { "Fn::GetAtt": [PIPELINES_ROLE_LOGICAL_ID, "Arn"] },
|
|
2720
|
+
Stages: [{
|
|
2721
|
+
Actions: [{
|
|
2722
|
+
ActionTypeId: {
|
|
2723
|
+
Category: "Source",
|
|
2724
|
+
Owner: "AWS",
|
|
2725
|
+
Provider: "S3",
|
|
2726
|
+
Version: 1
|
|
2727
|
+
},
|
|
2728
|
+
Configuration: {
|
|
2729
|
+
S3Bucket: { "Fn::ImportValue": BASE_STACK_BUCKET_NAME_EXPORTED_NAME },
|
|
2730
|
+
S3ObjectKey: getTriggerPipelinesObjectKey({
|
|
2731
|
+
prefix: triggerPipelinesObjectKeyPrefix,
|
|
2732
|
+
pipeline
|
|
2733
|
+
})
|
|
2734
|
+
},
|
|
2735
|
+
Name: `Pipeline${pipelinePascalCase}S3SourceAction`,
|
|
2736
|
+
OutputArtifacts: [{ Name: pipelineS3SourceOutputName }]
|
|
2737
|
+
}],
|
|
2738
|
+
Name: `Pipeline${pipelinePascalCase}S3SourceStage`
|
|
2739
|
+
}, {
|
|
2740
|
+
Actions: [{
|
|
2741
|
+
ActionTypeId: {
|
|
2742
|
+
Category: "Invoke",
|
|
2743
|
+
Owner: "AWS",
|
|
2744
|
+
Provider: "Lambda",
|
|
2745
|
+
Version: 1
|
|
2746
|
+
},
|
|
2747
|
+
Configuration: {
|
|
2748
|
+
FunctionName: { Ref: PIPELINES_HANDLER_LAMBDA_FUNCTION_LOGICAL_ID },
|
|
2749
|
+
UserParameters: (() => {
|
|
2750
|
+
return pipeline;
|
|
2751
|
+
})()
|
|
2752
|
+
},
|
|
2753
|
+
InputArtifacts: [{ Name: pipelineS3SourceOutputName }],
|
|
2754
|
+
Name: `Pipeline${pipelinePascalCase}RunECSTasksAction`
|
|
2755
|
+
}, {
|
|
2756
|
+
ActionTypeId: {
|
|
2757
|
+
Category: "Approval",
|
|
2758
|
+
Owner: "AWS",
|
|
2759
|
+
Provider: "Manual",
|
|
2760
|
+
Version: 1
|
|
2761
|
+
},
|
|
2762
|
+
Name: PIPELINE_ECS_TASK_EXECUTION_MANUAL_APPROVAL_ACTION_NAME
|
|
2763
|
+
}],
|
|
2764
|
+
Name: PIPELINE_ECS_TASK_EXECUTION_STAGE_NAME
|
|
2765
|
+
}]
|
|
2766
|
+
}
|
|
2767
|
+
};
|
|
2768
|
+
};
|
|
2769
|
+
if (pipelines.includes("main")) resources[PIPELINES_MAIN_LOGICAL_ID] = getCodePipelinePipeline("main");
|
|
2770
|
+
if (pipelines.includes("tag")) resources[PIPELINES_TAG_LOGICAL_ID] = getCodePipelinePipeline("tag");
|
|
2643
2771
|
}
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2772
|
+
return {
|
|
2773
|
+
AWSTemplateFormatVersion: "2010-09-09",
|
|
2774
|
+
Transform: "AWS::Serverless-2016-10-31",
|
|
2775
|
+
Resources: resources,
|
|
2776
|
+
Parameters: {
|
|
2777
|
+
SSHKey: {
|
|
2778
|
+
NoEcho: true,
|
|
2779
|
+
Type: "String"
|
|
2780
|
+
},
|
|
2781
|
+
SSHUrl: { Type: "String" }
|
|
2782
|
+
},
|
|
2783
|
+
Outputs: {
|
|
2784
|
+
[REPOSITORY_IMAGE_CODE_BUILD_PROJECT_LOGICAL_ID]: { Value: { Ref: REPOSITORY_IMAGE_CODE_BUILD_PROJECT_LOGICAL_ID } },
|
|
2785
|
+
ApiV1Endpoint: {
|
|
2786
|
+
Description: "CICD API v1 stage endpoint.",
|
|
2787
|
+
Value: { "Fn::Sub": `https://\${${API_LOGICAL_ID}}.execute-api.\${AWS::Region}.amazonaws.com/v1/` }
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
};
|
|
2652
2791
|
};
|
|
2653
2792
|
//#endregion
|
|
2654
2793
|
//#region src/deploy/cicd/getCicdStackName.ts
|
|
2655
2794
|
const getCicdStackName = () => {
|
|
2795
|
+
const project = getProjectName();
|
|
2656
2796
|
return pascalCase([
|
|
2657
2797
|
NAME,
|
|
2658
2798
|
"Cicd",
|
|
2659
|
-
|
|
2799
|
+
project
|
|
2660
2800
|
].join(" "));
|
|
2661
2801
|
};
|
|
2662
2802
|
//#endregion
|
|
2663
2803
|
//#region src/deploy/cicd/deployCicd.ts
|
|
2664
2804
|
const logPrefix$10 = "cicd";
|
|
2665
2805
|
const getLambdaInput = (extension) => {
|
|
2666
|
-
return path$
|
|
2806
|
+
return path$2.resolve(__dirname, `lambdas/index.${extension}`);
|
|
2667
2807
|
};
|
|
2668
2808
|
const deployCicdLambdas = async ({ stackName }) => {
|
|
2809
|
+
const lambdaInput = (() => {
|
|
2810
|
+
/**
|
|
2811
|
+
* This case happens when carlin command is executed when the package is
|
|
2812
|
+
* built.
|
|
2813
|
+
*/
|
|
2814
|
+
if (fs$3.existsSync(getLambdaInput("js"))) return getLambdaInput("js");
|
|
2815
|
+
/**
|
|
2816
|
+
* The package isn't built.
|
|
2817
|
+
*/
|
|
2818
|
+
if (fs$3.existsSync(getLambdaInput("ts"))) return getLambdaInput("ts");
|
|
2819
|
+
throw new Error("Cannot read CICD lambdas file.");
|
|
2820
|
+
})();
|
|
2669
2821
|
const s3 = await deployLambdaCode({
|
|
2670
|
-
lambdaEntryPoints: [
|
|
2671
|
-
/**
|
|
2672
|
-
* This case happens when carlin command is executed when the package is
|
|
2673
|
-
* built.
|
|
2674
|
-
*/
|
|
2675
|
-
if (fs$2.existsSync(getLambdaInput("js"))) return getLambdaInput("js");
|
|
2676
|
-
/**
|
|
2677
|
-
* The package isn't built.
|
|
2678
|
-
*/
|
|
2679
|
-
if (fs$2.existsSync(getLambdaInput("ts"))) return getLambdaInput("ts");
|
|
2680
|
-
throw new Error("Cannot read CICD lambdas file.");
|
|
2681
|
-
})()],
|
|
2822
|
+
lambdaEntryPoints: [lambdaInput],
|
|
2682
2823
|
lambdaExternal: [],
|
|
2683
2824
|
/**
|
|
2684
2825
|
* Needs stackName to define the S3 key.
|
|
@@ -2864,17 +3005,40 @@ const cloudFormationTypes = [
|
|
|
2864
3005
|
}
|
|
2865
3006
|
}
|
|
2866
3007
|
];
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
3008
|
+
/**
|
|
3009
|
+
* The tags are load-only: dumping writes the intrinsic functions as plain
|
|
3010
|
+
* mappings (`Ref: SomeRef`), which CloudFormation also accepts.
|
|
3011
|
+
*/
|
|
3012
|
+
const getYamlTag = ({ tag, options }) => {
|
|
3013
|
+
if (options.kind === "scalar") return defineScalarTag(tag, {
|
|
3014
|
+
resolve: (source) => {
|
|
3015
|
+
return options.construct(source);
|
|
3016
|
+
},
|
|
3017
|
+
identify: () => {
|
|
3018
|
+
return false;
|
|
3019
|
+
}
|
|
3020
|
+
});
|
|
3021
|
+
return defineSequenceTag(tag, {
|
|
3022
|
+
create: () => {
|
|
3023
|
+
return [];
|
|
3024
|
+
},
|
|
3025
|
+
addItem: (carrier, item) => {
|
|
3026
|
+
carrier.push(item);
|
|
3027
|
+
},
|
|
3028
|
+
finalize: (carrier) => {
|
|
3029
|
+
return options.construct(carrier);
|
|
3030
|
+
},
|
|
3031
|
+
identify: () => {
|
|
3032
|
+
return false;
|
|
3033
|
+
}
|
|
2870
3034
|
});
|
|
2871
3035
|
};
|
|
2872
3036
|
/**
|
|
2873
3037
|
* Transform CloudFormation directives in objects. For example, transform
|
|
2874
|
-
* !Ref Something in { Ref: Something }.
|
|
3038
|
+
* !Ref Something in { Ref: Something }. Merge keys (`<<`) are supported.
|
|
2875
3039
|
*/
|
|
2876
3040
|
const getSchema = (tagAndTypeArr = []) => {
|
|
2877
|
-
return
|
|
3041
|
+
return CORE_SCHEMA.withTags(mergeTag, [...tagAndTypeArr, ...cloudFormationTypes].map(getYamlTag));
|
|
2878
3042
|
};
|
|
2879
3043
|
/**
|
|
2880
3044
|
* Transform YAML string in JSON object.
|
|
@@ -2884,7 +3048,7 @@ const getSchema = (tagAndTypeArr = []) => {
|
|
|
2884
3048
|
* @returns JSON template.
|
|
2885
3049
|
*/
|
|
2886
3050
|
const loadCloudFormationTemplate = (template, tagAndTypeArr = []) => {
|
|
2887
|
-
return
|
|
3051
|
+
return load(template, { schema: getSchema(tagAndTypeArr) });
|
|
2888
3052
|
};
|
|
2889
3053
|
//#endregion
|
|
2890
3054
|
//#region ../cloudformation/src/readCloudFormationYamlTemplate.ts
|
|
@@ -2904,7 +3068,8 @@ const getTypes = () => {
|
|
|
2904
3068
|
* @param param0
|
|
2905
3069
|
*/
|
|
2906
3070
|
const readCloudFormationYamlTemplate = ({ templatePath }) => {
|
|
2907
|
-
const
|
|
3071
|
+
const template = fs$3.readFileSync(templatePath).toString();
|
|
3072
|
+
const parsed = loadCloudFormationTemplate(template, getTypes());
|
|
2908
3073
|
if (!parsed || typeof parsed === "string") throw new Error("Cannot parse CloudFormation template.");
|
|
2909
3074
|
return parsed;
|
|
2910
3075
|
};
|
|
@@ -2932,8 +3097,9 @@ const findAndReadCloudFormationTemplate = async ({ templatePath: defaultTemplate
|
|
|
2932
3097
|
* "Error message: "unknown tag !<!Ref> at line 21, column 34:\n"
|
|
2933
3098
|
*/
|
|
2934
3099
|
if (["yaml", "yml"].includes(extension)) return readCloudFormationYamlTemplate({ templatePath });
|
|
3100
|
+
const configFilePath = path$2.resolve(process.cwd(), templatePath);
|
|
2935
3101
|
return readConfigFile({
|
|
2936
|
-
configFilePath
|
|
3102
|
+
configFilePath,
|
|
2937
3103
|
options
|
|
2938
3104
|
});
|
|
2939
3105
|
};
|
|
@@ -2974,8 +3140,6 @@ const getLambdaEntryPointsFromTemplate = (template) => {
|
|
|
2974
3140
|
//#endregion
|
|
2975
3141
|
//#region src/deploy/cloudformation.ts
|
|
2976
3142
|
const logPrefix$8 = "cloudformation";
|
|
2977
|
-
log.addLevel("event", 1e4, { fg: "yellow" });
|
|
2978
|
-
log.addLevel("output", 1e4, { fg: "blue" });
|
|
2979
3143
|
[
|
|
2980
3144
|
"ts",
|
|
2981
3145
|
"js",
|
|
@@ -3165,47 +3329,6 @@ const deployCloudFormation = async (cliOptions) => {
|
|
|
3165
3329
|
});
|
|
3166
3330
|
}
|
|
3167
3331
|
};
|
|
3168
|
-
const emptyStackBuckets = async ({ stackName }) => {
|
|
3169
|
-
const buckets = [];
|
|
3170
|
-
await (async ({ nextToken }) => {
|
|
3171
|
-
const { StackResourceSummaries } = await cloudFormationV2().listStackResources({
|
|
3172
|
-
StackName: stackName,
|
|
3173
|
-
NextToken: nextToken
|
|
3174
|
-
}).promise();
|
|
3175
|
-
for (const { ResourceType, PhysicalResourceId } of StackResourceSummaries || []) if (ResourceType === "AWS::S3::Bucket" && PhysicalResourceId) buckets.push(PhysicalResourceId);
|
|
3176
|
-
})({});
|
|
3177
|
-
return Promise.all(buckets.map((bucket) => {
|
|
3178
|
-
return emptyS3Directory({ bucket });
|
|
3179
|
-
}));
|
|
3180
|
-
};
|
|
3181
|
-
/**
|
|
3182
|
-
* 1. Check if `environment` is defined. If defined, do nothing. It doesn't
|
|
3183
|
-
* destroy stacks with defined `environment`.
|
|
3184
|
-
* 1. Check if termination protection is disabled.
|
|
3185
|
-
* 1. Empty all buckets in the stack (if any).
|
|
3186
|
-
* 1. Delete the stack.
|
|
3187
|
-
*/
|
|
3188
|
-
const destroy = async ({ stackName }) => {
|
|
3189
|
-
const environment = getEnvironment();
|
|
3190
|
-
if (environment) {
|
|
3191
|
-
log.info(logPrefix$8, `Cannot destroy stack when environment (${environment}) is defined.`);
|
|
3192
|
-
return;
|
|
3193
|
-
}
|
|
3194
|
-
if (!await doesStackExist({ stackName })) {
|
|
3195
|
-
log.info(logPrefix$8, `Stack ${stackName} doesn't exist.`);
|
|
3196
|
-
return;
|
|
3197
|
-
}
|
|
3198
|
-
if (!await canDestroyStack({ stackName })) {
|
|
3199
|
-
const message = `Stack ${stackName} cannot be destroyed while TerminationProtection is enabled.`;
|
|
3200
|
-
throw new Error(message);
|
|
3201
|
-
}
|
|
3202
|
-
try {
|
|
3203
|
-
await emptyStackBuckets({ stackName });
|
|
3204
|
-
} catch (error) {
|
|
3205
|
-
log.warn(logPrefix$8, `Failed to empty buckets for stack ${stackName}: ${error?.message || error}. Proceeding with stack deletion.`);
|
|
3206
|
-
}
|
|
3207
|
-
await deleteStack({ stackName });
|
|
3208
|
-
};
|
|
3209
3332
|
const destroyCloudFormation = async ({ stackName: defaultStackName } = {}) => {
|
|
3210
3333
|
try {
|
|
3211
3334
|
log.info(logPrefix$8, "CAUTION! Starting CloudFormation destroy...");
|
|
@@ -3453,13 +3576,16 @@ const invalidateCloudFront = async ({ outputs }) => {
|
|
|
3453
3576
|
}
|
|
3454
3577
|
}
|
|
3455
3578
|
};
|
|
3456
|
-
|
|
3579
|
+
/**
|
|
3580
|
+
* CloudFront is a global service whose API is signed in us-east-1.
|
|
3581
|
+
*/
|
|
3582
|
+
const cloudFront = new CloudFrontClient({ region: CLOUDFRONT_REGION });
|
|
3457
3583
|
try {
|
|
3458
|
-
await cloudFront.
|
|
3584
|
+
await cloudFront.send(new CreateInvalidationCommand(params));
|
|
3459
3585
|
log.info(logPrefix$5, `CloudFront Distribution ID ${distributionId} invalidated with success.`);
|
|
3460
|
-
} catch (
|
|
3586
|
+
} catch (error) {
|
|
3461
3587
|
log.error(logPrefix$5, `Error while trying to invalidate CloudFront distribution ${distributionId}.`);
|
|
3462
|
-
log.error(logPrefix$5,
|
|
3588
|
+
log.error(logPrefix$5, error);
|
|
3463
3589
|
}
|
|
3464
3590
|
} else log.info(logPrefix$5, `Cannot invalidate because distribution does not exist.`);
|
|
3465
3591
|
};
|
|
@@ -3646,7 +3772,7 @@ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
|
|
|
3646
3772
|
*
|
|
3647
3773
|
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-function-quotas.html
|
|
3648
3774
|
*/
|
|
3649
|
-
const MAX_FUNCTION_SIZE_BYTES =
|
|
3775
|
+
const MAX_FUNCTION_SIZE_BYTES = 10240;
|
|
3650
3776
|
/**
|
|
3651
3777
|
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html
|
|
3652
3778
|
*/
|
|
@@ -3817,8 +3943,8 @@ const CLOUDFRONT_CACHE_POLICY_LOGICAL_ID = "CachePolicy";
|
|
|
3817
3943
|
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html
|
|
3818
3944
|
*/
|
|
3819
3945
|
const CACHE_POLICY_CONFIG = {
|
|
3820
|
-
DefaultTTL:
|
|
3821
|
-
MaxTTL:
|
|
3946
|
+
DefaultTTL: 86400,
|
|
3947
|
+
MaxTTL: 31536e3,
|
|
3822
3948
|
MinTTL: 0,
|
|
3823
3949
|
ParametersInCacheKeyAndForwardedToOrigin: {
|
|
3824
3950
|
CookiesConfig: { CookieBehavior: "none" },
|
|
@@ -3955,7 +4081,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, redirectToT
|
|
|
3955
4081
|
Comment: { "Fn::Sub": ["CloudFront Distribution for ${Project} project.", { Project: { Ref: "Project" } }] },
|
|
3956
4082
|
CustomErrorResponses: [403, 404].map((errorCode) => {
|
|
3957
4083
|
if (spa) return {
|
|
3958
|
-
ErrorCachingMinTTL:
|
|
4084
|
+
ErrorCachingMinTTL: 86400,
|
|
3959
4085
|
ErrorCode: errorCode,
|
|
3960
4086
|
ResponseCode: 200,
|
|
3961
4087
|
ResponsePagePath: "/index.html"
|
|
@@ -4466,7 +4592,7 @@ const deployStaticAppCommand = {
|
|
|
4466
4592
|
if (!cloudfront) throw new Error("The viewer-request-function-code option requires the cloudfront option.");
|
|
4467
4593
|
return true;
|
|
4468
4594
|
}).middleware(() => {
|
|
4469
|
-
|
|
4595
|
+
setEnvVar("REGION", CLOUDFRONT_REGION);
|
|
4470
4596
|
});
|
|
4471
4597
|
},
|
|
4472
4598
|
handler: ({ destroy, ...rest }) => {
|
|
@@ -4564,73 +4690,106 @@ const generateSSHCommandWithPwd = ({ userName, host, password, port }) => {
|
|
|
4564
4690
|
//#endregion
|
|
4565
4691
|
//#region src/deploy/vm/deployVM.ts
|
|
4566
4692
|
const logPrefix$3 = "deploy-vm";
|
|
4693
|
+
/**
|
|
4694
|
+
* SSH requires private keys to have restricted permissions (400 or 600 only).
|
|
4695
|
+
* Fix them when `fixPermissions` is set, otherwise throw.
|
|
4696
|
+
*/
|
|
4697
|
+
const ensureKeyPermissions = ({ keyPath, fixPermissions }) => {
|
|
4698
|
+
const permissions = statSync(keyPath).mode & 511;
|
|
4699
|
+
if (permissions === 256 || permissions === 384) {
|
|
4700
|
+
log.info(logPrefix$3, `SSH key permissions OK: ${permissions.toString(8)}`);
|
|
4701
|
+
return;
|
|
4702
|
+
}
|
|
4703
|
+
const permissionStr = permissions.toString(8);
|
|
4704
|
+
if (fixPermissions) {
|
|
4705
|
+
log.info(logPrefix$3, `Fixing SSH key permissions: ${keyPath} (${permissionStr} → 400)`);
|
|
4706
|
+
chmodSync(keyPath, 256);
|
|
4707
|
+
log.info(logPrefix$3, `Permissions set to 400 (read-only by owner)`);
|
|
4708
|
+
return;
|
|
4709
|
+
}
|
|
4710
|
+
log.error(logPrefix$3, `SSH key permissions too open: ${permissionStr} (octal)`);
|
|
4711
|
+
log.error(logPrefix$3, `SSH requires permissions 400 or 600`);
|
|
4712
|
+
log.error(logPrefix$3, `Fix manually: chmod 400 ${keyPath}`);
|
|
4713
|
+
log.error(logPrefix$3, `Or run with: --fix-permissions`);
|
|
4714
|
+
throw new Error(`Invalid SSH key permissions: ${permissionStr}. Expected 400 or 600.`);
|
|
4715
|
+
};
|
|
4716
|
+
/**
|
|
4717
|
+
* Check and fix SSH key permissions. Only invalid permissions stop the
|
|
4718
|
+
* deployment; failing to read them is a warning.
|
|
4719
|
+
*/
|
|
4720
|
+
const checkKeyPermissions = ({ keyPath, fixPermissions }) => {
|
|
4721
|
+
try {
|
|
4722
|
+
ensureKeyPermissions({
|
|
4723
|
+
keyPath,
|
|
4724
|
+
fixPermissions
|
|
4725
|
+
});
|
|
4726
|
+
} catch (error) {
|
|
4727
|
+
if (!(error instanceof Error)) {
|
|
4728
|
+
log.warn(logPrefix$3, "Warning: Could not check key permissions: Unknown error");
|
|
4729
|
+
return;
|
|
4730
|
+
}
|
|
4731
|
+
if (error.message.includes("Invalid SSH key permissions")) throw error;
|
|
4732
|
+
log.warn(logPrefix$3, `Warning: Could not check key permissions: ${error.message}`);
|
|
4733
|
+
}
|
|
4734
|
+
};
|
|
4735
|
+
const getSSHCommand = ({ userName, host, keyPath, password, port }) => {
|
|
4736
|
+
if (keyPath) return {
|
|
4737
|
+
sshCommand: generateSSHCommand({
|
|
4738
|
+
userName,
|
|
4739
|
+
host,
|
|
4740
|
+
keyPath,
|
|
4741
|
+
port
|
|
4742
|
+
}),
|
|
4743
|
+
sshPassword: void 0
|
|
4744
|
+
};
|
|
4745
|
+
if (!password) throw new Error("Password authentication selected but no password was provided.");
|
|
4746
|
+
const result = generateSSHCommandWithPwd({
|
|
4747
|
+
userName,
|
|
4748
|
+
host,
|
|
4749
|
+
password,
|
|
4750
|
+
port
|
|
4751
|
+
});
|
|
4752
|
+
return {
|
|
4753
|
+
sshCommand: result.command,
|
|
4754
|
+
sshPassword: result.password
|
|
4755
|
+
};
|
|
4756
|
+
};
|
|
4757
|
+
const validateStdin = (stdin) => {
|
|
4758
|
+
if (!stdin) {
|
|
4759
|
+
log.error(logPrefix$3, "SSH process stdin is null or undefined");
|
|
4760
|
+
return false;
|
|
4761
|
+
}
|
|
4762
|
+
if (stdin.destroyed) {
|
|
4763
|
+
log.error(logPrefix$3, "SSH process stdin has been destroyed");
|
|
4764
|
+
return false;
|
|
4765
|
+
}
|
|
4766
|
+
if (!stdin.writable) {
|
|
4767
|
+
log.error(logPrefix$3, "SSH process stdin is not writable");
|
|
4768
|
+
return false;
|
|
4769
|
+
}
|
|
4770
|
+
return true;
|
|
4771
|
+
};
|
|
4567
4772
|
const deployVM = async ({ userName, host, scriptPath, keyPath, password, port, fixPermissions = false }) => {
|
|
4568
4773
|
if (!userName || !host || !scriptPath) throw new Error("Missing required parameters: userName, host, scriptPath");
|
|
4569
4774
|
return new Promise((resolve, reject) => {
|
|
4570
4775
|
if (!keyPath && !password) throw new Error(`Authentication method required. Provide either --key-path for SSH key authentication or --password for password authentication.`);
|
|
4571
4776
|
if (keyPath && !existsSync(keyPath)) throw new Error(`SSH key not found at ${keyPath}`);
|
|
4572
|
-
if (keyPath)
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
if (fixPermissions) {
|
|
4578
|
-
log.info(logPrefix$3, `Fixing SSH key permissions: ${keyPath} (${permissionStr} → 400)`);
|
|
4579
|
-
chmodSync(keyPath, 256);
|
|
4580
|
-
log.info(logPrefix$3, `Permissions set to 400 (read-only by owner)`);
|
|
4581
|
-
} else {
|
|
4582
|
-
log.error(logPrefix$3, `SSH key permissions too open: ${permissionStr} (octal)`);
|
|
4583
|
-
log.error(logPrefix$3, `SSH requires permissions 400 or 600`);
|
|
4584
|
-
log.error(logPrefix$3, `Fix manually: ${fixCommand}`);
|
|
4585
|
-
log.error(logPrefix$3, `Or run with: --fix-permissions`);
|
|
4586
|
-
throw new Error(`Invalid SSH key permissions: ${permissionStr}. Expected 400 or 600.`);
|
|
4587
|
-
}
|
|
4588
|
-
} else log.info(logPrefix$3, `SSH key permissions OK: ${permissions.toString(8)}`);
|
|
4589
|
-
} catch (error) {
|
|
4590
|
-
if (error instanceof Error) {
|
|
4591
|
-
if (error.message.includes("Invalid SSH key permissions")) throw error;
|
|
4592
|
-
log.warn(logPrefix$3, `Warning: Could not check key permissions: ${error.message}`);
|
|
4593
|
-
} else log.warn(logPrefix$3, "Warning: Could not check key permissions: Unknown error");
|
|
4594
|
-
}
|
|
4595
|
-
let sshCommand;
|
|
4596
|
-
let sshPassword;
|
|
4597
|
-
if (keyPath) sshCommand = generateSSHCommand({
|
|
4777
|
+
if (keyPath) checkKeyPermissions({
|
|
4778
|
+
keyPath,
|
|
4779
|
+
fixPermissions
|
|
4780
|
+
});
|
|
4781
|
+
const { sshCommand, sshPassword } = getSSHCommand({
|
|
4598
4782
|
userName,
|
|
4599
4783
|
host,
|
|
4600
4784
|
keyPath,
|
|
4785
|
+
password,
|
|
4601
4786
|
port
|
|
4602
4787
|
});
|
|
4603
|
-
else {
|
|
4604
|
-
if (!password) throw new Error("Password authentication selected but no password was provided.");
|
|
4605
|
-
const result = generateSSHCommandWithPwd({
|
|
4606
|
-
userName,
|
|
4607
|
-
host,
|
|
4608
|
-
password,
|
|
4609
|
-
port
|
|
4610
|
-
});
|
|
4611
|
-
sshCommand = result.command;
|
|
4612
|
-
sshPassword = result.password;
|
|
4613
|
-
}
|
|
4614
4788
|
const sshProcess = spawn(sshCommand[0], sshCommand.slice(1), { stdio: [
|
|
4615
4789
|
"pipe",
|
|
4616
4790
|
"inherit",
|
|
4617
4791
|
"inherit"
|
|
4618
4792
|
] });
|
|
4619
|
-
const validateStdin = (stdin) => {
|
|
4620
|
-
if (!stdin) {
|
|
4621
|
-
log.error(logPrefix$3, "SSH process stdin is null or undefined");
|
|
4622
|
-
return false;
|
|
4623
|
-
}
|
|
4624
|
-
if (stdin.destroyed) {
|
|
4625
|
-
log.error(logPrefix$3, "SSH process stdin has been destroyed");
|
|
4626
|
-
return false;
|
|
4627
|
-
}
|
|
4628
|
-
if (!stdin.writable) {
|
|
4629
|
-
log.error(logPrefix$3, "SSH process stdin is not writable");
|
|
4630
|
-
return false;
|
|
4631
|
-
}
|
|
4632
|
-
return true;
|
|
4633
|
-
};
|
|
4634
4793
|
if (!validateStdin(sshProcess.stdin)) {
|
|
4635
4794
|
reject(/* @__PURE__ */ new Error("SSH process stdin is not available or not writable"));
|
|
4636
4795
|
return;
|
|
@@ -4724,7 +4883,8 @@ const reportDeployCommand = {
|
|
|
4724
4883
|
await reportToGitHubPR();
|
|
4725
4884
|
return;
|
|
4726
4885
|
}
|
|
4727
|
-
|
|
4886
|
+
const newStackName = stackName || await getStackName();
|
|
4887
|
+
await printStackOutputsAfterDeploy({ stackName: newStackName });
|
|
4728
4888
|
} catch (error) {
|
|
4729
4889
|
log.info(logPrefix$1, "Cannot report stack. Message: %s", error.message);
|
|
4730
4890
|
}
|
|
@@ -4981,8 +5141,9 @@ const generateEnv = async ({ defaultEnvironment, envFromDeployOutputs, path: env
|
|
|
4981
5141
|
const key = trimmed.split("=")[0].trim();
|
|
4982
5142
|
return !deployOutputKeys.has(key);
|
|
4983
5143
|
}).join("\n");
|
|
5144
|
+
const content = deployOutputLines.length > 0 ? `${filteredEnvFile}\n${deployOutputLines.join("\n")}\n` : envFile;
|
|
4984
5145
|
await writeEnvFile({
|
|
4985
|
-
content
|
|
5146
|
+
content,
|
|
4986
5147
|
envFileName: ".env"
|
|
4987
5148
|
});
|
|
4988
5149
|
log.info(logPrefix, "Generate env file %s from %s successfully.", ".env", envFileName);
|
|
@@ -5149,7 +5310,7 @@ const readConfigFiles = () => {
|
|
|
5149
5310
|
options: getConfigFileOptions()
|
|
5150
5311
|
}) || {};
|
|
5151
5312
|
});
|
|
5152
|
-
return
|
|
5313
|
+
return deepmerge.all(configs.reverse());
|
|
5153
5314
|
};
|
|
5154
5315
|
/**
|
|
5155
5316
|
* Load the appropriate .env file. If an environment is specified (e.g. `-e
|
|
@@ -5161,8 +5322,11 @@ const readConfigFiles = () => {
|
|
|
5161
5322
|
const loadDotEnv = () => {
|
|
5162
5323
|
const { environment } = getConfigFileOptions();
|
|
5163
5324
|
if (environment) {
|
|
5164
|
-
if (dotenv.config({
|
|
5165
|
-
|
|
5325
|
+
if (dotenv.config({
|
|
5326
|
+
path: path.resolve(process.cwd(), `.env.${environment}`),
|
|
5327
|
+
quiet: true
|
|
5328
|
+
}).error) dotenv.config({ quiet: true });
|
|
5329
|
+
} else dotenv.config({ quiet: true });
|
|
5166
5330
|
};
|
|
5167
5331
|
const syncEnvironmentOption = (argv) => {
|
|
5168
5332
|
const finalEnvironment = argv.environment || process.env.ENVIRONMENT;
|
|
@@ -5198,7 +5362,6 @@ const cli = () => {
|
|
|
5198
5362
|
return yargs(hideBin(process.argv)).strictCommands().scriptName(NAME).env(getEnv()).options(addGroupToOptions(options, "Common Options")).middleware(syncEnvironmentOption).middleware(handleEnvironments).middleware(({ environment }) => {
|
|
5199
5363
|
if (!["string", "undefined"].includes(typeof environment)) throw new Error(`environment type is invalid. The value: ${JSON.stringify(environment)}`);
|
|
5200
5364
|
}).middleware(({ region }) => {
|
|
5201
|
-
AWS.config.region = region;
|
|
5202
5365
|
setEnvVar("REGION", region);
|
|
5203
5366
|
}).pkgConf(getPkgConfig()).config(getConfig()).config("config", (configFilePath) => {
|
|
5204
5367
|
return readConfigFileSync({
|