@aws/nx-plugin 1.0.0-rc.85 → 1.0.0-rc.87
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/migrations.json +11 -1
- package/package.json +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +34 -8
- package/src/infra/app/files/app/README.md.template +14 -0
- package/src/infra/app/generator.js +15 -2
- package/src/infra/app/generator.js.map +1 -1
- package/src/mcp-server/tools/general-guidance.js +1 -1
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/migrations/latest/add-destroy-sandbox-target/metadata.json +3 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.d.ts +6 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.js +150 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.js.map +1 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/__snapshots__/migration.spec.ts.snap +23 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/metadata.json +3 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.d.ts +6 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.js +88 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.js.map +1 -0
- package/src/open-api/ts-client/generator.js.map +1 -1
- package/src/open-api/ts-hooks/generator.spec.tsx +1 -1
- package/src/py/project/generator.js +5 -5
- package/src/py/project/generator.js.map +1 -1
- package/src/py/rdb/__snapshots__/generator.spec.ts.snap +21 -9
- package/src/py/rdb/files/__name__/utils.py.template +17 -1
- package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +8 -8
- package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +16 -16
- package/src/ts/dcr-proxy/__snapshots__/generator.spec.ts.snap +3 -3
- package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +3 -3
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +132 -261
- package/src/ts/rdb/files/src/utils.ts.template +28 -1
- package/src/ts/react-website/cognito-auth/generator.js +1 -1
- package/src/ts/react-website/cognito-auth/generator.js.map +1 -1
- package/src/ts/react-website/runtime-config/generator.js +1 -1
- package/src/ts/react-website/runtime-config/generator.js.map +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js +3 -2
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +1 -1
- package/src/utils/api-constructs/api-constructs.js +7 -4
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +4 -4
- package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +4 -4
- package/src/utils/api-constructs/files/cdk/core/api/rest/api-gateway-account.ts.template +1 -1
- package/src/utils/api-constructs/files/terraform/app/apis/http/__apiNameKebabCase__/__apiNameKebabCase__.tf.template +4 -4
- package/src/utils/api-constructs/files/terraform/app/apis/rest/__apiNameKebabCase__/__apiNameKebabCase__.tf.template +4 -4
- package/src/utils/ast.d.ts +13 -0
- package/src/utils/ast.js +36 -0
- package/src/utils/ast.js.map +1 -1
- package/src/utils/bundle/bundle.js +5 -2
- package/src/utils/bundle/bundle.js.map +1 -1
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js +5 -3
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js.map +1 -1
- package/src/utils/dcr-proxy-constructs/files/cdk/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.ts.template +1 -1
- package/src/utils/dcr-proxy-constructs/files/terraform/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.tf.template +2 -2
- package/src/utils/files/common/scripts/src/infra/stage-credentials/cdk-command.ts.template +7 -3
- package/src/utils/function-constructs/function-constructs.js +3 -3
- package/src/utils/function-constructs/function-constructs.js.map +1 -1
- package/src/utils/lambda-runtime-resolution.d.ts +74 -0
- package/src/utils/lambda-runtime-resolution.js +97 -0
- package/src/utils/lambda-runtime-resolution.js.map +1 -0
- package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +3 -3
- package/src/utils/rdb-constructs/files/terraform/app/dbs/__nameKebabCase__/__nameKebabCase__.tf.template +10 -29
- package/src/utils/rdb-constructs/files/terraform/core/rdb/aurora/aurora.tf.template +28 -116
- package/src/utils/rdb-constructs/rdb-constructs.js +5 -3
- package/src/utils/rdb-constructs/rdb-constructs.js.map +1 -1
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.d.ts +28 -0
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.js +148 -0
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.js.map +1 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.d.ts +31 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.js +110 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.js.map +1 -0
- package/src/utils/version-upgrade-migration/sync-vended-versions.js +36 -7
- package/src/utils/version-upgrade-migration/sync-vended-versions.js.map +1 -1
- package/src/utils/versions.d.ts +60 -0
- package/src/utils/versions.js +51 -0
- package/src/utils/versions.js.map +1 -1
package/migrations.json
CHANGED
|
@@ -77,6 +77,16 @@
|
|
|
77
77
|
"description": "Add the Terraform checkov target and config, make bootstrap-destroy non-interactive, and declare required_version in the vended providers.tf",
|
|
78
78
|
"implementation": "./src/migrations/latest/terraform-project-checkov-target-and-bootstrap-destroy/migration"
|
|
79
79
|
},
|
|
80
|
+
"latest-add-destroy-sandbox-target": {
|
|
81
|
+
"version": "1.0.0-rc.87",
|
|
82
|
+
"description": "Add a destroy-sandbox target to CDK infrastructure projects which destroys the sandbox stage, and drop the --require-approval flag from cdk destroy, which has no such option",
|
|
83
|
+
"implementation": "./src/migrations/latest/add-destroy-sandbox-target/migration"
|
|
84
|
+
},
|
|
85
|
+
"latest-terraform-rdb-proxy-iam-connect-grant": {
|
|
86
|
+
"version": "1.0.0-rc.87",
|
|
87
|
+
"description": "Replace the MySQL RDS Proxy role's admin secret access with the rds-db:connect grant it needs for end-to-end IAM auth",
|
|
88
|
+
"implementation": "./src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration"
|
|
89
|
+
},
|
|
80
90
|
"v1.0.0-rc.50-0001-modernize-function-props-cast": {
|
|
81
91
|
"version": "1.0.0-rc.50",
|
|
82
92
|
"description": "Replace the legacy angle-bracket FunctionProps type assertion with the modern as syntax in generated API constructs",
|
|
@@ -218,7 +228,7 @@
|
|
|
218
228
|
"implementation": "./src/migrations/v1.0.0-rc.75/0001-ts-agent-session-id-middleware-extraction/migration"
|
|
219
229
|
},
|
|
220
230
|
"sync-vended-versions": {
|
|
221
|
-
"version": "1.0.0-rc.
|
|
231
|
+
"version": "1.0.0-rc.87",
|
|
222
232
|
"description": "Sync vended dependency versions and the tracked plugin version to those vended by this release",
|
|
223
233
|
"implementation": "./src/utils/version-upgrade-migration/migration"
|
|
224
234
|
}
|
package/package.json
CHANGED
|
@@ -98,7 +98,7 @@ exports[`infra generator > should configure project.json with correct targets >
|
|
|
98
98
|
],
|
|
99
99
|
"executor": "nx:run-commands",
|
|
100
100
|
"options": {
|
|
101
|
-
"command": "cdk destroy
|
|
101
|
+
"command": "cdk destroy",
|
|
102
102
|
"cwd": "{projectRoot}",
|
|
103
103
|
},
|
|
104
104
|
}
|
|
@@ -202,14 +202,25 @@ exports[`infra generator > should configure project.json with correct targets >
|
|
|
202
202
|
],
|
|
203
203
|
"executor": "nx:run-commands",
|
|
204
204
|
"options": {
|
|
205
|
-
"command": "cdk destroy
|
|
205
|
+
"command": "cdk destroy",
|
|
206
206
|
"cwd": "{projectRoot}",
|
|
207
207
|
},
|
|
208
208
|
},
|
|
209
209
|
"destroy-ci": {
|
|
210
210
|
"executor": "nx:run-commands",
|
|
211
211
|
"options": {
|
|
212
|
-
"command": "cdk destroy --
|
|
212
|
+
"command": "cdk destroy --app ../../dist/{projectRoot}/cdk.out",
|
|
213
|
+
"cwd": "{projectRoot}",
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
"destroy-sandbox": {
|
|
217
|
+
"dependsOn": [
|
|
218
|
+
"^build",
|
|
219
|
+
"compile",
|
|
220
|
+
],
|
|
221
|
+
"executor": "nx:run-commands",
|
|
222
|
+
"options": {
|
|
223
|
+
"command": "cdk destroy "proj-test-sandbox/*"",
|
|
213
224
|
"cwd": "{projectRoot}",
|
|
214
225
|
},
|
|
215
226
|
},
|
|
@@ -797,14 +808,25 @@ exports[`infra generator > should handle custom project names correctly > custom
|
|
|
797
808
|
],
|
|
798
809
|
"executor": "nx:run-commands",
|
|
799
810
|
"options": {
|
|
800
|
-
"command": "cdk destroy
|
|
811
|
+
"command": "cdk destroy",
|
|
801
812
|
"cwd": "{projectRoot}",
|
|
802
813
|
},
|
|
803
814
|
},
|
|
804
815
|
"destroy-ci": {
|
|
805
816
|
"executor": "nx:run-commands",
|
|
806
817
|
"options": {
|
|
807
|
-
"command": "cdk destroy --
|
|
818
|
+
"command": "cdk destroy --app ../../dist/{projectRoot}/cdk.out",
|
|
819
|
+
"cwd": "{projectRoot}",
|
|
820
|
+
},
|
|
821
|
+
},
|
|
822
|
+
"destroy-sandbox": {
|
|
823
|
+
"dependsOn": [
|
|
824
|
+
"^build",
|
|
825
|
+
"compile",
|
|
826
|
+
],
|
|
827
|
+
"executor": "nx:run-commands",
|
|
828
|
+
"options": {
|
|
829
|
+
"command": "cdk destroy "proj-custom-infra-sandbox/*"",
|
|
808
830
|
"cwd": "{projectRoot}",
|
|
809
831
|
},
|
|
810
832
|
},
|
|
@@ -1046,9 +1068,10 @@ exports[`infra generator > with stageConfig > should snapshot generated scripts
|
|
|
1046
1068
|
"/**
|
|
1047
1069
|
* Builds the CDK command as an array of arguments for spawnSync.
|
|
1048
1070
|
*
|
|
1049
|
-
*
|
|
1071
|
+
* Deploys default to --require-approval=never (standard for local dev deploys).
|
|
1050
1072
|
* If the user explicitly passes --require-approval with any value, we
|
|
1051
|
-
* respect their choice and don't add the default.
|
|
1073
|
+
* respect their choice and don't add the default. \`cdk destroy\` has no
|
|
1074
|
+
* --require-approval option, so nothing is added for it.
|
|
1052
1075
|
*
|
|
1053
1076
|
* Pass --express to opt into CloudFormation express mode for faster
|
|
1054
1077
|
* iteration; it is not enabled by default so deploys wait for full
|
|
@@ -1061,7 +1084,10 @@ export function buildCdkCommand(
|
|
|
1061
1084
|
const hasRequireApproval = remainingArgs.some(
|
|
1062
1085
|
(a) => a === '--require-approval' || a.startsWith('--require-approval='),
|
|
1063
1086
|
);
|
|
1064
|
-
const defaults =
|
|
1087
|
+
const defaults =
|
|
1088
|
+
action === 'destroy' || hasRequireApproval
|
|
1089
|
+
? []
|
|
1090
|
+
: ['--require-approval=never'];
|
|
1065
1091
|
return ['cdk', action, ...defaults, ...remainingArgs];
|
|
1066
1092
|
}
|
|
1067
1093
|
"
|
|
@@ -50,6 +50,20 @@ Currently hot swapping supports Lambda functions, Step Functions state machines,
|
|
|
50
50
|
|
|
51
51
|
Run `<%= pkgMgrCmd %> nx deploy-sandbox <%= fullyQualifiedName %> --hotswap`
|
|
52
52
|
|
|
53
|
+
## Tear Down from AWS
|
|
54
|
+
|
|
55
|
+
### Tear down your Sandbox Stage
|
|
56
|
+
|
|
57
|
+
Run `<%= pkgMgrCmd %> nx destroy-sandbox <%= fullyQualifiedName %>`
|
|
58
|
+
|
|
59
|
+
### Tear down all Stacks in a Stage
|
|
60
|
+
|
|
61
|
+
Run `<%= pkgMgrCmd %> nx destroy <%= fullyQualifiedName %> "[stageName]/*"`
|
|
62
|
+
|
|
63
|
+
### Tear down a single Stack
|
|
64
|
+
|
|
65
|
+
Run `<%= pkgMgrCmd %> nx destroy <%= fullyQualifiedName %> [stageName]/[stackName]`
|
|
66
|
+
|
|
53
67
|
## Checkov Rule Suppressions
|
|
54
68
|
|
|
55
69
|
There may be instances where you want to suppress certain rules on resources. You can do this in two ways:
|
|
@@ -206,14 +206,27 @@ export async function tsInfraGenerator(tree, schema) {
|
|
|
206
206
|
command: `tsx packages/common/scripts/src/infra/infra-destroy.ts ${libraryRoot}`
|
|
207
207
|
}) : withCdkEnv({
|
|
208
208
|
cwd: '{projectRoot}',
|
|
209
|
-
command: 'cdk destroy
|
|
209
|
+
command: 'cdk destroy'
|
|
210
|
+
})
|
|
211
|
+
};
|
|
212
|
+
config.targets['destroy-sandbox'] = {
|
|
213
|
+
executor: 'nx:run-commands',
|
|
214
|
+
dependsOn: [
|
|
215
|
+
'^build',
|
|
216
|
+
'compile'
|
|
217
|
+
],
|
|
218
|
+
options: stageConfig ? withCdkEnv({
|
|
219
|
+
command: `tsx packages/common/scripts/src/infra/infra-destroy.ts ${libraryRoot} ${sandboxStagePattern}`
|
|
220
|
+
}) : withCdkEnv({
|
|
221
|
+
cwd: '{projectRoot}',
|
|
222
|
+
command: `cdk destroy ${sandboxStagePattern}`
|
|
210
223
|
})
|
|
211
224
|
};
|
|
212
225
|
config.targets['destroy-ci'] = {
|
|
213
226
|
executor: 'nx:run-commands',
|
|
214
227
|
options: withCdkEnv({
|
|
215
228
|
cwd: '{projectRoot}',
|
|
216
|
-
command: `cdk destroy --
|
|
229
|
+
command: `cdk destroy --app ${distDirFromProjectRoot}`
|
|
217
230
|
})
|
|
218
231
|
};
|
|
219
232
|
config.targets.cdk = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/infra/app/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n readProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport path from 'path';\nimport tsProjectGenerator, { getTsLibDetails } from '../../ts/lib/generator.js';\nimport { mergeTsReferences } from '../../ts/lib/ts-project-utils.js';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport { resolveContainers } from '../../utils/containers.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { esmVars } from '../../utils/module-format.js';\nimport { kebabCase } from '../../utils/names.js';\nimport { getNpmScopePrefix } from '../../utils/npm-scope.js';\nimport {\n addDependencyToTargetIfNotPresent,\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n projectExists,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { getPackageManagerDisplayCommands } from '../../utils/pkg-manager.js';\nimport { uvxCommand } from '../../utils/py.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../utils/shared-constructs.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_INFRA_CONFIG_DIR,\n} from '../../utils/shared-constructs-constants.js';\nimport { sharedInfraConfigGenerator } from '../../utils/shared-infra-config.js';\nimport {\n SHARED_INFRA_SCRIPTS_DEPENDENCIES,\n sharedInfraScriptsGenerator,\n} from '../../utils/shared-infra-scripts.js';\nimport type { TsInfraGeneratorSchema } from './schema';\n\n// This generator records no metadata, so nothing a predicate could read: the\n// CDK app always needs the app libraries, and the CLI, bundler and tsx are\n// shared tooling.\nexport const DEPENDENCIES = declareDependencies()({\n ts: [\n { name: 'aws-cdk-lib' },\n { name: 'constructs' },\n { name: 'source-map-support' },\n // The `aws-cdk` CLI, esbuild (CDK bundling) and tsx are shared tooling.\n { name: 'aws-cdk', dev: true, root: true },\n { name: 'esbuild', dev: true, root: true },\n { name: 'tsx', dev: true, root: true },\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ...ownedElsewhere(SHARED_INFRA_SCRIPTS_DEPENDENCIES),\n ],\n});\n\nexport const INFRA_APP_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport async function tsInfraGenerator(\n tree: Tree,\n schema: TsInfraGeneratorSchema,\n): Promise<GeneratorCallback> {\n const lib = getTsLibDetails(tree, schema);\n\n if (!projectExists(tree, lib.fullyQualifiedName)) {\n await tsProjectGenerator(tree, {\n ...schema,\n preferInstallDependencies: false,\n });\n }\n\n // CDK shells out to a container engine to build image assets. Default\n // (docker) needs no env override; finch is set via CDK_DOCKER per\n // https://docs.aws.amazon.com/cdk/v2/guide/build-containers.html#build-container-replace.\n const containers = await resolveContainers(tree, 'inherit');\n const cdkEnv: Record<string, string> | undefined =\n containers === 'docker' ? undefined : { CDK_DOCKER: containers };\n const withCdkEnv = <T extends Record<string, unknown>>(opts: T): T => {\n if (!cdkEnv) return opts;\n const existingEnv = (opts.env as Record<string, string> | undefined) ?? {};\n return { ...opts, env: { ...existingEnv, ...cdkEnv } } as T;\n };\n\n // This generator IS the CDK infrastructure project, so the provider is fixed.\n addGeneratorMetadata(tree, lib.fullyQualifiedName, INFRA_APP_GENERATOR_INFO, {\n iac: 'cdk',\n });\n\n // Shared constructs always in CDK for typescript infra generator\n await sharedConstructsGenerator(\n tree,\n {\n iac: 'cdk',\n },\n DEPENDENCIES,\n );\n\n // Shared infra-config and infra-scripts packages (lazy creation, only when enabled)\n const stageConfig = schema.stageConfig ?? false;\n if (stageConfig) {\n await sharedInfraConfigGenerator(tree);\n await sharedInfraScriptsGenerator(tree, DEPENDENCIES);\n }\n\n const synthDirFromRoot = `/dist/${lib.dir}/cdk.out`;\n const synthDirFromProject =\n lib.dir\n .split('/')\n .map(() => '..')\n .join('/') + `/dist/${lib.dir}/cdk.out`;\n const distDirFromProjectRoot =\n lib.dir\n .split('/')\n .map(() => '..')\n .join('/') + '/dist/{projectRoot}/cdk.out';\n const projectConfig = readProjectConfiguration(tree, lib.fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const fullyQualifiedName = `${npmScopePrefix}${schema.name}`;\n const namespace = kebabCase(fullyQualifiedName);\n // The stage instantiated in main.ts. Quoted so the shell does not glob `*`.\n const sandboxStagePattern = `\"${namespace}-sandbox/*\"`;\n tree.delete(joinPathFragments(libraryRoot, 'src'));\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, './files/app'), // path to the file templates\n libraryRoot, // destination path of the files\n {\n synthDir: synthDirFromProject,\n scopeAlias: scopeAlias,\n namespace,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n dir: lib.dir,\n stageConfig,\n ...schema,\n ...esmVars(tree),\n },\n {\n overwriteStrategy: OverwriteStrategy.Overwrite,\n },\n );\n\n updateJson(\n tree,\n `${libraryRoot}/project.json`,\n (config: ProjectConfiguration) => {\n config.projectType = 'application';\n addDependencyToTargetIfNotPresent(config, 'build', 'synth');\n addDependencyToTargetIfNotPresent(config, 'build', 'checkov');\n config.targets.compile.outputs = [\n '{workspaceRoot}/dist/{projectRoot}/tsc',\n ];\n config.targets.synth = {\n cache: true,\n executor: 'nx:run-commands',\n inputs: ['default'],\n outputs: ['{workspaceRoot}/dist/{projectRoot}/cdk.out'],\n dependsOn: ['^build', 'compile'], // compile clobbers dist directory, so ensure synth runs afterwards\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk synth',\n }),\n };\n config.targets.checkov = {\n cache: true,\n executor: 'nx:run-commands',\n inputs: ['{workspaceRoot}/dist/{projectRoot}/cdk.out'],\n outputs: ['{workspaceRoot}/dist/{projectRoot}/checkov'],\n dependsOn: ['synth'],\n options: {\n command: uvxCommand(\n 'checkov',\n '--config-file {projectRoot}/checkov.yml --directory dist/{projectRoot}/cdk.out --framework cloudformation',\n ),\n },\n };\n config.targets.deploy = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-deploy.ts ${libraryRoot}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk deploy --require-approval=never',\n }),\n };\n config.targets['deploy-sandbox'] = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-deploy.ts ${libraryRoot} ${sandboxStagePattern}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk deploy --require-approval=never ${sandboxStagePattern}`,\n }),\n };\n config.targets['deploy-ci'] = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk deploy --require-approval=never --app ${distDirFromProjectRoot}`,\n }),\n };\n config.targets.destroy = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-destroy.ts ${libraryRoot}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk destroy --require-approval=never',\n }),\n };\n config.targets['destroy-ci'] = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk destroy --require-approval=never --app ${distDirFromProjectRoot}`,\n }),\n };\n config.targets.cdk = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk',\n }),\n };\n config.targets.bootstrap = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk bootstrap',\n }),\n };\n config.targets = sortObjectKeys(config.targets);\n return config;\n },\n );\n\n addTsDependencies(tree, DEPENDENCIES, { projectRoot: libraryRoot });\n\n updateJson(tree, `${libraryRoot}/tsconfig.lib.json`, (tsConfig) => ({\n ...tsConfig,\n references: mergeTsReferences(tsConfig.references, [\n {\n path: `${path.relative(\n libraryRoot,\n `${tree.root}/${PACKAGES_DIR}`,\n )}/${SHARED_CONSTRUCTS_DIR}/tsconfig.lib.json`,\n },\n ...(stageConfig\n ? [\n {\n path: `${path.relative(\n libraryRoot,\n `${tree.root}/${PACKAGES_DIR}`,\n )}/${SHARED_INFRA_CONFIG_DIR}/tsconfig.json`,\n },\n ]\n : []),\n ]),\n }));\n\n await addGeneratorMetricsIfApplicable(tree, [INFRA_APP_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n });\n}\nexport default tsInfraGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readProjectConfiguration","updateJson","path","tsProjectGenerator","getTsLibDetails","mergeTsReferences","addTsDependencies","resolveContainers","declareDependencies","ownedElsewhere","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","esmVars","kebabCase","getNpmScopePrefix","addDependencyToTargetIfNotPresent","addGeneratorMetadata","getGeneratorInfo","projectExists","sortObjectKeys","getPackageManagerDisplayCommands","uvxCommand","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_INFRA_CONFIG_DIR","sharedInfraConfigGenerator","SHARED_INFRA_SCRIPTS_DEPENDENCIES","sharedInfraScriptsGenerator","DEPENDENCIES","ts","name","dev","root","INFRA_APP_GENERATOR_INFO","filename","tsInfraGenerator","tree","schema","lib","fullyQualifiedName","preferInstallDependencies","containers","cdkEnv","undefined","CDK_DOCKER","withCdkEnv","opts","existingEnv","env","iac","stageConfig","synthDirFromRoot","dir","synthDirFromProject","split","map","join","distDirFromProjectRoot","projectConfig","libraryRoot","npmScopePrefix","scopeAlias","namespace","sandboxStagePattern","delete","dirname","synthDir","pkgMgrCmd","exec","overwriteStrategy","Overwrite","config","projectType","targets","compile","outputs","synth","cache","executor","inputs","dependsOn","options","cwd","command","checkov","deploy","destroy","cdk","bootstrap","projectRoot","tsConfig","references","relative","languages"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iB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YACzBV,UAAU;YACVG,SAASpC,WAAW;gBAClBqC,KAAK;gBACLC,SAAS;YACX;QACF;QACAZ,OAAOE,OAAO,GAAGxD,eAAesD,OAAOE,OAAO;QAC9C,OAAOF;IACT;IAGFpE,kBAAkBiC,MAAMR,cAAc;QAAE6D,aAAa9B;IAAY;IAEjE7D,WAAWsC,MAAM,GAAGuB,YAAY,kBAAkB,CAAC,EAAE,CAAC+B,WAAc,CAAA;YAClE,GAAGA,QAAQ;YACXC,YAAYzF,kBAAkBwF,SAASC,UAAU,EAAE;gBACjD;oBACE5F,MAAM,GAAGA,KAAK6F,QAAQ,CACpBjC,aACA,GAAGvB,KAAKJ,IAAI,CAAC,CAAC,EAAEV,cAAc,EAC9B,CAAC,EAAEC,sBAAsB,kBAAkB,CAAC;gBAChD;mBACI2B,cACA;oBACE;wBACEnD,MAAM,GAAGA,KAAK6F,QAAQ,CACpBjC,aACA,GAAGvB,KAAKJ,IAAI,CAAC,CAAC,EAAEV,cAAc,EAC9B,CAAC,EAAEE,wBAAwB,cAAc,CAAC;oBAC9C;iBACD,GACD,EAAE;aACP;QACH,CAAA;IAEA,MAAMf,gCAAgC2B,MAAM;QAACH;KAAyB;IAEtE,MAAM1B,qBAAqB6B;IAC3B,OAAO,IACL5B,oBAAoB4B,MAAMC,OAAOG,yBAAyB,EAAE;YAC1DqD,WAAW;gBAAC;aAAa;QAC3B;AACJ;AACA,eAAe1D,iBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/infra/app/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n readProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport path from 'path';\nimport tsProjectGenerator, { getTsLibDetails } from '../../ts/lib/generator.js';\nimport { mergeTsReferences } from '../../ts/lib/ts-project-utils.js';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport { resolveContainers } from '../../utils/containers.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { esmVars } from '../../utils/module-format.js';\nimport { kebabCase } from '../../utils/names.js';\nimport { getNpmScopePrefix } from '../../utils/npm-scope.js';\nimport {\n addDependencyToTargetIfNotPresent,\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n projectExists,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { getPackageManagerDisplayCommands } from '../../utils/pkg-manager.js';\nimport { uvxCommand } from '../../utils/py.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../utils/shared-constructs.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_INFRA_CONFIG_DIR,\n} from '../../utils/shared-constructs-constants.js';\nimport { sharedInfraConfigGenerator } from '../../utils/shared-infra-config.js';\nimport {\n SHARED_INFRA_SCRIPTS_DEPENDENCIES,\n sharedInfraScriptsGenerator,\n} from '../../utils/shared-infra-scripts.js';\nimport type { TsInfraGeneratorSchema } from './schema';\n\n// This generator records no metadata, so nothing a predicate could read: the\n// CDK app always needs the app libraries, and the CLI, bundler and tsx are\n// shared tooling.\nexport const DEPENDENCIES = declareDependencies()({\n ts: [\n { name: 'aws-cdk-lib' },\n { name: 'constructs' },\n { name: 'source-map-support' },\n // The `aws-cdk` CLI, esbuild (CDK bundling) and tsx are shared tooling.\n { name: 'aws-cdk', dev: true, root: true },\n { name: 'esbuild', dev: true, root: true },\n { name: 'tsx', dev: true, root: true },\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ...ownedElsewhere(SHARED_INFRA_SCRIPTS_DEPENDENCIES),\n ],\n});\n\nexport const INFRA_APP_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport async function tsInfraGenerator(\n tree: Tree,\n schema: TsInfraGeneratorSchema,\n): Promise<GeneratorCallback> {\n const lib = getTsLibDetails(tree, schema);\n\n if (!projectExists(tree, lib.fullyQualifiedName)) {\n await tsProjectGenerator(tree, {\n ...schema,\n preferInstallDependencies: false,\n });\n }\n\n // CDK shells out to a container engine to build image assets. Default\n // (docker) needs no env override; finch is set via CDK_DOCKER per\n // https://docs.aws.amazon.com/cdk/v2/guide/build-containers.html#build-container-replace.\n const containers = await resolveContainers(tree, 'inherit');\n const cdkEnv: Record<string, string> | undefined =\n containers === 'docker' ? undefined : { CDK_DOCKER: containers };\n const withCdkEnv = <T extends Record<string, unknown>>(opts: T): T => {\n if (!cdkEnv) return opts;\n const existingEnv = (opts.env as Record<string, string> | undefined) ?? {};\n return { ...opts, env: { ...existingEnv, ...cdkEnv } } as T;\n };\n\n // This generator IS the CDK infrastructure project, so the provider is fixed.\n addGeneratorMetadata(tree, lib.fullyQualifiedName, INFRA_APP_GENERATOR_INFO, {\n iac: 'cdk',\n });\n\n // Shared constructs always in CDK for typescript infra generator\n await sharedConstructsGenerator(\n tree,\n {\n iac: 'cdk',\n },\n DEPENDENCIES,\n );\n\n // Shared infra-config and infra-scripts packages (lazy creation, only when enabled)\n const stageConfig = schema.stageConfig ?? false;\n if (stageConfig) {\n await sharedInfraConfigGenerator(tree);\n await sharedInfraScriptsGenerator(tree, DEPENDENCIES);\n }\n\n const synthDirFromRoot = `/dist/${lib.dir}/cdk.out`;\n const synthDirFromProject =\n lib.dir\n .split('/')\n .map(() => '..')\n .join('/') + `/dist/${lib.dir}/cdk.out`;\n const distDirFromProjectRoot =\n lib.dir\n .split('/')\n .map(() => '..')\n .join('/') + '/dist/{projectRoot}/cdk.out';\n const projectConfig = readProjectConfiguration(tree, lib.fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const fullyQualifiedName = `${npmScopePrefix}${schema.name}`;\n const namespace = kebabCase(fullyQualifiedName);\n // The stage instantiated in main.ts. Quoted so the shell does not glob `*`.\n const sandboxStagePattern = `\"${namespace}-sandbox/*\"`;\n tree.delete(joinPathFragments(libraryRoot, 'src'));\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, './files/app'), // path to the file templates\n libraryRoot, // destination path of the files\n {\n synthDir: synthDirFromProject,\n scopeAlias: scopeAlias,\n namespace,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n dir: lib.dir,\n stageConfig,\n ...schema,\n ...esmVars(tree),\n },\n {\n overwriteStrategy: OverwriteStrategy.Overwrite,\n },\n );\n\n updateJson(\n tree,\n `${libraryRoot}/project.json`,\n (config: ProjectConfiguration) => {\n config.projectType = 'application';\n addDependencyToTargetIfNotPresent(config, 'build', 'synth');\n addDependencyToTargetIfNotPresent(config, 'build', 'checkov');\n config.targets.compile.outputs = [\n '{workspaceRoot}/dist/{projectRoot}/tsc',\n ];\n config.targets.synth = {\n cache: true,\n executor: 'nx:run-commands',\n inputs: ['default'],\n outputs: ['{workspaceRoot}/dist/{projectRoot}/cdk.out'],\n dependsOn: ['^build', 'compile'], // compile clobbers dist directory, so ensure synth runs afterwards\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk synth',\n }),\n };\n config.targets.checkov = {\n cache: true,\n executor: 'nx:run-commands',\n inputs: ['{workspaceRoot}/dist/{projectRoot}/cdk.out'],\n outputs: ['{workspaceRoot}/dist/{projectRoot}/checkov'],\n dependsOn: ['synth'],\n options: {\n command: uvxCommand(\n 'checkov',\n '--config-file {projectRoot}/checkov.yml --directory dist/{projectRoot}/cdk.out --framework cloudformation',\n ),\n },\n };\n config.targets.deploy = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-deploy.ts ${libraryRoot}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk deploy --require-approval=never',\n }),\n };\n config.targets['deploy-sandbox'] = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-deploy.ts ${libraryRoot} ${sandboxStagePattern}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk deploy --require-approval=never ${sandboxStagePattern}`,\n }),\n };\n config.targets['deploy-ci'] = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk deploy --require-approval=never --app ${distDirFromProjectRoot}`,\n }),\n };\n config.targets.destroy = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-destroy.ts ${libraryRoot}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk destroy',\n }),\n };\n config.targets['destroy-sandbox'] = {\n executor: 'nx:run-commands',\n dependsOn: ['^build', 'compile'],\n options: stageConfig\n ? withCdkEnv({\n command: `tsx packages/common/scripts/src/infra/infra-destroy.ts ${libraryRoot} ${sandboxStagePattern}`,\n })\n : withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk destroy ${sandboxStagePattern}`,\n }),\n };\n config.targets['destroy-ci'] = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: `cdk destroy --app ${distDirFromProjectRoot}`,\n }),\n };\n config.targets.cdk = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk',\n }),\n };\n config.targets.bootstrap = {\n executor: 'nx:run-commands',\n options: withCdkEnv({\n cwd: '{projectRoot}',\n command: 'cdk bootstrap',\n }),\n };\n config.targets = sortObjectKeys(config.targets);\n return config;\n },\n );\n\n addTsDependencies(tree, DEPENDENCIES, { projectRoot: libraryRoot });\n\n updateJson(tree, `${libraryRoot}/tsconfig.lib.json`, (tsConfig) => ({\n ...tsConfig,\n references: mergeTsReferences(tsConfig.references, [\n {\n path: `${path.relative(\n libraryRoot,\n `${tree.root}/${PACKAGES_DIR}`,\n )}/${SHARED_CONSTRUCTS_DIR}/tsconfig.lib.json`,\n },\n ...(stageConfig\n ? [\n {\n path: `${path.relative(\n libraryRoot,\n `${tree.root}/${PACKAGES_DIR}`,\n )}/${SHARED_INFRA_CONFIG_DIR}/tsconfig.json`,\n },\n ]\n : []),\n ]),\n }));\n\n await addGeneratorMetricsIfApplicable(tree, [INFRA_APP_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n });\n}\nexport default tsInfraGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readProjectConfiguration","updateJson","path","tsProjectGenerator","getTsLibDetails","mergeTsReferences","addTsDependencies","resolveContainers","declareDependencies","ownedElsewhere","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","esmVars","kebabCase","getNpmScopePrefix","addDependencyToTargetIfNotPresent","addGeneratorMetadata","getGeneratorInfo","projectExists","sortObjectKeys","getPackageManagerDisplayCommands","uvxCommand","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_INFRA_CONFIG_DIR","sharedInfraConfigGenerator","SHARED_INFRA_SCRIPTS_DEPENDENCIES","sharedInfraScriptsGenerator","DEPENDENCIES","ts","name","dev","root","INFRA_APP_GENERATOR_INFO","filename","tsInfraGenerator","tree","schema","lib","fullyQualifiedName","preferInstallDependencies","containers","cdkEnv","undefined","CDK_DOCKER","withCdkEnv","opts","existingEnv","env","iac","stageConfig","synthDirFromRoot","dir","synthDirFromProject","split","map","join","distDirFromProjectRoot","projectConfig","libraryRoot","npmScopePrefix","scopeAlias","namespace","sandboxStagePattern","delete","dirname","synthDir","pkgMgrCmd","exec","overwriteStrategy","Overwrite","config","projectType","targets","compile","outputs","synth","cache","executor","inputs","dependsOn","options","cwd","command","checkov","deploy","destroy","cdk","bootstrap","projectRoot","tsConfig","references","relative","languages"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAEjBC,wBAAwB,EAExBC,UAAU,QACL,aAAa;AACpB,OAAOC,UAAU,OAAO;AACxB,OAAOC,sBAAsBC,eAAe,QAAQ,4BAA4B;AAChF,SAASC,iBAAiB,QAAQ,mCAAmC;AACrE,SAASC,iBAAiB,QAAQ,kCAAkC;AACpE,SAASC,iBAAiB,QAAQ,4BAA4B;AAC9D,SACEC,mBAAmB,EACnBC,cAAc,QACT,uCAAuC;AAC9C,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,mBAAmB,QAAQ,yBAAyB;AAC7D,SAASC,+BAA+B,QAAQ,yBAAyB;AACzE,SAASC,OAAO,QAAQ,+BAA+B;AACvD,SAASC,SAAS,QAAQ,uBAAuB;AACjD,SAASC,iBAAiB,QAAQ,2BAA2B;AAC7D,SACEC,iCAAiC,EACjCC,oBAAoB,EACpBC,gBAAgB,EAEhBC,aAAa,QACR,oBAAoB;AAC3B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,gCAAgC,QAAQ,6BAA6B;AAC9E,SAASC,UAAU,QAAQ,oBAAoB;AAC/C,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,mCAAmC;AAC1C,SACEC,YAAY,EACZC,qBAAqB,EACrBC,uBAAuB,QAClB,6CAA6C;AACpD,SAASC,0BAA0B,QAAQ,qCAAqC;AAChF,SACEC,iCAAiC,EACjCC,2BAA2B,QACtB,sCAAsC;AAG7C,6EAA6E;AAC7E,2EAA2E;AAC3E,kBAAkB;AAClB,OAAO,MAAMC,eAAevB,sBAAsB;IAChD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2B,MAAM;QAACH;KAAyB;IAEtE,MAAM1B,qBAAqB6B;IAC3B,OAAO,IACL5B,oBAAoB4B,MAAMC,OAAOG,yBAAyB,EAAE;YAC1DqD,WAAW;gBAAC;aAAa;QAC3B;AACJ;AACA,eAAe1D,iBAAiB"}
|
|
@@ -65,7 +65,7 @@ ${PACKAGE_MANAGERS.map((pm)=>buildNxCommand('<options>', pm)).join(' - \n')}
|
|
|
65
65
|
- Generate all projects into the \`packages/\` directory
|
|
66
66
|
- After making changes to your projects, fix linting issues, then run a full build
|
|
67
67
|
- When it's time to start testing a project, suggest to the user that infrastructure is deployed to AWS. For websites, if a runtime-config.json is needed, use the load-runtime-config target after a deployment to point a local website at a sandbox stack.
|
|
68
|
-
- For CDK infrastructure projects, deploy the sandbox stage with the \`deploy-sandbox\` target (eg \`nx deploy-sandbox infra\`) rather than passing a stage pattern to \`deploy\` — it already targets the sandbox stage declared in \`main.ts\`.
|
|
68
|
+
- For CDK infrastructure projects, deploy the sandbox stage with the \`deploy-sandbox\` target (eg \`nx deploy-sandbox infra\`) rather than passing a stage pattern to \`deploy\` — it already targets the sandbox stage declared in \`main.ts\`. Likewise \`destroy-sandbox\` tears that stage back down.
|
|
69
69
|
|
|
70
70
|
## Batching Generators
|
|
71
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/mcp-server/tools/general-guidance.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { NxGeneratorInfo } from '../../utils/generators.js';\nimport { IAC_PROVIDERS } from '../../utils/iac-providers.js';\nimport { buildNxCommand, fetchGuidePages } from '../generator-info.js';\nimport { PACKAGE_MANAGERS } from '../schema.js';\n\nexport const TOOL_SELECTION_GUIDE = `## Tool Selection Guide\n\n- Use the \\`general-guidance\\` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the \\`create-workspace-command\\` tool to discover how to create a workspace to start a new project.\n- Use the \\`add-to-existing-project\\` tool when adding the plugin to an existing Nx workspace or non-Nx monorepo, or when troubleshooting configuration errors in such a workspace.\n- Use the \\`upgrade-workspace\\` tool when upgrading Nx or the Nx Plugin for AWS to a newer version.\n- Use the \\`list-generators\\` tool to discover the available generators and how to run them.\n- Use the \\`generator-guide\\` tool to retrieve detailed information about a specific generator.`;\n\n/**\n * Add a tool which provides general guidance for using Nx and the Nx Plugin for AWS\n */\nexport const addGeneralGuidanceTool = (\n server: McpServer,\n generators: NxGeneratorInfo[],\n) => {\n server.registerTool(\n 'general-guidance',\n {\n title: 'General Guidance',\n description:\n 'Tool for guidance and best practices for working with Nx and the Nx Plugin for AWS',\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: `# Nx Plugin for AWS Guidance\n\n${TOOL_SELECTION_GUIDE}\n\n## Getting Started\n\n- Choose a package manager first. You can choose between ${PACKAGE_MANAGERS.join(', ')}. It's recommended to use \"pnpm\" if the user has no preference\n- Choose an infrastructure as code (IaC) provider next. You can choose between ${IAC_PROVIDERS.join(', ')}. It's recommended to use CDK if the user has no preference\n- Next, you must create an Nx workspace. Use the \\`create-workspace-command\\` tool for more details, and provide it with your chosen package manager\n- After this, you can start scaffolding the main components of your application using generators. Use the \\`list-generators\\` tool to discover available generators, and the \\`generator-guide\\` tool for more detailed information about a specific generator\n\n## Nx Primer\n\n- Prefix nx commands with the appropriate prefix for your package manager, for example:\n${PACKAGE_MANAGERS.map((pm) => buildNxCommand('<options>', pm)).join(' - \\n')}\n- Each project in your workspace has a file named \\`project.json\\` which contains important project information such as its name, and defines the \"targets\" which can be run for that project, for example building or testing the project\n- Use the command \\`nx reset\\` to reset the Nx daemon when unexpected issues arise\n- After adding dependencies between TypeScript projects, use \\`nx sync\\` to ensure project references are set up correctly\n\n## General Instructions\n\n- Each project declares the third-party runtime dependencies its source imports in its own \\`package.json\\`; shared build/test tooling (test runners, bundlers, etc.) is declared in the root \\`package.json\\` \\`devDependencies\\`. Versions follow a single version policy, recorded in the package manager's dependency catalog where supported (referenced as \\`catalog:\\`). Install with the appropriate command for your package manager:\n - Add a project runtime dependency: \\`pnpm add <package> --filter <project>\\` / \\`yarn workspace <project> add <package>\\` / \\`npm install <package> -w <project>\\` / \\`bun add <package> --cwd <project-directory>\\`\n - Add a shared dev tool at the root: \\`pnpm add -Dw <package>\\` / \\`yarn add -D <package>\\` / \\`npm install --legacy-peer-deps -D <package>\\` / \\`bun install -D <package>\\`\n- The \\`noUndeclaredDependencies\\` lint rule enforces that a project's source only imports packages declared in its own \\`package.json\\`\n- Projects in the same workspace can import one another directly by package name (eg \\`@workspace-name/project-name\\`) without declaring a dependency in \\`package.json\\` — TypeScript path aliases in \\`tsconfig.base.json\\` resolve these imports\n- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example \\`@workspace-name/project-name\\`. Check the \\`project.json\\` file for the specific package to find its fully qualified name\n- When no generator exists for a specific framework required, use the base \\`ts#project\\` and \\`py#project\\` generators and build on top.\n- Leave the \\`--infra\\` option at its default value unless the user has explicitly instructed otherwise. Generators choose a sensible default type of infrastructure to deploy the project with, so only override \\`--infra\\` when the user has specified a particular requirement.\n\n## Useful Commands\n\n- Fix lint issues with \\`nx run-many --target lint --configuration=fix --all --output-style=stream\\`\n- Build all projects with \\`nx run-many --target build --all --output-style=stream\\`\n- Prefer importing the CDK constructs vended by generators in \\`packages/common/constructs\\` over writing your own\n\n## Best Practices\n\n- After running a generator, use the \\`nx show projects\\` command to check which projects have been added (if any)\n- Carefully examine the files that have been generated and always refer back to the generator guide when working in a generated project\n- Generate all projects into the \\`packages/\\` directory\n- After making changes to your projects, fix linting issues, then run a full build\n- When it's time to start testing a project, suggest to the user that infrastructure is deployed to AWS. For websites, if a runtime-config.json is needed, use the load-runtime-config target after a deployment to point a local website at a sandbox stack.\n- For CDK infrastructure projects, deploy the sandbox stage with the \\`deploy-sandbox\\` target (eg \\`nx deploy-sandbox infra\\`) rather than passing a stage pattern to \\`deploy\\` — it already targets the sandbox stage declared in \\`main.ts
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/mcp-server/tools/general-guidance.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { NxGeneratorInfo } from '../../utils/generators.js';\nimport { IAC_PROVIDERS } from '../../utils/iac-providers.js';\nimport { buildNxCommand, fetchGuidePages } from '../generator-info.js';\nimport { PACKAGE_MANAGERS } from '../schema.js';\n\nexport const TOOL_SELECTION_GUIDE = `## Tool Selection Guide\n\n- Use the \\`general-guidance\\` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the \\`create-workspace-command\\` tool to discover how to create a workspace to start a new project.\n- Use the \\`add-to-existing-project\\` tool when adding the plugin to an existing Nx workspace or non-Nx monorepo, or when troubleshooting configuration errors in such a workspace.\n- Use the \\`upgrade-workspace\\` tool when upgrading Nx or the Nx Plugin for AWS to a newer version.\n- Use the \\`list-generators\\` tool to discover the available generators and how to run them.\n- Use the \\`generator-guide\\` tool to retrieve detailed information about a specific generator.`;\n\n/**\n * Add a tool which provides general guidance for using Nx and the Nx Plugin for AWS\n */\nexport const addGeneralGuidanceTool = (\n server: McpServer,\n generators: NxGeneratorInfo[],\n) => {\n server.registerTool(\n 'general-guidance',\n {\n title: 'General Guidance',\n description:\n 'Tool for guidance and best practices for working with Nx and the Nx Plugin for AWS',\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: `# Nx Plugin for AWS Guidance\n\n${TOOL_SELECTION_GUIDE}\n\n## Getting Started\n\n- Choose a package manager first. You can choose between ${PACKAGE_MANAGERS.join(', ')}. It's recommended to use \"pnpm\" if the user has no preference\n- Choose an infrastructure as code (IaC) provider next. You can choose between ${IAC_PROVIDERS.join(', ')}. It's recommended to use CDK if the user has no preference\n- Next, you must create an Nx workspace. Use the \\`create-workspace-command\\` tool for more details, and provide it with your chosen package manager\n- After this, you can start scaffolding the main components of your application using generators. Use the \\`list-generators\\` tool to discover available generators, and the \\`generator-guide\\` tool for more detailed information about a specific generator\n\n## Nx Primer\n\n- Prefix nx commands with the appropriate prefix for your package manager, for example:\n${PACKAGE_MANAGERS.map((pm) => buildNxCommand('<options>', pm)).join(' - \\n')}\n- Each project in your workspace has a file named \\`project.json\\` which contains important project information such as its name, and defines the \"targets\" which can be run for that project, for example building or testing the project\n- Use the command \\`nx reset\\` to reset the Nx daemon when unexpected issues arise\n- After adding dependencies between TypeScript projects, use \\`nx sync\\` to ensure project references are set up correctly\n\n## General Instructions\n\n- Each project declares the third-party runtime dependencies its source imports in its own \\`package.json\\`; shared build/test tooling (test runners, bundlers, etc.) is declared in the root \\`package.json\\` \\`devDependencies\\`. Versions follow a single version policy, recorded in the package manager's dependency catalog where supported (referenced as \\`catalog:\\`). Install with the appropriate command for your package manager:\n - Add a project runtime dependency: \\`pnpm add <package> --filter <project>\\` / \\`yarn workspace <project> add <package>\\` / \\`npm install <package> -w <project>\\` / \\`bun add <package> --cwd <project-directory>\\`\n - Add a shared dev tool at the root: \\`pnpm add -Dw <package>\\` / \\`yarn add -D <package>\\` / \\`npm install --legacy-peer-deps -D <package>\\` / \\`bun install -D <package>\\`\n- The \\`noUndeclaredDependencies\\` lint rule enforces that a project's source only imports packages declared in its own \\`package.json\\`\n- Projects in the same workspace can import one another directly by package name (eg \\`@workspace-name/project-name\\`) without declaring a dependency in \\`package.json\\` — TypeScript path aliases in \\`tsconfig.base.json\\` resolve these imports\n- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example \\`@workspace-name/project-name\\`. Check the \\`project.json\\` file for the specific package to find its fully qualified name\n- When no generator exists for a specific framework required, use the base \\`ts#project\\` and \\`py#project\\` generators and build on top.\n- Leave the \\`--infra\\` option at its default value unless the user has explicitly instructed otherwise. Generators choose a sensible default type of infrastructure to deploy the project with, so only override \\`--infra\\` when the user has specified a particular requirement.\n\n## Useful Commands\n\n- Fix lint issues with \\`nx run-many --target lint --configuration=fix --all --output-style=stream\\`\n- Build all projects with \\`nx run-many --target build --all --output-style=stream\\`\n- Prefer importing the CDK constructs vended by generators in \\`packages/common/constructs\\` over writing your own\n\n## Best Practices\n\n- After running a generator, use the \\`nx show projects\\` command to check which projects have been added (if any)\n- Carefully examine the files that have been generated and always refer back to the generator guide when working in a generated project\n- Generate all projects into the \\`packages/\\` directory\n- After making changes to your projects, fix linting issues, then run a full build\n- When it's time to start testing a project, suggest to the user that infrastructure is deployed to AWS. For websites, if a runtime-config.json is needed, use the load-runtime-config target after a deployment to point a local website at a sandbox stack.\n- For CDK infrastructure projects, deploy the sandbox stage with the \\`deploy-sandbox\\` target (eg \\`nx deploy-sandbox infra\\`) rather than passing a stage pattern to \\`deploy\\` — it already targets the sandbox stage declared in \\`main.ts\\`. Likewise \\`destroy-sandbox\\` tears that stage back down.\n\n## Batching Generators\n\nWhen scaffolding several projects in one go, chain generators to avoid a slow dependency install after every generator:\n\n- **Chain generators** with \\`&&\\` in a single command. Pass \\`--prefer-install-dependencies=false\\` on each generator except the last so dependencies install once at the end, for example:\n\n${PACKAGE_MANAGERS.map(\n (pm) => ` \\`\\`\\`bash\n ${buildNxCommand('g @aws/nx-plugin:ts#trpc-api --no-interactive --name=my-app-api --auth=iam --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#react-website --no-interactive --name=my-app-website --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:connection --no-interactive --sourceProject=@my-app/my-app-website --targetProject=@my-app/my-app-api --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#infra --no-interactive --name=infra', pm)} && \\\\\n ${buildNxCommand('sync', pm)}\n \\`\\`\\``,\n).join('\\n')}\n\n- **\\`--prefer-install-dependencies=false\\`** asks a generator to defer its dependency install so the batch installs once at the end (the final generator above omits the flag and installs everything).\n- **\\`nx sync\\`** is required before building — generators modify TypeScript project references.\n\n## Detailed Guides\n\nPlease refer to the below documentation for important details regarding workspaces and working with TypeScript or Python projects.\n\n${await fetchGuidePages(['workspace', 'typescript-project', 'python-project'], generators)}\n\n `,\n },\n ],\n }),\n );\n};\n"],"names":["IAC_PROVIDERS","buildNxCommand","fetchGuidePages","PACKAGE_MANAGERS","TOOL_SELECTION_GUIDE","addGeneralGuidanceTool","server","generators","registerTool","title","description","content","type","text","join","map","pm"],"mappings":"AAAA;;;CAGC,GAGD,SAASA,aAAa,QAAQ,+BAA+B;AAC7D,SAASC,cAAc,EAAEC,eAAe,QAAQ,uBAAuB;AACvE,SAASC,gBAAgB,QAAQ,eAAe;AAEhD,OAAO,MAAMC,uBAAuB,CAAC;;;;;;;+FAO0D,CAAC,CAAC;AAEjG;;CAEC,GACD,OAAO,MAAMC,yBAAyB,CACpCC,QACAC;IAEAD,OAAOE,YAAY,CACjB,oBACA;QACEC,OAAO;QACPC,aACE;IACJ,GACA,UAAa,CAAA;YACXC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC;;AAEjB,EAAET,qBAAqB;;;;yDAIkC,EAAED,iBAAiBW,IAAI,CAAC,MAAM;+EACR,EAAEd,cAAcc,IAAI,CAAC,MAAM;;;;;;;AAO1G,EAAEX,iBAAiBY,GAAG,CAAC,CAACC,KAAOf,eAAe,aAAae,KAAKF,IAAI,CAAC,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqC9E,EAAEX,iBAAiBY,GAAG,CACpB,CAACC,KAAO,CAAC;EACT,EAAEf,eAAe,kHAAkHe,IAAI;IACrI,EAAEf,eAAe,gHAAgHe,IAAI;IACrI,EAAEf,eAAe,8JAA8Je,IAAI;IACnL,EAAEf,eAAe,2DAA2De,IAAI;IAChF,EAAEf,eAAe,QAAQe,IAAI;QACzB,CAAC,EACPF,IAAI,CAAC,MAAM;;;;;;;;;AASb,EAAE,MAAMZ,gBAAgB;wBAAC;wBAAa;wBAAsB;qBAAiB,EAAEK,YAAY;;IAEvF,CAAC;gBACG;aACD;QACH,CAAA;AAEJ,EAAE"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
import { type MigrationReturnObject, type Tree } from '@nx/devkit';
|
|
6
|
+
export default function migration(tree: Tree): Promise<MigrationReturnObject>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/ import { getProjects, joinPathFragments, updateProjectConfiguration } from "@nx/devkit";
|
|
5
|
+
import { readFileSync } from "fs";
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
import { INFRA_APP_GENERATOR_INFO } from "../../../infra/app/generator.js";
|
|
8
|
+
import { captureGritQLVariable } from "../../../utils/ast.js";
|
|
9
|
+
import { formatFilesInSubtree } from "../../../utils/format.js";
|
|
10
|
+
import { normalizeTargetKeyOrder } from "../../../utils/nx.js";
|
|
11
|
+
import { sortObjectKeys } from "../../../utils/object.js";
|
|
12
|
+
import { PACKAGES_DIR, SHARED_SCRIPTS_DIR } from "../../../utils/shared-constructs-constants.js";
|
|
13
|
+
/**
|
|
14
|
+
* CDK infrastructure projects gained a `destroy-sandbox` target, mirroring
|
|
15
|
+
* `deploy-sandbox`: it tears down the sandbox stage without the user having to
|
|
16
|
+
* spell out its stage pattern (`nx destroy-sandbox infra` rather than
|
|
17
|
+
* `nx destroy infra "my-app-infra-sandbox/*"`).
|
|
18
|
+
*
|
|
19
|
+
* The stage id is read from `main.ts` rather than recomputed from the project
|
|
20
|
+
* name, so a project whose sandbox stage has been renamed gets a target that
|
|
21
|
+
* destroys the stage it actually declares.
|
|
22
|
+
*
|
|
23
|
+
* The destroy targets also drop `--require-approval=never`. `cdk destroy` has no
|
|
24
|
+
* such option, so it only warns that the flag is being ignored. The same fix
|
|
25
|
+
* lands in the vended `buildCdkCommand`, which builds the command for
|
|
26
|
+
* `stageConfig` workspaces.
|
|
27
|
+
*
|
|
28
|
+
* How to write a migration:
|
|
29
|
+
* - https://nx.dev/docs/kb/migration-generators
|
|
30
|
+
* - What `nextSteps` means: https://nx.dev/docs/reference/devkit/MigrationReturnObject
|
|
31
|
+
*/ const TARGET = 'destroy-sandbox';
|
|
32
|
+
/** The destroy targets the ignored flag is stripped from. */ const DESTROY_TARGETS = [
|
|
33
|
+
'destroy',
|
|
34
|
+
'destroy-ci'
|
|
35
|
+
];
|
|
36
|
+
/** `cdk destroy` has no such option, so it only warns and carries on. */ const IGNORED_APPROVAL_FLAG = /\s*--require-approval(=\S*)?/;
|
|
37
|
+
/**
|
|
38
|
+
* Matches `new ApplicationStage(app, '<id>-sandbox', { ... })`, binding the
|
|
39
|
+
* quoted stage id. The regex spans the quotes because it is matched against the
|
|
40
|
+
* whole string literal node; both quote styles are accepted since the user's
|
|
41
|
+
* formatter may have rewritten them.
|
|
42
|
+
*
|
|
43
|
+
* `main.ts` can declare several stages (beta, prod), so the pattern selects the
|
|
44
|
+
* sandbox one rather than whichever comes first.
|
|
45
|
+
*/ const SANDBOX_STAGE_PATTERN = '`new ApplicationStage($app, $id, $props)` where { $id <: r"[\'\\"].*-sandbox[\'\\"]" }';
|
|
46
|
+
/** The id of the sandbox stage a project's `main.ts` instantiates. */ const sandboxStageId = async (tree, projectRoot)=>{
|
|
47
|
+
const captured = await captureGritQLVariable(tree, joinPathFragments(projectRoot, 'src', 'main.ts'), SANDBOX_STAGE_PATTERN, 'id');
|
|
48
|
+
// The binding keeps the quotes from the source.
|
|
49
|
+
return captured?.slice(1, -1);
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Strip the ignored `--require-approval` from a `cdk destroy` command. Returns
|
|
53
|
+
* undefined when the command isn't the shape the generator produced, or the flag
|
|
54
|
+
* is already gone.
|
|
55
|
+
*/ const withoutApprovalFlag = (command)=>{
|
|
56
|
+
if (typeof command !== 'string' || !command.includes('cdk destroy')) {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
if (!IGNORED_APPROVAL_FLAG.test(command)) return undefined;
|
|
60
|
+
return command.replace(IGNORED_APPROVAL_FLAG, '');
|
|
61
|
+
};
|
|
62
|
+
/** Drops the ignored approval flag from the project's destroy targets. */ const migrateDestroyFlags = (project)=>{
|
|
63
|
+
let changed = false;
|
|
64
|
+
for (const name of DESTROY_TARGETS){
|
|
65
|
+
const target = project.targets?.[name];
|
|
66
|
+
const command = withoutApprovalFlag(target?.options?.command);
|
|
67
|
+
if (command) {
|
|
68
|
+
target.options = {
|
|
69
|
+
...target.options,
|
|
70
|
+
command
|
|
71
|
+
};
|
|
72
|
+
changed = true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return changed;
|
|
76
|
+
};
|
|
77
|
+
/** Path the shared scripts package vends the CDK command builder at. */ const CDK_COMMAND_PATH = joinPathFragments(PACKAGES_DIR, SHARED_SCRIPTS_DIR, 'src/infra/stage-credentials/cdk-command.ts');
|
|
78
|
+
/** The builder as it stands today. The template carries no EJS variables. */ const CDK_COMMAND_TEMPLATE = readFileSync(join(import.meta.dirname, '../../../utils/files/common/scripts/src/infra/stage-credentials/cdk-command.ts.template'), 'utf-8');
|
|
79
|
+
/**
|
|
80
|
+
* Re-vends the CDK command builder, which no longer adds `--require-approval`
|
|
81
|
+
* for the `destroy` action. Only the shape the generator produced is replaced: a
|
|
82
|
+
* customised copy is the user's, so it is reported instead.
|
|
83
|
+
*/ const migrateCdkCommandBuilder = (tree, nextSteps)=>{
|
|
84
|
+
if (!tree.exists(CDK_COMMAND_PATH)) return;
|
|
85
|
+
const current = tree.read(CDK_COMMAND_PATH).toString();
|
|
86
|
+
// Already migrated, so a re-run is a no-op.
|
|
87
|
+
if (current.includes("action === 'destroy'")) return;
|
|
88
|
+
if (!current.includes('hasRequireApproval')) {
|
|
89
|
+
nextSteps.push(`${CDK_COMMAND_PATH}: has diverged from the generated shape — left untouched. Have it skip \`--require-approval\` for the \`destroy\` action, which has no such option.`);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
tree.write(CDK_COMMAND_PATH, CDK_COMMAND_TEMPLATE);
|
|
93
|
+
};
|
|
94
|
+
/** Adds the `destroy-sandbox` target, mirroring the project's `destroy`. */ const addSandboxTarget = async (tree, projectName, project, nextSteps)=>{
|
|
95
|
+
// The new target mirrors `destroy`, so it inherits whatever that resolved to
|
|
96
|
+
// when the project was generated: the `tsx` credential-resolving script
|
|
97
|
+
// under `stageConfig`, plain `cdk destroy` otherwise.
|
|
98
|
+
const destroy = project.targets.destroy;
|
|
99
|
+
const command = destroy?.options?.command;
|
|
100
|
+
const mainPath = joinPathFragments(project.root, 'src/main.ts');
|
|
101
|
+
const stageId = await sandboxStageId(tree, project.root);
|
|
102
|
+
if (typeof command !== 'string') {
|
|
103
|
+
nextSteps.push(`Add a '${TARGET}' target to ${projectName} by hand if necessary — its 'destroy' target no longer matches the shape the generator produced.`);
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
if (!stageId) {
|
|
107
|
+
nextSteps.push(`Add a '${TARGET}' target to ${projectName} by hand if necessary — no sandbox stage was found in ${mainPath}.`);
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
project.targets[TARGET] = normalizeTargetKeyOrder({
|
|
111
|
+
executor: destroy.executor,
|
|
112
|
+
...destroy.dependsOn ? {
|
|
113
|
+
dependsOn: [
|
|
114
|
+
...destroy.dependsOn
|
|
115
|
+
]
|
|
116
|
+
} : {},
|
|
117
|
+
// Quoted so the shell does not glob the `*`.
|
|
118
|
+
options: {
|
|
119
|
+
...destroy.options,
|
|
120
|
+
command: `${command} "${stageId}/*"`
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
return true;
|
|
124
|
+
};
|
|
125
|
+
export default async function migration(tree) {
|
|
126
|
+
const nextSteps = [];
|
|
127
|
+
for (const [projectName, project] of getProjects(tree)){
|
|
128
|
+
const generator = project.metadata?.generator;
|
|
129
|
+
// Not a CDK infrastructure project.
|
|
130
|
+
if (generator !== INFRA_APP_GENERATOR_INFO.id) continue;
|
|
131
|
+
// Corrected first so the new target inherits the fixed command.
|
|
132
|
+
let changed = migrateDestroyFlags(project);
|
|
133
|
+
if (!project.targets?.[TARGET]) {
|
|
134
|
+
changed = await addSandboxTarget(tree, projectName, project, nextSteps) || changed;
|
|
135
|
+
}
|
|
136
|
+
if (changed) {
|
|
137
|
+
updateProjectConfiguration(tree, projectName, {
|
|
138
|
+
...project,
|
|
139
|
+
targets: sortObjectKeys(project.targets)
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
migrateCdkCommandBuilder(tree, nextSteps);
|
|
144
|
+
await formatFilesInSubtree(tree);
|
|
145
|
+
return {
|
|
146
|
+
nextSteps
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
//# sourceMappingURL=migration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/migrations/latest/add-destroy-sandbox-target/migration.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getProjects,\n joinPathFragments,\n type MigrationReturnObject,\n type ProjectConfiguration,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\nimport { INFRA_APP_GENERATOR_INFO } from '../../../infra/app/generator.js';\nimport { captureGritQLVariable } from '../../../utils/ast.js';\nimport { formatFilesInSubtree } from '../../../utils/format.js';\nimport { normalizeTargetKeyOrder } from '../../../utils/nx.js';\nimport { sortObjectKeys } from '../../../utils/object.js';\nimport {\n PACKAGES_DIR,\n SHARED_SCRIPTS_DIR,\n} from '../../../utils/shared-constructs-constants.js';\n\n/**\n * CDK infrastructure projects gained a `destroy-sandbox` target, mirroring\n * `deploy-sandbox`: it tears down the sandbox stage without the user having to\n * spell out its stage pattern (`nx destroy-sandbox infra` rather than\n * `nx destroy infra \"my-app-infra-sandbox/*\"`).\n *\n * The stage id is read from `main.ts` rather than recomputed from the project\n * name, so a project whose sandbox stage has been renamed gets a target that\n * destroys the stage it actually declares.\n *\n * The destroy targets also drop `--require-approval=never`. `cdk destroy` has no\n * such option, so it only warns that the flag is being ignored. The same fix\n * lands in the vended `buildCdkCommand`, which builds the command for\n * `stageConfig` workspaces.\n *\n * How to write a migration:\n * - https://nx.dev/docs/kb/migration-generators\n * - What `nextSteps` means: https://nx.dev/docs/reference/devkit/MigrationReturnObject\n */\n\nconst TARGET = 'destroy-sandbox';\n\n/** The destroy targets the ignored flag is stripped from. */\nconst DESTROY_TARGETS = ['destroy', 'destroy-ci'] as const;\n\n/** `cdk destroy` has no such option, so it only warns and carries on. */\nconst IGNORED_APPROVAL_FLAG = /\\s*--require-approval(=\\S*)?/;\n\n/**\n * Matches `new ApplicationStage(app, '<id>-sandbox', { ... })`, binding the\n * quoted stage id. The regex spans the quotes because it is matched against the\n * whole string literal node; both quote styles are accepted since the user's\n * formatter may have rewritten them.\n *\n * `main.ts` can declare several stages (beta, prod), so the pattern selects the\n * sandbox one rather than whichever comes first.\n */\nconst SANDBOX_STAGE_PATTERN =\n '`new ApplicationStage($app, $id, $props)` where { $id <: r\"[\\'\\\\\"].*-sandbox[\\'\\\\\"]\" }';\n\n/** The id of the sandbox stage a project's `main.ts` instantiates. */\nconst sandboxStageId = async (\n tree: Tree,\n projectRoot: string,\n): Promise<string | undefined> => {\n const captured = await captureGritQLVariable(\n tree,\n joinPathFragments(projectRoot, 'src', 'main.ts'),\n SANDBOX_STAGE_PATTERN,\n 'id',\n );\n // The binding keeps the quotes from the source.\n return captured?.slice(1, -1);\n};\n\n/**\n * Strip the ignored `--require-approval` from a `cdk destroy` command. Returns\n * undefined when the command isn't the shape the generator produced, or the flag\n * is already gone.\n */\nconst withoutApprovalFlag = (command: unknown): string | undefined => {\n if (typeof command !== 'string' || !command.includes('cdk destroy')) {\n return undefined;\n }\n if (!IGNORED_APPROVAL_FLAG.test(command)) return undefined;\n return command.replace(IGNORED_APPROVAL_FLAG, '');\n};\n\n/** Drops the ignored approval flag from the project's destroy targets. */\nconst migrateDestroyFlags = (project: ProjectConfiguration): boolean => {\n let changed = false;\n for (const name of DESTROY_TARGETS) {\n const target = project.targets?.[name];\n const command = withoutApprovalFlag(target?.options?.command);\n if (command) {\n target.options = { ...target.options, command };\n changed = true;\n }\n }\n return changed;\n};\n\n/** Path the shared scripts package vends the CDK command builder at. */\nconst CDK_COMMAND_PATH = joinPathFragments(\n PACKAGES_DIR,\n SHARED_SCRIPTS_DIR,\n 'src/infra/stage-credentials/cdk-command.ts',\n);\n\n/** The builder as it stands today. The template carries no EJS variables. */\nconst CDK_COMMAND_TEMPLATE = readFileSync(\n join(\n import.meta.dirname,\n '../../../utils/files/common/scripts/src/infra/stage-credentials/cdk-command.ts.template',\n ),\n 'utf-8',\n);\n\n/**\n * Re-vends the CDK command builder, which no longer adds `--require-approval`\n * for the `destroy` action. Only the shape the generator produced is replaced: a\n * customised copy is the user's, so it is reported instead.\n */\nconst migrateCdkCommandBuilder = (tree: Tree, nextSteps: string[]): void => {\n if (!tree.exists(CDK_COMMAND_PATH)) return;\n\n const current = tree.read(CDK_COMMAND_PATH)!.toString();\n // Already migrated, so a re-run is a no-op.\n if (current.includes(\"action === 'destroy'\")) return;\n\n if (!current.includes('hasRequireApproval')) {\n nextSteps.push(\n `${CDK_COMMAND_PATH}: has diverged from the generated shape — left untouched. Have it skip \\`--require-approval\\` for the \\`destroy\\` action, which has no such option.`,\n );\n return;\n }\n\n tree.write(CDK_COMMAND_PATH, CDK_COMMAND_TEMPLATE);\n};\n\n/** Adds the `destroy-sandbox` target, mirroring the project's `destroy`. */\nconst addSandboxTarget = async (\n tree: Tree,\n projectName: string,\n project: ProjectConfiguration,\n nextSteps: string[],\n): Promise<boolean> => {\n // The new target mirrors `destroy`, so it inherits whatever that resolved to\n // when the project was generated: the `tsx` credential-resolving script\n // under `stageConfig`, plain `cdk destroy` otherwise.\n const destroy = project.targets.destroy;\n const command = destroy?.options?.command;\n const mainPath = joinPathFragments(project.root, 'src/main.ts');\n const stageId = await sandboxStageId(tree, project.root);\n\n if (typeof command !== 'string') {\n nextSteps.push(\n `Add a '${TARGET}' target to ${projectName} by hand if necessary — its 'destroy' target no longer matches the shape the generator produced.`,\n );\n return false;\n }\n if (!stageId) {\n nextSteps.push(\n `Add a '${TARGET}' target to ${projectName} by hand if necessary — no sandbox stage was found in ${mainPath}.`,\n );\n return false;\n }\n\n project.targets[TARGET] = normalizeTargetKeyOrder({\n executor: destroy.executor,\n ...(destroy.dependsOn ? { dependsOn: [...destroy.dependsOn] } : {}),\n // Quoted so the shell does not glob the `*`.\n options: { ...destroy.options, command: `${command} \"${stageId}/*\"` },\n });\n return true;\n};\n\nexport default async function migration(\n tree: Tree,\n): Promise<MigrationReturnObject> {\n const nextSteps: string[] = [];\n\n for (const [projectName, project] of getProjects(tree)) {\n const generator = (project.metadata as { generator?: string } | undefined)\n ?.generator;\n // Not a CDK infrastructure project.\n if (generator !== INFRA_APP_GENERATOR_INFO.id) continue;\n\n // Corrected first so the new target inherits the fixed command.\n let changed = migrateDestroyFlags(project);\n\n if (!project.targets?.[TARGET]) {\n changed =\n (await addSandboxTarget(tree, projectName, project, nextSteps)) ||\n changed;\n }\n\n if (changed) {\n updateProjectConfiguration(tree, projectName, {\n ...project,\n targets: sortObjectKeys(project.targets),\n });\n }\n }\n\n migrateCdkCommandBuilder(tree, nextSteps);\n\n await formatFilesInSubtree(tree);\n\n return { nextSteps };\n}\n"],"names":["getProjects","joinPathFragments","updateProjectConfiguration","readFileSync","join","INFRA_APP_GENERATOR_INFO","captureGritQLVariable","formatFilesInSubtree","normalizeTargetKeyOrder","sortObjectKeys","PACKAGES_DIR","SHARED_SCRIPTS_DIR","TARGET","DESTROY_TARGETS","IGNORED_APPROVAL_FLAG","SANDBOX_STAGE_PATTERN","sandboxStageId","tree","projectRoot","captured","slice","withoutApprovalFlag","command","includes","undefined","test","replace","migrateDestroyFlags","project","changed","name","target","targets","options","CDK_COMMAND_PATH","CDK_COMMAND_TEMPLATE","dirname","migrateCdkCommandBuilder","nextSteps","exists","current","read","toString","push","write","addSandboxTarget","projectName","destroy","mainPath","root","stageId","executor","dependsOn","migration","generator","metadata","id"],"mappings":"AAAA;;;CAGC,GACD,SACEA,WAAW,EACXC,iBAAiB,EAIjBC,0BAA0B,QACrB,aAAa;AACpB,SAASC,YAAY,QAAQ,KAAK;AAClC,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,wBAAwB,QAAQ,kCAAkC;AAC3E,SAASC,qBAAqB,QAAQ,wBAAwB;AAC9D,SAASC,oBAAoB,QAAQ,2BAA2B;AAChE,SAASC,uBAAuB,QAAQ,uBAAuB;AAC/D,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SACEC,YAAY,EACZC,kBAAkB,QACb,gDAAgD;AAEvD;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,SAAS;AAEf,2DAA2D,GAC3D,MAAMC,kBAAkB;IAAC;IAAW;CAAa;AAEjD,uEAAuE,GACvE,MAAMC,wBAAwB;AAE9B;;;;;;;;CAQC,GACD,MAAMC,wBACJ;AAEF,oEAAoE,GACpE,MAAMC,iBAAiB,OACrBC,MACAC;IAEA,MAAMC,WAAW,MAAMb,sBACrBW,MACAhB,kBAAkBiB,aAAa,OAAO,YACtCH,uBACA;IAEF,gDAAgD;IAChD,OAAOI,UAAUC,MAAM,GAAG,CAAC;AAC7B;AAEA;;;;CAIC,GACD,MAAMC,sBAAsB,CAACC;IAC3B,IAAI,OAAOA,YAAY,YAAY,CAACA,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BAAyBpB,MAAMqB;IAE/B,MAAM/B,qBAAqBU;IAE3B,OAAO;QAAEqB;IAAU;AACrB"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
|
2
|
+
|
|
3
|
+
exports[`terraform-rdb-proxy-iam-connect-grant migration > should replace the mysql admin secret grant with rds-db:connect 1`] = `
|
|
4
|
+
"resource "aws_iam_role_policy" "proxy_db_user_connect" {
|
|
5
|
+
count = var.enable_rds_proxy ? 1 : 0
|
|
6
|
+
|
|
7
|
+
role = module.aurora.proxy_role_name
|
|
8
|
+
|
|
9
|
+
policy = jsonencode({
|
|
10
|
+
Version = "2012-10-17"
|
|
11
|
+
Statement = [
|
|
12
|
+
{
|
|
13
|
+
Effect = "Allow"
|
|
14
|
+
Action = ["rds-db:connect"]
|
|
15
|
+
Resource = [
|
|
16
|
+
"arn:aws:rds-db:\${data.aws_region.current.region}:\${data.aws_caller_identity.current.account_id}:dbuser:\${module.aurora.cluster_resource_id}/\${local.database_runtime_user}"
|
|
17
|
+
]
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
"
|
|
23
|
+
`;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
import { type MigrationReturnObject, type Tree } from '@nx/devkit';
|
|
6
|
+
export default function migration(tree: Tree): Promise<MigrationReturnObject>;
|