@aws-cdk/toolkit-lib 0.1.2 → 0.1.3

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["aws-cdk.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk.ts", "../../../../aws-cdk/lib/api/aws-auth/account-cache.ts", "../../../../aws-cdk/lib/logging.ts", "../../../../aws-cdk/lib/toolkit/cli-io-host.ts", "../../../../aws-cdk/lib/toolkit/error.ts", "../../../../aws-cdk/lib/util/directories.ts", "../../../../aws-cdk/lib/api/aws-auth/cached.ts", "../../../../aws-cdk/lib/api/aws-auth/tracing.ts", "../../../../aws-cdk/lib/api/aws-auth/user-agent.ts", "../../../../aws-cdk/lib/api/aws-auth/util.ts", "../../../../aws-cdk/lib/util/format-error.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk-provider.ts", "../../../../aws-cdk/lib/api/aws-auth/awscli-compatible.ts", "../../../../aws-cdk/lib/api/aws-auth/provider-caching.ts", "../../../../aws-cdk/lib/api/aws-auth/credential-plugins.ts", "../../../../aws-cdk/lib/api/plugin/plugin.ts", "../../../../aws-cdk/lib/api/plugin/context-provider-plugin.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk-logger.ts", "../../../../aws-cdk/lib/util/serialize.ts", "../../../../aws-cdk/lib/util/bytes.ts", "../../../../aws-cdk/lib/util/yaml-cfn.ts", "../../../../aws-cdk/lib/api/settings.ts", "../../../../aws-cdk/lib/util/types.ts", "../../../../aws-cdk/lib/util/objects.ts", "../../../../aws-cdk/lib/api/context.ts", "../../../../aws-cdk/lib/api/deployments/cloudformation.ts", "../../../../aws-cdk/lib/api/deployments/asset-manifest-builder.ts", "../../../../aws-cdk/lib/cli/messages.ts", "../../../../aws-cdk/lib/api/stack-events/stack-activity-monitor.ts", "../../../../aws-cdk/lib/api/stack-events/stack-event-poller.ts", "../../../../aws-cdk/lib/api/stack-events/display.ts", "../../../../aws-cdk/lib/api/stack-events/stack-status.ts", "../../../../aws-cdk/lib/api/util/template-body-parameter.ts", "../../../../aws-cdk/lib/util/content-hash.ts", "../../../../aws-cdk/lib/api/deployments/deployments.ts", "../../../../aws-cdk/lib/api/deployments/asset-publishing.ts", "../../../../aws-cdk/lib/api/deployments/checks.ts", "../../../../aws-cdk/lib/api/deployments/deploy-stack.ts", "../../../../aws-cdk/lib/api/deployments/assets.ts", "../../../../aws-cdk/lib/api/deployments/hotswap-deployments.ts", "../../../../aws-cdk/lib/api/deployments/nested-stack-helpers.ts", "../../../../aws-cdk/lib/api/evaluate-cloudformation-template.ts", "../../../../aws-cdk/lib/api/hotswap/common.ts", "../../../../aws-cdk/lib/api/hotswap/appsync-mapping-templates.ts", "../../../../aws-cdk/lib/api/hotswap/code-build-projects.ts", "../../../../aws-cdk/lib/api/hotswap/ecs-services.ts", "../../../../aws-cdk/lib/api/hotswap/lambda-functions.ts", "../../../../aws-cdk/lib/util/archive.ts", "../../../../aws-cdk/lib/util/arrays.ts", "../../../../aws-cdk/lib/util/cloudformation.ts", "../../../../aws-cdk/lib/util/parallel.ts", "../../../../aws-cdk/lib/util/string-manipulation.ts", "../../../../aws-cdk/lib/util/version-range.ts", "../../../../aws-cdk/lib/api/hotswap/s3-bucket-deployments.ts", "../../../../aws-cdk/lib/api/hotswap/stepfunctions-state-machines.ts", "../../../../aws-cdk/lib/notices.ts", "../../../../aws-cdk/lib/cli/version.ts", "../../../../aws-cdk/lib/cli/util/console-formatters.ts", "../../../../aws-cdk/lib/cli/util/npm.ts", "../../../../aws-cdk/lib/tree.ts", "../../../../aws-cdk/lib/api/toolkit-info.ts", "../../../../aws-cdk/lib/api/bootstrap/bootstrap-props.ts", "../../../../aws-cdk/lib/api/environment/environment-resources.ts", "../../../../aws-cdk/lib/api/util/placeholders.ts", "../../../../aws-cdk/lib/api/environment/environment-access.ts", "../../../../aws-cdk/lib/api/deployments/deployment-result.ts", "../../../../aws-cdk/lib/api/tags.ts", "../../../../aws-cdk/lib/api/resource-import/importer.ts", "../../../../aws-cdk/lib/api/resource-import/migrator.ts", "../../../../aws-cdk/lib/api/logs/logs-monitor.ts", "../../../../aws-cdk/lib/api/logs/find-cloudwatch-logs.ts", "../../../../aws-cdk/lib/api/work-graph/work-graph.ts", "../../../../aws-cdk/lib/api/work-graph/work-graph-builder.ts", "../../../../aws-cdk/lib/context-providers/index.ts", "../../../../aws-cdk/lib/context-providers/ami.ts", "../../../../aws-cdk/lib/context-providers/availability-zones.ts", "../../../../aws-cdk/lib/util/json.ts", "../../../../aws-cdk/lib/context-providers/cc-api-provider.ts", "../../../../aws-cdk/lib/context-providers/endpoint-service-availability-zones.ts", "../../../../aws-cdk/lib/context-providers/hosted-zones.ts", "../../../../aws-cdk/lib/context-providers/keys.ts", "../../../../aws-cdk/lib/context-providers/load-balancers.ts", "../../../../aws-cdk/lib/context-providers/security-groups.ts", "../../../../aws-cdk/lib/context-providers/ssm-parameters.ts", "../../../../aws-cdk/lib/context-providers/vpcs.ts", "../../../../aws-cdk/lib/api/util/rwlock.ts", "../../../../aws-cdk/lib/api/cxapp/cloud-assembly.ts", "../../../../aws-cdk/lib/api/cxapp/exec.ts"],
4
- "sourcesContent": ["/* eslint-disable import/no-restricted-paths */\n\n// APIs\nexport { formatSdkLoggerContent, SdkProvider } from '../../../../aws-cdk/lib/api/aws-auth';\nexport { Context, PROJECT_CONTEXT } from '../../../../aws-cdk/lib/api/context';\nexport { Deployments, type SuccessfulDeployStackResult } from '../../../../aws-cdk/lib/api/deployments';\nexport { Settings } from '../../../../aws-cdk/lib/api/settings';\nexport { tagsForStack, Tag } from '../../../../aws-cdk/lib/api/tags';\nexport { DEFAULT_TOOLKIT_STACK_NAME } from '../../../../aws-cdk/lib/api/toolkit-info';\nexport { ResourceMigrator } from '../../../../aws-cdk/lib/api/resource-import';\nexport { StackActivityProgress } from '../../../../aws-cdk/lib/api/stack-events';\nexport { CloudWatchLogEventMonitor, findCloudWatchLogGroups } from '../../../../aws-cdk/lib/api/logs';\nexport { type WorkGraph, WorkGraphBuilder, AssetBuildNode, AssetPublishNode, StackNode, Concurrency } from '../../../../aws-cdk/lib/api/work-graph';\n\n// Context Providers\nexport * as contextproviders from '../../../../aws-cdk/lib/context-providers';\n\n// utils\nexport { formatTime } from '../../../../aws-cdk/lib/util/string-manipulation';\nexport { formatErrorMessage } from '../../../../aws-cdk/lib/util/format-error';\nexport { obscureTemplate, serializeStructure } from '../../../../aws-cdk/lib/util/serialize';\nexport { validateSnsTopicArn } from '../../../../aws-cdk/lib/util/cloudformation';\nexport { splitBySize } from '../../../../aws-cdk/lib/util/objects';\n\n// @todo APIs not clean import\nexport { HotswapMode } from '../../../../aws-cdk/lib/api/hotswap/common';\nexport { HotswapPropertyOverrides, EcsHotswapProperties } from '../../../../aws-cdk/lib/api/hotswap/common';\nexport { RWLock, type ILock } from '../../../../aws-cdk/lib/api/util/rwlock';\n\n// @todo Not yet API probably should be\nexport { loadTree, some } from '../../../../aws-cdk/lib/tree';\n\n// @todo Cloud Assembly and Executable - this is a messy API right now\nexport { CloudAssembly, sanitizePatterns, type StackDetails, StackCollection, ExtendedStackSelection } from '../../../../aws-cdk/lib/api/cxapp/cloud-assembly';\nexport { prepareDefaultEnvironment, prepareContext, spaceAvailableForContext } from '../../../../aws-cdk/lib/api/cxapp/exec';\nexport { guessExecutable } from '../../../../aws-cdk/lib/api/cxapp/exec';\n\n// @todo Should not use! investigate how to replace\nexport { versionNumber } from '../../../../aws-cdk/lib/cli/version';\nexport { CliIoHost } from '../../../../aws-cdk/lib/toolkit/cli-io-host';\n", "import {\n AppSyncClient,\n FunctionConfiguration,\n GetSchemaCreationStatusCommand,\n type GetSchemaCreationStatusCommandInput,\n type GetSchemaCreationStatusCommandOutput,\n type ListFunctionsCommandInput,\n paginateListFunctions,\n StartSchemaCreationCommand,\n type StartSchemaCreationCommandInput,\n type StartSchemaCreationCommandOutput,\n UpdateApiKeyCommand,\n type UpdateApiKeyCommandInput,\n type UpdateApiKeyCommandOutput,\n UpdateFunctionCommand,\n type UpdateFunctionCommandInput,\n type UpdateFunctionCommandOutput,\n UpdateResolverCommand,\n type UpdateResolverCommandInput,\n type UpdateResolverCommandOutput,\n} from '@aws-sdk/client-appsync';\nimport {\n CloudControlClient,\n GetResourceCommand,\n GetResourceCommandInput,\n GetResourceCommandOutput,\n ListResourcesCommand,\n ListResourcesCommandInput,\n ListResourcesCommandOutput,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudFormationClient,\n ContinueUpdateRollbackCommand,\n ContinueUpdateRollbackCommandInput,\n ContinueUpdateRollbackCommandOutput,\n CreateChangeSetCommand,\n type CreateChangeSetCommandInput,\n type CreateChangeSetCommandOutput,\n CreateGeneratedTemplateCommand,\n type CreateGeneratedTemplateCommandInput,\n type CreateGeneratedTemplateCommandOutput,\n CreateStackCommand,\n type CreateStackCommandInput,\n type CreateStackCommandOutput,\n DeleteChangeSetCommand,\n type DeleteChangeSetCommandInput,\n type DeleteChangeSetCommandOutput,\n DeleteGeneratedTemplateCommand,\n type DeleteGeneratedTemplateCommandInput,\n type DeleteGeneratedTemplateCommandOutput,\n DeleteStackCommand,\n type DeleteStackCommandInput,\n type DeleteStackCommandOutput,\n DescribeChangeSetCommand,\n type DescribeChangeSetCommandInput,\n type DescribeChangeSetCommandOutput,\n DescribeGeneratedTemplateCommand,\n type DescribeGeneratedTemplateCommandInput,\n type DescribeGeneratedTemplateCommandOutput,\n DescribeResourceScanCommand,\n type DescribeResourceScanCommandInput,\n type DescribeResourceScanCommandOutput,\n DescribeStackEventsCommand,\n type DescribeStackEventsCommandInput,\n DescribeStackEventsCommandOutput,\n DescribeStackResourcesCommand,\n DescribeStackResourcesCommandInput,\n DescribeStackResourcesCommandOutput,\n DescribeStacksCommand,\n type DescribeStacksCommandInput,\n type DescribeStacksCommandOutput,\n ExecuteChangeSetCommand,\n type ExecuteChangeSetCommandInput,\n type ExecuteChangeSetCommandOutput,\n GetGeneratedTemplateCommand,\n type GetGeneratedTemplateCommandInput,\n type GetGeneratedTemplateCommandOutput,\n GetTemplateCommand,\n type GetTemplateCommandInput,\n type GetTemplateCommandOutput,\n GetTemplateSummaryCommand,\n type GetTemplateSummaryCommandInput,\n type GetTemplateSummaryCommandOutput,\n ListExportsCommand,\n type ListExportsCommandInput,\n type ListExportsCommandOutput,\n ListResourceScanRelatedResourcesCommand,\n type ListResourceScanRelatedResourcesCommandInput,\n type ListResourceScanRelatedResourcesCommandOutput,\n ListResourceScanResourcesCommand,\n type ListResourceScanResourcesCommandInput,\n type ListResourceScanResourcesCommandOutput,\n ListResourceScansCommand,\n type ListResourceScansCommandInput,\n type ListResourceScansCommandOutput,\n type ListStackResourcesCommandInput,\n ListStacksCommand,\n ListStacksCommandInput,\n ListStacksCommandOutput,\n paginateListStackResources,\n RollbackStackCommand,\n RollbackStackCommandInput,\n RollbackStackCommandOutput,\n StackResourceSummary,\n StartResourceScanCommand,\n type StartResourceScanCommandInput,\n type StartResourceScanCommandOutput,\n UpdateStackCommand,\n type UpdateStackCommandInput,\n type UpdateStackCommandOutput,\n UpdateTerminationProtectionCommand,\n type UpdateTerminationProtectionCommandInput,\n type UpdateTerminationProtectionCommandOutput,\n} from '@aws-sdk/client-cloudformation';\nimport {\n CloudWatchLogsClient,\n DescribeLogGroupsCommand,\n type DescribeLogGroupsCommandInput,\n type DescribeLogGroupsCommandOutput,\n FilterLogEventsCommand,\n FilterLogEventsCommandInput,\n FilterLogEventsCommandOutput,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CodeBuildClient,\n UpdateProjectCommand,\n type UpdateProjectCommandInput,\n type UpdateProjectCommandOutput,\n} from '@aws-sdk/client-codebuild';\nimport {\n DescribeAvailabilityZonesCommand,\n type DescribeAvailabilityZonesCommandInput,\n type DescribeAvailabilityZonesCommandOutput,\n DescribeImagesCommand,\n type DescribeImagesCommandInput,\n type DescribeImagesCommandOutput,\n DescribeInstancesCommand,\n type DescribeInstancesCommandInput,\n type DescribeInstancesCommandOutput,\n DescribeRouteTablesCommand,\n type DescribeRouteTablesCommandInput,\n type DescribeRouteTablesCommandOutput,\n DescribeSecurityGroupsCommand,\n type DescribeSecurityGroupsCommandInput,\n type DescribeSecurityGroupsCommandOutput,\n DescribeSubnetsCommand,\n type DescribeSubnetsCommandInput,\n type DescribeSubnetsCommandOutput,\n DescribeVpcEndpointServicesCommand,\n type DescribeVpcEndpointServicesCommandInput,\n type DescribeVpcEndpointServicesCommandOutput,\n DescribeVpcsCommand,\n type DescribeVpcsCommandInput,\n type DescribeVpcsCommandOutput,\n DescribeVpnGatewaysCommand,\n type DescribeVpnGatewaysCommandInput,\n type DescribeVpnGatewaysCommandOutput,\n EC2Client,\n} from '@aws-sdk/client-ec2';\nimport {\n BatchDeleteImageCommand,\n BatchDeleteImageCommandInput,\n BatchDeleteImageCommandOutput,\n CreateRepositoryCommand,\n type CreateRepositoryCommandInput,\n type CreateRepositoryCommandOutput,\n DescribeImagesCommand as ECRDescribeImagesCommand,\n type DescribeImagesCommandInput as ECRDescribeImagesCommandInput,\n type DescribeImagesCommandOutput as ECRDescribeImagesCommandOutput,\n DescribeRepositoriesCommand,\n type DescribeRepositoriesCommandInput,\n type DescribeRepositoriesCommandOutput,\n ECRClient,\n GetAuthorizationTokenCommand,\n type GetAuthorizationTokenCommandInput,\n type GetAuthorizationTokenCommandOutput,\n ListImagesCommand,\n ListImagesCommandInput,\n ListImagesCommandOutput,\n PutImageCommand,\n PutImageCommandInput,\n PutImageCommandOutput,\n PutImageScanningConfigurationCommand,\n type PutImageScanningConfigurationCommandInput,\n type PutImageScanningConfigurationCommandOutput,\n BatchGetImageCommandInput,\n BatchGetImageCommand,\n BatchGetImageCommandOutput,\n} from '@aws-sdk/client-ecr';\nimport {\n DescribeServicesCommandInput,\n ECSClient,\n ListClustersCommand,\n type ListClustersCommandInput,\n type ListClustersCommandOutput,\n RegisterTaskDefinitionCommand,\n RegisterTaskDefinitionCommandInput,\n type RegisterTaskDefinitionCommandOutput,\n UpdateServiceCommand,\n type UpdateServiceCommandInput,\n type UpdateServiceCommandOutput,\n waitUntilServicesStable,\n} from '@aws-sdk/client-ecs';\nimport {\n DescribeListenersCommand,\n type DescribeListenersCommandInput,\n type DescribeListenersCommandOutput,\n DescribeLoadBalancersCommand,\n type DescribeLoadBalancersCommandInput,\n type DescribeLoadBalancersCommandOutput,\n DescribeTagsCommand,\n type DescribeTagsCommandInput,\n type DescribeTagsCommandOutput,\n ElasticLoadBalancingV2Client,\n Listener,\n LoadBalancer,\n paginateDescribeListeners,\n paginateDescribeLoadBalancers,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n CreatePolicyCommand,\n type CreatePolicyCommandInput,\n type CreatePolicyCommandOutput,\n GetPolicyCommand,\n type GetPolicyCommandInput,\n type GetPolicyCommandOutput,\n GetRoleCommand,\n type GetRoleCommandInput,\n type GetRoleCommandOutput,\n IAMClient,\n} from '@aws-sdk/client-iam';\nimport {\n DescribeKeyCommand,\n type DescribeKeyCommandInput,\n type DescribeKeyCommandOutput,\n KMSClient,\n ListAliasesCommand,\n type ListAliasesCommandInput,\n type ListAliasesCommandOutput,\n} from '@aws-sdk/client-kms';\nimport {\n InvokeCommand,\n type InvokeCommandInput,\n type InvokeCommandOutput,\n LambdaClient,\n PublishVersionCommand,\n type PublishVersionCommandInput,\n type PublishVersionCommandOutput,\n UpdateAliasCommand,\n type UpdateAliasCommandInput,\n type UpdateAliasCommandOutput,\n UpdateFunctionCodeCommand,\n type UpdateFunctionCodeCommandInput,\n type UpdateFunctionCodeCommandOutput,\n UpdateFunctionConfigurationCommand,\n type UpdateFunctionConfigurationCommandInput,\n type UpdateFunctionConfigurationCommandOutput,\n waitUntilFunctionUpdatedV2,\n} from '@aws-sdk/client-lambda';\nimport {\n GetHostedZoneCommand,\n type GetHostedZoneCommandInput,\n type GetHostedZoneCommandOutput,\n ListHostedZonesByNameCommand,\n type ListHostedZonesByNameCommandInput,\n type ListHostedZonesByNameCommandOutput,\n ListHostedZonesCommand,\n type ListHostedZonesCommandInput,\n type ListHostedZonesCommandOutput,\n Route53Client,\n} from '@aws-sdk/client-route-53';\nimport {\n type CompleteMultipartUploadCommandOutput,\n DeleteObjectsCommand,\n DeleteObjectsCommandInput,\n DeleteObjectsCommandOutput,\n DeleteObjectTaggingCommand,\n DeleteObjectTaggingCommandInput,\n DeleteObjectTaggingCommandOutput,\n GetBucketEncryptionCommand,\n type GetBucketEncryptionCommandInput,\n type GetBucketEncryptionCommandOutput,\n GetBucketLocationCommand,\n type GetBucketLocationCommandInput,\n type GetBucketLocationCommandOutput,\n GetObjectCommand,\n type GetObjectCommandInput,\n type GetObjectCommandOutput,\n GetObjectTaggingCommand,\n GetObjectTaggingCommandInput,\n GetObjectTaggingCommandOutput,\n ListObjectsV2Command,\n type ListObjectsV2CommandInput,\n type ListObjectsV2CommandOutput,\n type PutObjectCommandInput,\n PutObjectTaggingCommand,\n PutObjectTaggingCommandInput,\n PutObjectTaggingCommandOutput,\n S3Client,\n} from '@aws-sdk/client-s3';\nimport {\n GetSecretValueCommand,\n type GetSecretValueCommandInput,\n type GetSecretValueCommandOutput,\n SecretsManagerClient,\n} from '@aws-sdk/client-secrets-manager';\nimport {\n SFNClient,\n UpdateStateMachineCommand,\n UpdateStateMachineCommandInput,\n UpdateStateMachineCommandOutput,\n} from '@aws-sdk/client-sfn';\nimport {\n GetParameterCommand,\n type GetParameterCommandInput,\n type GetParameterCommandOutput,\n SSMClient,\n} from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { ConfiguredRetryStrategy } from '@smithy/util-retry';\nimport { WaiterResult } from '@smithy/util-waiter';\nimport { AccountAccessKeyCache } from './account-cache';\nimport { cachedAsync } from './cached';\nimport { Account } from './sdk-provider';\nimport { traceMemberMethods } from './tracing';\nimport { defaultCliUserAgent } from './user-agent';\nimport { debug } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\n\nexport interface S3ClientOptions {\n /**\n * If APIs are used that require MD5 checksums.\n *\n * Some S3 APIs in SDKv2 have a bug that always requires them to use a MD5 checksum.\n * These APIs are not going to be supported in a FIPS environment.\n */\n needsMd5Checksums?: boolean;\n}\n\n/**\n * Additional SDK configuration options\n */\nexport interface SdkOptions {\n /**\n * Additional descriptive strings that indicate where the \"AssumeRole\" credentials are coming from\n *\n * Will be printed in an error message to help users diagnose auth problems.\n */\n readonly assumeRoleCredentialsSourceDescription?: string;\n}\n\n// TODO: still some cleanup here. Make the pagination functions do all the work here instead of in individual packages.\n// Also add async/await. Does that actually matter in this context? Find out and update accordingly.\n\n// Also add notes to the PR about why you imported everything individually and used 'type' so reviewers don't have to ask.\n\nexport interface ConfigurationOptions {\n region: string;\n credentials: AwsCredentialIdentityProvider;\n requestHandler: NodeHttpHandlerOptions;\n retryStrategy: ConfiguredRetryStrategy;\n customUserAgent: string;\n logger?: Logger;\n s3DisableBodySigning?: boolean;\n computeChecksums?: boolean;\n}\n\nexport interface IAppSyncClient {\n getSchemaCreationStatus(input: GetSchemaCreationStatusCommandInput): Promise<GetSchemaCreationStatusCommandOutput>;\n startSchemaCreation(input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput>;\n updateApiKey(input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput>;\n updateFunction(input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput>;\n updateResolver(input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput>;\n // Pagination functions\n listFunctions(input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]>;\n}\n\nexport interface ICloudControlClient{\n listResources(input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput>;\n getResource(input: GetResourceCommandInput): Promise<GetResourceCommandOutput>;\n}\n\nexport interface ICloudFormationClient {\n continueUpdateRollback(input: ContinueUpdateRollbackCommandInput): Promise<ContinueUpdateRollbackCommandOutput>;\n createChangeSet(input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput>;\n createGeneratedTemplate(input: CreateGeneratedTemplateCommandInput): Promise<CreateGeneratedTemplateCommandOutput>;\n createStack(input: CreateStackCommandInput): Promise<CreateStackCommandOutput>;\n deleteChangeSet(input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput>;\n deleteGeneratedTemplate(input: DeleteGeneratedTemplateCommandInput): Promise<DeleteGeneratedTemplateCommandOutput>;\n deleteStack(input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput>;\n describeChangeSet(input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput>;\n describeGeneratedTemplate(\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput>;\n describeResourceScan(input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput>;\n describeStacks(input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput>;\n describeStackResources(input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput>;\n executeChangeSet(input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput>;\n getGeneratedTemplate(input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput>;\n getTemplate(input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput>;\n getTemplateSummary(input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput>;\n listExports(input: ListExportsCommandInput): Promise<ListExportsCommandOutput>;\n listResourceScanRelatedResources(\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput>;\n listResourceScanResources(\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput>;\n listResourceScans(input?: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput>;\n listStacks(input: ListStacksCommandInput): Promise<ListStacksCommandOutput>;\n rollbackStack(input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput>;\n startResourceScan(input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput>;\n updateStack(input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput>;\n updateTerminationProtection(\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput>;\n // Pagination functions\n describeStackEvents(input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput>;\n listStackResources(input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]>;\n}\n\nexport interface ICloudWatchLogsClient {\n describeLogGroups(input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput>;\n filterLogEvents(input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput>;\n}\n\nexport interface ICodeBuildClient {\n updateProject(input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput>;\n}\nexport interface IEC2Client {\n describeAvailabilityZones(\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput>;\n describeImages(input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput>;\n describeInstances(input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput>;\n describeRouteTables(input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput>;\n describeSecurityGroups(input: DescribeSecurityGroupsCommandInput): Promise<DescribeSecurityGroupsCommandOutput>;\n describeSubnets(input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput>;\n describeVpcEndpointServices(\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput>;\n describeVpcs(input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput>;\n describeVpnGateways(input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput>;\n}\n\nexport interface IECRClient {\n batchDeleteImage(input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput>;\n batchGetImage(input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput>;\n createRepository(input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput>;\n describeImages(input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput>;\n describeRepositories(input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput>;\n getAuthorizationToken(input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput>;\n listImages(input: ListImagesCommandInput): Promise<ListImagesCommandOutput>;\n putImage(input: PutImageCommandInput): Promise<PutImageCommandOutput>;\n putImageScanningConfiguration(\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput>;\n}\n\nexport interface IECSClient {\n listClusters(input: ListClustersCommandInput): Promise<ListClustersCommandOutput>;\n registerTaskDefinition(input: RegisterTaskDefinitionCommandInput): Promise<RegisterTaskDefinitionCommandOutput>;\n updateService(input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput>;\n // Waiters\n waitUntilServicesStable(input: DescribeServicesCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IElasticLoadBalancingV2Client {\n describeListeners(input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput>;\n describeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput>;\n describeTags(input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput>;\n // Pagination\n paginateDescribeListeners(input: DescribeListenersCommandInput): Promise<Listener[]>;\n paginateDescribeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]>;\n}\n\nexport interface IIAMClient {\n createPolicy(input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput>;\n getPolicy(input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput>;\n getRole(input: GetRoleCommandInput): Promise<GetRoleCommandOutput>;\n}\n\nexport interface IKMSClient {\n describeKey(input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput>;\n listAliases(input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput>;\n}\n\nexport interface ILambdaClient {\n invokeCommand(input: InvokeCommandInput): Promise<InvokeCommandOutput>;\n publishVersion(input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput>;\n updateAlias(input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput>;\n updateFunctionCode(input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput>;\n updateFunctionConfiguration(\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput>;\n // Waiters\n waitUntilFunctionUpdated(delaySeconds: number, input: UpdateFunctionConfigurationCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IRoute53Client {\n getHostedZone(input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput>;\n listHostedZones(input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput>;\n listHostedZonesByName(input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput>;\n}\n\nexport interface IS3Client {\n deleteObjects(input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput>;\n deleteObjectTagging(input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput>;\n getBucketEncryption(input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput>;\n getBucketLocation(input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput>;\n getObject(input: GetObjectCommandInput): Promise<GetObjectCommandOutput>;\n getObjectTagging(input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput>;\n listObjectsV2(input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput>;\n putObjectTagging(input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput>;\n upload(input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput>;\n}\n\nexport interface ISecretsManagerClient {\n getSecretValue(input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput>;\n}\n\nexport interface ISSMClient {\n getParameter(input: GetParameterCommandInput): Promise<GetParameterCommandOutput>;\n}\n\nexport interface IStepFunctionsClient {\n updateStateMachine(input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput>;\n}\n\n/**\n * Base functionality of SDK without credential fetching\n */\n@traceMemberMethods\nexport class SDK {\n private static readonly accountCache = new AccountAccessKeyCache();\n\n public readonly currentRegion: string;\n\n public readonly config: ConfigurationOptions;\n\n protected readonly logger?: Logger;\n\n /**\n * STS is used to check credential validity, don't do too many retries.\n */\n private readonly stsRetryStrategy = new ConfiguredRetryStrategy(3, (attempt) => 100 * (2 ** attempt));\n\n /**\n * Whether we have proof that the credentials have not expired\n *\n * We need to do some manual plumbing around this because the JS SDKv2 treats `ExpiredToken`\n * as retriable and we have hefty retries on CFN calls making the CLI hang for a good 15 minutes\n * if the credentials have expired.\n */\n private _credentialsValidated = false;\n\n constructor(\n private readonly credProvider: AwsCredentialIdentityProvider,\n region: string,\n requestHandler: NodeHttpHandlerOptions,\n logger?: Logger,\n ) {\n this.config = {\n region,\n credentials: credProvider,\n requestHandler,\n retryStrategy: new ConfiguredRetryStrategy(7, (attempt) => 300 * (2 ** attempt)),\n customUserAgent: defaultCliUserAgent(),\n logger,\n };\n this.logger = logger;\n this.currentRegion = region;\n }\n\n public appendCustomUserAgent(userAgentData?: string): void {\n if (!userAgentData) {\n return;\n }\n\n const currentCustomUserAgent = this.config.customUserAgent;\n this.config.customUserAgent = currentCustomUserAgent ? `${currentCustomUserAgent} ${userAgentData}` : userAgentData;\n }\n\n public removeCustomUserAgent(userAgentData: string): void {\n this.config.customUserAgent = this.config.customUserAgent?.replace(userAgentData, '');\n }\n\n public appsync(): IAppSyncClient {\n const client = new AppSyncClient(this.config);\n return {\n getSchemaCreationStatus: (\n input: GetSchemaCreationStatusCommandInput,\n ): Promise<GetSchemaCreationStatusCommandOutput> => client.send(new GetSchemaCreationStatusCommand(input)),\n startSchemaCreation: (input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput> =>\n client.send(new StartSchemaCreationCommand(input)),\n updateApiKey: (input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput> =>\n client.send(new UpdateApiKeyCommand(input)),\n updateFunction: (input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput> =>\n client.send(new UpdateFunctionCommand(input)),\n updateResolver: (input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput> =>\n client.send(new UpdateResolverCommand(input)),\n\n // Pagination Functions\n listFunctions: async (input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]> => {\n const functions = Array<FunctionConfiguration>();\n const paginator = paginateListFunctions({ client }, input);\n for await (const page of paginator) {\n functions.push(...(page.functions || []));\n }\n return functions;\n },\n };\n }\n\n public cloudControl(): ICloudControlClient {\n const client = new CloudControlClient(this.config);\n return {\n listResources: (input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput> =>\n client.send(new ListResourcesCommand(input)),\n getResource: (input: GetResourceCommandInput): Promise<GetResourceCommandOutput> =>\n client.send(new GetResourceCommand(input)),\n };\n }\n\n public cloudFormation(): ICloudFormationClient {\n const client = new CloudFormationClient({\n ...this.config,\n retryStrategy: new ConfiguredRetryStrategy(11, (attempt: number) => 1000 * (2 ** attempt)),\n });\n return {\n continueUpdateRollback: async (\n input: ContinueUpdateRollbackCommandInput,\n ): Promise<ContinueUpdateRollbackCommandOutput> => client.send(new ContinueUpdateRollbackCommand(input)),\n createChangeSet: (input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput> =>\n client.send(new CreateChangeSetCommand(input)),\n createGeneratedTemplate: (\n input: CreateGeneratedTemplateCommandInput,\n ): Promise<CreateGeneratedTemplateCommandOutput> => client.send(new CreateGeneratedTemplateCommand(input)),\n createStack: (input: CreateStackCommandInput): Promise<CreateStackCommandOutput> =>\n client.send(new CreateStackCommand(input)),\n deleteChangeSet: (input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput> =>\n client.send(new DeleteChangeSetCommand(input)),\n deleteGeneratedTemplate: (\n input: DeleteGeneratedTemplateCommandInput,\n ): Promise<DeleteGeneratedTemplateCommandOutput> => client.send(new DeleteGeneratedTemplateCommand(input)),\n deleteStack: (input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput> =>\n client.send(new DeleteStackCommand(input)),\n describeChangeSet: (input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput> =>\n client.send(new DescribeChangeSetCommand(input)),\n describeGeneratedTemplate: (\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput> => client.send(new DescribeGeneratedTemplateCommand(input)),\n describeResourceScan: (input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput> =>\n client.send(new DescribeResourceScanCommand(input)),\n describeStacks: (input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput> =>\n client.send(new DescribeStacksCommand(input)),\n describeStackResources: (input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput> =>\n client.send(new DescribeStackResourcesCommand(input)),\n executeChangeSet: (input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput> =>\n client.send(new ExecuteChangeSetCommand(input)),\n getGeneratedTemplate: (input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput> =>\n client.send(new GetGeneratedTemplateCommand(input)),\n getTemplate: (input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput> =>\n client.send(new GetTemplateCommand(input)),\n getTemplateSummary: (input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput> =>\n client.send(new GetTemplateSummaryCommand(input)),\n listExports: (input: ListExportsCommandInput): Promise<ListExportsCommandOutput> =>\n client.send(new ListExportsCommand(input)),\n listResourceScanRelatedResources: (\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput> =>\n client.send(new ListResourceScanRelatedResourcesCommand(input)),\n listResourceScanResources: (\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput> => client.send(new ListResourceScanResourcesCommand(input)),\n listResourceScans: (input: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput> =>\n client.send(new ListResourceScansCommand(input)),\n listStacks: (input: ListStacksCommandInput): Promise<ListStacksCommandOutput> =>\n client.send(new ListStacksCommand(input)),\n rollbackStack: (input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput> =>\n client.send(new RollbackStackCommand(input)),\n startResourceScan: (input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput> =>\n client.send(new StartResourceScanCommand(input)),\n updateStack: (input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput> =>\n client.send(new UpdateStackCommand(input)),\n updateTerminationProtection: (\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput> =>\n client.send(new UpdateTerminationProtectionCommand(input)),\n describeStackEvents: (input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput> => {\n return client.send(new DescribeStackEventsCommand(input));\n },\n listStackResources: async (input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]> => {\n const stackResources = Array<StackResourceSummary>();\n const paginator = paginateListStackResources({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackResourceSummaries || []));\n }\n return stackResources;\n },\n };\n }\n\n public cloudWatchLogs(): ICloudWatchLogsClient {\n const client = new CloudWatchLogsClient(this.config);\n return {\n describeLogGroups: (input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput> =>\n client.send(new DescribeLogGroupsCommand(input)),\n filterLogEvents: (input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput> =>\n client.send(new FilterLogEventsCommand(input)),\n };\n }\n\n public codeBuild(): ICodeBuildClient {\n const client = new CodeBuildClient(this.config);\n return {\n updateProject: (input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput> =>\n client.send(new UpdateProjectCommand(input)),\n };\n }\n\n public ec2(): IEC2Client {\n const client = new EC2Client(this.config);\n return {\n describeAvailabilityZones: (\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput> => client.send(new DescribeAvailabilityZonesCommand(input)),\n describeImages: (input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput> =>\n client.send(new DescribeImagesCommand(input)),\n describeInstances: (input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput> =>\n client.send(new DescribeInstancesCommand(input)),\n describeRouteTables: (input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput> =>\n client.send(new DescribeRouteTablesCommand(input)),\n describeSecurityGroups: (\n input: DescribeSecurityGroupsCommandInput,\n ): Promise<DescribeSecurityGroupsCommandOutput> => client.send(new DescribeSecurityGroupsCommand(input)),\n describeSubnets: (input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput> =>\n client.send(new DescribeSubnetsCommand(input)),\n describeVpcEndpointServices: (\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput> =>\n client.send(new DescribeVpcEndpointServicesCommand(input)),\n describeVpcs: (input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput> =>\n client.send(new DescribeVpcsCommand(input)),\n describeVpnGateways: (input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput> =>\n client.send(new DescribeVpnGatewaysCommand(input)),\n };\n }\n\n public ecr(): IECRClient {\n const client = new ECRClient(this.config);\n return {\n batchDeleteImage: (input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput> =>\n client.send(new BatchDeleteImageCommand(input)),\n batchGetImage: (input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput> =>\n client.send(new BatchGetImageCommand(input)),\n createRepository: (input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput> =>\n client.send(new CreateRepositoryCommand(input)),\n describeImages: (input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput> =>\n client.send(new ECRDescribeImagesCommand(input)),\n describeRepositories: (input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput> =>\n client.send(new DescribeRepositoriesCommand(input)),\n getAuthorizationToken: (input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput> =>\n client.send(new GetAuthorizationTokenCommand(input)),\n listImages: (input: ListImagesCommandInput): Promise<ListImagesCommandOutput> =>\n client.send(new ListImagesCommand(input)),\n putImage: (input: PutImageCommandInput): Promise<PutImageCommandOutput> =>\n client.send(new PutImageCommand(input)),\n putImageScanningConfiguration: (\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput> =>\n client.send(new PutImageScanningConfigurationCommand(input)),\n };\n }\n\n public ecs(): IECSClient {\n const client = new ECSClient(this.config);\n return {\n listClusters: (input: ListClustersCommandInput): Promise<ListClustersCommandOutput> =>\n client.send(new ListClustersCommand(input)),\n registerTaskDefinition: (\n input: RegisterTaskDefinitionCommandInput,\n ): Promise<RegisterTaskDefinitionCommandOutput> => client.send(new RegisterTaskDefinitionCommand(input)),\n updateService: (input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput> =>\n client.send(new UpdateServiceCommand(input)),\n // Waiters\n waitUntilServicesStable: (input: DescribeServicesCommandInput): Promise<WaiterResult> => {\n return waitUntilServicesStable(\n {\n client,\n maxWaitTime: 600,\n minDelay: 6,\n maxDelay: 6,\n },\n input,\n );\n },\n };\n }\n\n public elbv2(): IElasticLoadBalancingV2Client {\n const client = new ElasticLoadBalancingV2Client(this.config);\n return {\n describeListeners: (input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput> =>\n client.send(new DescribeListenersCommand(input)),\n describeLoadBalancers: (input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput> =>\n client.send(new DescribeLoadBalancersCommand(input)),\n describeTags: (input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput> =>\n client.send(new DescribeTagsCommand(input)),\n // Pagination Functions\n paginateDescribeListeners: async (input: DescribeListenersCommandInput): Promise<Listener[]> => {\n const listeners = Array<Listener>();\n const paginator = paginateDescribeListeners({ client }, input);\n for await (const page of paginator) {\n listeners.push(...(page?.Listeners || []));\n }\n return listeners;\n },\n paginateDescribeLoadBalancers: async (input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]> => {\n const loadBalancers = Array<LoadBalancer>();\n const paginator = paginateDescribeLoadBalancers({ client }, input);\n for await (const page of paginator) {\n loadBalancers.push(...(page?.LoadBalancers || []));\n }\n return loadBalancers;\n },\n };\n }\n\n public iam(): IIAMClient {\n const client = new IAMClient(this.config);\n return {\n createPolicy: (input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput> =>\n client.send(new CreatePolicyCommand(input)),\n getPolicy: (input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput> =>\n client.send(new GetPolicyCommand(input)),\n getRole: (input: GetRoleCommandInput): Promise<GetRoleCommandOutput> => client.send(new GetRoleCommand(input)),\n };\n }\n\n public kms(): IKMSClient {\n const client = new KMSClient(this.config);\n return {\n describeKey: (input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput> =>\n client.send(new DescribeKeyCommand(input)),\n listAliases: (input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput> =>\n client.send(new ListAliasesCommand(input)),\n };\n }\n\n public lambda(): ILambdaClient {\n const client = new LambdaClient(this.config);\n return {\n invokeCommand: (input: InvokeCommandInput): Promise<InvokeCommandOutput> => client.send(new InvokeCommand(input)),\n publishVersion: (input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput> =>\n client.send(new PublishVersionCommand(input)),\n updateAlias: (input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput> =>\n client.send(new UpdateAliasCommand(input)),\n updateFunctionCode: (input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput> =>\n client.send(new UpdateFunctionCodeCommand(input)),\n updateFunctionConfiguration: (\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput> =>\n client.send(new UpdateFunctionConfigurationCommand(input)),\n // Waiters\n waitUntilFunctionUpdated: (\n delaySeconds: number,\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<WaiterResult> => {\n return waitUntilFunctionUpdatedV2(\n {\n client,\n maxDelay: delaySeconds,\n minDelay: delaySeconds,\n maxWaitTime: delaySeconds * 60,\n },\n input,\n );\n },\n };\n }\n\n public route53(): IRoute53Client {\n const client = new Route53Client(this.config);\n return {\n getHostedZone: (input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput> =>\n client.send(new GetHostedZoneCommand(input)),\n listHostedZones: (input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput> =>\n client.send(new ListHostedZonesCommand(input)),\n listHostedZonesByName: (input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput> =>\n client.send(new ListHostedZonesByNameCommand(input)),\n };\n }\n\n public s3(): IS3Client {\n const client = new S3Client(this.config);\n return {\n deleteObjects: (input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput> =>\n client.send(new DeleteObjectsCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n deleteObjectTagging: (input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput> =>\n client.send(new DeleteObjectTaggingCommand(input)),\n getBucketEncryption: (input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput> =>\n client.send(new GetBucketEncryptionCommand(input)),\n getBucketLocation: (input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput> =>\n client.send(new GetBucketLocationCommand(input)),\n getObject: (input: GetObjectCommandInput): Promise<GetObjectCommandOutput> =>\n client.send(new GetObjectCommand(input)),\n getObjectTagging: (input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput> =>\n client.send(new GetObjectTaggingCommand(input)),\n listObjectsV2: (input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput> =>\n client.send(new ListObjectsV2Command(input)),\n putObjectTagging: (input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput> =>\n client.send(new PutObjectTaggingCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n upload: (input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput> => {\n try {\n const upload = new Upload({\n client,\n params: { ...input, ChecksumAlgorithm: 'SHA256' },\n });\n\n return upload.done();\n } catch (e: any) {\n throw new AuthenticationError(`Upload failed: ${formatErrorMessage(e)}`);\n }\n },\n };\n }\n\n public secretsManager(): ISecretsManagerClient {\n const client = new SecretsManagerClient(this.config);\n return {\n getSecretValue: (input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput> =>\n client.send(new GetSecretValueCommand(input)),\n };\n }\n\n public ssm(): ISSMClient {\n const client = new SSMClient(this.config);\n return {\n getParameter: (input: GetParameterCommandInput): Promise<GetParameterCommandOutput> =>\n client.send(new GetParameterCommand(input)),\n };\n }\n\n public stepFunctions(): IStepFunctionsClient {\n const client = new SFNClient(this.config);\n return {\n updateStateMachine: (input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput> =>\n client.send(new UpdateStateMachineCommand(input)),\n };\n }\n\n /**\n * The AWS SDK v3 requires a client config and a command in order to get an endpoint for\n * any given service.\n */\n public async getUrlSuffix(region: string): Promise<string> {\n const cfn = new CloudFormationClient({ region });\n const endpoint = await getEndpointFromInstructions({}, DescribeStackResourcesCommand, { ...cfn.config });\n return endpoint.url.hostname.split(`${region}.`).pop()!;\n }\n\n public async currentAccount(): Promise<Account> {\n return cachedAsync(this, CURRENT_ACCOUNT_KEY, async () => {\n const creds = await this.credProvider();\n return SDK.accountCache.fetch(creds.accessKeyId, async () => {\n // if we don't have one, resolve from STS and store in cache.\n debug('Looking up default account ID from STS');\n const client = new STSClient({\n ...this.config,\n retryStrategy: this.stsRetryStrategy,\n });\n const command = new GetCallerIdentityCommand({});\n const result = await client.send(command);\n const accountId = result.Account;\n const partition = result.Arn!.split(':')[1];\n if (!accountId) {\n throw new AuthenticationError(\"STS didn't return an account ID\");\n }\n debug('Default account ID:', accountId);\n\n // Save another STS call later if this one already succeeded\n this._credentialsValidated = true;\n return { accountId, partition };\n });\n });\n }\n\n /**\n * Make sure the the current credentials are not expired\n */\n public async validateCredentials() {\n if (this._credentialsValidated) {\n return;\n }\n\n const client = new STSClient({ ...this.config, retryStrategy: this.stsRetryStrategy });\n await client.send(new GetCallerIdentityCommand({}));\n this._credentialsValidated = true;\n }\n}\n\nconst CURRENT_ACCOUNT_KEY = Symbol('current_account_key');\n", "import * as path from 'path';\nimport * as fs from 'fs-extra';\nimport { Account } from './sdk-provider';\nimport { debug } from '../../logging';\nimport { cdkCacheDir } from '../../util/directories';\n\n/**\n * Disk cache which maps access key IDs to account IDs.\n * Usage:\n * cache.get(accessKey) => accountId | undefined\n * cache.put(accessKey, accountId)\n */\nexport class AccountAccessKeyCache {\n /**\n * Max number of entries in the cache, after which the cache will be reset.\n */\n public static readonly MAX_ENTRIES = 1000;\n\n private readonly cacheFile: string;\n\n /**\n * @param filePath Path to the cache file\n */\n constructor(filePath?: string) {\n this.cacheFile = filePath || path.join(cdkCacheDir(), 'accounts_partitions.json');\n }\n\n /**\n * Tries to fetch the account ID from cache. If it's not in the cache, invokes\n * the resolver function which should retrieve the account ID and return it.\n * Then, it will be stored into disk cache returned.\n *\n * Example:\n *\n * const accountId = cache.fetch(accessKey, async () => {\n * return await fetchAccountIdFromSomewhere(accessKey);\n * });\n */\n public async fetch<A extends Account>(accessKeyId: string, resolver: () => Promise<A>) {\n // try to get account ID based on this access key ID from disk.\n const cached = await this.get(accessKeyId);\n if (cached) {\n debug(`Retrieved account ID ${cached.accountId} from disk cache`);\n return cached;\n }\n\n // if it's not in the cache, resolve and put in cache.\n const account = await resolver();\n if (account) {\n await this.put(accessKeyId, account);\n }\n\n return account;\n }\n\n /** Get the account ID from an access key or undefined if not in cache */\n public async get(accessKeyId: string): Promise<Account | undefined> {\n const map = await this.loadMap();\n return map[accessKeyId];\n }\n\n /** Put a mapping between access key and account ID */\n public async put(accessKeyId: string, account: Account) {\n let map = await this.loadMap();\n\n // nuke cache if it's too big.\n if (Object.keys(map).length >= AccountAccessKeyCache.MAX_ENTRIES) {\n map = {};\n }\n\n map[accessKeyId] = account;\n await this.saveMap(map);\n }\n\n private async loadMap(): Promise<{ [accessKeyId: string]: Account }> {\n try {\n return await fs.readJson(this.cacheFile);\n } catch (e: any) {\n // File doesn't exist or is not readable. This is a cache,\n // pretend we successfully loaded an empty map.\n if (e.code === 'ENOENT' || e.code === 'EACCES') {\n return {};\n }\n // File is not JSON, could be corrupted because of concurrent writes.\n // Again, an empty cache is fine.\n if (e instanceof SyntaxError) {\n return {};\n }\n throw e;\n }\n }\n\n private async saveMap(map: { [accessKeyId: string]: Account }) {\n try {\n await fs.ensureFile(this.cacheFile);\n await fs.writeJson(this.cacheFile, map, { spaces: 2 });\n } catch (e: any) {\n // File doesn't exist or file/dir isn't writable. This is a cache,\n // if we can't write it then too bad.\n if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'EROFS') {\n return;\n }\n throw e;\n }\n }\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport { IoMessageLevel, IoMessage, CliIoHost, IoMessageSpecificCode, IoMessageCode, IoMessageCodeCategory, IoCodeLevel } from './toolkit/cli-io-host';\n\n/**\n * Internal helper that processes log inputs into a consistent format.\n * Handles string interpolation, format strings, and object parameter styles.\n * Applies optional styling and sends the message to the IoHost.\n */\nfunction formatMessageAndLog(\n level: IoMessageLevel,\n input: LogInput<IoCodeLevel>,\n style?: (str: string) => string,\n ...args: unknown[]\n): void {\n // Extract message and code from input, using new default code format\n const { message, code = getDefaultCode(level) } = typeof input === 'object' ? input : { message: input };\n\n // Format message if args are provided\n const formattedMessage = args.length > 0\n ? util.format(message, ...args)\n : message;\n\n // Apply style if provided\n const finalMessage = style ? style(formattedMessage) : formattedMessage;\n\n const ioHost = CliIoHost.instance();\n const ioMessage: IoMessage<undefined> = {\n time: new Date(),\n action: ioHost.currentAction,\n level,\n message: finalMessage,\n code,\n };\n\n void ioHost.notify(ioMessage);\n}\n\nfunction getDefaultCode(level: IoMessageLevel, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessageCode {\n const levelIndicator = level === 'error' ? 'E' :\n level === 'warn' ? 'W' :\n 'I';\n return `CDK_${category}_${levelIndicator}0000`;\n}\n\n// Type for the object parameter style\ninterface LogParams<L extends IoCodeLevel> {\n /**\n * @see {@link IoMessage.code}\n */\n readonly code?: IoMessageSpecificCode<L>;\n /**\n * @see {@link IoMessage.message}\n */\n readonly message: string;\n}\n\n// Type for the exported log function arguments\ntype LogInput<L extends IoCodeLevel> = string | LogParams<L>;\n\n// Exported logging functions. If any additional logging functionality is required, it should be added as\n// a new logging function here.\n\n/**\n * Logs an error level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * error(`operation failed: ${e}`) // infers default error code `CDK_TOOLKIT_E000`\n * error('operation failed: %s', e) // infers default error code `CDK_TOOLKIT_E000`\n * error({ message: 'operation failed', code: 'CDK_SDK_E001' }) // specifies error code `CDK_SDK_E001`\n * error({ message: 'operation failed: %s', code: 'CDK_SDK_E001' }, e) // specifies error code `CDK_SDK_E001`\n * ```\n */\nexport const error = (input: LogInput<'E'>, ...args: unknown[]) => {\n return formatMessageAndLog('error', input, undefined, ...args);\n};\n\n/**\n * Logs an warning level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * warning(`deprected feature: ${message}`) // infers default warning code `CDK_TOOLKIT_W000`\n * warning('deprected feature: %s', message) // infers default warning code `CDK_TOOLKIT_W000`\n * warning({ message: 'deprected feature', code: 'CDK_SDK_W001' }) // specifies warning code `CDK_SDK_W001`\n * warning({ message: 'deprected feature: %s', code: 'CDK_SDK_W001' }, message) // specifies warning code `CDK_SDK_W001`\n * ```\n */\nexport const warning = (input: LogInput<'W'>, ...args: unknown[]) => {\n return formatMessageAndLog('warn', input, undefined, ...args);\n};\n\n/**\n * Logs an info level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * info(`processing: ${message}`) // infers default info code `CDK_TOOLKIT_I000`\n * info('processing: %s', message) // infers default info code `CDK_TOOLKIT_I000`\n * info({ message: 'processing', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * info({ message: 'processing: %s', code: 'CDK_TOOLKIT_I001' }, message) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const info = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, undefined, ...args);\n};\n\n/**\n * Logs an result. In the CLI, this always goes to stdout.\n *\n * Can be used in multiple ways:\n * ```ts\n * result(`${JSON.stringify(stats)}`) // infers default info code `CDK_TOOLKIT_I000`\n * result('{\"count\": %d}', count) // infers default info code `CDK_TOOLKIT_I000`\n * result({ message: 'stats: %j', code: 'CDK_DATA_I001' }) // specifies info code `CDK_DATA_I001`\n * result({ message: 'stats: %j', code: 'CDK_DATA_I001' }, stats) // specifies info code `CDK_DATA_I001`\n * ```\n */\nexport const result = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('result', input, undefined, ...args);\n};\n\n/**\n * Logs a debug level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * debug(`state: ${JSON.stringify(state)}`) // infers default info code `CDK_TOOLKIT_I000`\n * debug('cache hit ratio: %d%%', ratio) // infers default info code `CDK_TOOLKIT_I000`\n * debug({ message: 'state update', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * debug({ message: 'ratio: %d%%', code: 'CDK_TOOLKIT_I001' }, ratio) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const debug = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('debug', input, undefined, ...args);\n};\n\n/**\n * Logs a trace level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * trace(`entered ${name} with ${args}`) // infers default info code `CDK_TOOLKIT_I000`\n * trace('method: %s, args: %j', name, args) // infers default info code `CDK_TOOLKIT_I000`\n * trace({ message: 'entered', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * trace({ message: 'method: %s', code: 'CDK_TOOLKIT_I001' }, name) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const trace = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('trace', input, undefined, ...args);\n};\n\n/**\n * Logs an info level success message in green text.\n *\n * Can be used in multiple ways:\n * ```ts\n * success(`deployment completed: ${name}`) // infers default info code `CDK_TOOLKIT_I000`\n * success('processed %d items', count) // infers default info code `CDK_TOOLKIT_I000`\n * success({ message: 'completed', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * success({ message: 'items: %d', code: 'CDK_TOOLKIT_I001' }, count) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const success = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, chalk.green, ...args);\n};\n\n/**\n * Logs an info level message in bold text.\n *\n * Can be used in multiple ways:\n * ```ts\n * highlight(`important: ${msg}`) // infers default info code `CDK_TOOLKIT_I000`\n * highlight('attention required: %s', reason) // infers default info code `CDK_TOOLKIT_I000`\n * highlight({ message: 'notice', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * highlight({ message: 'notice: %s', code: 'CDK_TOOLKIT_I001' }, msg) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const highlight = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, chalk.bold, ...args);\n};\n", "import * as util from 'node:util';\nimport * as chalk from 'chalk';\nimport * as promptly from 'promptly';\nimport { ToolkitError } from './error';\n\nexport type IoMessageCodeCategory = 'TOOLKIT' | 'SDK' | 'ASSETS';\nexport type IoCodeLevel = 'E' | 'W' | 'I';\nexport type IoMessageSpecificCode<L extends IoCodeLevel> = `CDK_${IoMessageCodeCategory}_${L}${number}${number}${number}${number}`;\nexport type IoMessageCode = IoMessageSpecificCode<IoCodeLevel>;\n\n/**\n * Basic message structure for toolkit notifications.\n * Messages are emitted by the toolkit and handled by the IoHost.\n */\nexport interface IoMessage<T> {\n /**\n * The time the message was emitted.\n */\n readonly time: Date;\n\n /**\n * The log level of the message.\n */\n readonly level: IoMessageLevel;\n\n /**\n * The action that triggered the message.\n */\n readonly action: ToolkitAction;\n\n /**\n * A short message code uniquely identifying a message type using the format CDK_[CATEGORY]_[E/W/I][000-999].\n *\n * The level indicator follows these rules:\n * - 'E' for error level messages\n * - 'W' for warning level messages\n * - 'I' for info/debug/trace level messages\n *\n * Codes ending in 000 are generic messages, while codes ending in 001-999 are specific to a particular message.\n * The following are examples of valid and invalid message codes:\n * ```ts\n * 'CDK_ASSETS_I000' // valid: generic assets info message\n * 'CDK_TOOLKIT_E002' // valid: specific toolkit error message\n * 'CDK_SDK_W023' // valid: specific sdk warning message\n * ```\n */\n readonly code: IoMessageCode;\n\n /**\n * The message text.\n */\n readonly message: string;\n\n /**\n * The data attached to the message.\n */\n readonly data?: T;\n}\n\nexport interface IoRequest<T, U> extends IoMessage<T> {\n /**\n * The default response that will be used if no data is returned.\n */\n readonly defaultResponse: U;\n}\n\nexport type IoMessageLevel = 'error' | 'result' | 'warn' | 'info' | 'debug' | 'trace';\n\nexport const levelPriority: Record<IoMessageLevel, number> = {\n error: 0,\n result: 1,\n warn: 2,\n info: 3,\n debug: 4,\n trace: 5,\n};\n\n/**\n * Temporary helper to group required props for IoMessages\n */\nexport interface IoMessaging {\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\n/**\n * The current action being performed by the CLI. 'none' represents the absence of an action.\n */\nexport type ToolkitAction =\n| 'assembly'\n| 'bootstrap'\n| 'synth'\n| 'list'\n| 'diff'\n| 'deploy'\n| 'rollback'\n| 'watch'\n| 'destroy'\n| 'context'\n| 'docs'\n| 'doctor'\n| 'gc'\n| 'import'\n| 'metadata'\n| 'notices'\n| 'init'\n| 'migrate'\n| 'version';\n\nexport interface IIoHost {\n /**\n * Notifies the host of a message.\n * The caller waits until the notification completes.\n */\n notify<T>(msg: IoMessage<T>): Promise<void>;\n\n /**\n * Notifies the host of a message that requires a response.\n *\n * If the host does not return a response the suggested\n * default response from the input message will be used.\n */\n requestResponse<T, U>(msg: IoRequest<T, U>): Promise<U>;\n}\n\nexport interface CliIoHostProps {\n /**\n * The initial Toolkit action the hosts starts with.\n *\n * @default 'none'\n */\n readonly currentAction?: ToolkitAction;\n\n /**\n * Determines the verbosity of the output.\n *\n * The CliIoHost will still receive all messages and requests,\n * but only the messages included in this level will be printed.\n *\n * @default 'info'\n */\n readonly logLevel?: IoMessageLevel;\n\n /**\n * Overrides the automatic TTY detection.\n *\n * When TTY is disabled, the CLI will have no interactions or color.\n *\n * @default - determined from the current process\n */\n readonly isTTY?: boolean;\n\n /**\n * Whether the CliIoHost is running in CI mode.\n *\n * In CI mode, all non-error output goes to stdout instead of stderr.\n * Set to false in the CliIoHost constructor it will be overwritten if the CLI CI argument is passed\n *\n * @default - determined from the environment, specifically based on `process.env.CI`\n */\n readonly isCI?: boolean;\n}\n\n/**\n * A simple IO host for the CLI that writes messages to the console.\n */\nexport class CliIoHost implements IIoHost {\n /**\n * Returns the singleton instance\n */\n static instance(props: CliIoHostProps = {}, forceNew = false): CliIoHost {\n if (forceNew || !CliIoHost._instance) {\n CliIoHost._instance = new CliIoHost(props);\n }\n return CliIoHost._instance;\n }\n\n /**\n * Singleton instance of the CliIoHost\n */\n private static _instance: CliIoHost | undefined;\n\n // internal state for getters/setter\n private _currentAction: ToolkitAction;\n private _isCI: boolean;\n private _isTTY: boolean;\n private _logLevel: IoMessageLevel;\n private _internalIoHost?: IIoHost;\n\n // Corked Logging\n private corkedCounter = 0;\n private readonly corkedLoggingBuffer: IoMessage<any>[] = [];\n\n private constructor(props: CliIoHostProps = {}) {\n this._currentAction = props.currentAction ?? 'none' as ToolkitAction;\n this._isTTY = props.isTTY ?? process.stdout.isTTY ?? false;\n this._logLevel = props.logLevel ?? 'info';\n this._isCI = props.isCI ?? isCI();\n }\n\n /**\n * Returns the singleton instance\n */\n public registerIoHost(ioHost: IIoHost) {\n if (ioHost !== this) {\n this._internalIoHost = ioHost;\n }\n }\n\n /**\n * The current action being performed by the CLI.\n */\n public get currentAction(): ToolkitAction {\n return this._currentAction;\n }\n\n /**\n * Sets the current action being performed by the CLI.\n *\n * @param action The action being performed by the CLI.\n */\n public set currentAction(action: ToolkitAction) {\n this._currentAction = action;\n }\n\n /**\n * Whether the host can use interactions and message styling.\n */\n public get isTTY(): boolean {\n return this._isTTY;\n }\n\n /**\n * Set TTY mode, i.e can the host use interactions and message styling.\n *\n * @param value set TTY mode\n */\n public set isTTY(value: boolean) {\n this._isTTY = value;\n }\n\n /**\n * Whether the CliIoHost is running in CI mode. In CI mode, all non-error output goes to stdout instead of stderr.\n */\n public get isCI(): boolean {\n return this._isCI;\n }\n\n /**\n * Set the CI mode. In CI mode, all non-error output goes to stdout instead of stderr.\n * @param value set the CI mode\n */\n public set isCI(value: boolean) {\n this._isCI = value;\n }\n\n /**\n * The current threshold. Messages with a lower priority level will be ignored.\n */\n public get logLevel(): IoMessageLevel {\n return this._logLevel;\n }\n\n /**\n * Sets the current threshold. Messages with a lower priority level will be ignored.\n * @param level The new log level threshold\n */\n public set logLevel(level: IoMessageLevel) {\n this._logLevel = level;\n }\n\n /**\n * Executes a block of code with corked logging. All log messages during execution\n * are buffered and only written when all nested cork blocks complete (when CORK_COUNTER reaches 0).\n * The corking is bound to the specific instance of the CliIoHost.\n *\n * @param block - Async function to execute with corked logging\n * @returns Promise that resolves with the block's return value\n */\n public async withCorkedLogging<T>(block: () => Promise<T>): Promise<T> {\n this.corkedCounter++;\n try {\n return await block();\n } finally {\n this.corkedCounter--;\n if (this.corkedCounter === 0) {\n // Process each buffered message through notify\n for (const ioMessage of this.corkedLoggingBuffer) {\n await this.notify(ioMessage);\n }\n // remove all buffered messages in-place\n this.corkedLoggingBuffer.splice(0);\n }\n }\n }\n\n /**\n * Notifies the host of a message.\n * The caller waits until the notification completes.\n */\n public async notify<T>(msg: IoMessage<T>): Promise<void> {\n if (this._internalIoHost) {\n return this._internalIoHost.notify(msg);\n }\n\n if (levelPriority[msg.level] > levelPriority[this.logLevel]) {\n return;\n }\n\n if (this.corkedCounter > 0) {\n this.corkedLoggingBuffer.push(msg);\n return;\n }\n\n const output = this.formatMessage(msg);\n const stream = this.selectStream(msg.level);\n stream.write(output);\n }\n\n /**\n * Determines the output stream, based on message level and configuration.\n */\n private selectStream(level: IoMessageLevel) {\n // The stream selection policy for the CLI is the following:\n //\n // (1) Messages of level `result` always go to `stdout`\n // (2) Messages of level `error` always go to `stderr`.\n // (3a) All remaining messages go to `stderr`.\n // (3b) If we are in CI mode, all remaining messages go to `stdout`.\n //\n switch (level) {\n case 'error':\n return process.stderr;\n case 'result':\n return process.stdout;\n default:\n return this.isCI ? process.stdout : process.stderr;\n }\n }\n\n /**\n * Notifies the host of a message that requires a response.\n *\n * If the host does not return a response the suggested\n * default response from the input message will be used.\n */\n public async requestResponse<DataType, ResponseType>(msg: IoRequest<DataType, ResponseType>): Promise<ResponseType> {\n // First call out to a registered instance if we have one\n if (this._internalIoHost) {\n return this._internalIoHost.requestResponse(msg);\n }\n\n // If the request cannot be prompted for by the CliIoHost, we just accept the default\n if (!isPromptableRequest(msg)) {\n await this.notify(msg);\n return msg.defaultResponse;\n }\n\n const response = await this.withCorkedLogging(async (): Promise<string | number | true> => {\n // prepare prompt data\n // @todo this format is not defined anywhere, probably should be\n const data: {\n motivation?: string;\n concurrency?: number;\n } = msg.data ?? {};\n\n const motivation = data.motivation ?? 'User input is needed';\n const concurrency = data.concurrency ?? 0;\n\n // only talk to user if STDIN is a terminal (otherwise, fail)\n if (!this.isTTY) {\n throw new ToolkitError(`${motivation}, but terminal (TTY) is not attached so we are unable to get a confirmation from the user`);\n }\n\n // only talk to user if concurrency is 1 (otherwise, fail)\n if (concurrency > 1) {\n throw new ToolkitError(`${motivation}, but concurrency is greater than 1 so we are unable to get a confirmation from the user`);\n }\n\n // Basic confirmation prompt\n // We treat all requests with a boolean response as confirmation prompts\n if (isConfirmationPrompt(msg)) {\n const confirmed = await promptly.confirm(`${chalk.cyan(msg.message)} (y/n)`);\n if (!confirmed) {\n throw new ToolkitError('Aborted by user');\n }\n return confirmed;\n }\n\n // Asking for a specific value\n const prompt = extractPromptInfo(msg);\n const answer = await promptly.prompt(`${chalk.cyan(msg.message)} (${prompt.default})`, {\n default: prompt.default,\n });\n return prompt.convertAnswer(answer);\n });\n\n // We need to cast this because it is impossible to narrow the generic type\n // isPromptableRequest ensures that the response type is one we can prompt for\n // the remaining code ensure we are indeed returning the correct type\n return response as ResponseType;\n }\n\n /**\n * Formats a message for console output with optional color support\n */\n private formatMessage(msg: IoMessage<any>): string {\n // apply provided style or a default style if we're in TTY mode\n let message_text = this._isTTY\n ? styleMap[msg.level](msg.message)\n : msg.message;\n\n // prepend timestamp if IoMessageLevel is DEBUG or TRACE. Postpend a newline.\n return ((msg.level === 'debug' || msg.level === 'trace')\n ? `[${this.formatTime(msg.time)}] ${message_text}`\n : message_text) + '\\n';\n }\n\n /**\n * Formats date to HH:MM:SS\n */\n private formatTime(d: Date): string {\n const pad = (n: number): string => n.toString().padStart(2, '0');\n return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;\n }\n}\n\n/**\n * This IoHost implementation considers a request promptable, if:\n * - it's a yes/no confirmation\n * - asking for a string or number value\n */\nfunction isPromptableRequest(msg: IoRequest<any, any>): msg is IoRequest<any, string | number | boolean> {\n return isConfirmationPrompt(msg)\n || typeof msg.defaultResponse === 'string'\n || typeof msg.defaultResponse === 'number';\n}\n\n/**\n * Check if the request is a confirmation prompt\n * We treat all requests with a boolean response as confirmation prompts\n */\nfunction isConfirmationPrompt(msg: IoRequest<any, any>): msg is IoRequest<any, boolean> {\n return typeof msg.defaultResponse === 'boolean';\n}\n\n/**\n * Helper to extract information for promptly from the request\n */\nfunction extractPromptInfo(msg: IoRequest<any, any>): {\n default: string;\n convertAnswer: (input: string) => string | number;\n} {\n const isNumber = (typeof msg.defaultResponse === 'number');\n return {\n default: util.format(msg.defaultResponse),\n convertAnswer: isNumber ? (v) => Number(v) : (v) => String(v),\n };\n}\n\nconst styleMap: Record<IoMessageLevel, (str: string) => string> = {\n error: chalk.red,\n warn: chalk.yellow,\n result: chalk.white,\n info: chalk.white,\n debug: chalk.gray,\n trace: chalk.gray,\n};\n\n/**\n * Returns true if the current process is running in a CI environment\n * @returns true if the current process is running in a CI environment\n */\nexport function isCI(): boolean {\n return process.env.CI !== undefined && process.env.CI !== 'false' && process.env.CI !== '0';\n}\n", "const TOOLKIT_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.ToolkitError');\nconst AUTHENTICATION_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.AuthenticationError');\nconst ASSEMBLY_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.AssemblyError');\nconst CONTEXT_PROVIDER_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.ContextProviderError');\n\n/**\n * Represents a general toolkit error in the AWS CDK Toolkit.\n */\nexport class ToolkitError extends Error {\n /**\n * Determines if a given error is an instance of ToolkitError.\n */\n public static isToolkitError(x: any): x is ToolkitError {\n return x !== null && typeof(x) === 'object' && TOOLKIT_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AuthenticationError.\n */\n public static isAuthenticationError(x: any): x is AuthenticationError {\n return this.isToolkitError(x) && AUTHENTICATION_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isAssemblyError(x: any): x is AssemblyError {\n return this.isToolkitError(x) && ASSEMBLY_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isContextProviderError(x: any): x is ContextProviderError {\n return this.isToolkitError(x) && CONTEXT_PROVIDER_ERROR_SYMBOL in x;\n }\n\n /**\n * The type of the error, defaults to \"toolkit\".\n */\n public readonly type: string;\n\n constructor(message: string, type: string = 'toolkit') {\n super(message);\n Object.setPrototypeOf(this, ToolkitError.prototype);\n Object.defineProperty(this, TOOLKIT_ERROR_SYMBOL, { value: true });\n this.name = new.target.name;\n this.type = type;\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AuthenticationError extends ToolkitError {\n constructor(message: string) {\n super(message, 'authentication');\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n Object.defineProperty(this, AUTHENTICATION_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AssemblyError extends ToolkitError {\n constructor(message: string) {\n super(message, 'assembly');\n Object.setPrototypeOf(this, AssemblyError.prototype);\n Object.defineProperty(this, ASSEMBLY_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an error originating from a Context Provider\n */\nexport class ContextProviderError extends ToolkitError {\n constructor(message: string) {\n super(message, 'context-provider');\n Object.setPrototypeOf(this, ContextProviderError.prototype);\n Object.defineProperty(this, CONTEXT_PROVIDER_ERROR_SYMBOL, { value: true });\n }\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { ToolkitError } from '../toolkit/error';\n\n/**\n * Return a location that will be used as the CDK home directory.\n * Currently the only thing that is placed here is the cache.\n *\n * First try to use the users home directory (i.e. /home/someuser/),\n * but if that directory does not exist for some reason create a tmp directory.\n *\n * Typically it wouldn't make sense to create a one time use tmp directory for\n * the purpose of creating a cache, but since this only applies to users that do\n * not have a home directory (some CI systems?) this should be fine.\n */\nexport function cdkHomeDir() {\n const tmpDir = fs.realpathSync(os.tmpdir());\n let home;\n try {\n let userInfoHome: string | undefined = os.userInfo().homedir;\n // Node returns this if the user doesn't have a home directory\n /* istanbul ignore if: will not happen in normal setups */\n if (userInfoHome == '/var/empty') {\n userInfoHome = undefined;\n }\n home = path.join((userInfoHome ?? os.homedir()).trim(), '.cdk');\n } catch {\n }\n return process.env.CDK_HOME\n ? path.resolve(process.env.CDK_HOME)\n : home || fs.mkdtempSync(path.join(tmpDir, '.cdk')).trim();\n}\n\nexport function cdkCacheDir() {\n return path.join(cdkHomeDir(), 'cache');\n}\n\n/**\n * From the current file, find the directory that contains the CLI's package.json\n *\n * Can't use `__dirname` in production code, as the CLI will get bundled as it's\n * released and `__dirname` will refer to a different location in the `.ts` form\n * as it will in the final executing form.\n */\nexport function rootDir(): string;\nexport function rootDir(fail: true): string;\nexport function rootDir(fail: false): string | undefined;\nexport function rootDir(fail?: boolean) {\n function _rootDir(dirname: string): string | undefined {\n const manifestPath = path.join(dirname, 'package.json');\n if (fs.existsSync(manifestPath)) {\n return dirname;\n }\n if (path.dirname(dirname) === dirname) {\n if (fail ?? true) {\n throw new ToolkitError('Unable to find package manifest');\n }\n return undefined;\n }\n return _rootDir(path.dirname(dirname));\n }\n\n return _rootDir(__dirname);\n}\n", "/**\n * Cache the result of a function on an object\n *\n * We could have used @decorators to make this nicer but we don't use them anywhere yet,\n * so let's keep it simple and readable.\n */\nexport function cached<A extends object, B>(obj: A, sym: symbol, fn: () => B): B {\n if (!(sym in obj)) {\n (obj as any)[sym] = fn();\n }\n return (obj as any)[sym];\n}\n\n/**\n * Like 'cached', but async\n */\nexport async function cachedAsync<A extends object, B>(obj: A, sym: symbol, fn: () => Promise<B>): Promise<B> {\n if (!(sym in obj)) {\n (obj as any)[sym] = await fn();\n }\n return (obj as any)[sym];\n}\n", "import type { Logger } from '@smithy/types';\n\nlet ENABLED = false;\nlet INDENT = 0;\n\nexport function setSdkTracing(enabled: boolean) {\n ENABLED = enabled;\n}\n\n/**\n * Method decorator to trace a single static or member method, any time it's called\n */\nexport function callTrace(fn: string, className?: string, logger?: Logger) {\n if (!ENABLED || !logger) {\n return;\n }\n\n logger.info(`[trace] ${' '.repeat(INDENT)}${className || '(anonymous)'}#${fn}()`);\n}\n\n/**\n * Method decorator to trace a single member method any time it's called\n */\nfunction traceCall(receiver: object, _propertyKey: string, descriptor: PropertyDescriptor, parentClassName?: string) {\n const fn = descriptor.value;\n const className = typeof receiver === 'function' ? receiver.name : parentClassName;\n\n descriptor.value = function (...args: any[]) {\n const logger = (this as any).logger;\n if (!ENABLED || typeof logger?.info !== 'function') {\n return fn.apply(this, args);\n }\n\n logger.info.apply(logger, [`[trace] ${' '.repeat(INDENT)}${className || this.constructor.name || '(anonymous)'}#${fn.name}()`]);\n INDENT += 2;\n\n const ret = fn.apply(this, args);\n if (ret instanceof Promise) {\n return ret.finally(() => {\n INDENT -= 2;\n });\n } else {\n INDENT -= 2;\n return ret;\n }\n };\n return descriptor;\n}\n\n/**\n * Class decorator, enable tracing for all member methods on this class\n * @deprecated this doesn't work well with localized logging instances, don't use\n */\nexport function traceMemberMethods(constructor: Function) {\n // Instance members\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(constructor.prototype))) {\n if (typeof descriptor.value !== 'function') {\n continue;\n }\n const newDescriptor = traceCall(constructor.prototype, name, descriptor, constructor.name) ?? descriptor;\n Object.defineProperty(constructor.prototype, name, newDescriptor);\n }\n}\n", "import * as path from 'path';\nimport { readIfPossible } from './util';\nimport { rootDir } from '../../util/directories';\n\n/**\n * Find the package.json from the main toolkit.\n *\n * If we can't read it for some reason, try to do something reasonable anyway.\n * Fall back to argv[1], or a standard string if that is undefined for some reason.\n */\nexport function defaultCliUserAgent() {\n const root = rootDir(false);\n const pkg = JSON.parse((root ? readIfPossible(path.join(root, 'package.json')) : undefined) ?? '{}');\n const name = pkg.name ?? path.basename(process.argv[1] ?? 'cdk-cli');\n const version = pkg.version ?? '<unknown>';\n return `${name}/${version}`;\n}\n", "import * as fs from 'fs-extra';\nimport { debug } from '../../logging';\n\n/**\n * Read a file if it exists, or return undefined\n *\n * Not async because it is used in the constructor\n */\nexport function readIfPossible(filename: string): string | undefined {\n try {\n if (!fs.pathExistsSync(filename)) {\n return undefined;\n }\n return fs.readFileSync(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n debug(e);\n return undefined;\n }\n}\n", "/**\n * Takes in an error and returns a correctly formatted string of its error message.\n * If it is an AggregateError, it will return a string with all the inner errors\n * formatted and separated by a newline.\n *\n * @param error The error to format\n * @returns A string with the error message(s) of the error\n */\nexport function formatErrorMessage(error: any): string {\n if (error && Array.isArray(error.errors)) {\n const innerMessages = error.errors\n .map((innerError: { message: any; toString: () => any }) => (innerError?.message || innerError?.toString()))\n .join('\\n');\n return `AggregateError: ${innerMessages}`;\n }\n\n // Fallback for regular Error or other types\n return error?.message || error?.toString() || 'Unknown error';\n}\n", "import * as os from 'os';\nimport { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema';\nimport { Environment, EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport { AssumeRoleCommandInput } from '@aws-sdk/client-sts';\nimport { fromTemporaryCredentials } from '@aws-sdk/credential-providers';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { AwsCliCompatible } from './awscli-compatible';\nimport { cached } from './cached';\nimport { CredentialPlugins } from './credential-plugins';\nimport { makeCachingProvider } from './provider-caching';\nimport { SDK } from './sdk';\nimport { callTrace, traceMemberMethods } from './tracing';\nimport { debug, warning } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { Mode } from '../plugin/mode';\n\nexport type AssumeRoleAdditionalOptions = Partial<Omit<AssumeRoleCommandInput, 'ExternalId' | 'RoleArn'>>;\n\n/**\n * Options for the default SDK provider\n */\nexport interface SdkProviderOptions {\n /**\n * Profile to read from ~/.aws\n *\n * @default - No profile\n */\n readonly profile?: string;\n\n /**\n * HTTP options for SDK\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * The logger for sdk calls.\n */\n readonly logger?: Logger;\n}\n\n/**\n * Options for individual SDKs\n */\nexport interface SdkHttpOptions {\n /**\n * Proxy address to use\n *\n * @default No proxy\n */\n readonly proxyAddress?: string;\n\n /**\n * A path to a certificate bundle that contains a cert to be trusted.\n *\n * @default No certificate bundle\n */\n readonly caBundlePath?: string;\n}\n\nconst CACHED_ACCOUNT = Symbol('cached_account');\n\n/**\n * SDK configuration for a given environment\n * 'forEnvironment' will attempt to assume a role and if it\n * is not successful, then it will either:\n * 1. Check to see if the default credentials (local credentials the CLI was executed with)\n * are for the given environment. If they are then return those.\n * 2. If the default credentials are not for the given environment then\n * throw an error\n *\n * 'didAssumeRole' allows callers to whether they are receiving the assume role\n * credentials or the default credentials.\n */\nexport interface SdkForEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * Whether or not the assume role was successful.\n * If the assume role was not successful (false)\n * then that means that the 'sdk' returned contains\n * the default credentials (not the assume role credentials)\n */\n readonly didAssumeRole: boolean;\n}\n\n/**\n * Creates instances of the AWS SDK appropriate for a given account/region.\n *\n * Behavior is as follows:\n *\n * - First, a set of \"base\" credentials are established\n * - If a target environment is given and the default (\"current\") SDK credentials are for\n * that account, return those; otherwise\n * - If a target environment is given, scan all credential provider plugins\n * for credentials, and return those if found; otherwise\n * - Return default (\"current\") SDK credentials, noting that they might be wrong.\n *\n * - Second, a role may optionally need to be assumed. Use the base credentials\n * established in the previous process to assume that role.\n * - If assuming the role fails and the base credentials are for the correct\n * account, return those. This is a fallback for people who are trying to interact\n * with a Default Synthesized stack and already have right credentials setup.\n *\n * Typical cases we see in the wild:\n * - Credential plugin setup that, although not recommended, works for them\n * - Seeded terminal with `ReadOnly` credentials in order to do `cdk diff`--the `ReadOnly`\n * role doesn't have `sts:AssumeRole` and will fail for no real good reason.\n */\n@traceMemberMethods\nexport class SdkProvider {\n /**\n * Create a new SdkProvider which gets its defaults in a way that behaves like the AWS CLI does\n *\n * The AWS SDK for JS behaves slightly differently from the AWS CLI in a number of ways; see the\n * class `AwsCliCompatible` for the details.\n */\n public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions = {}) {\n callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger);\n const credentialProvider = await AwsCliCompatible.credentialChainBuilder({\n profile: options.profile,\n httpOptions: options.httpOptions,\n logger: options.logger,\n });\n\n const region = await AwsCliCompatible.region(options.profile);\n const requestHandler = AwsCliCompatible.requestHandlerBuilder(options.httpOptions);\n return new SdkProvider(credentialProvider, region, requestHandler, options.logger);\n }\n\n private readonly plugins = new CredentialPlugins();\n\n public constructor(\n private readonly defaultCredentialProvider: AwsCredentialIdentityProvider,\n /**\n * Default region\n */\n public readonly defaultRegion: string,\n private readonly requestHandler: NodeHttpHandlerOptions = {},\n private readonly logger?: Logger,\n ) {\n }\n\n /**\n * Return an SDK which can do operations in the given environment\n *\n * The `environment` parameter is resolved first (see `resolveEnvironment()`).\n */\n public async forEnvironment(\n environment: Environment,\n mode: Mode,\n options?: CredentialsOptions,\n quiet = false,\n ): Promise<SdkForEnvironment> {\n const env = await this.resolveEnvironment(environment);\n\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n\n // At this point, we need at least SOME credentials\n if (baseCreds.source === 'none') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Simple case is if we don't need to \"assumeRole\" here. If so, we must now have credentials for the right\n // account.\n if (options?.assumeRoleArn === undefined) {\n if (baseCreds.source === 'incorrectDefault') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Our current credentials must be valid and not expired. Confirm that before we get into doing\n // actual CloudFormation calls, which might take a long time to hang.\n const sdk = new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger);\n await sdk.validateCredentials();\n return { sdk, didAssumeRole: false };\n }\n\n try {\n // We will proceed to AssumeRole using whatever we've been given.\n const sdk = await this.withAssumedRole(\n baseCreds,\n options.assumeRoleArn,\n options.assumeRoleExternalId,\n options.assumeRoleAdditionalOptions,\n env.region,\n );\n\n return { sdk, didAssumeRole: true };\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n // AssumeRole failed. Proceed and warn *if and only if* the baseCredentials were already for the right account\n // or returned from a plugin. This is to cover some current setups for people using plugins or preferring to\n // feed the CLI credentials which are sufficient by themselves. Prefer to assume the correct role if we can,\n // but if we can't then let's just try with available credentials anyway.\n if (baseCreds.source === 'correctDefault' || baseCreds.source === 'plugin') {\n debug(err.message);\n const logger = quiet ? debug : warning;\n logger(\n `${fmtObtainedCredentials(baseCreds)} could not be used to assume '${options.assumeRoleArn}', but are for the right account. Proceeding anyway.`,\n );\n return {\n sdk: new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger),\n didAssumeRole: false,\n };\n }\n\n throw err;\n }\n }\n\n /**\n * Return the partition that base credentials are for\n *\n * Returns `undefined` if there are no base credentials.\n */\n public async baseCredentialsPartition(environment: Environment, mode: Mode): Promise<string | undefined> {\n const env = await this.resolveEnvironment(environment);\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n if (baseCreds.source === 'none') {\n return undefined;\n }\n return (await new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger).currentAccount()).partition;\n }\n\n /**\n * Resolve the environment for a stack\n *\n * Replaces the magic values `UNKNOWN_REGION` and `UNKNOWN_ACCOUNT`\n * with the defaults for the current SDK configuration (`~/.aws/config` or\n * otherwise).\n *\n * It is an error if `UNKNOWN_ACCOUNT` is used but the user hasn't configured\n * any SDK credentials.\n */\n public async resolveEnvironment(env: Environment): Promise<Environment> {\n const region = env.region !== UNKNOWN_REGION ? env.region : this.defaultRegion;\n const account = env.account !== UNKNOWN_ACCOUNT ? env.account : (await this.defaultAccount())?.accountId;\n\n if (!account) {\n throw new AuthenticationError(\n 'Unable to resolve AWS account to use. It must be either configured when you define your CDK Stack, or through the environment',\n );\n }\n\n return {\n region,\n account,\n name: EnvironmentUtils.format(account, region),\n };\n }\n\n /**\n * The account we'd auth into if we used default credentials.\n *\n * Default credentials are the set of ambiently configured credentials using\n * one of the environment variables, or ~/.aws/credentials, or the *one*\n * profile that was passed into the CLI.\n *\n * Might return undefined if there are no default/ambient credentials\n * available (in which case the user should better hope they have\n * credential plugins configured).\n *\n * Uses a cache to avoid STS calls if we don't need 'em.\n */\n public async defaultAccount(): Promise<Account | undefined> {\n return cached(this, CACHED_ACCOUNT, async () => {\n try {\n return await new SDK(this.defaultCredentialProvider, this.defaultRegion, this.requestHandler, this.logger).currentAccount();\n } catch (e: any) {\n // Treat 'ExpiredToken' specially. This is a common situation that people may find themselves in, and\n // they are complaining about if we fail 'cdk synth' on them. We loudly complain in order to show that\n // the current situation is probably undesirable, but we don't fail.\n if (e.name === 'ExpiredToken') {\n warning(\n 'There are expired AWS credentials in your environment. The CDK app will synth without current account information.',\n );\n return undefined;\n }\n\n debug(`Unable to determine the default AWS account (${e.name}): ${formatErrorMessage(e)}`);\n return undefined;\n }\n });\n }\n\n /**\n * Get credentials for the given account ID in the given mode\n *\n * 1. Use the default credentials if the destination account matches the\n * current credentials' account.\n * 2. Otherwise try all credential plugins.\n * 3. Fail if neither of these yield any credentials.\n * 4. Return a failure if any of them returned credentials\n */\n private async obtainBaseCredentials(accountId: string, mode: Mode): Promise<ObtainBaseCredentialsResult> {\n // First try 'current' credentials\n const defaultAccountId = (await this.defaultAccount())?.accountId;\n if (defaultAccountId === accountId) {\n return {\n source: 'correctDefault',\n credentials: await this.defaultCredentialProvider,\n };\n }\n\n // Then try the plugins\n const pluginCreds = await this.plugins.fetchCredentialsFor(accountId, mode);\n if (pluginCreds) {\n return { source: 'plugin', ...pluginCreds };\n }\n\n // Fall back to default credentials with a note that they're not the right ones yet\n if (defaultAccountId !== undefined) {\n return {\n source: 'incorrectDefault',\n accountId: defaultAccountId,\n credentials: await this.defaultCredentialProvider,\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n // Apparently we didn't find any at all\n return {\n source: 'none',\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n /**\n * Return an SDK which uses assumed role credentials\n *\n * The base credentials used to retrieve the assumed role credentials will be the\n * same credentials returned by obtainCredentials if an environment and mode is passed,\n * otherwise it will be the current credentials.\n */\n private async withAssumedRole(\n mainCredentials: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>,\n roleArn: string,\n externalId?: string,\n additionalOptions?: AssumeRoleAdditionalOptions,\n region?: string,\n ): Promise<SDK> {\n debug(`Assuming role '${roleArn}'.`);\n\n region = region ?? this.defaultRegion;\n\n const sourceDescription = fmtObtainedCredentials(mainCredentials);\n\n try {\n const credentials = await makeCachingProvider(fromTemporaryCredentials({\n masterCredentials: mainCredentials.credentials,\n params: {\n RoleArn: roleArn,\n ExternalId: externalId,\n RoleSessionName: `aws-cdk-${safeUsername()}`,\n ...additionalOptions,\n TransitiveTagKeys: additionalOptions?.Tags ? additionalOptions.Tags.map((t) => t.Key!) : undefined,\n },\n clientConfig: {\n region,\n requestHandler: this.requestHandler,\n customUserAgent: 'aws-cdk',\n logger: this.logger,\n },\n logger: this.logger,\n }));\n\n // Call the provider at least once here, to catch an error if it occurs\n await credentials();\n\n return new SDK(credentials, region, this.requestHandler, this.logger);\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n debug(`Assuming role failed: ${err.message}`);\n throw new AuthenticationError(\n [\n 'Could not assume role in target account',\n ...(sourceDescription ? [`using ${sourceDescription}`] : []),\n err.message,\n \". Please make sure that this role exists in the account. If it doesn't exist, (re)-bootstrap the environment \" +\n \"with the right '--trust', using the latest version of the CDK CLI.\",\n ].join(' '),\n );\n }\n }\n}\n\n/**\n * An AWS account\n *\n * An AWS account always exists in only one partition. Usually we don't care about\n * the partition, but when we need to form ARNs we do.\n */\nexport interface Account {\n /**\n * The account number\n */\n readonly accountId: string;\n\n /**\n * The partition ('aws' or 'aws-cn' or otherwise)\n */\n readonly partition: string;\n}\n\n/**\n * Return the username with characters invalid for a RoleSessionName removed\n *\n * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters\n */\nfunction safeUsername() {\n try {\n return os.userInfo().username.replace(/[^\\w+=,.@-]/g, '@');\n } catch {\n return 'noname';\n }\n}\n\n/**\n * Options for obtaining credentials for an environment\n */\nexport interface CredentialsOptions {\n /**\n * The ARN of the role that needs to be assumed, if any\n */\n readonly assumeRoleArn?: string;\n\n /**\n * External ID required to assume the given role.\n */\n readonly assumeRoleExternalId?: string;\n\n /**\n * Session tags required to assume the given role.\n */\n readonly assumeRoleAdditionalOptions?: AssumeRoleAdditionalOptions;\n}\n\n/**\n * Result of obtaining base credentials\n */\ntype ObtainBaseCredentialsResult =\n | { source: 'correctDefault'; credentials: AwsCredentialIdentityProvider }\n | { source: 'plugin'; pluginName: string; credentials: AwsCredentialIdentityProvider }\n | {\n source: 'incorrectDefault';\n credentials: AwsCredentialIdentityProvider;\n accountId: string;\n unusedPlugins: string[];\n }\n | { source: 'none'; unusedPlugins: string[] };\n\n/**\n * Isolating the code that translates calculation errors into human error messages\n *\n * We cover the following cases:\n *\n * - No credentials are available at all\n * - Default credentials are for the wrong account\n */\nfunction fmtObtainCredentialsError(\n targetAccountId: string,\n obtainResult: ObtainBaseCredentialsResult & {\n source: 'none' | 'incorrectDefault';\n },\n): string {\n const msg = [`Need to perform AWS calls for account ${targetAccountId}`];\n switch (obtainResult.source) {\n case 'incorrectDefault':\n msg.push(`but the current credentials are for ${obtainResult.accountId}`);\n break;\n case 'none':\n msg.push('but no credentials have been configured');\n }\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`and none of these plugins found any: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n return msg.join(', ');\n}\n\n/**\n * Format a message indicating where we got base credentials for the assume role\n *\n * We cover the following cases:\n *\n * - Default credentials for the right account\n * - Default credentials for the wrong account\n * - Credentials returned from a plugin\n */\nfunction fmtObtainedCredentials(obtainResult: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>): string {\n switch (obtainResult.source) {\n case 'correctDefault':\n return 'current credentials';\n case 'plugin':\n return `credentials returned by plugin '${obtainResult.pluginName}'`;\n case 'incorrectDefault':\n const msg = [];\n msg.push(`current credentials (which are for account ${obtainResult.accountId}`);\n\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`, and none of the following plugins provided credentials: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n msg.push(')');\n\n return msg.join('');\n }\n}\n\n/**\n * Instantiate an SDK for context providers. This function ensures that all\n * lookup assume role options are used when context providers perform lookups.\n */\nexport async function initContextProviderSdk(aws: SdkProvider, options: ContextLookupRoleOptions): Promise<SDK> {\n const account = options.account;\n const region = options.region;\n\n const creds: CredentialsOptions = {\n assumeRoleArn: options.lookupRoleArn,\n assumeRoleExternalId: options.lookupRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n };\n\n return (await aws.forEnvironment(EnvironmentUtils.make(account, region), Mode.ForReading, creds)).sdk;\n}\n", "import { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers';\nimport { MetadataService } from '@aws-sdk/ec2-metadata-service';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport * as promptly from 'promptly';\nimport { ProxyAgent } from 'proxy-agent';\nimport { makeCachingProvider } from './provider-caching';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { readIfPossible } from './util';\nimport { debug } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\nconst DEFAULT_TIMEOUT = 300000;\n\n/**\n * Behaviors to match AWS CLI\n *\n * See these links:\n *\n * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html\n * https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html\n */\nexport class AwsCliCompatible {\n /**\n * Build an AWS CLI-compatible credential chain provider\n *\n * The credential chain returned by this function is always caching.\n */\n public static async credentialChainBuilder(\n options: CredentialChainOptions = {},\n ): Promise<AwsCredentialIdentityProvider> {\n const clientConfig = {\n requestHandler: AwsCliCompatible.requestHandlerBuilder(options.httpOptions),\n customUserAgent: 'aws-cdk',\n logger: options.logger,\n };\n\n // Super hacky solution to https://github.com/aws/aws-cdk/issues/32510, proposed by the SDK team.\n //\n // Summary of the problem: we were reading the region from the config file and passing it to\n // the credential providers. However, in the case of SSO, this makes the credential provider\n // use that region to do the SSO flow, which is incorrect. The region that should be used for\n // that is the one set in the sso_session section of the config file.\n //\n // The idea here: the \"clientConfig\" is for configuring the inner auth client directly,\n // and has the highest priority, whereas \"parentClientConfig\" is the upper data client\n // and has lower priority than the sso_region but still higher priority than STS global region.\n const parentClientConfig = {\n region: await this.region(options.profile),\n };\n /**\n * The previous implementation matched AWS CLI behavior:\n *\n * If a profile is explicitly set using `--profile`,\n * we use that to the exclusion of everything else.\n *\n * Note: this does not apply to AWS_PROFILE,\n * environment credentials still take precedence over AWS_PROFILE\n */\n if (options.profile) {\n return makeCachingProvider(fromIni({\n profile: options.profile,\n ignoreCache: true,\n mfaCodeProvider: tokenCodeFn,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n }));\n }\n\n const envProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE;\n\n /**\n * Env AWS - EnvironmentCredentials with string AWS\n * Env Amazon - EnvironmentCredentials with string AMAZON\n * Profile Credentials - PatchedSharedIniFileCredentials with implicit profile, credentials file, http options, and token fn\n * SSO with implicit profile only\n * SharedIniFileCredentials with implicit profile and preferStaticCredentials true (profile with source_profile)\n * Shared Credential file that points to Environment Credentials with AWS prefix\n * Shared Credential file that points to EC2 Metadata\n * Shared Credential file that points to ECS Credentials\n * SSO Credentials - SsoCredentials with implicit profile and http options\n * ProcessCredentials with implicit profile\n * ECS Credentials - ECSCredentials with no input OR Web Identity - TokenFileWebIdentityCredentials with no input OR EC2 Metadata - EC2MetadataCredentials with no input\n *\n * These translate to:\n * fromEnv()\n * fromSSO()/fromIni()\n * fromProcess()\n * fromContainerMetadata()\n * fromTokenFile()\n * fromInstanceMetadata()\n *\n * The NodeProviderChain is already cached.\n */\n const nodeProviderChain = fromNodeProviderChain({\n profile: envProfile,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n mfaCodeProvider: tokenCodeFn,\n ignoreCache: true,\n });\n\n return shouldPrioritizeEnv()\n ? createCredentialChain(fromEnv(), nodeProviderChain).expireAfter(60 * 60_000)\n : nodeProviderChain;\n }\n\n public static requestHandlerBuilder(options: SdkHttpOptions = {}): NodeHttpHandlerOptions {\n const agent = this.proxyAgent(options);\n\n return {\n connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,\n requestTimeout: DEFAULT_TIMEOUT,\n httpsAgent: agent,\n httpAgent: agent,\n };\n }\n\n public static proxyAgent(options: SdkHttpOptions) {\n // Force it to use the proxy provided through the command line.\n // Otherwise, let the ProxyAgent auto-detect the proxy using environment variables.\n const getProxyForUrl = options.proxyAddress != null\n ? () => Promise.resolve(options.proxyAddress!)\n : undefined;\n\n return new ProxyAgent({\n ca: tryGetCACert(options.caBundlePath),\n getProxyForUrl,\n });\n }\n\n /**\n * Attempts to get the region from a number of sources and falls back to us-east-1 if no region can be found,\n * as is done in the AWS CLI.\n *\n * The order of priority is the following:\n *\n * 1. Environment variables specifying region, with both an AWS prefix and AMAZON prefix\n * to maintain backwards compatibility, and without `DEFAULT` in the name because\n * Lambda and CodeBuild set the $AWS_REGION variable.\n * 2. Regions listed in the Shared Ini Files - First checking for the profile provided\n * and then checking for the default profile.\n * 3. IMDS instance identity region from the Metadata Service.\n * 4. us-east-1\n */\n public static async region(maybeProfile?: string): Promise<string> {\n const defaultRegion = 'us-east-1';\n const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';\n\n const region =\n process.env.AWS_REGION ||\n process.env.AMAZON_REGION ||\n process.env.AWS_DEFAULT_REGION ||\n process.env.AMAZON_DEFAULT_REGION ||\n (await getRegionFromIni(profile)) ||\n (await regionFromMetadataService());\n\n if (!region) {\n const usedProfile = !profile ? '' : ` (profile: \"${profile}\")`;\n debug(\n `Unable to determine AWS region from environment or AWS configuration${usedProfile}, defaulting to '${defaultRegion}'`,\n );\n return defaultRegion;\n }\n\n return region;\n }\n}\n\n/**\n * Looks up the region of the provided profile. If no region is present,\n * it will attempt to lookup the default region.\n * @param profile The profile to use to lookup the region\n * @returns The region for the profile or default profile, if present. Otherwise returns undefined.\n */\nasync function getRegionFromIni(profile: string): Promise<string | undefined> {\n const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true });\n\n // Priority:\n //\n // credentials come before config because aws-cli v1 behaves like that.\n //\n // 1. profile-region-in-credentials\n // 2. profile-region-in-config\n // 3. default-region-in-credentials\n // 4. default-region-in-config\n\n return getRegionFromIniFile(profile, sharedFiles.credentialsFile)\n ?? getRegionFromIniFile(profile, sharedFiles.configFile)\n ?? getRegionFromIniFile('default', sharedFiles.credentialsFile)\n ?? getRegionFromIniFile('default', sharedFiles.configFile);\n}\n\nfunction getRegionFromIniFile(profile: string, data?: any) {\n return data?.[profile]?.region;\n}\n\nfunction tryGetCACert(bundlePath?: string) {\n const path = bundlePath || caBundlePathFromEnvironment();\n if (path) {\n debug('Using CA bundle path: %s', path);\n return readIfPossible(path);\n }\n return undefined;\n}\n\n/**\n * Find and return a CA certificate bundle path to be passed into the SDK.\n */\nfunction caBundlePathFromEnvironment(): string | undefined {\n if (process.env.aws_ca_bundle) {\n return process.env.aws_ca_bundle;\n }\n if (process.env.AWS_CA_BUNDLE) {\n return process.env.AWS_CA_BUNDLE;\n }\n return undefined;\n}\n\n/**\n * We used to support both AWS and AMAZON prefixes for these environment variables.\n *\n * Adding this for backward compatibility.\n */\nfunction shouldPrioritizeEnv() {\n const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;\n const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;\n\n if (!!id && !!key) {\n process.env.AWS_ACCESS_KEY_ID = id;\n process.env.AWS_SECRET_ACCESS_KEY = key;\n\n const sessionToken = process.env.AWS_SESSION_TOKEN ?? process.env.AMAZON_SESSION_TOKEN;\n if (sessionToken) {\n process.env.AWS_SESSION_TOKEN = sessionToken;\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * The MetadataService class will attempt to fetch the instance identity document from\n * IMDSv2 first, and then will attempt v1 as a fallback.\n *\n * If this fails, we will use us-east-1 as the region so no error should be thrown.\n * @returns The region for the instance identity\n */\nasync function regionFromMetadataService() {\n debug('Looking up AWS region in the EC2 Instance Metadata Service (IMDS).');\n try {\n const metadataService = new MetadataService({\n httpOptions: {\n timeout: 1000,\n },\n });\n\n await metadataService.fetchMetadataToken();\n const document = await metadataService.request('/latest/dynamic/instance-identity/document', {});\n return JSON.parse(document).region;\n } catch (e) {\n debug(`Unable to retrieve AWS region from IMDS: ${e}`);\n }\n}\n\nexport interface CredentialChainOptions {\n readonly profile?: string;\n readonly httpOptions?: SdkHttpOptions;\n readonly logger?: Logger;\n}\n\n/**\n * Ask user for MFA token for given serial\n *\n * Result is send to callback function for SDK to authorize the request\n */\nasync function tokenCodeFn(serialArn: string): Promise<string> {\n debug('Require MFA token for serial ARN', serialArn);\n try {\n const token: string = await promptly.prompt(`MFA token for ${serialArn}: `, {\n trim: true,\n default: '',\n });\n debug('Successfully got MFA token from user');\n return token;\n } catch (err: any) {\n debug('Failed to get MFA token', err);\n const e = new AuthenticationError(`Error fetching MFA token: ${err.message ?? err}`);\n e.name = 'SharedIniFileCredentialsProviderFailure';\n throw e;\n }\n}\n", "import { memoize } from '@smithy/property-provider';\nimport { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\n\n/**\n * Wrap a credential provider in a cache\n *\n * Some credential providers in the SDKv3 are cached (the default Node\n * chain, specifically) but most others are not.\n *\n * Since we want to avoid duplicate calls to `AssumeRole`, or duplicate\n * MFA prompts or what have you, we are going to liberally wrap providers\n * in caches which will return the cached value until it expires.\n */\nexport function makeCachingProvider(provider: AwsCredentialIdentityProvider): AwsCredentialIdentityProvider {\n return memoize(\n provider,\n credentialsAboutToExpire,\n (token) => !!token.expiration,\n );\n}\n\nexport function credentialsAboutToExpire(token: AwsCredentialIdentity) {\n const expiryMarginSecs = 5;\n // token.expiration is sometimes null\n return !!token.expiration && token.expiration.getTime() - Date.now() < expiryMarginSecs * 1000;\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, ForReading, ForWriting, PluginProviderResult, SDKv2CompatibleCredentials, SDKv3CompatibleCredentialProvider, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\nimport { credentialsAboutToExpire, makeCachingProvider } from './provider-caching';\nimport { debug, warning } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { Mode } from '../plugin/mode';\nimport { PluginHost } from '../plugin/plugin';\n\n/**\n * Cache for credential providers.\n *\n * Given an account and an operating mode (read or write) will return an\n * appropriate credential provider for credentials for the given account. The\n * credential provider will be cached so that multiple AWS clients for the same\n * environment will not make multiple network calls to obtain credentials.\n *\n * Will use default credentials if they are for the right account; otherwise,\n * all loaded credential provider plugins will be tried to obtain credentials\n * for the given account.\n */\nexport class CredentialPlugins {\n private readonly cache: { [key: string]: PluginCredentialsFetchResult | undefined } = {};\n private readonly host: PluginHost;\n\n constructor(host?: PluginHost) {\n this.host = host ?? PluginHost.instance;\n }\n\n public async fetchCredentialsFor(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const key = `${awsAccountId}-${mode}`;\n if (!(key in this.cache)) {\n this.cache[key] = await this.lookupCredentials(awsAccountId, mode);\n }\n return this.cache[key];\n }\n\n public get availablePluginNames(): string[] {\n return this.host.credentialProviderSources.map((s) => s.name);\n }\n\n private async lookupCredentials(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const triedSources: CredentialProviderSource[] = [];\n // Otherwise, inspect the various credential sources we have\n for (const source of this.host.credentialProviderSources) {\n let available: boolean;\n try {\n available = await source.isAvailable();\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n warning(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`);\n available = false;\n }\n\n if (!available) {\n debug('Credentials source %s is not available, ignoring it.', source.name);\n continue;\n }\n triedSources.push(source);\n let canProvide: boolean;\n try {\n canProvide = await source.canProvideCredentials(awsAccountId);\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n warning(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`);\n canProvide = false;\n }\n if (!canProvide) {\n continue;\n }\n debug(`Using ${source.name} credentials for account ${awsAccountId}`);\n\n return {\n credentials: await v3ProviderFromPlugin(() => source.getProvider(awsAccountId, mode as ForReading | ForWriting, {\n supportsV3Providers: true,\n })),\n pluginName: source.name,\n };\n }\n return undefined;\n }\n}\n\n/**\n * Result from trying to fetch credentials from the Plugin host\n */\nexport interface PluginCredentialsFetchResult {\n /**\n * SDK-v3 compatible credential provider\n */\n readonly credentials: AwsCredentialIdentityProvider;\n\n /**\n * Name of plugin that successfully provided credentials\n */\n readonly pluginName: string;\n}\n\n/**\n * Take a function that calls the plugin, and turn it into an SDKv3-compatible credential provider.\n *\n * What we will do is the following:\n *\n * - Query the plugin and see what kind of result it gives us.\n * - If the result is self-refreshing or doesn't need refreshing, we turn it into an SDKv3 provider\n * and return it directly.\n * * If the underlying return value is a provider, we will make it a caching provider\n * (because we can't know if it will cache by itself or not).\n * * If the underlying return value is a static credential, caching isn't relevant.\n * * If the underlying return value is V2 credentials, those have caching built-in.\n * - If the result is a static credential that expires, we will wrap it in an SDKv3 provider\n * that will query the plugin again when the credential expires.\n */\nasync function v3ProviderFromPlugin(producer: () => Promise<PluginProviderResult>): Promise<AwsCredentialIdentityProvider> {\n const initial = await producer();\n\n if (isV3Provider(initial)) {\n // Already a provider, make caching\n return makeCachingProvider(initial);\n } else if (isV3Credentials(initial) && initial.expiration === undefined) {\n // Static credentials that don't need refreshing nor caching\n return () => Promise.resolve(initial);\n } else if (isV3Credentials(initial) && initial.expiration !== undefined) {\n // Static credentials that do need refreshing and caching\n return refreshFromPluginProvider(initial, producer);\n } else if (isV2Credentials(initial)) {\n // V2 credentials that refresh and cache themselves\n return v3ProviderFromV2Credentials(initial);\n } else {\n throw new AuthenticationError(`Plugin returned a value that doesn't resemble AWS credentials: ${inspect(initial)}`);\n }\n}\n\n/**\n * Converts a V2 credential into a V3-compatible provider\n */\nfunction v3ProviderFromV2Credentials(x: SDKv2CompatibleCredentials): AwsCredentialIdentityProvider {\n return async () => {\n // Get will fetch or refresh as necessary\n await x.getPromise();\n\n return {\n accessKeyId: x.accessKeyId,\n secretAccessKey: x.secretAccessKey,\n sessionToken: x.sessionToken,\n expiration: x.expireTime ?? undefined,\n };\n };\n}\n\nfunction refreshFromPluginProvider(current: AwsCredentialIdentity, producer: () => Promise<PluginProviderResult>): AwsCredentialIdentityProvider {\n return async () => {\n if (credentialsAboutToExpire(current)) {\n const newCreds = await producer();\n if (!isV3Credentials(newCreds)) {\n throw new AuthenticationError(`Plugin initially returned static V3 credentials but now returned something else: ${inspect(newCreds)}`);\n }\n current = newCreds;\n }\n return current;\n };\n}\n\nfunction isV3Provider(x: PluginProviderResult): x is SDKv3CompatibleCredentialProvider {\n return typeof x === 'function';\n}\n\nfunction isV2Credentials(x: PluginProviderResult): x is SDKv2CompatibleCredentials {\n return !!(x && typeof x === 'object' && (x as SDKv2CompatibleCredentials).getPromise);\n}\n\nfunction isV3Credentials(x: PluginProviderResult): x is SDKv3CompatibleCredentials {\n return !!(x && typeof x === 'object' && x.accessKeyId && !isV2Credentials(x));\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';\n\nimport * as chalk from 'chalk';\nimport { type ContextProviderPlugin, isContextProviderPlugin } from './context-provider-plugin';\nimport { error } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\n\nexport let TESTING = false;\n\nexport function markTesting() {\n TESTING = true;\n}\n\n/**\n * A utility to manage plug-ins.\n *\n */\nexport class PluginHost implements IPluginHost {\n public static instance = new PluginHost();\n\n /**\n * Access the currently registered CredentialProviderSources. New sources can\n * be registered using the +registerCredentialProviderSource+ method.\n */\n public readonly credentialProviderSources = new Array<CredentialProviderSource>();\n\n public readonly contextProviderPlugins: Record<string, ContextProviderPlugin> = {};\n\n constructor() {\n if (!TESTING && PluginHost.instance && PluginHost.instance !== this) {\n throw new ToolkitError('New instances of PluginHost must not be built. Use PluginHost.instance instead!');\n }\n }\n\n /**\n * Loads a plug-in into this PluginHost.\n *\n * @param moduleSpec the specification (path or name) of the plug-in module to be loaded.\n */\n public load(moduleSpec: string) {\n try {\n /* eslint-disable @typescript-eslint/no-require-imports */\n const plugin = require(moduleSpec);\n /* eslint-enable */\n if (!isPlugin(plugin)) {\n error(`Module ${chalk.green(moduleSpec)} is not a valid plug-in, or has an unsupported version.`);\n throw new ToolkitError(`Module ${moduleSpec} does not define a valid plug-in.`);\n }\n if (plugin.init) {\n plugin.init(this);\n }\n } catch (e: any) {\n error(`Unable to load ${chalk.green(moduleSpec)}: ${e.stack}`);\n throw new ToolkitError(`Unable to load plug-in: ${moduleSpec}: ${e}`);\n }\n\n function isPlugin(x: any): x is Plugin {\n return x != null && x.version === '1';\n }\n }\n\n /**\n * Allows plug-ins to register new CredentialProviderSources.\n *\n * @param source a new CredentialProviderSource to register.\n */\n public registerCredentialProviderSource(source: CredentialProviderSource) {\n // Forward to the right credentials-related plugin host\n this.credentialProviderSources.push(source);\n }\n\n /**\n * (EXPERIMENTAL) Allow plugins to register context providers\n *\n * Context providers are objects with the following method:\n *\n * ```ts\n * getValue(args: {[key: string]: any}): Promise<any>;\n * ```\n *\n * Currently, they cannot reuse the CDK's authentication mechanisms, so they\n * must be prepared to either not make AWS calls or use their own source of\n * AWS credentials.\n *\n * This feature is experimental, and only intended to be used internally at Amazon\n * as a trial.\n *\n * After registering with 'my-plugin-name', the provider must be addressed as follows:\n *\n * ```ts\n * const value = ContextProvider.getValue(this, {\n * providerName: 'plugin',\n * props: {\n * pluginName: 'my-plugin-name',\n * myParameter1: 'xyz',\n * },\n * includeEnvironment: true | false,\n * dummyValue: 'what-to-return-on-the-first-pass',\n * })\n * ```\n *\n * @experimental\n */\n public registerContextProviderAlpha(pluginProviderName: string, provider: ContextProviderPlugin) {\n if (!isContextProviderPlugin(provider)) {\n throw new ToolkitError(`Object you gave me does not look like a ContextProviderPlugin: ${inspect(provider)}`);\n }\n this.contextProviderPlugins[pluginProviderName] = provider;\n }\n}\n", "export interface ContextProviderPlugin {\n getValue(args: {[key: string]: any}): Promise<any>;\n}\n\nexport function isContextProviderPlugin(x: unknown): x is ContextProviderPlugin {\n return typeof x === 'object' && !!x && !!(x as any).getValue;\n}\n", "import { inspect, format } from 'util';\nimport { Logger } from '@smithy/types';\nimport type { IIoHost } from '../../toolkit/cli-io-host';\nimport { replacerBufferWithInfo } from '../../util/serialize';\n\nexport class SdkToCliLogger implements Logger {\n private readonly ioHost: IIoHost;\n\n public constructor(ioHost: IIoHost) {\n this.ioHost = ioHost;\n }\n\n private notify(level: 'debug' | 'info' | 'warn' | 'error', ...content: any[]) {\n void this.ioHost.notify({\n time: new Date(),\n level: 'trace', // always log all SDK logs at trace level, no matter what level they are coming from the SDK\n action: 'none' as any,\n code: 'CDK_SDK_I0000',\n message: format('[SDK %s] %s', level, formatSdkLoggerContent(content)),\n });\n }\n\n public trace(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('trace', ...content);\n }\n\n public debug(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('debug', ...content);\n }\n\n /**\n * Info is called mostly (exclusively?) for successful API calls\n *\n * Payload:\n *\n * (Note the input contains entire CFN templates, for example)\n *\n * ```\n * {\n * clientName: 'S3Client',\n * commandName: 'GetBucketLocationCommand',\n * input: {\n * Bucket: '.....',\n * ExpectedBucketOwner: undefined\n * },\n * output: { LocationConstraint: 'eu-central-1' },\n * metadata: {\n * httpStatusCode: 200,\n * requestId: '....',\n * extendedRequestId: '...',\n * cfId: undefined,\n * attempts: 1,\n * totalRetryDelay: 0\n * }\n * }\n * ```\n */\n public info(...content: any[]) {\n this.notify('info', ...content);\n }\n\n public warn(...content: any[]) {\n this.notify('warn', ...content);\n }\n\n /**\n * Error is called mostly (exclusively?) for failing API calls\n *\n * Payload (input would be the entire API call arguments).\n *\n * ```\n * {\n * clientName: 'STSClient',\n * commandName: 'GetCallerIdentityCommand',\n * input: {},\n * error: AggregateError [ECONNREFUSED]:\n * at internalConnectMultiple (node:net:1121:18)\n * at afterConnectMultiple (node:net:1688:7) {\n * code: 'ECONNREFUSED',\n * '$metadata': { attempts: 3, totalRetryDelay: 600 },\n * [errors]: [ [Error], [Error] ]\n * },\n * metadata: { attempts: 3, totalRetryDelay: 600 }\n * }\n * ```\n */\n public error(...content: any[]) {\n this.notify('error', ...content);\n }\n}\n\n/**\n * This can be anything.\n *\n * For debug, it seems to be mostly strings.\n * For info, it seems to be objects.\n *\n * Stringify and join without separator.\n */\nexport function formatSdkLoggerContent(content: any[]) {\n if (content.length === 1) {\n const apiFmt = formatApiCall(content[0]);\n if (apiFmt) {\n return apiFmt;\n }\n }\n return content.map((x) => typeof x === 'string' ? x : inspect(x)).join('');\n}\n\nfunction formatApiCall(content: any): string | undefined {\n if (!isSdkApiCallSuccess(content) && !isSdkApiCallError(content)) {\n return undefined;\n }\n\n const service = content.clientName.replace(/Client$/, '');\n const api = content.commandName.replace(/Command$/, '');\n\n const parts = [];\n if ((content.metadata?.attempts ?? 0) > 1) {\n parts.push(`[${content.metadata?.attempts} attempts, ${content.metadata?.totalRetryDelay}ms retry]`);\n }\n\n parts.push(`${service}.${api}(${JSON.stringify(content.input, replacerBufferWithInfo)})`);\n\n if (isSdkApiCallSuccess(content)) {\n parts.push('-> OK');\n } else {\n parts.push(`-> ${content.error}`);\n }\n\n return parts.join(' ');\n}\n\ninterface SdkApiCallBase {\n clientName: string;\n commandName: string;\n input: Record<string, unknown>;\n metadata?: {\n httpStatusCode?: number;\n requestId?: string;\n extendedRequestId?: string;\n cfId?: string;\n attempts?: number;\n totalRetryDelay?: number;\n };\n}\n\ntype SdkApiCallSuccess = SdkApiCallBase & { output: Record<string, unknown> };\ntype SdkApiCallError = SdkApiCallBase & { error: Error };\n\nfunction isSdkApiCallSuccess(x: any): x is SdkApiCallSuccess {\n return x && typeof x === 'object' && x.commandName && x.output;\n}\n\nfunction isSdkApiCallError(x: any): x is SdkApiCallError {\n return x && typeof x === 'object' && x.commandName && x.error;\n}\n", "import * as fs from 'fs-extra';\nimport { formatBytes } from './bytes';\nimport * as yaml_cfn from './yaml-cfn';\n\n/**\n * Stringify to YAML\n */\nexport function toYAML(obj: any): string {\n return yaml_cfn.serialize(obj);\n}\n\n/**\n * Parse either YAML or JSON\n */\nexport function deserializeStructure(str: string): any {\n return yaml_cfn.deserialize(str);\n}\n\n/**\n * Serialize to either YAML or JSON\n */\nexport function serializeStructure(object: any, json: boolean) {\n if (json) {\n return JSON.stringify(object, undefined, 2);\n } else {\n return toYAML(object);\n }\n}\n\n/**\n * Load a YAML or JSON file from disk\n */\nexport async function loadStructuredFile(fileName: string) {\n const contents = await fs.readFile(fileName, { encoding: 'utf-8' });\n return deserializeStructure(contents);\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n */\nexport function obscureTemplate(template: any = {}) {\n if (template.Rules) {\n // see https://github.com/aws/aws-cdk/issues/17942\n if (template.Rules.CheckBootstrapVersion) {\n if (Object.keys(template.Rules).length > 1) {\n delete template.Rules.CheckBootstrapVersion;\n } else {\n delete template.Rules;\n }\n }\n }\n\n return template;\n}\n\n/**\n * Detects a buffer that has been converted to a JSON-like object\n * In Node, `Buffer`s have `toJSON()` method that converts the buffer\n * into a JS object that can be JSON stringified.\n * Unfortunately this conversion happens before the replacer is called,\n * so normal means of detecting a `Buffer` objet don't work anymore.\n * @see https://github.com/nodejs/node-v0.x-archive/issues/5110\n */\nfunction isJsonBuffer(value: any): value is {\n type: 'Buffer';\n data: number[];\n} {\n return typeof value === 'object'\n && 'type' in value\n && value.type === 'Buffer'\n && 'data' in value\n && Array.isArray(value.data);\n}\n\n/**\n * A JSON.stringify() replacer that converts Buffers into a string with information\n * Use this if you plan to print out JSON stringified objects that may contain a Buffer.\n * Without this, large buffers (think: Megabytes) will completely fill up the output\n * and even crash the system.\n */\nexport function replacerBufferWithInfo(_key: any, value: any): any {\n if (isJsonBuffer(value)) {\n return `<Buffer: ${formatBytes(value.data.length)}>`;\n }\n return value;\n}\n", "/**\n * Format bytes as a human readable string\n *\n * @param bytes Number of bytes to format\n * @param decimals Number of decimal places to show (default 2)\n * @returns Formatted string with appropriate unit suffix\n */\nexport function formatBytes(bytes: number, decimals: number = 2): string {\n decimals = decimals < 0 ? 0 : decimals;\n\n if (bytes === 0) {\n return '0 Bytes';\n }\n\n const k = 1024;\n const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;\n}\n", "import * as yaml from 'yaml';\nimport * as yaml_cst from 'yaml/parse-cst';\nimport * as yaml_types from 'yaml/types';\n\n/**\n * Serializes the given data structure into valid YAML.\n *\n * @param obj the data structure to serialize\n * @returns a string containing the YAML representation of {@param obj}\n */\nexport function serialize(obj: any): string {\n const oldFold = yaml_types.strOptions.fold.lineWidth;\n try {\n yaml_types.strOptions.fold.lineWidth = 0;\n return yaml.stringify(obj, { schema: 'yaml-1.1' });\n } finally {\n yaml_types.strOptions.fold.lineWidth = oldFold;\n }\n}\n\n/**\n * Deserialize the YAML into the appropriate data structure.\n *\n * @param str the string containing YAML\n * @returns the data structure the YAML represents\n * (most often in case of CloudFormation, an object)\n */\nexport function deserialize(str: string): any {\n return parseYamlStrWithCfnTags(str);\n}\n\nfunction makeTagForCfnIntrinsic(intrinsicName: string, addFnPrefix: boolean): yaml_types.Schema.CustomTag {\n return {\n identify(value: any) {\n return typeof value === 'string';\n },\n tag: `!${intrinsicName}`,\n resolve: (_doc: yaml.Document, cstNode: yaml_cst.CST.Node) => {\n const ret: any = {};\n ret[addFnPrefix ? `Fn::${intrinsicName}` : intrinsicName] =\n // the +1 is to account for the ! the short form begins with\n parseYamlStrWithCfnTags(cstNode.toString().substring(intrinsicName.length + 1));\n return ret;\n },\n };\n}\n\nconst shortForms: yaml_types.Schema.CustomTag[] = [\n 'Base64', 'Cidr', 'FindInMap', 'GetAZs', 'ImportValue', 'Join', 'Sub',\n 'Select', 'Split', 'Transform', 'And', 'Equals', 'If', 'Not', 'Or', 'GetAtt',\n].map(name => makeTagForCfnIntrinsic(name, true)).concat(\n makeTagForCfnIntrinsic('Ref', false),\n makeTagForCfnIntrinsic('Condition', false),\n);\n\nfunction parseYamlStrWithCfnTags(text: string): any {\n return yaml.parse(text, {\n customTags: shortForms,\n schema: 'core',\n });\n}\n", "import * as os from 'os';\nimport * as fs_path from 'path';\nimport * as fs from 'fs-extra';\nimport { warning } from '../logging';\nimport { ToolkitError } from '../toolkit/error';\nimport * as util from '../util/objects';\n\nexport type SettingsMap = { [key: string]: any };\n\n/**\n * If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json\n */\nexport const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';\n\n/**\n * A single bag of settings\n */\nexport class Settings {\n public static mergeAll(...settings: Settings[]): Settings {\n let ret = new Settings();\n for (const setting of settings) {\n ret = ret.merge(setting);\n }\n return ret;\n }\n\n constructor(\n private settings: SettingsMap = {},\n public readonly readOnly = false,\n ) {\n }\n\n public async load(fileName: string): Promise<this> {\n if (this.readOnly) {\n throw new ToolkitError(\n `Can't load ${fileName}: settings object is readonly`,\n );\n }\n this.settings = {};\n\n const expanded = expandHomeDir(fileName);\n if (await fs.pathExists(expanded)) {\n this.settings = await fs.readJson(expanded);\n }\n\n // See https://github.com/aws/aws-cdk/issues/59\n this.prohibitContextKey('default-account', fileName);\n this.prohibitContextKey('default-region', fileName);\n this.warnAboutContextKey('aws:', fileName);\n\n return this;\n }\n\n public async save(fileName: string): Promise<this> {\n const expanded = expandHomeDir(fileName);\n await fs.writeJson(expanded, stripTransientValues(this.settings), {\n spaces: 2,\n });\n return this;\n }\n\n public get all(): any {\n return this.get([]);\n }\n\n public merge(other: Settings): Settings {\n return new Settings(util.deepMerge(this.settings, other.settings));\n }\n\n public subSettings(keyPrefix: string[]) {\n return new Settings(this.get(keyPrefix) || {}, false);\n }\n\n public makeReadOnly(): Settings {\n return new Settings(this.settings, true);\n }\n\n public clear() {\n if (this.readOnly) {\n throw new ToolkitError('Cannot clear(): settings are readonly');\n }\n this.settings = {};\n }\n\n public get empty(): boolean {\n return Object.keys(this.settings).length === 0;\n }\n\n public get(path: string[]): any {\n return util.deepClone(util.deepGet(this.settings, path));\n }\n\n public set(path: string[], value: any): Settings {\n if (this.readOnly) {\n throw new ToolkitError(`Can't set ${path}: settings object is readonly`);\n }\n if (path.length === 0) {\n // deepSet can't handle this case\n this.settings = value;\n } else {\n util.deepSet(this.settings, path, value);\n }\n return this;\n }\n\n public unset(path: string[]) {\n this.set(path, undefined);\n }\n\n private prohibitContextKey(key: string, fileName: string) {\n if (!this.settings.context) {\n return;\n }\n if (key in this.settings.context) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `The 'context.${key}' key was found in ${fs_path.resolve(\n fileName,\n )}, but it is no longer supported. Please remove it.`,\n );\n }\n }\n\n private warnAboutContextKey(prefix: string, fileName: string) {\n if (!this.settings.context) {\n return;\n }\n for (const contextKey of Object.keys(this.settings.context)) {\n if (contextKey.startsWith(prefix)) {\n // eslint-disable-next-line max-len\n warning(\n `A reserved context key ('context.${prefix}') key was found in ${fs_path.resolve(\n fileName,\n )}, it might cause surprising behavior and should be removed.`,\n );\n }\n }\n }\n}\n\nfunction expandHomeDir(x: string) {\n if (x.startsWith('~')) {\n return fs_path.join(os.homedir(), x.slice(1));\n }\n return x;\n}\n\n/**\n * Return all context value that are not transient context values\n */\nfunction stripTransientValues(obj: { [key: string]: any }) {\n const ret: any = {};\n for (const [key, value] of Object.entries(obj)) {\n if (!isTransientValue(value)) {\n ret[key] = value;\n }\n }\n return ret;\n}\n\n/**\n * Return whether the given value is a transient context value\n *\n * Values that are objects with a magic key set to a truthy value are considered transient.\n */\nfunction isTransientValue(value: any) {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as any)[TRANSIENT_CONTEXT_KEY]\n );\n}\n", "/**\n * Type of a map mapping strings to some arbitrary type\n *\n * Name is not ideal, but:\n *\n * - Cannot call it Object, that already means something.\n * - Cannot call it Dict or Dictionary, since in other languages\n * those also allow specifying the key type.\n */\nexport type Obj<T> = {[key: string]: T};\n\n/**\n * Return whether the given value is an object\n *\n * Even though arrays technically are objects, we usually want to treat them differently,\n * so we return false in those cases.\n */\nexport function isObject(x: any): x is Obj<any> {\n return x !== null && typeof x === 'object' && !isArray(x);\n}\n\n/**\n * Return whether the given value is an array\n */\nexport const isArray = Array.isArray;\n\n/**\n * Return the value of the first argument if it's not undefined, otherwise the default\n */\nexport function ifDefined<T>(x: T | undefined, def: T): T {\n return typeof x !== 'undefined' ? x : def;\n}\n", "import { isArray, isObject, Obj } from './types';\nimport { ToolkitError } from '../toolkit/error';\n\n/**\n * Return a new object by adding missing keys into another object\n */\nexport function applyDefaults(hash: any, defaults: any) {\n const result: any = { };\n\n Object.keys(hash).forEach(k => result[k] = hash[k]);\n\n Object.keys(defaults)\n .filter(k => !(k in result))\n .forEach(k => result[k] = defaults[k]);\n\n return result;\n}\n\n/**\n * Return whether the given parameter is an empty object or empty list.\n */\nexport function isEmpty(x: any) {\n if (x == null) {\n return false;\n }\n if (isArray(x)) {\n return x.length === 0;\n }\n return Object.keys(x).length === 0;\n}\n\n/**\n * Deep clone a tree of objects, lists or scalars\n *\n * Does not support cycles.\n */\nexport function deepClone(x: any): any {\n if (typeof x === 'undefined') {\n return undefined;\n }\n if (x === null) {\n return null;\n }\n if (isArray(x)) {\n return x.map(deepClone);\n }\n if (isObject(x)) {\n return makeObject(mapObject(x, (k, v) => [k, deepClone(v)] as [string, any]));\n }\n return x;\n}\n\n/**\n * Map over an object, treating it as a dictionary\n */\nexport function mapObject<T, U>(x: Obj<T>, fn: (key: string, value: T) => U): U[] {\n const ret: U[] = [];\n Object.keys(x).forEach(key => {\n ret.push(fn(key, x[key]));\n });\n return ret;\n}\n\n/**\n * Construct an object from a list of (k, v) pairs\n */\nexport function makeObject<T>(pairs: Array<[string, T]>): Obj<T> {\n const ret: Obj<T> = {};\n for (const pair of pairs) {\n ret[pair[0]] = pair[1];\n }\n return ret;\n}\n\n/**\n * Deep get a value from a tree of nested objects\n *\n * Returns undefined if any part of the path was unset or\n * not an object.\n */\nexport function deepGet(x: any, path: string[]): any {\n path = path.slice();\n\n while (path.length > 0 && isObject(x)) {\n const key = path.shift()!;\n x = x[key];\n }\n return path.length === 0 ? x : undefined;\n}\n\n/**\n * Deep set a value in a tree of nested objects\n *\n * Throws an error if any part of the path is not an object.\n */\nexport function deepSet(x: any, path: string[], value: any) {\n path = path.slice();\n\n if (path.length === 0) {\n throw new ToolkitError('Path may not be empty');\n }\n\n while (path.length > 1 && isObject(x)) {\n const key = path.shift()!;\n if (!(key in x)) {\n x[key] = {};\n }\n x = x[key];\n }\n\n if (!isObject(x)) {\n throw new ToolkitError(`Expected an object, got '${x}'`);\n }\n\n if (value !== undefined) {\n x[path[0]] = value;\n } else {\n delete x[path[0]];\n }\n}\n\n/**\n * Recursively merge objects together\n *\n * The leftmost object is mutated and returned. Arrays are not merged\n * but overwritten just like scalars.\n *\n * If an object is merged into a non-object, the non-object is lost.\n */\nexport function deepMerge(...objects: Array<Obj<any> | undefined>) {\n function mergeOne(target: Obj<any>, source: Obj<any>) {\n for (const key of Object.keys(source)) {\n if (key === '__proto__' || key === 'constructor') {\n continue;\n }\n\n const value = source[key];\n\n if (isObject(value)) {\n if (!isObject(target[key])) {\n target[key] = {};\n } // Overwrite on purpose\n mergeOne(target[key], value);\n } else if (typeof value !== 'undefined') {\n target[key] = value;\n }\n }\n }\n\n const others = objects.filter(x => x != null) as Array<Obj<any>>;\n\n if (others.length === 0) {\n return {};\n }\n const into = others.splice(0, 1)[0];\n\n others.forEach(other => mergeOne(into, other));\n return into;\n}\n\n/**\n * Splits the given object into two, such that:\n *\n * 1. The size of the first object (after stringified in UTF-8) is less than or equal to the provided size limit.\n * 2. Merging the two objects results in the original one.\n */\nexport function splitBySize(data: any, maxSizeBytes: number): [any, any] {\n if (maxSizeBytes < 2) {\n // It's impossible to fit anything in the first object\n return [undefined, data];\n }\n const entries = Object.entries(data);\n return recurse(0, 0);\n\n function recurse(index: number, runningTotalSize: number): [any, any] {\n if (index >= entries.length) {\n // Everything fits in the first object\n return [data, undefined];\n }\n\n const size = runningTotalSize + entrySize(entries[index]);\n return (size > maxSizeBytes) ? cutAt(index) : recurse(index + 1, size);\n }\n\n function entrySize(entry: [string, unknown]) {\n return Buffer.byteLength(JSON.stringify(Object.fromEntries([entry])));\n }\n\n function cutAt(index: number): [any, any] {\n return [\n Object.fromEntries(entries.slice(0, index)),\n Object.fromEntries(entries.slice(index)),\n ];\n }\n}\n", "import { Settings } from './settings';\nimport { ToolkitError } from '../toolkit/error';\n\nexport { TRANSIENT_CONTEXT_KEY } from './settings';\nexport const PROJECT_CONTEXT = 'cdk.context.json';\n\ninterface ContextBag {\n /**\n * The file name of the context. Will be used to potentially\n * save new context back to the original file.\n */\n fileName?: string;\n\n /**\n * The context values.\n */\n bag: Settings;\n}\n\n/**\n * Class that supports overlaying property bags\n *\n * Reads come from the first property bag that can has the given key,\n * writes go to the first property bag that is not readonly. A write\n * will remove the value from all property bags after the first\n * writable one.\n */\nexport class Context {\n private readonly bags: Settings[];\n private readonly fileNames: (string | undefined)[];\n\n constructor(...bags: ContextBag[]) {\n this.bags = bags.length > 0 ? bags.map((b) => b.bag) : [new Settings()];\n this.fileNames =\n bags.length > 0 ? bags.map((b) => b.fileName) : ['default'];\n }\n\n public get keys(): string[] {\n return Object.keys(this.all);\n }\n\n public has(key: string) {\n return this.keys.indexOf(key) > -1;\n }\n\n public get all(): { [key: string]: any } {\n let ret = new Settings();\n\n // In reverse order so keys to the left overwrite keys to the right of them\n for (const bag of [...this.bags].reverse()) {\n ret = ret.merge(bag);\n }\n\n return ret.all;\n }\n\n public get(key: string): any {\n for (const bag of this.bags) {\n const v = bag.get([key]);\n if (v !== undefined) {\n return v;\n }\n }\n return undefined;\n }\n\n public set(key: string, value: any) {\n for (const bag of this.bags) {\n if (bag.readOnly) {\n continue;\n }\n\n // All bags past the first one have the value erased\n bag.set([key], value);\n value = undefined;\n }\n }\n\n public unset(key: string) {\n this.set(key, undefined);\n }\n\n public clear() {\n for (const key of this.keys) {\n this.unset(key);\n }\n }\n\n /**\n * Save a specific context file\n */\n public async save(fileName: string): Promise<this> {\n const index = this.fileNames.indexOf(fileName);\n\n // File not found, don't do anything in this scenario\n if (index === -1) {\n return this;\n }\n\n const bag = this.bags[index];\n if (bag.readOnly) {\n throw new ToolkitError(`Context file ${fileName} is read only!`);\n }\n\n await bag.save(fileName);\n return this;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { SSMPARAM_NO_INVALIDATE } from '@aws-cdk/cx-api';\nimport {\n ChangeSetStatus,\n type DescribeChangeSetCommandOutput,\n type Parameter,\n type ResourceIdentifierSummary,\n type ResourceToImport,\n type Stack,\n type Tag,\n} from '@aws-sdk/client-cloudformation';\nimport { AssetManifest, FileManifestEntry } from 'cdk-assets';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { Deployments } from './deployments';\nimport { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { deserializeStructure } from '../../util/serialize';\nimport type { ICloudFormationClient, SdkProvider } from '../aws-auth';\nimport { StackStatus } from '../stack-events';\nimport { makeBodyParameter, TemplateBodyParameter } from '../util/template-body-parameter';\n\nexport type ResourcesToImport = ResourceToImport[];\nexport type ResourceIdentifierSummaries = ResourceIdentifierSummary[];\nexport type ResourceIdentifierProperties = Record<string, string>;\n\nexport type Template = {\n Parameters?: Record<string, TemplateParameter>;\n [key: string]: any;\n};\n\ninterface TemplateParameter {\n Type: string;\n Default?: any;\n Description?: string;\n [key: string]: any;\n}\n\n/**\n * Represents an (existing) Stack in CloudFormation\n *\n * Bundle and cache some information that we need during deployment (so we don't have to make\n * repeated calls to CloudFormation).\n */\nexport class CloudFormationStack {\n public static async lookup(\n cfn: ICloudFormationClient,\n stackName: string,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<CloudFormationStack> {\n try {\n const response = await cfn.describeStacks({ StackName: stackName });\n return new CloudFormationStack(cfn, stackName, response.Stacks && response.Stacks[0], retrieveProcessedTemplate);\n } catch (e: any) {\n if (e.name === 'ValidationError' && formatErrorMessage(e) === `Stack with id ${stackName} does not exist`) {\n return new CloudFormationStack(cfn, stackName, undefined);\n }\n throw e;\n }\n }\n\n /**\n * Return a copy of the given stack that does not exist\n *\n * It's a little silly that it needs arguments to do that, but there we go.\n */\n public static doesNotExist(cfn: ICloudFormationClient, stackName: string) {\n return new CloudFormationStack(cfn, stackName);\n }\n\n /**\n * From static information (for testing)\n */\n public static fromStaticInformation(cfn: ICloudFormationClient, stackName: string, stack: Stack) {\n return new CloudFormationStack(cfn, stackName, stack);\n }\n\n private _template: any;\n\n protected constructor(\n private readonly cfn: ICloudFormationClient,\n public readonly stackName: string,\n private readonly stack?: Stack,\n private readonly retrieveProcessedTemplate: boolean = false,\n ) {\n }\n\n /**\n * Retrieve the stack's deployed template\n *\n * Cached, so will only be retrieved once. Will return an empty\n * structure if the stack does not exist.\n */\n public async template(): Promise<Template> {\n if (!this.exists) {\n return {};\n }\n\n if (this._template === undefined) {\n const response = await this.cfn.getTemplate({\n StackName: this.stackName,\n TemplateStage: this.retrieveProcessedTemplate ? 'Processed' : 'Original',\n });\n this._template = (response.TemplateBody && deserializeStructure(response.TemplateBody)) || {};\n }\n return this._template;\n }\n\n /**\n * Whether the stack exists\n */\n public get exists() {\n return this.stack !== undefined;\n }\n\n /**\n * The stack's ID\n *\n * Throws if the stack doesn't exist.\n */\n public get stackId() {\n this.assertExists();\n return this.stack!.StackId!;\n }\n\n /**\n * The stack's current outputs\n *\n * Empty object if the stack doesn't exist\n */\n public get outputs(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const result: { [name: string]: string } = {};\n (this.stack!.Outputs || []).forEach((output) => {\n result[output.OutputKey!] = output.OutputValue!;\n });\n return result;\n }\n\n /**\n * The stack's status\n *\n * Special status NOT_FOUND if the stack does not exist.\n */\n public get stackStatus(): StackStatus {\n if (!this.exists) {\n return new StackStatus('NOT_FOUND', 'Stack not found during lookup');\n }\n return StackStatus.fromStackDescription(this.stack!);\n }\n\n /**\n * The stack's current tags\n *\n * Empty list if the stack does not exist\n */\n public get tags(): Tag[] {\n return this.stack?.Tags || [];\n }\n\n /**\n * SNS Topic ARNs that will receive stack events.\n *\n * Empty list if the stack does not exist\n */\n public get notificationArns(): string[] {\n return this.stack?.NotificationARNs ?? [];\n }\n\n /**\n * Return the names of all current parameters to the stack\n *\n * Empty list if the stack does not exist.\n */\n public get parameterNames(): string[] {\n return Object.keys(this.parameters);\n }\n\n /**\n * Return the names and values of all current parameters to the stack\n *\n * Empty object if the stack does not exist.\n */\n public get parameters(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const ret: Record<string, string> = {};\n for (const param of this.stack!.Parameters ?? []) {\n ret[param.ParameterKey!] = param.ResolvedValue ?? param.ParameterValue!;\n }\n return ret;\n }\n\n /**\n * Return the termination protection of the stack\n */\n public get terminationProtection(): boolean | undefined {\n return this.stack?.EnableTerminationProtection;\n }\n\n private assertExists() {\n if (!this.exists) {\n throw new ToolkitError(`No stack named '${this.stackName}'`);\n }\n }\n}\n\n/**\n * Describe a changeset in CloudFormation, regardless of its current state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the change set description.\n *\n * @returns CloudFormation information about the ChangeSet\n */\nasync function describeChangeSet(\n cfn: ICloudFormationClient,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n const response = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n\n // If fetchAll is true, traverse all pages from the change set description.\n while (fetchAll && response.NextToken != null) {\n const nextPage = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: response.ChangeSetId ?? changeSetName,\n NextToken: response.NextToken,\n });\n\n // Consolidate the changes\n if (nextPage.Changes != null) {\n response.Changes = response.Changes != null ? response.Changes.concat(nextPage.Changes) : nextPage.Changes;\n }\n\n // Forward the new NextToken\n response.NextToken = nextPage.NextToken;\n }\n\n return response;\n}\n\n/**\n * Waits for a function to return non-+undefined+ before returning.\n *\n * @param valueProvider a function that will return a value that is not +undefined+ once the wait should be over\n * @param timeout the time to wait between two calls to +valueProvider+\n *\n * @returns the value that was returned by +valueProvider+\n */\nasync function waitFor<T>(\n valueProvider: () => Promise<T | null | undefined>,\n timeout: number = 5000,\n): Promise<T | undefined> {\n while (true) {\n const result = await valueProvider();\n if (result === null) {\n return undefined;\n } else if (result !== undefined) {\n return result;\n }\n await new Promise((cb) => setTimeout(cb, timeout));\n }\n}\n\n/**\n * Waits for a ChangeSet to be available for triggering a StackUpdate.\n *\n * Will return a changeset that is either ready to be executed or has no changes.\n * Will throw in other cases.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack that the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the ChangeSet before returning.\n *\n * @returns the CloudFormation description of the ChangeSet\n */\nexport async function waitForChangeSet(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n await ioHost.notify(debug(action, format('Waiting for changeset %s on stack %s to finish creating...', changeSetName, stackName)));\n const ret = await waitFor(async () => {\n const description = await describeChangeSet(cfn, stackName, changeSetName, {\n fetchAll,\n });\n // The following doesn't use a switch because tsc will not allow fall-through, UNLESS it is allows\n // EVERYWHERE that uses this library directly or indirectly, which is undesirable.\n if (description.Status === 'CREATE_PENDING' || description.Status === 'CREATE_IN_PROGRESS') {\n await ioHost.notify(debug(action, format('Changeset %s on stack %s is still creating', changeSetName, stackName)));\n return undefined;\n }\n\n if (description.Status === ChangeSetStatus.CREATE_COMPLETE || changeSetHasNoChanges(description)) {\n return description;\n }\n\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `Failed to create ChangeSet ${changeSetName} on ${stackName}: ${description.Status || 'NO_STATUS'}, ${description.StatusReason || 'no reason provided'}`,\n );\n });\n\n if (!ret) {\n throw new ToolkitError('Change set took too long to be created; aborting');\n }\n\n return ret;\n}\n\nexport type PrepareChangeSetOptions = {\n stack: cxapi.CloudFormationStackArtifact;\n deployments: Deployments;\n uuid: string;\n willExecute: boolean;\n sdkProvider: SdkProvider;\n stream: NodeJS.WritableStream;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourcesToImport;\n}\n\nexport type CreateChangeSetOptions = {\n cfn: ICloudFormationClient;\n changeSetName: string;\n willExecute: boolean;\n exists: boolean;\n uuid: string;\n stack: cxapi.CloudFormationStackArtifact;\n bodyParameter: TemplateBodyParameter;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourceToImport[];\n role?: string;\n};\n\n/**\n * Create a changeset for a diff operation\n */\nexport async function createDiffChangeSet(\n { ioHost, action }: IoMessaging,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n // `options.stack` has been modified to include any nested stack templates directly inline with its own template, under a special `NestedTemplate` property.\n // Thus the parent template's Resources section contains the nested template's CDK metadata check, which uses Fn::Equals.\n // This causes CreateChangeSet to fail with `Template Error: Fn::Equals cannot be partially collapsed`.\n for (const resource of Object.values(options.stack.template.Resources ?? {})) {\n if ((resource as any).Type === 'AWS::CloudFormation::Stack') {\n await ioHost.notify(debug(action, 'This stack contains one or more nested stacks, falling back to template-only diff...'));\n\n return undefined;\n }\n }\n\n return uploadBodyParameterAndCreateChangeSet({ ioHost, action }, options);\n}\n\n/**\n * Returns all file entries from an AssetManifestArtifact that look like templates.\n *\n * This is used in the `uploadBodyParameterAndCreateChangeSet` function to find\n * all template asset files to build and publish.\n *\n * Returns a tuple of [AssetManifest, FileManifestEntry[]]\n */\nfunction templatesFromAssetManifestArtifact(\n artifact: cxapi.AssetManifestArtifact,\n): [AssetManifest, FileManifestEntry[]] {\n const assets: FileManifestEntry[] = [];\n const fileName = artifact.file;\n const assetManifest = AssetManifest.fromFile(fileName);\n\n assetManifest.entries.forEach((entry) => {\n if (entry.type === 'file') {\n const source = (entry as FileManifestEntry).source;\n if (source.path && source.path.endsWith('.template.json')) {\n assets.push(entry as FileManifestEntry);\n }\n }\n });\n return [assetManifest, assets];\n}\n\nasync function uploadBodyParameterAndCreateChangeSet(\n { ioHost, action }: IoMessaging,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n try {\n await uploadStackTemplateAssets(options.stack, options.deployments);\n const env = await options.deployments.envs.accessStackForMutableStackOperations(options.stack);\n\n const bodyParameter = await makeBodyParameter(\n options.stack,\n env.resolvedEnvironment,\n new AssetManifestBuilder(),\n env.resources,\n );\n const cfn = env.sdk.cloudFormation();\n const exists = (await CloudFormationStack.lookup(cfn, options.stack.stackName, false)).exists;\n\n const executionRoleArn = await env.replacePlaceholders(options.stack.cloudFormationExecutionRoleArn);\n options.stream.write(\n 'Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)\\n',\n );\n\n return await createChangeSet({ ioHost, action }, {\n cfn,\n changeSetName: 'cdk-diff-change-set',\n stack: options.stack,\n exists,\n uuid: options.uuid,\n willExecute: options.willExecute,\n bodyParameter,\n parameters: options.parameters,\n resourcesToImport: options.resourcesToImport,\n role: executionRoleArn,\n });\n } catch (e: any) {\n await ioHost.notify(debug(action, e));\n options.stream.write(\n 'Could not create a change set, will base the diff on template differences (run again with -v to see the reason)\\n',\n );\n\n return undefined;\n }\n}\n\n/**\n * Uploads the assets that look like templates for this CloudFormation stack\n *\n * This is necessary for any CloudFormation call that needs the template, it may need\n * to be uploaded to an S3 bucket first. We have to follow the instructions in the\n * asset manifest, because technically that is the only place that knows about\n * bucket and assumed roles and such.\n */\nexport async function uploadStackTemplateAssets(stack: cxapi.CloudFormationStackArtifact, deployments: Deployments) {\n for (const artifact of stack.dependencies) {\n // Skip artifact if it is not an Asset Manifest Artifact\n if (!cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n continue;\n }\n\n const [assetManifest, file_entries] = templatesFromAssetManifestArtifact(artifact);\n for (const entry of file_entries) {\n await deployments.buildSingleAsset(artifact, assetManifest, entry, {\n stack,\n });\n await deployments.publishSingleAsset(assetManifest, entry, {\n stack,\n });\n }\n }\n}\n\nexport async function createChangeSet(\n { ioHost, action }: IoMessaging,\n options: CreateChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput> {\n await cleanupOldChangeset(options.cfn, { ioHost, action }, options.changeSetName, options.stack.stackName);\n\n await ioHost.notify(debug(action, `Attempting to create ChangeSet with name ${options.changeSetName} for stack ${options.stack.stackName}`));\n\n const templateParams = TemplateParameters.fromTemplate(options.stack.template);\n const stackParams = templateParams.supplyAll(options.parameters);\n\n const changeSet = await options.cfn.createChangeSet({\n StackName: options.stack.stackName,\n ChangeSetName: options.changeSetName,\n ChangeSetType: options.resourcesToImport ? 'IMPORT' : options.exists ? 'UPDATE' : 'CREATE',\n Description: `CDK Changeset for diff ${options.uuid}`,\n ClientToken: `diff${options.uuid}`,\n TemplateURL: options.bodyParameter.TemplateURL,\n TemplateBody: options.bodyParameter.TemplateBody,\n Parameters: stackParams.apiParameters,\n ResourcesToImport: options.resourcesToImport,\n RoleARN: options.role,\n Tags: toCfnTags(options.stack.tags),\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n });\n\n await ioHost.notify(debug(action, format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n const createdChangeSet = await waitForChangeSet(options.cfn, { ioHost, action }, options.stack.stackName, options.changeSetName, {\n fetchAll: options.willExecute,\n });\n await cleanupOldChangeset(options.cfn, { ioHost, action }, options.changeSetName, options.stack.stackName);\n\n return createdChangeSet;\n}\n\nfunction toCfnTags(tags: { [id: string]: string }): Tag[] {\n return Object.entries(tags).map(([k, v]) => ({\n Key: k,\n Value: v,\n }));\n}\n\nasync function cleanupOldChangeset(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n changeSetName: string,\n stackName: string,\n) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await ioHost.notify(debug(action, `Removing existing change set with name ${changeSetName} if it exists`));\n await cfn.deleteChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n}\n\n/**\n * Return true if the given change set has no changes\n *\n * This must be determined from the status, not the 'Changes' array on the\n * object; the latter can be empty because no resources were changed, but if\n * there are changes to Outputs, the change set can still be executed.\n */\nexport function changeSetHasNoChanges(description: DescribeChangeSetCommandOutput) {\n const noChangeErrorPrefixes = [\n // Error message for a regular template\n \"The submitted information didn't contain changes.\",\n // Error message when a Transform is involved (see #10650)\n 'No updates are to be performed.',\n ];\n\n return (\n description.Status === 'FAILED' && noChangeErrorPrefixes.some((p) => (description.StatusReason ?? '').startsWith(p))\n );\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after a delete operation is issued.\n *\n * Fails if the stack is in a FAILED state. Will not fail if the stack was\n * already deleted.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after a delete\n *\n * @returns the CloudFormation description of the stabilized stack after the delete attempt\n */\nexport async function waitForStackDelete(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n if (status.isFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} is in a failed state. You may need to delete it from the AWS console : ${status}`,\n );\n } else if (status.isDeleted) {\n return undefined;\n }\n return stack;\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after an update/create operation is issued.\n *\n * Fails if the stack is in a FAILED state, ROLLBACK state, or DELETED state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after an update\n *\n * @returns the CloudFormation description of the stabilized stack after the update attempt\n */\nexport async function waitForStackDeploy(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n\n if (status.isCreationFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} failed creation, it may need to be manually deleted from the AWS console: ${status}`,\n );\n } else if (!status.isDeploySuccess) {\n throw new ToolkitError(`The stack named ${stackName} failed to deploy: ${status}`);\n }\n\n return stack;\n}\n\n/**\n * Wait for a stack to become stable (no longer _IN_PROGRESS), returning it\n */\nexport async function stabilizeStack(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging, stackName: string,\n) {\n await ioHost.notify(debug(action, format('Waiting for stack %s to finish creating or updating...', stackName)));\n return waitFor(async () => {\n const stack = await CloudFormationStack.lookup(cfn, stackName);\n if (!stack.exists) {\n await ioHost.notify(debug(action, format('Stack %s does not exist', stackName)));\n return null;\n }\n const status = stack.stackStatus;\n if (status.isInProgress) {\n await ioHost.notify(debug(action, format('Stack %s has an ongoing operation in progress and is not stable (%s)', stackName, status)));\n return undefined;\n } else if (status.isReviewInProgress) {\n // This may happen if a stack creation operation is interrupted before the ChangeSet execution starts. Recovering\n // from this would requiring manual intervention (deleting or executing the pending ChangeSet), and failing to do\n // so will result in an endless wait here (the ChangeSet wont delete or execute itself). Instead of blocking\n // \"forever\" we proceed as if the stack was existing and stable. If there is a concurrent operation that just\n // hasn't finished proceeding just yet, either this operation or the concurrent one may fail due to the other one\n // having made progress. Which is fine. I guess.\n await ioHost.notify(debug(action, format('Stack %s is in REVIEW_IN_PROGRESS state. Considering this is a stable status (%s)', stackName, status)));\n }\n\n return stack;\n });\n}\n\n/**\n * The set of (formal) parameters that have been declared in a template\n */\nexport class TemplateParameters {\n public static fromTemplate(template: Template) {\n return new TemplateParameters(template.Parameters || {});\n }\n\n constructor(private readonly params: Record<string, TemplateParameter>) {\n }\n\n /**\n * Calculate stack parameters to pass from the given desired parameter values\n *\n * Will throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public supplyAll(updates: Record<string, string | undefined>): ParameterValues {\n return new ParameterValues(this.params, updates);\n }\n\n /**\n * From the template, the given desired values and the current values, calculate the changes to the stack parameters\n *\n * Will take into account parameters already set on the template (will emit\n * 'UsePreviousValue: true' for those unless the value is changed), and will\n * throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public updateExisting(\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string>,\n ): ParameterValues {\n return new ParameterValues(this.params, updates, previousValues);\n }\n}\n\n/**\n * The set of parameters we're going to pass to a Stack\n */\nexport class ParameterValues {\n public readonly values: Record<string, string> = {};\n public readonly apiParameters: Parameter[] = [];\n\n constructor(\n private readonly formalParams: Record<string, TemplateParameter>,\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string> = {},\n ) {\n const missingRequired = new Array<string>();\n\n for (const [key, formalParam] of Object.entries(this.formalParams)) {\n // Check updates first, then use the previous value (if available), then use\n // the default (if available).\n //\n // If we don't find a parameter value using any of these methods, then that's an error.\n const updatedValue = updates[key];\n if (updatedValue !== undefined) {\n this.values[key] = updatedValue;\n this.apiParameters.push({\n ParameterKey: key,\n ParameterValue: updates[key],\n });\n continue;\n }\n\n if (key in previousValues) {\n this.values[key] = previousValues[key];\n this.apiParameters.push({ ParameterKey: key, UsePreviousValue: true });\n continue;\n }\n\n if (formalParam.Default !== undefined) {\n this.values[key] = formalParam.Default;\n continue;\n }\n\n // Oh no\n missingRequired.push(key);\n }\n\n if (missingRequired.length > 0) {\n throw new ToolkitError(`The following CloudFormation Parameters are missing a value: ${missingRequired.join(', ')}`);\n }\n\n // Just append all supplied overrides that aren't really expected (this\n // will fail CFN but maybe people made typos that they want to be notified\n // of)\n const unknownParam = ([key, _]: [string, any]) => this.formalParams[key] === undefined;\n const hasValue = ([_, value]: [string, any]) => !!value;\n for (const [key, value] of Object.entries(updates).filter(unknownParam).filter(hasValue)) {\n this.values[key] = value!;\n this.apiParameters.push({ ParameterKey: key, ParameterValue: value });\n }\n }\n\n /**\n * Whether this set of parameter updates will change the actual stack values\n */\n public hasChanges(currentValues: Record<string, string>): ParameterChanges {\n // If any of the parameters are SSM parameters, deploying must always happen\n // because we can't predict what the values will be. We will allow some\n // parameters to opt out of this check by having a magic string in their description.\n if (\n Object.values(this.formalParams).some(\n (p) => p.Type.startsWith('AWS::SSM::Parameter::') && !p.Description?.includes(SSMPARAM_NO_INVALIDATE),\n )\n ) {\n return 'ssm';\n }\n\n // Otherwise we're dirty if:\n // - any of the existing values are removed, or changed\n if (Object.entries(currentValues).some(([key, value]) => !(key in this.values) || value !== this.values[key])) {\n return true;\n }\n\n // - any of the values we're setting are new\n if (Object.keys(this.values).some((key) => !(key in currentValues))) {\n return true;\n }\n\n return false;\n }\n}\n\nexport type ParameterChanges = boolean | 'ssm';\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport { AssetManifest } from 'cdk-assets';\n\nexport class AssetManifestBuilder {\n private readonly manifest: cxschema.AssetManifest = {\n version: cxschema.Manifest.version(),\n files: {},\n dockerImages: {},\n };\n\n public addFileAsset(id: string, source: cxschema.FileSource, destination: cxschema.FileDestination) {\n this.manifest.files![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public addDockerImageAsset(id: string, source: cxschema.DockerImageSource, destination: cxschema.DockerImageDestination) {\n this.manifest.dockerImages![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public toManifest(directory: string): AssetManifest {\n return new AssetManifest(directory, this.manifest);\n }\n}\n", "// This file is a backport from @aws-cdk/toolkit.\n// The CLI cannot depend on the toolkit yet, because the toolkit currently depends on the CLI.\n// Once we have complete the repo split, we will create a temporary, private library package\n// for all code that is shared between CLI and toolkit. This is where this file will then live.\nimport { IoMessage, IoMessageCode, IoMessageCodeCategory, IoMessageLevel, ToolkitAction } from '../toolkit/cli-io-host';\n\ntype Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;\ntype SimplifiedMessage<T> = Omit<IoMessage<T>, 'time'>;\n\n/**\n * Internal helper that processes log inputs into a consistent format.\n * Handles string interpolation, format strings, and object parameter styles.\n * Applies optional styling and prepares the final message for logging.\n */\nexport function formatMessage<T>(msg: Optional<SimplifiedMessage<T>, 'code'>, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessage<T> {\n return {\n time: new Date(),\n level: msg.level,\n action: msg.action,\n code: msg.code ?? defaultMessageCode(msg.level, category),\n message: msg.message,\n data: msg.data,\n };\n}\n\n/**\n * Build a message code from level and category. The code must be valid for this function to pass.\n * Otherwise it returns a ToolkitError.\n */\nfunction defaultMessageCode(level: IoMessageLevel, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessageCode {\n const levelIndicator = level === 'error' ? 'E' :\n level === 'warn' ? 'W' :\n 'I';\n return `CDK_${category}_${levelIndicator}0000`;\n}\n\n/**\n * Creates an error level message.\n * Errors must always have a unique code.\n */\nexport const error = <T>(action: ToolkitAction, message: string, code: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'error',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a result level message and represents the most important message for a given action.\n *\n * They should be used sparsely, with an action usually having no or exactly one result.\n * However actions that operate on Cloud Assemblies might include a result per Stack.\n * Unlike other messages, results must always have a code and a payload.\n */\nexport const result = <T>(action: ToolkitAction, message: string, code: IoMessageCode, payload: T) => {\n return formatMessage({\n level: 'result',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a warning level message.\n */\nexport const warn = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'warn',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates an info level message.\n */\nexport const info = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'info',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a debug level message.\n */\nexport const debug = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'debug',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a trace level message.\n */\nexport const trace = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'trace',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n", "import * as util from 'util';\nimport { ArtifactMetadataEntryType, type MetadataEntry } from '@aws-cdk/cloud-assembly-schema';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { ResourceEvent, StackEventPoller } from './stack-event-poller';\nimport { error, info } from '../../logging';\nimport { CliIoHost, IoMessageLevel } from '../../toolkit/cli-io-host';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { RewritableBlock } from './display';\n\nexport interface StackActivity extends ResourceEvent {\n readonly metadata?: ResourceMetadata;\n}\n\nexport interface ResourceMetadata {\n entry: MetadataEntry;\n constructPath: string;\n}\n\n/**\n * Supported display modes for stack deployment activity\n */\nexport enum StackActivityProgress {\n /**\n * Displays a progress bar with only the events for the resource currently being deployed\n */\n BAR = 'bar',\n\n /**\n * Displays complete history with all CloudFormation stack events\n */\n EVENTS = 'events',\n}\n\nexport interface WithDefaultPrinterProps {\n /**\n * Total number of resources to update\n *\n * Used to calculate a progress bar.\n *\n * @default - No progress reporting.\n */\n readonly resourcesTotal?: number;\n\n /**\n * The log level that was requested in the CLI\n *\n * If verbose or trace is requested, we'll always use the full history printer.\n *\n * @default - Use value from logging.logLevel\n */\n readonly logLevel?: IoMessageLevel;\n\n /**\n * Whether to display all stack events or to display only the events for the\n * resource currently being deployed\n *\n * If not set, the stack history with all stack events will be displayed\n *\n * @default false\n */\n progress?: StackActivityProgress;\n\n /**\n * Whether we are on a CI system\n *\n * If so, disable the \"optimized\" stack monitor.\n *\n * @default false\n */\n readonly ci?: boolean;\n\n /**\n * Creation time of the change set\n *\n * This will be used to filter events, only showing those from after the change\n * set creation time.\n *\n * It is recommended to use this, otherwise the filtering will be subject\n * to clock drift between local and cloud machines.\n *\n * @default - local machine's current time\n */\n readonly changeSetCreationTime?: Date;\n}\n\nexport class StackActivityMonitor {\n /**\n * Create a Stack Activity Monitor using a default printer, based on context clues\n */\n public static withDefaultPrinter(\n cfn: ICloudFormationClient,\n stackName: string,\n stackArtifact: CloudFormationStackArtifact,\n options: WithDefaultPrinterProps = {},\n ) {\n const stream = options.ci ? process.stdout : process.stderr;\n\n const props: PrinterProps = {\n resourceTypeColumnWidth: calcMaxResourceTypeLength(stackArtifact.template),\n resourcesTotal: options.resourcesTotal,\n stream,\n };\n\n const isWindows = process.platform === 'win32';\n const verbose = options.logLevel ?? 'info';\n // On some CI systems (such as CircleCI) output still reports as a TTY so we also\n // need an individual check for whether we're running on CI.\n // see: https://discuss.circleci.com/t/circleci-terminal-is-a-tty-but-term-is-not-set/9965\n const fancyOutputAvailable = !isWindows && stream.isTTY && !options.ci;\n const progress = options.progress ?? StackActivityProgress.BAR;\n\n const printer =\n fancyOutputAvailable && !verbose && progress === StackActivityProgress.BAR\n ? new CurrentActivityPrinter(props)\n : new HistoryActivityPrinter(props);\n\n return new StackActivityMonitor(cfn, stackName, printer, stackArtifact, options.changeSetCreationTime);\n }\n\n /**\n * The poller used to read stack events\n */\n public readonly poller: StackEventPoller;\n\n public readonly errors: string[] = [];\n\n private active = false;\n\n /**\n * Current tick timer\n */\n private tickTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * Set to the activity of reading the current events\n */\n private readPromise?: Promise<any>;\n\n constructor(\n cfn: ICloudFormationClient,\n private readonly stackName: string,\n private readonly printer: IActivityPrinter,\n private readonly stack?: CloudFormationStackArtifact,\n changeSetCreationTime?: Date,\n ) {\n this.poller = new StackEventPoller(cfn, {\n stackName,\n startTime: changeSetCreationTime?.getTime() ?? Date.now(),\n });\n }\n\n public start() {\n this.active = true;\n this.printer.start();\n this.scheduleNextTick();\n return this;\n }\n\n public async stop() {\n this.active = false;\n if (this.tickTimer) {\n clearTimeout(this.tickTimer);\n }\n\n // Do a final poll for all events. This is to handle the situation where DescribeStackStatus\n // already returned an error, but the monitor hasn't seen all the events yet and we'd end\n // up not printing the failure reason to users.\n await this.finalPollToEnd();\n\n this.printer.stop();\n }\n\n private scheduleNextTick() {\n if (!this.active) {\n return;\n }\n\n this.tickTimer = setTimeout(() => void this.tick(), this.printer.updateSleep);\n }\n\n private async tick() {\n if (!this.active) {\n return;\n }\n\n try {\n this.readPromise = this.readNewEvents();\n await this.readPromise;\n this.readPromise = undefined;\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.active) {\n return;\n }\n\n this.printer.print();\n } catch (e) {\n error('Error occurred while monitoring stack: %s', e);\n }\n this.scheduleNextTick();\n }\n\n private findMetadataFor(logicalId: string | undefined): ResourceMetadata | undefined {\n const metadata = this.stack?.manifest?.metadata;\n if (!logicalId || !metadata) {\n return undefined;\n }\n for (const path of Object.keys(metadata)) {\n const entry = metadata[path]\n .filter((e) => e.type === ArtifactMetadataEntryType.LOGICAL_ID)\n .find((e) => e.data === logicalId);\n if (entry) {\n return {\n entry,\n constructPath: this.simplifyConstructPath(path),\n };\n }\n }\n return undefined;\n }\n\n /**\n * Reads all new events from the stack history\n *\n * The events are returned in reverse chronological order; we continue to the next page if we\n * see a next page and the last event in the page is new to us (and within the time window).\n * haven't seen the final event\n */\n private async readNewEvents(): Promise<void> {\n const pollEvents = await this.poller.poll();\n\n const activities: StackActivity[] = pollEvents.map((event) => ({\n ...event,\n metadata: this.findMetadataFor(event.event.LogicalResourceId),\n }));\n\n for (const activity of activities) {\n this.checkForErrors(activity);\n this.printer.addActivity(activity);\n }\n }\n\n /**\n * Perform a final poll to the end and flush out all events to the printer\n *\n * Finish any poll currently in progress, then do a final one until we've\n * reached the last page.\n */\n private async finalPollToEnd() {\n // If we were doing a poll, finish that first. It was started before\n // the moment we were sure we weren't going to get any new events anymore\n // so we need to do a new one anyway. Need to wait for this one though\n // because our state is single-threaded.\n if (this.readPromise) {\n await this.readPromise;\n }\n\n await this.readNewEvents();\n }\n\n private checkForErrors(activity: StackActivity) {\n if (hasErrorMessage(activity.event.ResourceStatus ?? '')) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason, nor is the stack message (stack\n // message will just say something like \"stack failed to update\")\n if (!isCancelled && activity.event.StackName !== activity.event.LogicalResourceId) {\n this.errors.push(activity.event.ResourceStatusReason ?? '');\n }\n }\n }\n\n private simplifyConstructPath(path: string) {\n path = path.replace(/\\/Resource$/, '');\n path = path.replace(/^\\//, ''); // remove \"/\" prefix\n\n // remove \"<stack-name>/\" prefix\n if (path.startsWith(this.stackName + '/')) {\n path = path.slice(this.stackName.length + 1);\n }\n return path;\n }\n}\n\nfunction padRight(n: number, x: string): string {\n return x + ' '.repeat(Math.max(0, n - x.length));\n}\n\n/**\n * Infamous padLeft()\n */\nfunction padLeft(n: number, x: string): string {\n return ' '.repeat(Math.max(0, n - x.length)) + x;\n}\n\nfunction calcMaxResourceTypeLength(template: any) {\n const resources = (template && template.Resources) || {};\n let maxWidth = 0;\n for (const id of Object.keys(resources)) {\n const type = resources[id].Type || '';\n if (type.length > maxWidth) {\n maxWidth = type.length;\n }\n }\n return maxWidth;\n}\n\ninterface PrinterProps {\n /**\n * Total resources to deploy\n */\n readonly resourcesTotal?: number;\n\n /**\n * The with of the \"resource type\" column.\n */\n readonly resourceTypeColumnWidth: number;\n\n /**\n * Stream to write to\n */\n readonly stream: NodeJS.WriteStream;\n}\n\nexport interface IActivityPrinter {\n readonly updateSleep: number;\n\n addActivity(activity: StackActivity): void;\n print(): void;\n start(): void;\n stop(): void;\n}\n\nabstract class ActivityPrinterBase implements IActivityPrinter {\n /**\n * Fetch new activity every 5 seconds\n */\n public readonly updateSleep: number = 5_000;\n\n /**\n * A list of resource IDs which are currently being processed\n */\n protected resourcesInProgress: Record<string, StackActivity> = {};\n\n /**\n * Previous completion state observed by logical ID\n *\n * We use this to detect that if we see a DELETE_COMPLETE after a\n * CREATE_COMPLETE, it's actually a rollback and we should DECREASE\n * resourcesDone instead of increase it\n */\n protected resourcesPrevCompleteState: Record<string, string> = {};\n\n /**\n * Count of resources that have reported a _COMPLETE status\n */\n protected resourcesDone: number = 0;\n\n /**\n * How many digits we need to represent the total count (for lining up the status reporting)\n */\n protected readonly resourceDigits: number = 0;\n\n protected readonly resourcesTotal?: number;\n\n protected rollingBack = false;\n\n protected readonly failures = new Array<StackActivity>();\n\n protected hookFailureMap = new Map<string, Map<string, string>>();\n\n constructor(protected readonly props: PrinterProps) {\n // +1 because the stack also emits a \"COMPLETE\" event at the end, and that wasn't\n // counted yet. This makes it line up with the amount of events we expect.\n this.resourcesTotal = props.resourcesTotal ? props.resourcesTotal + 1 : undefined;\n\n // How many digits does this number take to represent?\n this.resourceDigits = this.resourcesTotal ? Math.ceil(Math.log10(this.resourcesTotal)) : 0;\n }\n\n public failureReason(activity: StackActivity) {\n const resourceStatusReason = activity.event.ResourceStatusReason ?? '';\n const logicalResourceId = activity.event.LogicalResourceId ?? '';\n const hookFailureReasonMap = this.hookFailureMap.get(logicalResourceId);\n\n if (hookFailureReasonMap !== undefined) {\n for (const hookType of hookFailureReasonMap.keys()) {\n if (resourceStatusReason.includes(hookType)) {\n return resourceStatusReason + ' : ' + hookFailureReasonMap.get(hookType);\n }\n }\n }\n return resourceStatusReason;\n }\n\n public addActivity(activity: StackActivity) {\n const status = activity.event.ResourceStatus;\n const hookStatus = activity.event.HookStatus;\n const hookType = activity.event.HookType;\n if (!status || !activity.event.LogicalResourceId) {\n return;\n }\n\n if (status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS') {\n // Only triggered on the stack once we've started doing a rollback\n this.rollingBack = true;\n }\n\n if (status.endsWith('_IN_PROGRESS')) {\n this.resourcesInProgress[activity.event.LogicalResourceId] = activity;\n }\n\n if (hasErrorMessage(status)) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason\n if (!isCancelled) {\n this.failures.push(activity);\n }\n }\n\n if (status.endsWith('_COMPLETE') || status.endsWith('_FAILED')) {\n delete this.resourcesInProgress[activity.event.LogicalResourceId];\n }\n\n if (status.endsWith('_COMPLETE_CLEANUP_IN_PROGRESS')) {\n this.resourcesDone++;\n }\n\n if (status.endsWith('_COMPLETE')) {\n const prevState = this.resourcesPrevCompleteState[activity.event.LogicalResourceId];\n if (!prevState) {\n this.resourcesDone++;\n } else {\n // If we completed this before and we're completing it AGAIN, means we're rolling back.\n // Protect against silly underflow.\n this.resourcesDone--;\n if (this.resourcesDone < 0) {\n this.resourcesDone = 0;\n }\n }\n this.resourcesPrevCompleteState[activity.event.LogicalResourceId] = status;\n }\n\n if (\n hookStatus !== undefined &&\n hookStatus.endsWith('_COMPLETE_FAILED') &&\n activity.event.LogicalResourceId !== undefined &&\n hookType !== undefined\n ) {\n if (this.hookFailureMap.has(activity.event.LogicalResourceId)) {\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n } else {\n this.hookFailureMap.set(activity.event.LogicalResourceId, new Map<string, string>());\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n }\n }\n }\n\n public abstract print(): void;\n\n public start() {\n // Empty on purpose\n }\n\n public stop() {\n // Empty on purpose\n }\n}\n\n/**\n * Activity Printer which shows a full log of all CloudFormation events\n *\n * When there hasn't been activity for a while, it will print the resources\n * that are currently in progress, to show what's holding up the deployment.\n */\nexport class HistoryActivityPrinter extends ActivityPrinterBase {\n /**\n * Last time we printed something to the console.\n *\n * Used to measure timeout for progress reporting.\n */\n private lastPrintTime = Date.now();\n\n /**\n * Number of ms of change absence before we tell the user about the resources that are currently in progress.\n */\n private readonly inProgressDelay = 30_000;\n\n private readonly printable = new Array<StackActivity>();\n\n constructor(props: PrinterProps) {\n super(props);\n }\n\n public addActivity(activity: StackActivity) {\n super.addActivity(activity);\n this.printable.push(activity);\n this.print();\n }\n\n public print() {\n for (const activity of this.printable) {\n this.printOne(activity);\n }\n this.printable.splice(0, this.printable.length);\n this.printInProgress();\n }\n\n public stop() {\n // Print failures at the end\n if (this.failures.length > 0) {\n info('\\nFailed resources:');\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (failure.isStackEvent) {\n continue;\n }\n\n this.printOne(failure, false);\n }\n }\n }\n\n private printOne(activity: StackActivity, progress?: boolean) {\n const event = activity.event;\n const color = colorFromStatusResult(event.ResourceStatus);\n let reasonColor = chalk.cyan;\n\n let stackTrace = '';\n const metadata = activity.metadata;\n\n if (event.ResourceStatus && event.ResourceStatus.indexOf('FAILED') !== -1) {\n if (progress == undefined || progress) {\n event.ResourceStatusReason = event.ResourceStatusReason ? this.failureReason(activity) : '';\n }\n if (metadata) {\n stackTrace = metadata.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '';\n }\n reasonColor = chalk.red;\n }\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n info(\n util.format(\n '%s | %s%s | %s | %s | %s %s%s%s',\n event.StackName,\n progress !== false ? `${this.progress()} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n color(padRight(STATUS_WIDTH, (event.ResourceStatus || '').slice(0, STATUS_WIDTH))), // pad left and trim\n padRight(this.props.resourceTypeColumnWidth, event.ResourceType || ''),\n color(chalk.bold(resourceName)),\n logicalId,\n reasonColor(chalk.bold(event.ResourceStatusReason ? event.ResourceStatusReason : '')),\n reasonColor(stackTrace),\n ),\n );\n\n this.lastPrintTime = Date.now();\n }\n\n /**\n * Report the current progress as a [34/42] string, or just [34] if the total is unknown\n */\n private progress(): string {\n if (this.resourcesTotal == null) {\n // Don't have total, show simple count and hope the human knows\n return padLeft(3, util.format('%s', this.resourcesDone)); // max 500 resources\n }\n\n return util.format(\n '%s/%s',\n padLeft(this.resourceDigits, this.resourcesDone.toString()),\n padLeft(this.resourceDigits, this.resourcesTotal != null ? this.resourcesTotal.toString() : '?'),\n );\n }\n\n /**\n * If some resources are taking a while to create, notify the user about what's currently in progress\n */\n private printInProgress() {\n if (Date.now() < this.lastPrintTime + this.inProgressDelay) {\n return;\n }\n\n if (Object.keys(this.resourcesInProgress).length > 0) {\n info(\n util.format(\n '%s Currently in progress: %s',\n this.progress(),\n chalk.bold(Object.keys(this.resourcesInProgress).join(', ')),\n ),\n );\n }\n\n // We cheat a bit here. To prevent printInProgress() from repeatedly triggering,\n // we set the timestamp into the future. It will be reset whenever a regular print\n // occurs, after which we can be triggered again.\n this.lastPrintTime = +Infinity;\n }\n}\n\n/**\n * Activity Printer which shows the resources currently being updated\n *\n * It will continuously reupdate the terminal and show only the resources\n * that are currently being updated, in addition to a progress bar which\n * shows how far along the deployment is.\n *\n * Resources that have failed will always be shown, and will be recapitulated\n * along with their stack trace when the monitoring ends.\n *\n * Resources that failed deployment because they have been cancelled are\n * not included.\n */\nexport class CurrentActivityPrinter extends ActivityPrinterBase {\n /**\n * This looks very disorienting sleeping for 5 seconds. Update quicker.\n */\n public readonly updateSleep: number = 2_000;\n\n private oldLogThreshold: IoMessageLevel;\n private readonly stream: NodeJS.WriteStream;\n private block: RewritableBlock;\n\n constructor(props: PrinterProps) {\n super(props);\n this.oldLogThreshold = CliIoHost.instance().logLevel;\n this.stream = props.stream;\n this.block = new RewritableBlock(this.stream);\n }\n\n public print(): void {\n const lines = [];\n\n // Add a progress bar at the top\n const progressWidth = Math.max(\n Math.min((this.block.width ?? 80) - PROGRESSBAR_EXTRA_SPACE - 1, MAX_PROGRESSBAR_WIDTH),\n MIN_PROGRESSBAR_WIDTH,\n );\n const prog = this.progressBar(progressWidth);\n if (prog) {\n lines.push(' ' + prog, '');\n }\n\n // Normally we'd only print \"resources in progress\", but it's also useful\n // to keep an eye on the failures and know about the specific errors asquickly\n // as possible (while the stack is still rolling back), so add those in.\n const toPrint: StackActivity[] = [...this.failures, ...Object.values(this.resourcesInProgress)];\n toPrint.sort((a, b) => a.event.Timestamp!.getTime() - b.event.Timestamp!.getTime());\n\n lines.push(\n ...toPrint.map((res) => {\n const color = colorFromStatusActivity(res.event.ResourceStatus);\n const resourceName = res.metadata?.constructPath ?? res.event.LogicalResourceId ?? '';\n\n return util.format(\n '%s | %s | %s | %s%s',\n padLeft(TIMESTAMP_WIDTH, new Date(res.event.Timestamp!).toLocaleTimeString()),\n color(padRight(STATUS_WIDTH, (res.event.ResourceStatus || '').slice(0, STATUS_WIDTH))),\n padRight(this.props.resourceTypeColumnWidth, res.event.ResourceType || ''),\n color(chalk.bold(shorten(40, resourceName))),\n this.failureReasonOnNextLine(res),\n );\n }),\n );\n\n this.block.displayLines(lines);\n }\n\n public start() {\n // Need to prevent the waiter from printing 'stack not stable' every 5 seconds, it messes\n // with the output calculations.\n this.oldLogThreshold = CliIoHost.instance().logLevel;\n CliIoHost.instance().logLevel = 'info';\n }\n\n public stop() {\n CliIoHost.instance().logLevel = this.oldLogThreshold;\n\n // Print failures at the end\n const lines = new Array<string>();\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (failure.isStackEvent) {\n continue;\n }\n\n lines.push(\n util.format(\n chalk.red('%s | %s | %s | %s%s') + '\\n',\n padLeft(TIMESTAMP_WIDTH, new Date(failure.event.Timestamp!).toLocaleTimeString()),\n padRight(STATUS_WIDTH, (failure.event.ResourceStatus || '').slice(0, STATUS_WIDTH)),\n padRight(this.props.resourceTypeColumnWidth, failure.event.ResourceType || ''),\n shorten(40, failure.event.LogicalResourceId ?? ''),\n this.failureReasonOnNextLine(failure),\n ),\n );\n\n const trace = failure.metadata?.entry?.trace;\n if (trace) {\n lines.push(chalk.red(`\\t${trace.join('\\n\\t\\\\_ ')}\\n`));\n }\n }\n\n // Display in the same block space, otherwise we're going to have silly empty lines.\n this.block.displayLines(lines);\n this.block.removeEmptyLines();\n }\n\n private progressBar(width: number) {\n if (!this.resourcesTotal) {\n return '';\n }\n const fraction = Math.min(this.resourcesDone / this.resourcesTotal, 1);\n const innerWidth = Math.max(1, width - 2);\n const chars = innerWidth * fraction;\n const remainder = chars - Math.floor(chars);\n\n const fullChars = FULL_BLOCK.repeat(Math.floor(chars));\n const partialChar = PARTIAL_BLOCK[Math.floor(remainder * PARTIAL_BLOCK.length)];\n const filler = '\u00B7'.repeat(innerWidth - Math.floor(chars) - (partialChar ? 1 : 0));\n\n const color = this.rollingBack ? chalk.yellow : chalk.green;\n\n return '[' + color(fullChars + partialChar) + filler + `] (${this.resourcesDone}/${this.resourcesTotal})`;\n }\n\n private failureReasonOnNextLine(activity: StackActivity) {\n return hasErrorMessage(activity.event.ResourceStatus ?? '')\n ? `\\n${' '.repeat(TIMESTAMP_WIDTH + STATUS_WIDTH + 6)}${chalk.red(this.failureReason(activity) ?? '')}`\n : '';\n }\n}\n\nconst FULL_BLOCK = '\u2588';\nconst PARTIAL_BLOCK = ['', '\u258F', '\u258E', '\u258D', '\u258C', '\u258B', '\u258A', '\u2589'];\nconst MAX_PROGRESSBAR_WIDTH = 60;\nconst MIN_PROGRESSBAR_WIDTH = 10;\nconst PROGRESSBAR_EXTRA_SPACE =\n 2 /* leading spaces */ + 2 /* brackets */ + 4 /* progress number decoration */ + 6; /* 2 progress numbers up to 999 */\n\nfunction hasErrorMessage(status: string) {\n return status.endsWith('_FAILED') || status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS';\n}\n\nfunction colorFromStatusResult(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.indexOf('FAILED') !== -1) {\n return chalk.red;\n }\n if (status.indexOf('ROLLBACK') !== -1) {\n return chalk.yellow;\n }\n if (status.indexOf('COMPLETE') !== -1) {\n return chalk.green;\n }\n\n return chalk.reset;\n}\n\nfunction colorFromStatusActivity(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.endsWith('_FAILED')) {\n return chalk.red;\n }\n\n if (status.startsWith('CREATE_') || status.startsWith('UPDATE_') || status.startsWith('IMPORT_')) {\n return chalk.green;\n }\n // For stacks, it may also be 'UPDDATE_ROLLBACK_IN_PROGRESS'\n if (status.indexOf('ROLLBACK_') !== -1) {\n return chalk.yellow;\n }\n if (status.startsWith('DELETE_')) {\n return chalk.yellow;\n }\n\n return chalk.reset;\n}\n\nfunction shorten(maxWidth: number, p: string) {\n if (p.length <= maxWidth) {\n return p;\n }\n const half = Math.floor((maxWidth - 3) / 2);\n return p.slice(0, half) + '...' + p.slice(-half);\n}\n\nconst TIMESTAMP_WIDTH = 12;\nconst STATUS_WIDTH = 20;\n", "import type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { ICloudFormationClient } from '../aws-auth';\n\nexport interface StackEventPollerProps {\n /**\n * The stack to poll\n */\n readonly stackName: string;\n\n /**\n * IDs of parent stacks of this resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds?: string[];\n\n /**\n * Timestamp for the oldest event we're interested in\n *\n * @default - Read all events\n */\n readonly startTime?: number;\n\n /**\n * Stop reading when we see the stack entering this status\n *\n * Should be something like `CREATE_IN_PROGRESS`, `UPDATE_IN_PROGRESS`,\n * `DELETE_IN_PROGRESS, `ROLLBACK_IN_PROGRESS`.\n *\n * @default - Read all events\n */\n readonly stackStatuses?: string[];\n}\n\nexport interface ResourceEvent {\n readonly event: StackEvent;\n readonly parentStackLogicalIds: string[];\n\n /**\n * Whether this event regards the root stack\n *\n * @default false\n */\n readonly isStackEvent?: boolean;\n}\n\nexport class StackEventPoller {\n public readonly events: ResourceEvent[] = [];\n public complete: boolean = false;\n\n private readonly eventIds = new Set<string>();\n private readonly nestedStackPollers: Record<string, StackEventPoller> = {};\n\n constructor(\n private readonly cfn: ICloudFormationClient,\n private readonly props: StackEventPollerProps,\n ) {\n }\n\n /**\n * From all accumulated events, return only the errors\n */\n public get resourceErrors(): ResourceEvent[] {\n return this.events.filter((e) => e.event.ResourceStatus?.endsWith('_FAILED') && !e.isStackEvent);\n }\n\n /**\n * Poll for new stack events\n *\n * Will not return events older than events indicated by the constructor filters.\n *\n * Recurses into nested stacks, and returns events old-to-new.\n */\n public async poll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = await this.doPoll();\n\n // Also poll all nested stacks we're currently tracking\n for (const [logicalId, poller] of Object.entries(this.nestedStackPollers)) {\n events.push(...(await poller.poll()));\n if (poller.complete) {\n delete this.nestedStackPollers[logicalId];\n }\n }\n\n // Return what we have so far\n events.sort((a, b) => a.event.Timestamp!.valueOf() - b.event.Timestamp!.valueOf());\n this.events.push(...events);\n return events;\n }\n\n private async doPoll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = [];\n try {\n let nextToken: string | undefined;\n let finished = false;\n\n while (!finished) {\n const page = await this.cfn.describeStackEvents({ StackName: this.props.stackName, NextToken: nextToken });\n for (const event of page?.StackEvents ?? []) {\n // Event from before we were interested in 'em\n if (this.props.startTime !== undefined && event.Timestamp!.valueOf() < this.props.startTime) {\n return events;\n }\n\n // Already seen this one\n if (this.eventIds.has(event.EventId!)) {\n return events;\n }\n this.eventIds.add(event.EventId!);\n\n // The events for the stack itself are also included next to events about resources; we can test for them in this way.\n const isParentStackEvent = event.PhysicalResourceId === event.StackId;\n\n if (isParentStackEvent && this.props.stackStatuses?.includes(event.ResourceStatus ?? '')) {\n return events;\n }\n\n // Fresh event\n const resEvent: ResourceEvent = {\n event: event,\n parentStackLogicalIds: this.props.parentStackLogicalIds ?? [],\n isStackEvent: isParentStackEvent,\n };\n events.push(resEvent);\n\n if (\n !isParentStackEvent &&\n event.ResourceType === 'AWS::CloudFormation::Stack' &&\n isStackBeginOperationState(event.ResourceStatus)\n ) {\n // If the event is not for `this` stack and has a physical resource Id, recursively call for events in the nested stack\n this.trackNestedStack(event, [...(this.props.parentStackLogicalIds ?? []), event.LogicalResourceId ?? '']);\n }\n\n if (isParentStackEvent && isStackTerminalState(event.ResourceStatus)) {\n this.complete = true;\n }\n }\n\n nextToken = page?.NextToken;\n if (nextToken === undefined) {\n finished = true;\n }\n }\n } catch (e: any) {\n if (!(e.name === 'ValidationError' && formatErrorMessage(e) === `Stack [${this.props.stackName}] does not exist`)) {\n throw e;\n }\n }\n\n return events;\n }\n\n /**\n * On the CREATE_IN_PROGRESS, UPDATE_IN_PROGRESS, DELETE_IN_PROGRESS event of a nested stack, poll the nested stack updates\n */\n private trackNestedStack(event: StackEvent, parentStackLogicalIds: string[]) {\n const logicalId = event.LogicalResourceId;\n const physicalResourceId = event.PhysicalResourceId;\n\n // The CREATE_IN_PROGRESS event for a Nested Stack is emitted twice; first without a PhysicalResourceId\n // and then with. Ignore this event if we don't have that property yet.\n //\n // (At this point, I also don't trust that logicalId is always going to be there so validate that as well)\n if (!logicalId || !physicalResourceId) {\n return;\n }\n\n if (!this.nestedStackPollers[logicalId]) {\n this.nestedStackPollers[logicalId] = new StackEventPoller(this.cfn, {\n stackName: physicalResourceId,\n parentStackLogicalIds: parentStackLogicalIds,\n startTime: event.Timestamp!.valueOf(),\n });\n }\n }\n}\n\nfunction isStackBeginOperationState(state: string | undefined) {\n return [\n 'CREATE_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'DELETE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_IN_PROGRESS',\n ].includes(state ?? '');\n}\n\nfunction isStackTerminalState(state: string | undefined) {\n return !(state ?? '').endsWith('_IN_PROGRESS');\n}\n", "// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst wrapAnsi = require('wrap-ansi');\n\n/**\n * A class representing rewritable display lines\n */\nexport class RewritableBlock {\n private lastHeight = 0;\n private trailingEmptyLines = 0;\n\n constructor(private readonly stream: NodeJS.WriteStream) {\n }\n\n public get width() {\n // Might get changed if the user resizes the terminal\n return this.stream.columns;\n }\n\n public get height() {\n // Might get changed if the user resizes the terminal\n return this.stream.rows;\n }\n\n public displayLines(lines: string[]) {\n lines = terminalWrap(this.width, expandNewlines(lines));\n lines = lines.slice(0, getMaxBlockHeight(this.height, this.lastHeight, lines));\n\n this.stream.write(cursorUp(this.lastHeight));\n for (const line of lines) {\n this.stream.write(cll() + line + '\\n');\n }\n\n this.trailingEmptyLines = Math.max(0, this.lastHeight - lines.length);\n\n // Clear remainder of unwritten lines\n for (let i = 0; i < this.trailingEmptyLines; i++) {\n this.stream.write(cll() + '\\n');\n }\n\n // The block can only ever get bigger\n this.lastHeight = Math.max(this.lastHeight, lines.length);\n }\n\n public removeEmptyLines() {\n this.stream.write(cursorUp(this.trailingEmptyLines));\n }\n}\n\nconst ESC = '\\u001b';\n\n/*\n * Move cursor up `n` lines. Default is 1\n */\nfunction cursorUp(n: number) {\n n = typeof n === 'number' ? n : 1;\n return n > 0 ? ESC + '[' + n + 'A' : '';\n}\n\n/**\n * Clear to end of line\n */\nfunction cll() {\n return ESC + '[K';\n}\n\nfunction terminalWrap(width: number | undefined, lines: string[]) {\n if (width === undefined) {\n return lines;\n }\n\n return lines.flatMap(line => wrapAnsi(line, width - 1, {\n hard: true,\n trim: true,\n wordWrap: false,\n }).split('\\n'));\n}\n\n/**\n * Make sure there are no hidden newlines in the gin strings\n */\nfunction expandNewlines(lines: string[]): string[] {\n return lines.flatMap(line => line.split('\\n'));\n}\n\nfunction getMaxBlockHeight(windowHeight: number | undefined, lastHeight: number, lines: string[]): number {\n if (windowHeight === undefined) {\n return Math.max(lines.length, lastHeight);\n }\n return lines.length < windowHeight ? lines.length : windowHeight - 1;\n}\n", "import { type Stack, StackStatus as _StackStatus } from '@aws-sdk/client-cloudformation';\n\n/**\n * A utility class to inspect CloudFormation stack statuses.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html\n */\nexport class StackStatus {\n public static fromStackDescription(description: Stack) {\n return new StackStatus(description.StackStatus!, description.StackStatusReason);\n }\n\n constructor(\n public readonly name: string,\n public readonly reason?: string,\n ) {\n }\n\n get isCreationFailure(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.ROLLBACK_FAILED;\n }\n\n get isDeleted(): boolean {\n return this.name.startsWith('DELETE_');\n }\n\n get isFailure(): boolean {\n return this.name.endsWith('FAILED');\n }\n\n get isInProgress(): boolean {\n return this.name.endsWith('_IN_PROGRESS') && !this.isReviewInProgress;\n }\n\n get isReviewInProgress(): boolean {\n return this.name === _StackStatus.REVIEW_IN_PROGRESS;\n }\n\n get isNotFound(): boolean {\n return this.name === 'NOT_FOUND';\n }\n\n get isDeploySuccess(): boolean {\n return (\n !this.isNotFound &&\n (this.name === _StackStatus.CREATE_COMPLETE ||\n this.name === _StackStatus.UPDATE_COMPLETE ||\n this.name === _StackStatus.IMPORT_COMPLETE)\n );\n }\n\n get isRollbackSuccess(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.UPDATE_ROLLBACK_COMPLETE;\n }\n\n /**\n * Whether the stack is in a paused state due to `--no-rollback`.\n *\n * The possible actions here are retrying a new `--no-rollback` deployment, or initiating a rollback.\n */\n get rollbackChoice(): RollbackChoice {\n switch (this.name) {\n case _StackStatus.CREATE_FAILED:\n case _StackStatus.UPDATE_FAILED:\n return RollbackChoice.START_ROLLBACK;\n case _StackStatus.UPDATE_ROLLBACK_FAILED:\n return RollbackChoice.CONTINUE_UPDATE_ROLLBACK;\n case _StackStatus.ROLLBACK_FAILED:\n // Unfortunately there is no option to continue a failed rollback without\n // a stable target state.\n return RollbackChoice.ROLLBACK_FAILED;\n default:\n return RollbackChoice.NONE;\n }\n }\n\n get isRollbackable(): boolean {\n return [RollbackChoice.START_ROLLBACK, RollbackChoice.CONTINUE_UPDATE_ROLLBACK].includes(this.rollbackChoice);\n }\n\n public toString(): string {\n return this.name + (this.reason ? ` (${this.reason})` : '');\n }\n}\n\n/**\n * Describe the current rollback options for this state\n */\nexport enum RollbackChoice {\n START_ROLLBACK,\n CONTINUE_UPDATE_ROLLBACK,\n /**\n * A sign that stack creation AND its rollback have failed.\n *\n * There is no way to recover from this, other than recreating the stack.\n */\n ROLLBACK_FAILED,\n NONE,\n}\n", "import * as path from 'path';\nimport { type CloudFormationStackArtifact, type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { HeadObjectCommand, S3Client } from '@aws-sdk/client-s3';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport { debug, error } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\nimport { contentHash } from '../../util/content-hash';\nimport { toYAML } from '../../util/serialize';\nimport { type AssetManifestBuilder } from '../deployments';\nimport { EnvironmentResources } from '../environment';\n\nexport type TemplateBodyParameter = {\n TemplateBody?: string;\n TemplateURL?: string;\n};\n\nconst LARGE_TEMPLATE_SIZE_KB = 50;\n\n/**\n * Prepares the body parameter for +CreateChangeSet+.\n *\n * If the template is small enough to be inlined into the API call, just return\n * it immediately.\n *\n * Otherwise, add it to the asset manifest to get uploaded to the staging\n * bucket and return its coordinates. If there is no staging bucket, an error\n * is thrown.\n *\n * @param stack the synthesized stack that provides the CloudFormation template\n * @param toolkitInfo information about the toolkit stack\n */\nexport async function makeBodyParameter(\n stack: CloudFormationStackArtifact,\n resolvedEnvironment: Environment,\n assetManifest: AssetManifestBuilder,\n resources: EnvironmentResources,\n overrideTemplate?: any,\n): Promise<TemplateBodyParameter> {\n // If the template has already been uploaded to S3, just use it from there.\n if (stack.stackTemplateAssetObjectUrl && !overrideTemplate) {\n return {\n TemplateURL: await restUrlFromManifest(stack.stackTemplateAssetObjectUrl, resolvedEnvironment),\n };\n }\n\n // Otherwise, pass via API call (if small) or upload here (if large)\n const templateJson = toYAML(overrideTemplate ?? stack.template);\n\n if (templateJson.length <= LARGE_TEMPLATE_SIZE_KB * 1024) {\n return { TemplateBody: templateJson };\n }\n\n const toolkitInfo = await resources.lookupToolkit();\n if (!toolkitInfo.found) {\n error(\n `The template for stack \"${stack.displayName}\" is ${Math.round(templateJson.length / 1024)}KiB. ` +\n `Templates larger than ${LARGE_TEMPLATE_SIZE_KB}KiB must be uploaded to S3.\\n` +\n 'Run the following command in order to setup an S3 bucket in this environment, and then re-deploy:\\n\\n',\n chalk.blue(`\\t$ cdk bootstrap ${resolvedEnvironment.name}\\n`),\n );\n\n throw new ToolkitError('Template too large to deploy (\"cdk bootstrap\" is required)');\n }\n\n const templateHash = contentHash(templateJson);\n const key = `cdk/${stack.id}/${templateHash}.yml`;\n\n let templateFile = stack.templateFile;\n if (overrideTemplate) {\n // Add a variant of this template\n templateFile = `${stack.templateFile}-${templateHash}.yaml`;\n const templateFilePath = path.join(stack.assembly.directory, templateFile);\n await fs.writeFile(templateFilePath, templateJson, { encoding: 'utf-8' });\n }\n\n assetManifest.addFileAsset(\n templateHash,\n {\n path: templateFile,\n },\n {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n },\n );\n\n const templateURL = `${toolkitInfo.bucketUrl}/${key}`;\n debug('Storing template in S3 at:', templateURL);\n return { TemplateURL: templateURL };\n}\n\n/**\n * Format an S3 URL in the manifest for use with CloudFormation\n *\n * Replaces environment placeholders (which this field may contain),\n * and reformats s3://.../... urls into S3 REST URLs (which CloudFormation\n * expects)\n */\nasync function restUrlFromManifest(url: string, environment: Environment): Promise<string> {\n const doNotUseMarker = '**DONOTUSE**';\n const region = environment.region;\n // This URL may contain placeholders, so still substitute those.\n url = EnvironmentPlaceholders.replace(url, {\n accountId: environment.account,\n region,\n partition: doNotUseMarker,\n });\n\n // Yes, this is extremely crude, but we don't actually need this so I'm not inclined to spend\n // a lot of effort trying to thread the right value to this location.\n if (url.indexOf(doNotUseMarker) > -1) {\n throw new ToolkitError(\"Cannot use '${AWS::Partition}' in the 'stackTemplateAssetObjectUrl' field\");\n }\n\n const s3Url = url.match(/s3:\\/\\/([^/]+)\\/(.*)$/);\n if (!s3Url) {\n return url;\n }\n\n // We need to pass an 'https://s3.REGION.amazonaws.com[.cn]/bucket/object' URL to CloudFormation, but we\n // got an 's3://bucket/object' URL instead. Construct the rest API URL here.\n const bucketName = s3Url[1];\n const objectKey = s3Url[2];\n\n // SDK v3 no longer allows for getting endpoints from only region.\n // A command and client config must now be provided.\n const s3 = new S3Client({ region });\n const endpoint = await getEndpointFromInstructions({}, HeadObjectCommand, {\n ...s3.config,\n });\n endpoint.url.hostname;\n\n return `${endpoint.url.origin}/${bucketName}/${objectKey}`;\n}\n", "import * as crypto from 'crypto';\n\nexport function contentHash(data: string | Buffer | DataView) {\n return crypto.createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * A stably sorted hash of an arbitrary JS object\n */\nexport function contentHashAny(value: unknown) {\n const ret = crypto.createHash('sha256');\n recurse(value);\n return ret.digest('hex');\n\n function recurse(x: unknown) {\n if (typeof x === 'string') {\n ret.update(x);\n return;\n }\n\n if (Array.isArray(x)) {\n ret.update('[');\n for (const e of x) {\n recurse(e);\n ret.update('||');\n }\n ret.update(']');\n return;\n }\n\n if (x && typeof x === 'object') {\n ret.update('{');\n for (const key of Object.keys(x).sort()) {\n ret.update(key);\n ret.update(':');\n recurse((x as any)[key]);\n }\n ret.update('}');\n return;\n }\n\n ret.update(`${x}${typeof x}`); // typeof to make sure hash('123') !== hash(123)\n }\n}\n", "import { randomUUID } from 'crypto';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as cdk_assets from 'cdk-assets';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport {\n BasePublishProgressListener,\n PublishingAws,\n} from './asset-publishing';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport {\n CloudFormationStack,\n type ResourceIdentifierSummaries,\n ResourcesToImport,\n stabilizeStack,\n Template,\n uploadStackTemplateAssets,\n} from './cloudformation';\nimport { deployStack, destroyStack } from './deploy-stack';\nimport { DeploymentMethod } from './deployment-method';\nimport { DeployStackResult } from './deployment-result';\nimport {\n loadCurrentTemplate,\n loadCurrentTemplateWithNestedStacks,\n type RootTemplateWithNestedStacks,\n} from './nested-stack-helpers';\nimport { debug, warn } from '../../cli/messages';\nimport { IIoHost, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SdkProvider } from '../aws-auth/sdk-provider';\nimport { type EnvironmentResources, EnvironmentAccess } from '../environment';\nimport { HotswapMode, HotswapPropertyOverrides } from '../hotswap/common';\nimport { StackActivityMonitor, StackActivityProgress, StackEventPoller, RollbackChoice } from '../stack-events';\nimport type { Tag } from '../tags';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\nimport { makeBodyParameter } from '../util/template-body-parameter';\n\nconst BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK = 23;\n\nexport interface DeployStackOptions {\n /**\n * Stack to deploy\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Topic ARNs to send a message when deployment finishes (pass through to CloudFormation)\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Override name under which stack will be deployed\n *\n * @default - Use artifact default\n */\n readonly deployName?: string;\n\n /**\n * Don't show stack deployment events, just wait\n *\n * @default false\n */\n readonly quiet?: boolean;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * List of asset IDs which should NOT be built or uploaded\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Stack tags (pass through to CloudFormation)\n */\n readonly tags?: Tag[];\n\n /**\n * Stage the change set but don't execute it\n *\n * @default - true\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly execute?: boolean;\n\n /**\n * Optional name to use for the CloudFormation change set.\n * If not provided, a name will be generated automatically.\n *\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly changeSetName?: string;\n\n /**\n * Select the deployment method (direct or using a change set)\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Force deployment, even if the deployed template is identical to the one we are about to deploy.\n * @default false deployment will be skipped if the template is identical\n */\n readonly force?: boolean;\n\n /**\n * Extra parameters for CloudFormation\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Display mode for stack deployment progress.\n *\n * @default - StackActivityProgress.Bar - stack events will be displayed for\n * the resource currently being deployed.\n */\n readonly progress?: StackActivityProgress;\n\n /**\n * Whether we are on a CI system\n *\n * @default false\n */\n readonly ci?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * List of existing resources to be IMPORTED into the stack, instead of being CREATED\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @default false\n */\n ignoreNoStacks?: boolean;\n}\n\nexport interface RollbackStackOptions {\n /**\n * Stack to roll back\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Don't show stack deployment events, just wait\n *\n * @default false\n */\n readonly quiet?: boolean;\n\n /**\n * Whether we are on a CI system\n *\n * @default false\n */\n readonly ci?: boolean;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * Whether to force a rollback or not\n *\n * Forcing a rollback will orphan all undeletable resources.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Orphan the resources with the given logical IDs\n *\n * @default - No orphaning\n */\n readonly orphanLogicalIds?: string[];\n\n /**\n * Display mode for stack deployment progress.\n *\n * @default - StackActivityProgress.Bar - stack events will be displayed for\n * the resource currently being deployed.\n */\n readonly progress?: StackActivityProgress;\n\n /**\n * Whether to validate the version of the bootstrap stack permissions\n *\n * @default true\n */\n readonly validateBootstrapStackVersion?: boolean;\n}\n\nexport interface RollbackStackResult {\n readonly notInRollbackableState?: boolean;\n readonly success?: boolean;\n}\n\ninterface AssetOptions {\n /**\n * Stack with assets to build.\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the building.\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n}\n\nexport interface BuildStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\ninterface PublishStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\nexport interface DestroyStackOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n roleArn?: string;\n quiet?: boolean;\n force?: boolean;\n ci?: boolean;\n}\n\nexport interface StackExistsOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n tryLookupRole?: boolean;\n}\n\nexport interface DeploymentsProps {\n readonly sdkProvider: SdkProvider;\n readonly toolkitStackName?: string;\n readonly ioHost: IIoHost;\n readonly action: ToolkitAction;\n}\n\n/**\n * Scope for a single set of deployments from a set of Cloud Assembly Artifacts\n *\n * Manages lookup of SDKs, Bootstrap stacks, etc.\n */\nexport class Deployments {\n public readonly envs: EnvironmentAccess;\n\n /**\n * SDK provider for asset publishing (do not use for anything else).\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to asset handling routines.\n */\n private readonly assetSdkProvider: SdkProvider;\n\n /**\n * SDK provider for passing to deployStack\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to `deployStack`.\n */\n private readonly deployStackSdkProvider: SdkProvider;\n\n private readonly publisherCache = new Map<cdk_assets.AssetManifest, cdk_assets.AssetPublishing>();\n\n private _allowCrossAccountAssetPublishing: boolean | undefined;\n\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n constructor(private readonly props: DeploymentsProps) {\n this.assetSdkProvider = props.sdkProvider;\n this.deployStackSdkProvider = props.sdkProvider;\n this.ioHost = props.ioHost;\n this.action = props.action;\n this.envs = new EnvironmentAccess(\n props.sdkProvider,\n props.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME,\n { ioHost: this.ioHost, action: this.action },\n );\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.envs.resolveStackEnvironment(stack);\n }\n\n public async readCurrentTemplateWithNestedStacks(\n rootStackArtifact: cxapi.CloudFormationStackArtifact,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<RootTemplateWithNestedStacks> {\n const env = await this.envs.accessStackForLookupBestEffort(rootStackArtifact);\n return loadCurrentTemplateWithNestedStacks(rootStackArtifact, env.sdk, retrieveProcessedTemplate);\n }\n\n public async readCurrentTemplate(stackArtifact: cxapi.CloudFormationStackArtifact): Promise<Template> {\n await this.ioHost.notify(debug(this.action, `Reading existing template for stack ${stackArtifact.displayName}.`));\n const env = await this.envs.accessStackForLookupBestEffort(stackArtifact);\n return loadCurrentTemplate(stackArtifact, env.sdk);\n }\n\n public async resourceIdentifierSummaries(\n stackArtifact: cxapi.CloudFormationStackArtifact,\n ): Promise<ResourceIdentifierSummaries> {\n await this.ioHost.notify(debug(this.action, `Retrieving template summary for stack ${stackArtifact.displayName}.`));\n // Currently, needs to use `deploy-role` since it may need to read templates in the staging\n // bucket which have been encrypted with a KMS key (and lookup-role may not read encrypted things)\n const env = await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);\n const cfn = env.sdk.cloudFormation();\n\n await uploadStackTemplateAssets(stackArtifact, this);\n\n // Upload the template, if necessary, before passing it to CFN\n const builder = new AssetManifestBuilder();\n const cfnParam = await makeBodyParameter(\n stackArtifact,\n env.resolvedEnvironment,\n builder,\n env.resources);\n\n // If the `makeBodyParameter` before this added assets, make sure to publish them before\n // calling the API.\n const addedAssets = builder.toManifest(stackArtifact.assembly.directory);\n for (const entry of addedAssets.entries) {\n await this.buildSingleAsset('no-version-validation', addedAssets, entry, {\n stack: stackArtifact,\n });\n await this.publishSingleAsset(addedAssets, entry, {\n stack: stackArtifact,\n });\n }\n\n const response = await cfn.getTemplateSummary(cfnParam);\n if (!response.ResourceIdentifierSummaries) {\n await this.ioHost.notify(debug(this.action, 'GetTemplateSummary API call did not return \"ResourceIdentifierSummaries\"'));\n }\n return response.ResourceIdentifierSummaries ?? [];\n }\n\n public async deployStack(options: DeployStackOptions): Promise<DeployStackResult> {\n let deploymentMethod = options.deploymentMethod;\n if (options.changeSetName || options.execute !== undefined) {\n if (deploymentMethod) {\n throw new ToolkitError(\n \"You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.\",\n );\n }\n deploymentMethod = {\n method: 'change-set',\n changeSetName: options.changeSetName,\n execute: options.execute,\n };\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n options.stack.requiresBootstrapStackVersion,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return deployStack({\n stack: options.stack,\n resolvedEnvironment: env.resolvedEnvironment,\n deployName: options.deployName,\n notificationArns: options.notificationArns,\n quiet: options.quiet,\n sdk: env.sdk,\n sdkProvider: this.deployStackSdkProvider,\n roleArn: executionRoleArn,\n reuseAssets: options.reuseAssets,\n envResources: env.resources,\n tags: options.tags,\n deploymentMethod,\n force: options.force,\n parameters: options.parameters,\n usePreviousParameters: options.usePreviousParameters,\n progress: options.progress,\n ci: options.ci,\n rollback: options.rollback,\n hotswap: options.hotswap,\n hotswapPropertyOverrides: options.hotswapPropertyOverrides,\n extraUserAgent: options.extraUserAgent,\n resourcesToImport: options.resourcesToImport,\n overrideTemplate: options.overrideTemplate,\n assetParallelism: options.assetParallelism,\n }, { ioHost: this.ioHost, action: this.action });\n }\n\n public async rollbackStack(options: RollbackStackOptions): Promise<RollbackStackResult> {\n let resourcesToSkip: string[] = options.orphanLogicalIds ?? [];\n if (options.force && resourcesToSkip.length > 0) {\n throw new ToolkitError('Cannot combine --force with --orphan');\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n if (options.validateBootstrapStackVersion ?? true) {\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const cfn = env.sdk.cloudFormation();\n const deployName = options.stack.stackName;\n\n // We loop in case of `--force` and the stack ends up in `CONTINUE_UPDATE_ROLLBACK`.\n let maxLoops = 10;\n while (maxLoops--) {\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n switch (cloudFormationStack.stackStatus.rollbackChoice) {\n case RollbackChoice.NONE:\n await this.ioHost.notify(warn(this.action, `Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`));\n return { notInRollbackableState: true };\n\n case RollbackChoice.START_ROLLBACK:\n await this.ioHost.notify(debug(this.action, `Initiating rollback of stack ${deployName}`));\n await cfn.rollbackStack({\n StackName: deployName,\n RoleARN: executionRoleArn,\n ClientRequestToken: randomUUID(),\n // Enabling this is just the better overall default, the only reason it isn't the upstream default is backwards compatibility\n RetainExceptOnCreate: true,\n });\n break;\n\n case RollbackChoice.CONTINUE_UPDATE_ROLLBACK:\n if (options.force) {\n // Find the failed resources from the deployment and automatically skip them\n // (Using deployment log because we definitely have `DescribeStackEvents` permissions, and we might not have\n // `DescribeStackResources` permissions).\n const poller = new StackEventPoller(cfn, {\n stackName: deployName,\n stackStatuses: ['ROLLBACK_IN_PROGRESS', 'UPDATE_ROLLBACK_IN_PROGRESS'],\n });\n await poller.poll();\n resourcesToSkip = poller.resourceErrors\n .filter((r) => !r.isStackEvent && r.parentStackLogicalIds.length === 0)\n .map((r) => r.event.LogicalResourceId ?? '');\n }\n\n const skipDescription = resourcesToSkip.length > 0 ? ` (orphaning: ${resourcesToSkip.join(', ')})` : '';\n await this.ioHost.notify(warn(this.action, `Continuing rollback of stack ${deployName}${skipDescription}`));\n await cfn.continueUpdateRollback({\n StackName: deployName,\n ClientRequestToken: randomUUID(),\n RoleARN: executionRoleArn,\n ResourcesToSkip: resourcesToSkip,\n });\n break;\n\n case RollbackChoice.ROLLBACK_FAILED:\n await this.ioHost.notify(warn(\n this.action,\n `Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`,\n ));\n return { notInRollbackableState: true };\n\n default:\n throw new ToolkitError(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`);\n }\n\n const monitor = options.quiet\n ? undefined\n : StackActivityMonitor.withDefaultPrinter(cfn, deployName, options.stack, {\n ci: options.ci,\n }).start();\n\n let stackErrorMessage: string | undefined = undefined;\n let finalStackState = cloudFormationStack;\n try {\n const successStack = await stabilizeStack(cfn, { ioHost: this.ioHost, action: this.action }, deployName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were rolling it back)');\n }\n finalStackState = successStack;\n\n const errors = monitor?.errors?.join(', ');\n if (errors) {\n stackErrorMessage = errors;\n }\n } catch (e: any) {\n stackErrorMessage = suffixWithErrors(formatErrorMessage(e), monitor?.errors);\n } finally {\n await monitor?.stop();\n }\n\n if (finalStackState.stackStatus.isRollbackSuccess || !stackErrorMessage) {\n return { success: true };\n }\n\n // Either we need to ignore some resources to continue the rollback, or something went wrong\n if (finalStackState.stackStatus.rollbackChoice === RollbackChoice.CONTINUE_UPDATE_ROLLBACK && options.force) {\n // Do another loop-de-loop\n continue;\n }\n\n throw new ToolkitError(\n `${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`,\n );\n }\n throw new ToolkitError(\n \"Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.\",\n );\n }\n\n public async destroyStack(options: DestroyStackOptions): Promise<void> {\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return destroyStack({\n sdk: env.sdk,\n roleArn: executionRoleArn,\n stack: options.stack,\n deployName: options.deployName,\n quiet: options.quiet,\n ci: options.ci,\n }, { ioHost: this.ioHost, action: this.action });\n }\n\n public async stackExists(options: StackExistsOptions): Promise<boolean> {\n let env;\n if (options.tryLookupRole) {\n env = await this.envs.accessStackForLookupBestEffort(options.stack);\n } else {\n env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n }\n const stack = await CloudFormationStack.lookup(env.sdk.cloudFormation(), options.deployName ?? options.stack.stackName);\n return stack.exists;\n }\n\n /**\n * Build a single asset from an asset manifest\n *\n * If an assert manifest artifact is given, the bootstrap stack version\n * will be validated according to the constraints in that manifest artifact.\n * If that is not necessary, `'no-version-validation'` can be passed.\n */\n // eslint-disable-next-line max-len\n public async buildSingleAsset(\n assetArtifact: cxapi.AssetManifestArtifact | 'no-version-validation',\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: BuildStackAssetsOptions,\n ) {\n if (assetArtifact !== 'no-version-validation') {\n const env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n assetArtifact.requiresBootstrapStackVersion,\n assetArtifact.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const resolvedEnvironment = await this.envs.resolveStackEnvironment(options.stack);\n\n const publisher = this.cachedPublisher(assetManifest, resolvedEnvironment, options.stackName);\n await publisher.buildEntry(asset);\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to build asset ${asset.id}`);\n }\n }\n\n /**\n * Publish a single asset from an asset manifest\n */\n public async publishSingleAsset(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n\n // No need to validate anymore, we already did that during build\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n await publisher.publishEntry(asset, { allowCrossAccount: await this.allowCrossAccountAssetPublishingForEnv(options.stack) });\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to publish asset ${asset.id}`);\n }\n }\n\n private async allowCrossAccountAssetPublishingForEnv(stack: cxapi.CloudFormationStackArtifact): Promise<boolean> {\n if (this._allowCrossAccountAssetPublishing === undefined) {\n const env = await this.envs.accessStackForReadOnlyStackOperations(stack);\n this._allowCrossAccountAssetPublishing = await determineAllowCrossAccountAssetPublishing(env.sdk, {\n ioHost: this.ioHost,\n action: this.action,\n }, this.props.toolkitStackName);\n }\n return this._allowCrossAccountAssetPublishing;\n }\n\n /**\n * Return whether a single asset has been published already\n */\n public async isSingleAssetPublished(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n return publisher.isEntryPublished(asset);\n }\n\n /**\n * Validate that the bootstrap stack has the right version for this stack\n *\n * Call into envResources.validateVersion, but prepend the stack name in case of failure.\n */\n private async validateBootstrapStackVersion(\n stackName: string,\n requiresBootstrapStackVersion: number | undefined,\n bootstrapStackVersionSsmParameter: string | undefined,\n envResources: EnvironmentResources,\n ) {\n try {\n await envResources.validateVersion(requiresBootstrapStackVersion, bootstrapStackVersionSsmParameter);\n } catch (e: any) {\n throw new ToolkitError(`${stackName}: ${formatErrorMessage(e)}`);\n }\n }\n\n private cachedPublisher(assetManifest: cdk_assets.AssetManifest, env: cxapi.Environment, stackName?: string) {\n const existing = this.publisherCache.get(assetManifest);\n if (existing) {\n return existing;\n }\n const prefix = stackName ? `${chalk.bold(stackName)}: ` : '';\n const publisher = new cdk_assets.AssetPublishing(assetManifest, {\n // The AssetPublishing class takes care of role assuming etc, so it's okay to\n // give it a direct `SdkProvider`.\n aws: new PublishingAws(this.assetSdkProvider, env),\n progressListener: new ParallelSafeAssetProgress(prefix, { ioHost: this.ioHost, action: this.action }),\n });\n this.publisherCache.set(assetManifest, publisher);\n return publisher;\n }\n}\n\n/**\n * Asset progress that doesn't do anything with percentages (currently)\n */\nclass ParallelSafeAssetProgress extends BasePublishProgressListener {\n private readonly prefix: string;\n\n constructor(prefix: string, { ioHost, action }: IoMessaging) {\n super({ ioHost, action });\n this.prefix = prefix;\n }\n\n protected getMessage(type: cdk_assets.EventType, event: cdk_assets.IPublishProgress): string {\n return `${this.prefix}${type}: ${event.message}`;\n }\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n", "import { type Environment, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport {\n type Account,\n type AssetManifest,\n AssetPublishing,\n ClientOptions,\n EventType,\n type IAws,\n type IECRClient,\n type IPublishProgress,\n type IPublishProgressListener,\n type IS3Client,\n type ISecretsManagerClient,\n} from 'cdk-assets';\nimport type { SDK } from '..';\nimport { formatMessage } from '../../cli/messages';\nimport { IIoHost, IoMessageLevel, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SdkProvider } from '../aws-auth';\nimport { Mode } from '../plugin';\n\ninterface PublishAssetsOptions {\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly parallel?: boolean;\n\n /**\n * Whether cdk-assets is allowed to do cross account publishing.\n */\n readonly allowCrossAccount: boolean;\n}\n\n/**\n * Use cdk-assets to publish all assets in the given manifest.\n *\n * @deprecated used in legacy deployments only, should be migrated at some point\n */\nexport async function publishAssets(\n manifest: AssetManifest,\n sdk: SdkProvider,\n targetEnv: Environment,\n options: PublishAssetsOptions,\n { ioHost, action }: IoMessaging,\n) {\n // This shouldn't really happen (it's a programming error), but we don't have\n // the types here to guide us. Do an runtime validation to be super super sure.\n if (\n targetEnv.account === undefined ||\n targetEnv.account === UNKNOWN_ACCOUNT ||\n targetEnv.region === undefined ||\n targetEnv.account === UNKNOWN_REGION\n ) {\n throw new ToolkitError(`Asset publishing requires resolved account and region, got ${JSON.stringify(targetEnv)}`);\n }\n\n const publisher = new AssetPublishing(manifest, {\n aws: new PublishingAws(sdk, targetEnv),\n progressListener: new PublishingProgressListener({ ioHost, action }),\n throwOnError: false,\n publishInParallel: options.parallel ?? true,\n buildAssets: true,\n publishAssets: true,\n quiet: false,\n });\n await publisher.publish({ allowCrossAccount: options.allowCrossAccount });\n if (publisher.hasFailures) {\n throw new ToolkitError('Failed to publish one or more assets. See the error messages above for more information.');\n }\n}\n\nexport class PublishingAws implements IAws {\n private sdkCache: Map<String, SDK> = new Map();\n\n constructor(\n /**\n * The base SDK to work with\n */\n private readonly aws: SdkProvider,\n\n /**\n * Environment where the stack we're deploying is going\n */\n private readonly targetEnv: Environment,\n ) {\n }\n\n public async discoverPartition(): Promise<string> {\n return (await this.aws.baseCredentialsPartition(this.targetEnv, Mode.ForWriting)) ?? 'aws';\n }\n\n public async discoverDefaultRegion(): Promise<string> {\n return this.targetEnv.region;\n }\n\n public async discoverCurrentAccount(): Promise<Account> {\n const account = await this.aws.defaultAccount();\n return (\n account ?? {\n accountId: '<unknown account>',\n partition: 'aws',\n }\n );\n }\n\n public async discoverTargetAccount(options: ClientOptions): Promise<Account> {\n return (await this.sdk(options)).currentAccount();\n }\n\n public async s3Client(options: ClientOptions): Promise<IS3Client> {\n return (await this.sdk(options)).s3();\n }\n\n public async ecrClient(options: ClientOptions): Promise<IECRClient> {\n return (await this.sdk(options)).ecr();\n }\n\n public async secretsManagerClient(options: ClientOptions): Promise<ISecretsManagerClient> {\n return (await this.sdk(options)).secretsManager();\n }\n\n /**\n * Get an SDK appropriate for the given client options\n */\n private async sdk(options: ClientOptions): Promise<SDK> {\n const env = {\n ...this.targetEnv,\n region: options.region ?? this.targetEnv.region, // Default: same region as the stack\n };\n\n const cacheKeyMap: any = {\n env, // region, name, account\n assumeRuleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n quiet: options.quiet,\n };\n\n if (options.assumeRoleAdditionalOptions) {\n cacheKeyMap.assumeRoleAdditionalOptions = options.assumeRoleAdditionalOptions;\n }\n\n const cacheKey = JSON.stringify(cacheKeyMap);\n\n const maybeSdk = this.sdkCache.get(cacheKey);\n if (maybeSdk) {\n return maybeSdk;\n }\n\n const sdk = (\n await this.aws.forEnvironment(\n env,\n Mode.ForWriting,\n {\n assumeRoleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n },\n options.quiet,\n )\n ).sdk;\n this.sdkCache.set(cacheKey, sdk);\n\n return sdk;\n }\n}\n\nexport const EVENT_TO_LEVEL: Record<EventType, IoMessageLevel | false> = {\n build: 'debug',\n cached: 'debug',\n check: 'debug',\n debug: 'debug',\n fail: 'error',\n found: 'debug',\n start: 'info',\n success: 'info',\n upload: 'debug',\n shell_open: 'debug',\n shell_stderr: false,\n shell_stdout: false,\n shell_close: false,\n};\n\nexport abstract class BasePublishProgressListener implements IPublishProgressListener {\n protected readonly ioHost: IIoHost;\n protected readonly action: ToolkitAction;\n\n constructor({ ioHost, action }: IoMessaging) {\n this.ioHost = ioHost;\n this.action = action;\n }\n\n protected abstract getMessage(type: EventType, event: IPublishProgress): string;\n\n public onPublishEvent(type: EventType, event: IPublishProgress): void {\n const level = EVENT_TO_LEVEL[type];\n if (level) {\n void this.ioHost.notify(\n formatMessage({\n level,\n action: this.action,\n message: this.getMessage(type, event),\n }),\n );\n }\n }\n}\n\nclass PublishingProgressListener extends BasePublishProgressListener {\n protected getMessage(type: EventType, event: IPublishProgress): string {\n return `[${event.percentComplete}%] ${type}: ${event.message}`;\n }\n}\n", "import { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { SDK } from '../aws-auth';\n\nexport async function determineAllowCrossAccountAssetPublishing(\n sdk: SDK,\n { ioHost, action }: IoMessaging,\n customStackName?: string,\n): Promise<boolean> {\n try {\n const stackName = customStackName || 'CDKToolkit';\n const stackInfo = await getBootstrapStackInfo(sdk, stackName);\n\n if (!stackInfo.hasStagingBucket) {\n // indicates an intentional cross account setup\n return true;\n }\n\n if (stackInfo.bootstrapVersion >= 21) {\n // bootstrap stack version 21 contains a fix that will prevent cross\n // account publishing on the IAM level\n // https://github.com/aws/aws-cdk/pull/30823\n return true;\n }\n\n // If there is a staging bucket AND the bootstrap version is old, then we want to protect\n // against accidental cross-account publishing.\n return false;\n } catch (e) {\n // You would think we would need to fail closed here, but the reality is\n // that we get here if we couldn't find the bootstrap stack: that is\n // completely valid, and many large organizations may have their own method\n // of creating bootstrap resources. If they do, there's nothing for us to validate,\n // but we can't use that as a reason to disallow cross-account publishing. We'll just\n // have to trust they did their due diligence. So we fail open.\n await ioHost.notify(debug(action, `Error determining cross account asset publishing: ${e}`));\n await ioHost.notify(debug(action, 'Defaulting to allowing cross account asset publishing'));\n return true;\n }\n}\n\ninterface BootstrapStackInfo {\n hasStagingBucket: boolean;\n bootstrapVersion: number;\n}\n\nexport async function getBootstrapStackInfo(sdk: SDK, stackName: string): Promise<BootstrapStackInfo> {\n try {\n const cfn = sdk.cloudFormation();\n const stackResponse = await cfn.describeStacks({ StackName: stackName });\n\n if (!stackResponse.Stacks || stackResponse.Stacks.length === 0) {\n throw new ToolkitError(`Toolkit stack ${stackName} not found`);\n }\n\n const stack = stackResponse.Stacks[0];\n const versionOutput = stack.Outputs?.find(output => output.OutputKey === 'BootstrapVersion');\n\n if (!versionOutput?.OutputValue) {\n throw new ToolkitError(`Unable to find BootstrapVersion output in the toolkit stack ${stackName}`);\n }\n\n const bootstrapVersion = parseInt(versionOutput.OutputValue);\n if (isNaN(bootstrapVersion)) {\n throw new ToolkitError(`Invalid BootstrapVersion value: ${versionOutput.OutputValue}`);\n }\n\n // try to get bucketname from the logical resource id. If there is no\n // bucketname, or the value doesn't look like an S3 bucket name, we assume\n // the bucket doesn't exist (this is for the case where a template customizer did\n // not dare to remove the Output, but put a dummy value there like '' or '-' or '***').\n //\n // We would have preferred to look at the stack resources here, but\n // unfortunately the deploy role doesn't have permissions call DescribeStackResources.\n const bucketName = stack.Outputs?.find(output => output.OutputKey === 'BucketName')?.OutputValue;\n // Must begin and end with letter or number.\n const hasStagingBucket = !!(bucketName && bucketName.match(/^[a-z0-9]/) && bucketName.match(/[a-z0-9]$/));\n\n return {\n hasStagingBucket,\n bootstrapVersion,\n };\n } catch (e) {\n throw new ToolkitError(`Error retrieving toolkit stack info: ${e}`);\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport type {\n CreateChangeSetCommandInput,\n CreateStackCommandInput,\n DescribeChangeSetCommandOutput,\n ExecuteChangeSetCommandInput,\n UpdateStackCommandInput,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { publishAssets } from './asset-publishing';\nimport { addMetadataAssetsToManifest } from './assets';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport {\n changeSetHasNoChanges,\n CloudFormationStack,\n TemplateParameters,\n waitForChangeSet,\n waitForStackDeploy,\n waitForStackDelete,\n ParameterValues,\n ParameterChanges,\n ResourcesToImport,\n} from './cloudformation';\nimport { ChangeSetDeploymentMethod, DeploymentMethod } from './deployment-method';\nimport { DeployStackResult, SuccessfulDeployStackResult } from './deployment-result';\nimport { tryHotswapDeployment } from './hotswap-deployments';\nimport { debug, info, warn } from '../../cli/messages';\nimport { IIoHost, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK, SdkProvider, ICloudFormationClient } from '../aws-auth';\nimport type { EnvironmentResources } from '../environment';\nimport { CfnEvaluationException } from '../evaluate-cloudformation-template';\nimport { HotswapMode, HotswapPropertyOverrides, ICON } from '../hotswap/common';\nimport { StackActivityMonitor, type StackActivityProgress } from '../stack-events';\nimport { StringWithoutPlaceholders } from '../util/placeholders';\nimport { type TemplateBodyParameter, makeBodyParameter } from '../util/template-body-parameter';\n\nexport interface DeployStackOptions {\n /**\n * The stack to be deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * The SDK to use for deploying the stack\n *\n * Should have been initialized with the correct role with which\n * stack operations should be performed.\n */\n readonly sdk: SDK;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to:\n *\n * - Publish assets, either legacy assets or large CFN templates\n * that aren't themselves assets from a manifest. (Needs an SDK\n * Provider because the file publishing role is declared as part\n * of the asset).\n * - Hotswap\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Information about the bootstrap stack found in the target environment\n */\n readonly envResources: EnvironmentResources;\n\n /**\n * Role to pass to CloudFormation to execute the change set\n *\n * To obtain a `StringWithoutPlaceholders`, run a regular\n * string though `TargetEnvironment.replacePlaceholders`.\n *\n * @default - No execution role; CloudFormation either uses the role currently associated with\n * the stack, or otherwise uses current AWS credentials.\n */\n readonly roleArn?: StringWithoutPlaceholders;\n\n /**\n * Notification ARNs to pass to CloudFormation to notify when the change set has completed\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Name to deploy the stack under\n *\n * @default - Name from assembly\n */\n readonly deployName?: string;\n\n /**\n * Quiet or verbose deployment\n *\n * @default false\n */\n readonly quiet?: boolean;\n\n /**\n * List of asset IDs which shouldn't be built\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Tags to pass to CloudFormation to add to stack\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * What deployment method to use\n *\n * @default - Change set with defaults\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * The collection of extra parameters\n * (in addition to those used for assets)\n * to pass to the deployed template.\n * Note that parameters with `undefined` or empty values will be ignored,\n * and not passed to the template.\n *\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default false\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Display mode for stack deployment progress.\n *\n * @default StackActivityProgress.Bar stack events will be displayed for\n * the resource currently being deployed.\n */\n readonly progress?: StackActivityProgress;\n\n /**\n * Deploy even if the deployed template is identical to the one we are about to deploy.\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Whether we are on a CI system\n *\n * @default false\n */\n readonly ci?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Extra properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * If set, change set of type IMPORT will be created, and resourcesToImport\n * passed to it.\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n}\n\nexport async function deployStack(options: DeployStackOptions, { ioHost, action }: IoMessaging): Promise<DeployStackResult> {\n const stackArtifact = options.stack;\n\n const stackEnv = options.resolvedEnvironment;\n\n options.sdk.appendCustomUserAgent(options.extraUserAgent);\n const cfn = options.sdk.cloudFormation();\n const deployName = options.deployName || stackArtifact.stackName;\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n if (cloudFormationStack.stackStatus.isCreationFailure) {\n await ioHost.notify(debug(action,\n `Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`,\n ));\n await cfn.deleteStack({ StackName: deployName });\n const deletedStack = await waitForStackDelete(cfn, { ioHost, action }, deployName);\n if (deletedStack && deletedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(\n `Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`,\n );\n }\n // Update variable to mark that the stack does not exist anymore, but avoid\n // doing an actual lookup in CloudFormation (which would be silly to do if\n // we just deleted it).\n cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);\n }\n\n // Detect \"legacy\" assets (which remain in the metadata) and publish them via\n // an ad-hoc asset manifest, while passing their locations via template\n // parameters.\n const legacyAssets = new AssetManifestBuilder();\n const assetParams = await addMetadataAssetsToManifest(\n { ioHost, action },\n stackArtifact,\n legacyAssets,\n options.envResources,\n options.reuseAssets,\n );\n\n const finalParameterValues = { ...options.parameters, ...assetParams };\n\n const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);\n const stackParams = options.usePreviousParameters\n ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)\n : templateParams.supplyAll(finalParameterValues);\n\n const hotswapMode = options.hotswap ?? HotswapMode.FULL_DEPLOYMENT;\n const hotswapPropertyOverrides = options.hotswapPropertyOverrides ?? new HotswapPropertyOverrides();\n\n if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters), { ioHost, action })) {\n await ioHost.notify(debug(action, `${deployName}: skipping deployment (use --force to override)`));\n // if we can skip deployment and we are performing a hotswap, let the user know\n // that no hotswap deployment happened\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n await ioHost.notify(info(action,\n format(\n `\\n ${ICON} %s\\n`,\n chalk.bold('hotswap deployment skipped - no changes were detected (use --force to override)'),\n ),\n ));\n }\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: cloudFormationStack.outputs,\n stackArn: cloudFormationStack.stackId,\n };\n } else {\n await ioHost.notify(debug(action, `${deployName}: deploying...`));\n }\n\n const bodyParameter = await makeBodyParameter(\n stackArtifact,\n options.resolvedEnvironment,\n legacyAssets,\n options.envResources,\n options.overrideTemplate,\n );\n let bootstrapStackName: string | undefined;\n try {\n bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;\n } catch (e) {\n await ioHost.notify(debug(action, `Could not determine the bootstrap stack name: ${e}`));\n }\n await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {\n parallel: options.assetParallelism,\n allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, { ioHost, action }, bootstrapStackName),\n }, { ioHost, action });\n\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n // attempt to short-circuit the deployment if possible\n try {\n const hotswapDeploymentResult = await tryHotswapDeployment(\n options.sdkProvider,\n { ioHost, action },\n stackParams.values,\n cloudFormationStack,\n stackArtifact,\n hotswapMode, hotswapPropertyOverrides,\n );\n if (hotswapDeploymentResult) {\n return hotswapDeploymentResult;\n }\n await ioHost.notify(info(action, format(\n 'Could not perform a hotswap deployment, as the stack %s contains non-Asset changes',\n stackArtifact.displayName,\n )));\n } catch (e) {\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n await ioHost.notify(info(action, format(\n 'Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s',\n formatErrorMessage(e),\n )));\n }\n\n if (hotswapMode === HotswapMode.FALL_BACK) {\n await ioHost.notify(info(action, 'Falling back to doing a full deployment'));\n options.sdk.appendCustomUserAgent('cdk-hotswap/fallback');\n } else {\n return {\n type: 'did-deploy-stack',\n noOp: true,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n }\n\n // could not short-circuit the deployment, perform a full CFN deploy instead\n const fullDeployment = new FullCloudFormationDeployment(\n options,\n cloudFormationStack,\n stackArtifact,\n stackParams,\n bodyParameter,\n ioHost,\n action,\n );\n return fullDeployment.performDeployment();\n}\n\ntype CommonPrepareOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof CreateChangeSetCommandInput;\ntype CommonExecuteOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof ExecuteChangeSetCommandInput;\n\n/**\n * This class shares state and functionality between the different full deployment modes\n */\nclass FullCloudFormationDeployment {\n private readonly cfn: ICloudFormationClient;\n private readonly stackName: string;\n private readonly update: boolean;\n private readonly verb: string;\n private readonly uuid: string;\n\n constructor(\n private readonly options: DeployStackOptions,\n private readonly cloudFormationStack: CloudFormationStack,\n private readonly stackArtifact: cxapi.CloudFormationStackArtifact,\n private readonly stackParams: ParameterValues,\n private readonly bodyParameter: TemplateBodyParameter,\n private readonly ioHost: IIoHost,\n private readonly action: ToolkitAction,\n ) {\n this.cfn = options.sdk.cloudFormation();\n this.stackName = options.deployName ?? stackArtifact.stackName;\n\n this.update = cloudFormationStack.exists && cloudFormationStack.stackStatus.name !== 'REVIEW_IN_PROGRESS';\n this.verb = this.update ? 'update' : 'create';\n this.uuid = uuid.v4();\n }\n\n public async performDeployment(): Promise<DeployStackResult> {\n const deploymentMethod = this.options.deploymentMethod ?? {\n method: 'change-set',\n };\n\n if (deploymentMethod.method === 'direct' && this.options.resourcesToImport) {\n throw new ToolkitError('Importing resources requires a changeset deployment');\n }\n\n switch (deploymentMethod.method) {\n case 'change-set':\n return this.changeSetDeployment(deploymentMethod);\n\n case 'direct':\n return this.directDeployment();\n }\n }\n\n private async changeSetDeployment(deploymentMethod: ChangeSetDeploymentMethod): Promise<DeployStackResult> {\n const changeSetName = deploymentMethod.changeSetName ?? 'cdk-deploy-change-set';\n const execute = deploymentMethod.execute ?? true;\n const importExistingResources = deploymentMethod.importExistingResources ?? false;\n const changeSetDescription = await this.createChangeSet(changeSetName, execute, importExistingResources);\n await this.updateTerminationProtection();\n\n if (changeSetHasNoChanges(changeSetDescription)) {\n debug(this.action, format('No changes are to be performed on %s.', this.stackName));\n if (execute) {\n debug(this.action, format('Deleting empty change set %s', changeSetDescription.ChangeSetId));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n\n if (this.options.force) {\n await this.ioHost.notify(warn(\n this.action,\n [\n 'You used the --force flag, but CloudFormation reported that the deployment would not make any changes.',\n 'According to CloudFormation, all resources are already up-to-date with the state in your CDK app.',\n '',\n 'You cannot use the --force flag to get rid of changes you made in the console. Try using',\n 'CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html',\n ].join('\\n'),\n ));\n }\n\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n if (!execute) {\n info(this.action, format(\n 'Changeset %s created and waiting in review for manual execution (--no-execute)',\n changeSetDescription.ChangeSetId,\n ));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n // If there are replacements in the changeset, check the rollback flag and stack status\n const replacement = hasReplacement(changeSetDescription);\n const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;\n const rollback = this.options.rollback ?? true;\n if (isPausedFailState && replacement) {\n return { type: 'failpaused-need-rollback-first', reason: 'replacement', status: this.cloudFormationStack.stackStatus.name };\n }\n if (isPausedFailState && rollback) {\n return { type: 'failpaused-need-rollback-first', reason: 'not-norollback', status: this.cloudFormationStack.stackStatus.name };\n }\n if (!rollback && replacement) {\n return { type: 'replacement-requires-rollback' };\n }\n\n return this.executeChangeSet(changeSetDescription);\n }\n\n private async createChangeSet(changeSetName: string, willExecute: boolean, importExistingResources: boolean) {\n await this.cleanupOldChangeset(changeSetName);\n\n await this.ioHost.notify(debug(this.action, `Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`));\n await this.ioHost.notify(info(this.action, format('%s: creating CloudFormation changeset...', chalk.bold(this.stackName))));\n const changeSet = await this.cfn.createChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n ChangeSetType: this.options.resourcesToImport ? 'IMPORT' : this.update ? 'UPDATE' : 'CREATE',\n ResourcesToImport: this.options.resourcesToImport,\n Description: `CDK Changeset for execution ${this.uuid}`,\n ClientToken: `create${this.uuid}`,\n ImportExistingResources: importExistingResources,\n ...this.commonPrepareOptions(),\n });\n\n await this.ioHost.notify(debug(this.action, format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n return waitForChangeSet(this.cfn, { ioHost: this.ioHost, action: this.action }, this.stackName, changeSetName, {\n fetchAll: willExecute,\n });\n }\n\n private async executeChangeSet(changeSet: DescribeChangeSetCommandOutput): Promise<SuccessfulDeployStackResult> {\n await this.ioHost.notify(debug(this.action, format('Initiating execution of changeset %s on stack %s', changeSet.ChangeSetId, this.stackName)));\n\n await this.cfn.executeChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSet.ChangeSetName!,\n ClientRequestToken: `exec${this.uuid}`,\n ...this.commonExecuteOptions(),\n });\n\n await this.ioHost.notify(debug(\n this.action,\n format(\n 'Execution of changeset %s on stack %s has started; waiting for the update to complete...',\n changeSet.ChangeSetId,\n this.stackName,\n ),\n ));\n\n // +1 for the extra event emitted from updates.\n const changeSetLength: number = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);\n return this.monitorDeployment(changeSet.CreationTime!, changeSetLength);\n }\n\n private async cleanupOldChangeset(changeSetName: string) {\n if (this.cloudFormationStack.exists) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await this.ioHost.notify(debug(this.action, `Removing existing change set with name ${changeSetName} if it exists`));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n }\n\n private async updateTerminationProtection() {\n // Update termination protection only if it has changed.\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {\n await this.ioHost.notify(debug(\n this.action,\n format (\n 'Updating termination protection from %s to %s for stack %s',\n this.cloudFormationStack.terminationProtection,\n terminationProtection,\n this.stackName,\n ),\n ));\n await this.cfn.updateTerminationProtection({\n StackName: this.stackName,\n EnableTerminationProtection: terminationProtection,\n });\n await this.ioHost.notify(debug(this.action, format('Termination protection updated to %s for stack %s', terminationProtection, this.stackName)));\n }\n }\n\n private async directDeployment(): Promise<SuccessfulDeployStackResult> {\n await this.ioHost.notify(info(this.action, format('%s: %s stack...', chalk.bold(this.stackName), this.update ? 'updating' : 'creating')));\n\n const startTime = new Date();\n\n if (this.update) {\n await this.updateTerminationProtection();\n\n try {\n await this.cfn.updateStack({\n StackName: this.stackName,\n ClientRequestToken: `update${this.uuid}`,\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n } catch (err: any) {\n if (err.message === 'No updates are to be performed.') {\n await this.ioHost.notify(debug(this.action, format('No updates are to be performed for stack %s', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: this.cloudFormationStack.stackId,\n };\n }\n throw err;\n }\n\n return this.monitorDeployment(startTime, undefined);\n } else {\n // Take advantage of the fact that we can set termination protection during create\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n\n await this.cfn.createStack({\n StackName: this.stackName,\n ClientRequestToken: `create${this.uuid}`,\n ...(terminationProtection ? { EnableTerminationProtection: true } : undefined),\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n\n return this.monitorDeployment(startTime, undefined);\n }\n }\n\n private async monitorDeployment(startTime: Date, expectedChanges: number | undefined): Promise<SuccessfulDeployStackResult> {\n const monitor = this.options.quiet\n ? undefined\n : StackActivityMonitor.withDefaultPrinter(this.cfn, this.stackName, this.stackArtifact, {\n resourcesTotal: expectedChanges,\n progress: this.options.progress,\n changeSetCreationTime: startTime,\n ci: this.options.ci,\n }).start();\n\n let finalState = this.cloudFormationStack;\n try {\n const successStack = await waitForStackDeploy(this.cfn, { ioHost: this.ioHost, action: this.action }, this.stackName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were deploying it)');\n }\n finalState = successStack;\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor?.errors));\n } finally {\n await monitor?.stop();\n }\n debug(this.action, format('Stack %s has completed updating', this.stackName));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: finalState.outputs,\n stackArn: finalState.stackId,\n };\n }\n\n /**\n * Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet\n */\n private commonPrepareOptions(): Partial<Pick<UpdateStackCommandInput, CommonPrepareOptions>> {\n return {\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n NotificationARNs: this.options.notificationArns,\n Parameters: this.stackParams.apiParameters,\n RoleARN: this.options.roleArn,\n TemplateBody: this.bodyParameter.TemplateBody,\n TemplateURL: this.bodyParameter.TemplateURL,\n Tags: this.options.tags,\n };\n }\n\n /**\n * Return the options that are shared between UpdateStack and CreateChangeSet\n *\n * Be careful not to add in keys for options that aren't used, as the features may not have been\n * deployed everywhere yet.\n */\n private commonExecuteOptions(): Partial<Pick<UpdateStackCommandInput, CommonExecuteOptions>> {\n const shouldDisableRollback = this.options.rollback === false;\n\n return {\n StackName: this.stackName,\n ...(shouldDisableRollback ? { DisableRollback: true } : undefined),\n };\n }\n}\n\nexport interface DestroyStackOptions {\n /**\n * The stack to be destroyed\n */\n stack: cxapi.CloudFormationStackArtifact;\n\n sdk: SDK;\n roleArn?: string;\n deployName?: string;\n quiet?: boolean;\n ci?: boolean;\n}\n\nexport async function destroyStack(options: DestroyStackOptions, { ioHost, action }: IoMessaging) {\n const deployName = options.deployName || options.stack.stackName;\n const cfn = options.sdk.cloudFormation();\n\n const currentStack = await CloudFormationStack.lookup(cfn, deployName);\n if (!currentStack.exists) {\n return;\n }\n const monitor = options.quiet\n ? undefined\n : StackActivityMonitor.withDefaultPrinter(cfn, deployName, options.stack, {\n ci: options.ci,\n }).start();\n\n try {\n await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });\n const destroyedStack = await waitForStackDelete(cfn, { ioHost, action }, deployName);\n if (destroyedStack && destroyedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`);\n }\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor?.errors));\n } finally {\n if (monitor) {\n await monitor.stop();\n }\n }\n}\n\n/**\n * Checks whether we can skip deployment\n *\n * We do this in a complicated way by preprocessing (instead of just\n * looking at the changeset), because if there are nested stacks involved\n * the changeset will always show the nested stacks as needing to be\n * updated, and the deployment will take a long time to in effect not\n * do anything.\n */\nasync function canSkipDeploy(\n deployStackOptions: DeployStackOptions,\n cloudFormationStack: CloudFormationStack,\n parameterChanges: ParameterChanges,\n { ioHost, action }: IoMessaging,\n): Promise<boolean> {\n const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;\n await ioHost.notify(debug(action, `${deployName}: checking if we can skip deploy`));\n\n // Forced deploy\n if (deployStackOptions.force) {\n await ioHost.notify(debug(action, `${deployName}: forced deployment`));\n return false;\n }\n\n // Creating changeset only (default true), never skip\n if (\n deployStackOptions.deploymentMethod?.method === 'change-set' &&\n deployStackOptions.deploymentMethod.execute === false\n ) {\n await ioHost.notify(debug(action, `${deployName}: --no-execute, always creating change set`));\n return false;\n }\n\n // No existing stack\n if (!cloudFormationStack.exists) {\n await ioHost.notify(debug(action, `${deployName}: no existing stack`));\n return false;\n }\n\n // Template has changed (assets taken into account here)\n if (JSON.stringify(deployStackOptions.stack.template) !== JSON.stringify(await cloudFormationStack.template())) {\n await ioHost.notify(debug(action, `${deployName}: template has changed`));\n return false;\n }\n\n // Tags have changed\n if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {\n await ioHost.notify(debug(action, `${deployName}: tags have changed`));\n return false;\n }\n\n // Notification arns have changed\n if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {\n await ioHost.notify(debug(action, `${deployName}: notification arns have changed`));\n return false;\n }\n\n // Termination protection has been updated\n if (!!deployStackOptions.stack.terminationProtection !== !!cloudFormationStack.terminationProtection) {\n await ioHost.notify(debug(action, `${deployName}: termination protection has been updated`));\n return false;\n }\n\n // Parameters have changed\n if (parameterChanges) {\n if (parameterChanges === 'ssm') {\n await ioHost.notify(debug(action, `${deployName}: some parameters come from SSM so we have to assume they may have changed`));\n } else {\n await ioHost.notify(debug(action, `${deployName}: parameters have changed`));\n }\n return false;\n }\n\n // Existing stack is in a failed state\n if (cloudFormationStack.stackStatus.isFailure) {\n await ioHost.notify(debug(action, `${deployName}: stack is in a failure state`));\n return false;\n }\n\n // We can skip deploy\n return true;\n}\n\n/**\n * Compares two list of tags, returns true if identical.\n */\nfunction compareTags(a: Tag[], b: Tag[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (const aTag of a) {\n const bTag = b.find((tag) => tag.Key === aTag.Key);\n\n if (!bTag || bTag.Value !== aTag.Value) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n\nfunction arrayEquals(a: any[], b: any[]): boolean {\n return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));\n}\n\nfunction hasReplacement(cs: DescribeChangeSetCommandOutput) {\n return (cs.Changes ?? []).some(c => {\n const a = c.ResourceChange?.PolicyAction;\n return a === 'ReplaceAndDelete' || a === 'ReplaceAndRetain' || a === 'ReplaceAndSnapshot';\n });\n}\n", "// eslint-disable-next-line max-len\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { EnvironmentResources } from '../environment';\nimport { ToolkitInfo } from '../toolkit-info';\n\n/**\n * Take the metadata assets from the given stack and add them to the given asset manifest\n *\n * Returns the CloudFormation parameters that need to be sent to the template to\n * pass Asset coordinates.\n */\nexport async function addMetadataAssetsToManifest(\n { ioHost, action }: IoMessaging,\n stack: cxapi.CloudFormationStackArtifact,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n reuse?: string[],\n): Promise<Record<string, string>> {\n reuse = reuse || [];\n const assets = stack.assets;\n\n if (assets.length === 0) {\n return {};\n }\n\n const toolkitInfo = await envResources.lookupToolkit();\n if (!toolkitInfo.found) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(`This stack uses assets, so the toolkit stack must be deployed to the environment (Run \"${chalk.blue('cdk bootstrap ' + stack.environment!.name)}\")`);\n }\n\n const params: Record<string, string> = {};\n\n for (const asset of assets) {\n // FIXME: Should have excluded by construct path here instead of by unique ID, preferably using\n // minimatch so we can support globs. Maybe take up during artifact refactoring.\n const reuseAsset = reuse.indexOf(asset.id) > -1;\n\n if (reuseAsset) {\n await ioHost.notify(debug(action, `Reusing asset ${asset.id}: ${JSON.stringify(asset)}`));\n continue;\n }\n\n await ioHost.notify(debug(action, `Preparing asset ${asset.id}: ${JSON.stringify(asset)}`));\n if (!stack.assembly) {\n throw new ToolkitError('Unexpected: stack assembly is required in order to find assets in assembly directory');\n }\n\n Object.assign(params, await prepareAsset({ ioHost, action }, asset, assetManifest, envResources, toolkitInfo));\n }\n\n return params;\n}\n\n// eslint-disable-next-line max-len\nasync function prepareAsset(\n { ioHost, action }: IoMessaging,\n asset: cxschema.AssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n toolkitInfo: ToolkitInfo,\n): Promise<Record<string, string>> {\n switch (asset.packaging) {\n case 'zip':\n case 'file':\n return prepareFileAsset(\n { ioHost, action },\n asset,\n assetManifest,\n toolkitInfo,\n asset.packaging === 'zip' ? cxschema.FileAssetPackaging.ZIP_DIRECTORY : cxschema.FileAssetPackaging.FILE);\n case 'container-image':\n return prepareDockerImageAsset(asset, assetManifest, envResources);\n default:\n // eslint-disable-next-line max-len\n throw new ToolkitError(`Unsupported packaging type: ${(asset as any).packaging}. You might need to upgrade your aws-cdk toolkit to support this asset type.`);\n }\n}\n\nasync function prepareFileAsset(\n { ioHost, action }: IoMessaging,\n asset: cxschema.FileAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n toolkitInfo: ToolkitInfo,\n packaging: cxschema.FileAssetPackaging,\n): Promise<Record<string, string>> {\n const extension = packaging === cxschema.FileAssetPackaging.ZIP_DIRECTORY ? '.zip' : path.extname(asset.path);\n const baseName = `${asset.sourceHash}${extension}`;\n // Simplify key: assets/abcdef/abcdef.zip is kinda silly and unnecessary, so if they're the same just pick one component.\n const s3Prefix = asset.id === asset.sourceHash ? 'assets/' : `assets/${asset.id}/`;\n const key = `${s3Prefix}${baseName}`;\n const s3url = `s3://${toolkitInfo.bucketName}/${key}`;\n\n await ioHost.notify(debug(action, `Storing asset ${asset.path} at ${s3url}`));\n\n assetManifest.addFileAsset(asset.sourceHash, {\n path: asset.path,\n packaging,\n }, {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n });\n\n return {\n [asset.s3BucketParameter]: toolkitInfo.bucketName,\n [asset.s3KeyParameter]: `${s3Prefix}${cxapi.ASSET_PREFIX_SEPARATOR}${baseName}`,\n [asset.artifactHashParameter]: asset.sourceHash,\n };\n}\n\nasync function prepareDockerImageAsset(\n asset: cxschema.ContainerImageAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources): Promise<Record<string, string>> {\n // Pre-1.21.0, repositoryName can be specified by the user or can be left out, in which case we make\n // a per-asset repository which will get adopted and cleaned up along with the stack.\n // Post-1.21.0, repositoryName will always be specified and it will be a shared repository between\n // all assets, and asset will have imageTag specified as well. Validate the combination.\n if (!asset.imageNameParameter && (!asset.repositoryName || !asset.imageTag)) {\n throw new ToolkitError('Invalid Docker image asset configuration: \"repositoryName\" and \"imageTag\" are required when \"imageNameParameter\" is left out');\n }\n\n const repositoryName = asset.repositoryName ?? 'cdk/' + asset.id.replace(/[:/]/g, '-').toLowerCase();\n\n // Make sure the repository exists, since the 'cdk-assets' tool will not create it for us.\n const { repositoryUri } = await envResources.prepareEcrRepository(repositoryName);\n const imageTag = asset.imageTag ?? asset.sourceHash;\n\n assetManifest.addDockerImageAsset(asset.sourceHash, {\n directory: asset.path,\n dockerBuildArgs: asset.buildArgs,\n dockerBuildSsh: asset.buildSsh,\n dockerBuildTarget: asset.target,\n dockerFile: asset.file,\n networkMode: asset.networkMode,\n platform: asset.platform,\n dockerOutputs: asset.outputs,\n }, {\n repositoryName,\n imageTag,\n });\n\n if (!asset.imageNameParameter) {\n return {};\n }\n return { [asset.imageNameParameter]: `${repositoryUri}:${imageTag}` };\n}\n", "import { format } from 'util';\nimport * as cfn_diff from '@aws-cdk/cloudformation-diff';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { WaiterResult } from '@smithy/util-waiter';\nimport * as chalk from 'chalk';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { CloudFormationStack } from './cloudformation';\nimport { NestedStackTemplates, loadCurrentTemplateWithNestedStacks } from './nested-stack-helpers';\nimport { info } from '../../cli/messages';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\nimport { isHotswappableAppSyncChange } from '../hotswap/appsync-mapping-templates';\nimport { isHotswappableCodeBuildProjectChange } from '../hotswap/code-build-projects';\nimport {\n ICON,\n ChangeHotswapResult,\n HotswapMode,\n HotswappableChange,\n NonHotswappableChange,\n HotswappableChangeCandidate,\n HotswapPropertyOverrides, ClassifiedResourceChanges,\n reportNonHotswappableChange,\n reportNonHotswappableResource,\n} from '../hotswap/common';\nimport { isHotswappableEcsServiceChange } from '../hotswap/ecs-services';\nimport { isHotswappableLambdaFunctionChange } from '../hotswap/lambda-functions';\nimport {\n skipChangeForS3DeployCustomResourcePolicy,\n isHotswappableS3BucketDeploymentChange,\n} from '../hotswap/s3-bucket-deployments';\nimport { isHotswappableStateMachineChange } from '../hotswap/stepfunctions-state-machines';\nimport { Mode } from '../plugin';\nimport { SuccessfulDeployStackResult } from './deployment-result';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\n\n// Must use a require() otherwise esbuild complains about calling a namespace\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\ntype HotswapDetector = (\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n) => Promise<ChangeHotswapResult>;\n\nconst RESOURCE_DETECTORS: { [key: string]: HotswapDetector } = {\n // Lambda\n 'AWS::Lambda::Function': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Version': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Alias': isHotswappableLambdaFunctionChange,\n\n // AppSync\n 'AWS::AppSync::Resolver': isHotswappableAppSyncChange,\n 'AWS::AppSync::FunctionConfiguration': isHotswappableAppSyncChange,\n 'AWS::AppSync::GraphQLSchema': isHotswappableAppSyncChange,\n 'AWS::AppSync::ApiKey': isHotswappableAppSyncChange,\n\n 'AWS::ECS::TaskDefinition': isHotswappableEcsServiceChange,\n 'AWS::CodeBuild::Project': isHotswappableCodeBuildProjectChange,\n 'AWS::StepFunctions::StateMachine': isHotswappableStateMachineChange,\n 'Custom::CDKBucketDeployment': isHotswappableS3BucketDeploymentChange,\n 'AWS::IAM::Policy': async (\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n ): Promise<ChangeHotswapResult> => {\n // If the policy is for a S3BucketDeploymentChange, we can ignore the change\n if (await skipChangeForS3DeployCustomResourcePolicy(logicalId, change, evaluateCfnTemplate)) {\n return [];\n }\n\n return reportNonHotswappableResource(change, 'This resource type is not supported for hotswap deployments');\n },\n\n 'AWS::CDK::Metadata': async () => [],\n};\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * If it's not possible to short-circuit the deployment\n * (because the CDK Stack contains changes that cannot be deployed without CloudFormation),\n * returns `undefined`.\n */\nexport async function tryHotswapDeployment(\n sdkProvider: SdkProvider,\n { ioHost, action }: IoMessaging,\n assetParams: { [key: string]: string },\n cloudFormationStack: CloudFormationStack,\n stackArtifact: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode, hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<SuccessfulDeployStackResult | undefined> {\n // resolve the environment, so we can substitute things like AWS::Region in CFN expressions\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // create a new SDK using the CLI credentials, because the default one will not work for new-style synthesis -\n // it assumes the bootstrap deploy Role, which doesn't have permissions to update Lambda functions\n const sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForWriting)).sdk;\n\n const currentTemplate = await loadCurrentTemplateWithNestedStacks(stackArtifact, sdk);\n\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackName: stackArtifact.stackName,\n template: stackArtifact.template,\n parameters: assetParams,\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n nestedStacks: currentTemplate.nestedStacks,\n });\n\n const stackChanges = cfn_diff.fullDiff(currentTemplate.deployedRootTemplate, stackArtifact.template);\n const { hotswappableChanges, nonHotswappableChanges } = await classifyResourceChanges(\n stackChanges,\n evaluateCfnTemplate,\n sdk,\n currentTemplate.nestedStacks, hotswapPropertyOverrides,\n );\n\n await logNonHotswappableChanges({ ioHost, action }, nonHotswappableChanges, hotswapMode);\n\n // preserve classic hotswap behavior\n if (hotswapMode === HotswapMode.FALL_BACK) {\n if (nonHotswappableChanges.length > 0) {\n return undefined;\n }\n }\n\n // apply the short-circuitable changes\n await applyAllHotswappableChanges(sdk, { ioHost, action }, hotswappableChanges);\n\n return {\n type: 'did-deploy-stack',\n noOp: hotswappableChanges.length === 0,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n}\n\n/**\n * Classifies all changes to all resources as either hotswappable or not.\n * Metadata changes are excluded from the list of (non)hotswappable resources.\n */\nasync function classifyResourceChanges(\n stackChanges: cfn_diff.TemplateDiff,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n nestedStackNames: { [nestedStackName: string]: NestedStackTemplates },\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedResourceChanges> {\n const resourceDifferences = getStackResourceDifferences(stackChanges);\n\n const promises: Array<() => Promise<ChangeHotswapResult>> = [];\n const hotswappableResources = new Array<HotswappableChange>();\n const nonHotswappableResources = new Array<NonHotswappableChange>();\n for (const logicalId of Object.keys(stackChanges.outputs.changes)) {\n nonHotswappableResources.push({\n hotswappable: false,\n reason: 'output was changed',\n logicalId,\n rejectedChanges: [],\n resourceType: 'Stack Output',\n });\n }\n // gather the results of the detector functions\n for (const [logicalId, change] of Object.entries(resourceDifferences)) {\n if (change.newValue?.Type === 'AWS::CloudFormation::Stack' && change.oldValue?.Type === 'AWS::CloudFormation::Stack') {\n const nestedHotswappableResources = await findNestedHotswappableChanges(\n logicalId,\n change,\n nestedStackNames,\n evaluateCfnTemplate,\n sdk,\n hotswapPropertyOverrides,\n );\n hotswappableResources.push(...nestedHotswappableResources.hotswappableChanges);\n nonHotswappableResources.push(...nestedHotswappableResources.nonHotswappableChanges);\n\n continue;\n }\n\n const hotswappableChangeCandidate = isCandidateForHotswapping(change, logicalId);\n // we don't need to run this through the detector functions, we can already judge this\n if ('hotswappable' in hotswappableChangeCandidate) {\n if (!hotswappableChangeCandidate.hotswappable) {\n nonHotswappableResources.push(hotswappableChangeCandidate);\n }\n\n continue;\n }\n\n const resourceType: string = hotswappableChangeCandidate.newValue.Type;\n if (resourceType in RESOURCE_DETECTORS) {\n // run detector functions lazily to prevent unhandled promise rejections\n promises.push(() =>\n RESOURCE_DETECTORS[resourceType](logicalId, hotswappableChangeCandidate, evaluateCfnTemplate, hotswapPropertyOverrides),\n );\n } else {\n reportNonHotswappableChange(\n nonHotswappableResources,\n hotswappableChangeCandidate,\n undefined,\n 'This resource type is not supported for hotswap deployments',\n );\n }\n }\n\n // resolve all detector results\n const changesDetectionResults: Array<ChangeHotswapResult> = [];\n for (const detectorResultPromises of promises) {\n // Constant set of promises per resource\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const hotswapDetectionResults = await Promise.all(await detectorResultPromises());\n changesDetectionResults.push(hotswapDetectionResults);\n }\n\n for (const resourceDetectionResults of changesDetectionResults) {\n for (const propertyResult of resourceDetectionResults) {\n propertyResult.hotswappable\n ? hotswappableResources.push(propertyResult)\n : nonHotswappableResources.push(propertyResult);\n }\n }\n\n return {\n hotswappableChanges: hotswappableResources,\n nonHotswappableChanges: nonHotswappableResources,\n };\n}\n\n/**\n * Returns all changes to resources in the given Stack.\n *\n * @param stackChanges the collection of all changes to a given Stack\n */\nfunction getStackResourceDifferences(stackChanges: cfn_diff.TemplateDiff): {\n [logicalId: string]: cfn_diff.ResourceDifference;\n} {\n // we need to collapse logical ID rename changes into one change,\n // as they are represented in stackChanges as a pair of two changes: one addition and one removal\n const allResourceChanges: { [logId: string]: cfn_diff.ResourceDifference } = stackChanges.resources.changes;\n const allRemovalChanges = filterDict(allResourceChanges, (resChange) => resChange.isRemoval);\n const allNonRemovalChanges = filterDict(allResourceChanges, (resChange) => !resChange.isRemoval);\n for (const [logId, nonRemovalChange] of Object.entries(allNonRemovalChanges)) {\n if (nonRemovalChange.isAddition) {\n const addChange = nonRemovalChange;\n // search for an identical removal change\n const identicalRemovalChange = Object.entries(allRemovalChanges).find(([_, remChange]) => {\n return changesAreForSameResource(remChange, addChange);\n });\n // if we found one, then this means this is a rename change\n if (identicalRemovalChange) {\n const [removedLogId, removedResourceChange] = identicalRemovalChange;\n allNonRemovalChanges[logId] = makeRenameDifference(removedResourceChange, addChange);\n // delete the removal change that forms the rename pair\n delete allRemovalChanges[removedLogId];\n }\n }\n }\n // the final result are all of the remaining removal changes,\n // plus all of the non-removal changes\n // (we saved the rename changes in that object already)\n return {\n ...allRemovalChanges,\n ...allNonRemovalChanges,\n };\n}\n\n/** Filters an object with string keys based on whether the callback returns 'true' for the given value in the object. */\nfunction filterDict<T>(dict: { [key: string]: T }, func: (t: T) => boolean): { [key: string]: T } {\n return Object.entries(dict).reduce(\n (acc, [key, t]) => {\n if (func(t)) {\n acc[key] = t;\n }\n return acc;\n },\n {} as { [key: string]: T },\n );\n}\n\n/** Finds any hotswappable changes in all nested stacks. */\nasync function findNestedHotswappableChanges(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n nestedStackTemplates: { [nestedStackName: string]: NestedStackTemplates },\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedResourceChanges> {\n const nestedStack = nestedStackTemplates[logicalId];\n if (!nestedStack.physicalName) {\n return {\n hotswappableChanges: [],\n nonHotswappableChanges: [\n {\n hotswappable: false,\n logicalId,\n reason: `physical name for AWS::CloudFormation::Stack '${logicalId}' could not be found in CloudFormation, so this is a newly created nested stack and cannot be hotswapped`,\n rejectedChanges: [],\n resourceType: 'AWS::CloudFormation::Stack',\n },\n ],\n };\n }\n\n const evaluateNestedCfnTemplate = await evaluateCfnTemplate.createNestedEvaluateCloudFormationTemplate(\n nestedStack.physicalName,\n nestedStack.generatedTemplate,\n change.newValue?.Properties?.Parameters,\n );\n\n const nestedDiff = cfn_diff.fullDiff(\n nestedStackTemplates[logicalId].deployedTemplate,\n nestedStackTemplates[logicalId].generatedTemplate,\n );\n\n return classifyResourceChanges(\n nestedDiff,\n evaluateNestedCfnTemplate,\n sdk,\n nestedStackTemplates[logicalId].nestedStackTemplates,\n hotswapPropertyOverrides);\n}\n\n/** Returns 'true' if a pair of changes is for the same resource. */\nfunction changesAreForSameResource(\n oldChange: cfn_diff.ResourceDifference,\n newChange: cfn_diff.ResourceDifference,\n): boolean {\n return (\n oldChange.oldResourceType === newChange.newResourceType &&\n // this isn't great, but I don't want to bring in something like underscore just for this comparison\n JSON.stringify(oldChange.oldProperties) === JSON.stringify(newChange.newProperties)\n );\n}\n\nfunction makeRenameDifference(\n remChange: cfn_diff.ResourceDifference,\n addChange: cfn_diff.ResourceDifference,\n): cfn_diff.ResourceDifference {\n return new cfn_diff.ResourceDifference(\n // we have to fill in the old value, because otherwise this will be classified as a non-hotswappable change\n remChange.oldValue,\n addChange.newValue,\n {\n resourceType: {\n oldType: remChange.oldResourceType,\n newType: addChange.newResourceType,\n },\n propertyDiffs: (addChange as any).propertyDiffs,\n otherDiffs: (addChange as any).otherDiffs,\n },\n );\n}\n\n/**\n * Returns a `HotswappableChangeCandidate` if the change is hotswappable\n * Returns an empty `HotswappableChange` if the change is to CDK::Metadata\n * Returns a `NonHotswappableChange` if the change is not hotswappable\n */\nfunction isCandidateForHotswapping(\n change: cfn_diff.ResourceDifference,\n logicalId: string,\n): HotswappableChange | NonHotswappableChange | HotswappableChangeCandidate {\n // a resource has been removed OR a resource has been added; we can't short-circuit that change\n if (!change.oldValue) {\n return {\n hotswappable: false,\n resourceType: change.newValue!.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' was created by this deployment`,\n };\n } else if (!change.newValue) {\n return {\n hotswappable: false,\n resourceType: change.oldValue!.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' was destroyed by this deployment`,\n };\n }\n\n // a resource has had its type changed\n if (change.newValue?.Type !== change.oldValue?.Type) {\n return {\n hotswappable: false,\n resourceType: change.newValue?.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' had its type changed from '${change.oldValue?.Type}' to '${change.newValue?.Type}'`,\n };\n }\n\n return {\n logicalId,\n oldValue: change.oldValue,\n newValue: change.newValue,\n propertyUpdates: change.propertyUpdates,\n };\n}\n\nasync function applyAllHotswappableChanges(sdk: SDK, { ioHost, action }: IoMessaging, hotswappableChanges: HotswappableChange[]): Promise<void[]> {\n if (hotswappableChanges.length > 0) {\n await ioHost.notify(info(action, `\\n${ICON} hotswapping resources:`));\n }\n const limit = pLimit(10);\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(hotswappableChanges.map(hotswapOperation => limit(() => {\n return applyHotswappableChange(sdk, { ioHost, action }, hotswapOperation);\n })));\n}\n\nasync function applyHotswappableChange(sdk: SDK, { ioHost, action }: IoMessaging, hotswapOperation: HotswappableChange): Promise<void> {\n // note the type of service that was successfully hotswapped in the User-Agent\n const customUserAgent = `cdk-hotswap/success-${hotswapOperation.service}`;\n sdk.appendCustomUserAgent(customUserAgent);\n\n for (const name of hotswapOperation.resourceNames) {\n await ioHost.notify(info(action, format(` ${ICON} %s`, chalk.bold(name))));\n }\n\n // if the SDK call fails, an error will be thrown by the SDK\n // and will prevent the green 'hotswapped!' text from being displayed\n try {\n await hotswapOperation.apply(sdk);\n } catch (e: any) {\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n const result: WaiterResult = JSON.parse(formatErrorMessage(e));\n const error = new ToolkitError(formatWaiterErrorResult(result));\n error.name = e.name;\n throw error;\n }\n throw e;\n }\n\n for (const name of hotswapOperation.resourceNames) {\n await ioHost.notify(info(action, format(`${ICON} %s %s`, chalk.bold(name), chalk.green('hotswapped!'))));\n }\n\n sdk.removeCustomUserAgent(customUserAgent);\n}\n\nfunction formatWaiterErrorResult(result: WaiterResult) {\n const main = [\n `Resource is not in the expected state due to waiter status: ${result.state}`,\n result.reason ? `${result.reason}.` : '',\n ].join('. ');\n\n if (result.observedResponses != null) {\n const observedResponses = Object\n .entries(result.observedResponses)\n .map(([msg, count]) => ` - ${msg} (${count})`)\n .join('\\n');\n\n return `${main} Observed responses:\\n${observedResponses}`;\n }\n\n return main;\n}\n\nasync function logNonHotswappableChanges(\n { ioHost, action }: IoMessaging,\n nonHotswappableChanges: NonHotswappableChange[],\n hotswapMode: HotswapMode,\n): Promise<void> {\n if (nonHotswappableChanges.length === 0) {\n return;\n }\n /**\n * EKS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n if (hotswapMode === HotswapMode.HOTSWAP_ONLY) {\n nonHotswappableChanges = nonHotswappableChanges.filter((change) => change.hotswapOnlyVisible === true);\n\n if (nonHotswappableChanges.length === 0) {\n return;\n }\n }\n\n const messages = ['']; // start with empty line\n\n if (hotswapMode === HotswapMode.HOTSWAP_ONLY) {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found. To reconcile these using CloudFormation, specify --hotswap-fallback')));\n } else {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found:')));\n }\n\n for (const change of nonHotswappableChanges) {\n if (change.rejectedChanges.length > 0) {\n messages.push(format(\n ' logicalID: %s, type: %s, rejected changes: %s, reason: %s',\n chalk.bold(change.logicalId),\n chalk.bold(change.resourceType),\n chalk.bold(change.rejectedChanges),\n chalk.red(change.reason),\n ));\n } else {\n messages.push(format(\n ' logicalID: %s, type: %s, reason: %s',\n chalk.bold(change.logicalId),\n chalk.bold(change.resourceType),\n chalk.red(change.reason),\n ));\n }\n }\n messages.push(''); // newline\n\n await ioHost.notify(info(action, messages.join('\\n')));\n}\n", "import * as path from 'path';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { SDK } from '../aws-auth';\nimport { CloudFormationStack, type Template } from './cloudformation';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { LazyListStackResources, type ListStackResources } from '../evaluate-cloudformation-template';\n\nexport interface NestedStackTemplates {\n readonly physicalName: string | undefined;\n readonly deployedTemplate: Template;\n readonly generatedTemplate: Template;\n readonly nestedStackTemplates: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport interface RootTemplateWithNestedStacks {\n readonly deployedRootTemplate: Template;\n readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Reads the currently deployed template and all of its nested stack templates from CloudFormation.\n */\nexport async function loadCurrentTemplateWithNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<RootTemplateWithNestedStacks> {\n const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate);\n const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, {\n generatedTemplate: rootStackArtifact.template,\n deployedTemplate: deployedRootTemplate,\n deployedStackName: rootStackArtifact.stackName,\n });\n\n return {\n deployedRootTemplate,\n nestedStacks,\n };\n}\n\n/**\n * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`.\n */\nexport async function loadCurrentTemplate(\n stackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n return loadCurrentStackTemplate(stackArtifact.stackName, sdk, retrieveProcessedTemplate);\n}\n\nasync function loadCurrentStackTemplate(\n stackName: string,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n const cfn = sdk.cloudFormation();\n const stack = await CloudFormationStack.lookup(cfn, stackName, retrieveProcessedTemplate);\n return stack.template();\n}\n\nasync function loadNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n parentTemplates: StackTemplates,\n): Promise<{ [nestedStackLogicalId: string]: NestedStackTemplates }> {\n const listStackResources = parentTemplates.deployedStackName\n ? new LazyListStackResources(sdk, parentTemplates.deployedStackName)\n : undefined;\n const nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } = {};\n for (const [nestedStackLogicalId, generatedNestedStackResource] of Object.entries(\n parentTemplates.generatedTemplate.Resources ?? {},\n )) {\n if (!isCdkManagedNestedStack(generatedNestedStackResource)) {\n continue;\n }\n\n const assetPath = generatedNestedStackResource.Metadata['aws:asset:path'];\n const nestedStackTemplates = await getNestedStackTemplates(\n rootStackArtifact,\n assetPath,\n nestedStackLogicalId,\n listStackResources,\n sdk,\n );\n\n nestedStacks[nestedStackLogicalId] = {\n deployedTemplate: nestedStackTemplates.deployedTemplate,\n generatedTemplate: nestedStackTemplates.generatedTemplate,\n physicalName: nestedStackTemplates.deployedStackName,\n nestedStackTemplates: await loadNestedStacks(rootStackArtifact, sdk, nestedStackTemplates),\n };\n }\n\n return nestedStacks;\n}\n\nasync function getNestedStackTemplates(\n rootStackArtifact: CloudFormationStackArtifact,\n nestedTemplateAssetPath: string,\n nestedStackLogicalId: string,\n listStackResources: ListStackResources | undefined,\n sdk: SDK,\n): Promise<StackTemplates> {\n const nestedTemplatePath = path.join(rootStackArtifact.assembly.directory, nestedTemplateAssetPath);\n\n // CFN generates the nested stack name in the form `ParentStackName-NestedStackLogicalID-SomeHashWeCan'tCompute,\n // the arn is of the form: arn:aws:cloudformation:region:123456789012:stack/NestedStackName/AnotherHashWeDon'tNeed\n // so we get the ARN and manually extract the name.\n const nestedStackArn = await getNestedStackArn(nestedStackLogicalId, listStackResources);\n const deployedStackName = nestedStackArn?.slice(nestedStackArn.indexOf('/') + 1, nestedStackArn.lastIndexOf('/'));\n\n return {\n generatedTemplate: JSON.parse(fs.readFileSync(nestedTemplatePath, 'utf-8')),\n deployedTemplate: deployedStackName ? await loadCurrentStackTemplate(deployedStackName, sdk) : {},\n deployedStackName,\n };\n}\n\nasync function getNestedStackArn(\n nestedStackLogicalId: string,\n listStackResources?: ListStackResources,\n): Promise<string | undefined> {\n try {\n const stackResources = await listStackResources?.listStackResources();\n return stackResources?.find((sr) => sr.LogicalResourceId === nestedStackLogicalId)?.PhysicalResourceId;\n } catch (e: any) {\n if (formatErrorMessage(e).startsWith('Stack with id ') && formatErrorMessage(e).endsWith(' does not exist')) {\n return;\n }\n throw e;\n }\n}\n\nfunction isCdkManagedNestedStack(stackResource: any): stackResource is NestedStackResource {\n return (\n stackResource.Type === 'AWS::CloudFormation::Stack' &&\n stackResource.Metadata &&\n stackResource.Metadata['aws:asset:path']\n );\n}\n\ninterface StackTemplates {\n readonly generatedTemplate: any;\n readonly deployedTemplate: any;\n readonly deployedStackName: string | undefined;\n}\n\ninterface NestedStackResource {\n readonly Metadata: { 'aws:asset:path': string };\n readonly Properties: any;\n}\n", "import type { Export, ListExportsCommandOutput, StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport type { SDK } from './aws-auth';\nimport type { NestedStackTemplates } from './deployments';\nimport { ToolkitError } from '../toolkit/error';\n\nexport interface ListStackResources {\n listStackResources(): Promise<StackResourceSummary[]>;\n}\n\nexport class LazyListStackResources implements ListStackResources {\n private stackResources: Promise<StackResourceSummary[]> | undefined;\n\n constructor(\n private readonly sdk: SDK,\n private readonly stackName: string,\n ) {\n }\n\n public async listStackResources(): Promise<StackResourceSummary[]> {\n if (this.stackResources === undefined) {\n this.stackResources = this.sdk.cloudFormation().listStackResources({\n StackName: this.stackName,\n });\n }\n return this.stackResources;\n }\n}\n\nexport interface LookupExport {\n lookupExport(name: string): Promise<Export | undefined>;\n}\n\nexport class LookupExportError extends Error {\n}\n\nexport class LazyLookupExport implements LookupExport {\n private cachedExports: { [name: string]: Export } = {};\n\n constructor(private readonly sdk: SDK) {\n }\n\n async lookupExport(name: string): Promise<Export | undefined> {\n if (this.cachedExports[name]) {\n return this.cachedExports[name];\n }\n\n for await (const cfnExport of this.listExports()) {\n if (!cfnExport.Name) {\n continue; // ignore any result that omits a name\n }\n this.cachedExports[cfnExport.Name] = cfnExport;\n\n if (cfnExport.Name === name) {\n return cfnExport;\n }\n }\n\n return undefined; // export not found\n }\n\n // TODO: Paginate\n private async *listExports() {\n let nextToken: string | undefined = undefined;\n while (true) {\n const response: ListExportsCommandOutput = await this.sdk.cloudFormation().listExports({ NextToken: nextToken });\n for (const cfnExport of response.Exports ?? []) {\n yield cfnExport;\n }\n\n if (!response.NextToken) {\n return;\n }\n nextToken = response.NextToken;\n }\n }\n}\n\nexport class CfnEvaluationException extends Error {\n}\n\nexport interface ResourceDefinition {\n readonly LogicalId: string;\n readonly Type: string;\n readonly Properties: { [p: string]: any };\n}\n\nexport interface EvaluateCloudFormationTemplateProps {\n readonly stackName: string;\n readonly template: Template;\n readonly parameters: { [parameterName: string]: string };\n readonly account: string;\n readonly region: string;\n readonly partition: string;\n readonly sdk: SDK;\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport class EvaluateCloudFormationTemplate {\n private readonly stackName: string;\n private readonly template: Template;\n private readonly context: { [k: string]: any };\n private readonly account: string;\n private readonly region: string;\n private readonly partition: string;\n private readonly sdk: SDK;\n private readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n private readonly stackResources: ListStackResources;\n private readonly lookupExport: LookupExport;\n\n private cachedUrlSuffix: string | undefined;\n\n constructor(props: EvaluateCloudFormationTemplateProps) {\n this.stackName = props.stackName;\n this.template = props.template;\n this.context = {\n 'AWS::AccountId': props.account,\n 'AWS::Region': props.region,\n 'AWS::Partition': props.partition,\n ...props.parameters,\n };\n this.account = props.account;\n this.region = props.region;\n this.partition = props.partition;\n this.sdk = props.sdk;\n\n // We need names of nested stack so we can evaluate cross stack references\n this.nestedStacks = props.nestedStacks ?? {};\n\n // The current resources of the Stack.\n // We need them to figure out the physical name of a resource in case it wasn't specified by the user.\n // We fetch it lazily, to save a service call, in case all hotswapped resources have their physical names set.\n this.stackResources = new LazyListStackResources(this.sdk, this.stackName);\n\n // CloudFormation Exports lookup to be able to resolve Fn::ImportValue intrinsics in template\n this.lookupExport = new LazyLookupExport(this.sdk);\n }\n\n // clones current EvaluateCloudFormationTemplate object, but updates the stack name\n public async createNestedEvaluateCloudFormationTemplate(\n stackName: string,\n nestedTemplate: Template,\n nestedStackParameters: { [parameterName: string]: any },\n ) {\n const evaluatedParams = await this.evaluateCfnExpression(nestedStackParameters);\n return new EvaluateCloudFormationTemplate({\n stackName,\n template: nestedTemplate,\n parameters: evaluatedParams,\n account: this.account,\n region: this.region,\n partition: this.partition,\n sdk: this.sdk,\n nestedStacks: this.nestedStacks,\n });\n }\n\n public async establishResourcePhysicalName(\n logicalId: string,\n physicalNameInCfnTemplate: any,\n ): Promise<string | undefined> {\n if (physicalNameInCfnTemplate != null) {\n try {\n return await this.evaluateCfnExpression(physicalNameInCfnTemplate);\n } catch (e) {\n // If we can't evaluate the resource's name CloudFormation expression,\n // just look it up in the currently deployed Stack\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n }\n }\n return this.findPhysicalNameFor(logicalId);\n }\n\n public async findPhysicalNameFor(logicalId: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.LogicalResourceId === logicalId)?.PhysicalResourceId;\n }\n\n public async findLogicalIdForPhysicalName(physicalName: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.PhysicalResourceId === physicalName)?.LogicalResourceId;\n }\n\n public findReferencesTo(logicalId: string): Array<ResourceDefinition> {\n const ret = new Array<ResourceDefinition>();\n for (const [resourceLogicalId, resourceDef] of Object.entries(this.template?.Resources ?? {})) {\n if (logicalId !== resourceLogicalId && this.references(logicalId, resourceDef)) {\n ret.push({\n ...(resourceDef as any),\n LogicalId: resourceLogicalId,\n });\n }\n }\n return ret;\n }\n\n public async evaluateCfnExpression(cfnExpression: any): Promise<any> {\n const self = this;\n /**\n * Evaluates CloudFormation intrinsic functions\n *\n * Note that supported intrinsic functions are documented in README.md -- please update\n * list of supported functions when adding new evaluations\n *\n * See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html\n */\n class CfnIntrinsics {\n public evaluateIntrinsic(intrinsic: Intrinsic): any {\n const intrinsicFunc = (this as any)[intrinsic.name];\n if (!intrinsicFunc) {\n throw new CfnEvaluationException(`CloudFormation function ${intrinsic.name} is not supported`);\n }\n\n const argsAsArray = Array.isArray(intrinsic.args) ? intrinsic.args : [intrinsic.args];\n\n return intrinsicFunc.apply(this, argsAsArray);\n }\n\n async 'Fn::Join'(separator: string, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.join(separator);\n }\n\n async 'Fn::Split'(separator: string, args: any): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.split(separator);\n }\n\n async 'Fn::Select'(index: number, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs[index];\n }\n\n async Ref(logicalId: string): Promise<string> {\n const refTarget = await self.findRefTarget(logicalId);\n if (refTarget) {\n return refTarget;\n } else {\n throw new CfnEvaluationException(`Parameter or resource '${logicalId}' could not be found for evaluation`);\n }\n }\n\n async 'Fn::GetAtt'(logicalId: string, attributeName: string): Promise<string> {\n // ToDo handle the 'logicalId.attributeName' form of Fn::GetAtt\n const attrValue = await self.findGetAttTarget(logicalId, attributeName);\n if (attrValue) {\n return attrValue;\n } else {\n throw new CfnEvaluationException(\n `Attribute '${attributeName}' of resource '${logicalId}' could not be found for evaluation`,\n );\n }\n }\n\n async 'Fn::Sub'(template: string, explicitPlaceholders?: { [variable: string]: string }): Promise<string> {\n const placeholders = explicitPlaceholders ? await self.evaluateCfnExpression(explicitPlaceholders) : {};\n\n return asyncGlobalReplace(template, /\\${([^}]*)}/g, (key) => {\n if (key in placeholders) {\n return placeholders[key];\n } else {\n const splitKey = key.split('.');\n return splitKey.length === 1 ? this.Ref(key) : this['Fn::GetAtt'](splitKey[0], splitKey.slice(1).join('.'));\n }\n });\n }\n\n async 'Fn::ImportValue'(name: string): Promise<string> {\n const exported = await self.lookupExport.lookupExport(name);\n if (!exported) {\n throw new CfnEvaluationException(`Export '${name}' could not be found for evaluation`);\n }\n if (!exported.Value) {\n throw new CfnEvaluationException(`Export '${name}' exists without a value`);\n }\n return exported.Value;\n }\n }\n\n if (cfnExpression == null) {\n return cfnExpression;\n }\n\n if (Array.isArray(cfnExpression)) {\n // Small arrays in practice\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(cfnExpression.map((expr) => this.evaluateCfnExpression(expr)));\n }\n\n if (typeof cfnExpression === 'object') {\n const intrinsic = this.parseIntrinsic(cfnExpression);\n if (intrinsic) {\n return new CfnIntrinsics().evaluateIntrinsic(intrinsic);\n } else {\n const ret: { [key: string]: any } = {};\n for (const [key, val] of Object.entries(cfnExpression)) {\n ret[key] = await this.evaluateCfnExpression(val);\n }\n return ret;\n }\n }\n\n return cfnExpression;\n }\n\n public getResourceProperty(logicalId: string, propertyName: string): any {\n return this.template.Resources?.[logicalId]?.Properties?.[propertyName];\n }\n\n private references(logicalId: string, templateElement: any): boolean {\n if (typeof templateElement === 'string') {\n return logicalId === templateElement;\n }\n\n if (templateElement == null) {\n return false;\n }\n\n if (Array.isArray(templateElement)) {\n return templateElement.some((el) => this.references(logicalId, el));\n }\n\n if (typeof templateElement === 'object') {\n return Object.values(templateElement).some((el) => this.references(logicalId, el));\n }\n\n return false;\n }\n\n private parseIntrinsic(x: any): Intrinsic | undefined {\n const keys = Object.keys(x);\n if (keys.length === 1 && (keys[0].startsWith('Fn::') || keys[0] === 'Ref')) {\n return {\n name: keys[0],\n args: x[keys[0]],\n };\n }\n return undefined;\n }\n\n private async findRefTarget(logicalId: string): Promise<string | undefined> {\n // first, check to see if the Ref is a Parameter who's value we have\n if (logicalId === 'AWS::URLSuffix') {\n if (!this.cachedUrlSuffix) {\n this.cachedUrlSuffix = await this.sdk.getUrlSuffix(this.region);\n }\n\n return this.cachedUrlSuffix;\n }\n\n // Try finding the ref in the passed in parameters\n const parameterTarget = this.context[logicalId];\n if (parameterTarget) {\n return parameterTarget;\n }\n\n // If not in the passed in parameters, see if there is a default value in the template parameter that was not passed in\n const defaultParameterValue = this.template.Parameters?.[logicalId]?.Default;\n if (defaultParameterValue) {\n return defaultParameterValue;\n }\n\n // if it's not a Parameter, we need to search in the current Stack resources\n return this.findGetAttTarget(logicalId);\n }\n\n private async findGetAttTarget(logicalId: string, attribute?: string): Promise<string | undefined> {\n // Handle case where the attribute is referencing a stack output (used in nested stacks to share parameters)\n // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#w2ab1c17c23c19b5\n if (logicalId === 'Outputs' && attribute) {\n return this.evaluateCfnExpression(this.template.Outputs[attribute]?.Value);\n }\n\n const stackResources = await this.stackResources.listStackResources();\n const foundResource = stackResources.find((sr) => sr.LogicalResourceId === logicalId);\n if (!foundResource) {\n return undefined;\n }\n\n if (foundResource.ResourceType == 'AWS::CloudFormation::Stack' && attribute?.startsWith('Outputs.')) {\n const dependantStack = this.findNestedStack(logicalId, this.nestedStacks);\n if (!dependantStack || !dependantStack.physicalName) {\n // this is a newly created nested stack and cannot be hotswapped\n return undefined;\n }\n const evaluateCfnTemplate = await this.createNestedEvaluateCloudFormationTemplate(\n dependantStack.physicalName,\n dependantStack.generatedTemplate,\n dependantStack.generatedTemplate.Parameters!,\n );\n\n // Split Outputs.<refName> into 'Outputs' and '<refName>' and recursively call evaluate\n return evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::GetAtt': attribute.split(/\\.(.*)/s),\n });\n }\n // now, we need to format the appropriate identifier depending on the resource type,\n // and the requested attribute name\n return this.formatResourceAttribute(foundResource, attribute);\n }\n\n private findNestedStack(\n logicalId: string,\n nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n },\n ): NestedStackTemplates | undefined {\n for (const nestedStackLogicalId of Object.keys(nestedStacks)) {\n if (nestedStackLogicalId === logicalId) {\n return nestedStacks[nestedStackLogicalId];\n }\n const checkInNestedChildStacks = this.findNestedStack(\n logicalId,\n nestedStacks[nestedStackLogicalId].nestedStackTemplates,\n );\n if (checkInNestedChildStacks) return checkInNestedChildStacks;\n }\n return undefined;\n }\n\n private formatResourceAttribute(resource: StackResourceSummary, attribute: string | undefined): string | undefined {\n const physicalId = resource.PhysicalResourceId;\n\n // no attribute means Ref expression, for which we use the physical ID directly\n if (!attribute) {\n return physicalId;\n }\n\n const resourceTypeFormats = RESOURCE_TYPE_ATTRIBUTES_FORMATS[resource.ResourceType!];\n if (!resourceTypeFormats) {\n throw new CfnEvaluationException(\n `We don't support attributes of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const attributeFmtFunc = resourceTypeFormats[attribute];\n if (!attributeFmtFunc) {\n throw new CfnEvaluationException(\n `We don't support the '${attribute}' attribute of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const service = this.getServiceOfResource(resource);\n const resourceTypeArnPart = this.getResourceTypeArnPartOfResource(resource);\n return attributeFmtFunc({\n partition: this.partition,\n service,\n region: this.region,\n account: this.account,\n resourceType: resourceTypeArnPart,\n resourceName: physicalId!,\n });\n }\n\n private getServiceOfResource(resource: StackResourceSummary): string {\n return resource.ResourceType!.split('::')[1].toLowerCase();\n }\n\n private getResourceTypeArnPartOfResource(resource: StackResourceSummary): string {\n const resourceType = resource.ResourceType!;\n const specialCaseResourceType = RESOURCE_TYPE_SPECIAL_NAMES[resourceType]?.resourceType;\n return specialCaseResourceType\n ? specialCaseResourceType\n : // this is the default case\n resourceType.split('::')[2].toLowerCase();\n }\n}\n\nexport type Template = { [section: string]: { [headings: string]: any } };\n\ninterface ArnParts {\n readonly partition: string;\n readonly service: string;\n readonly region: string;\n readonly account: string;\n readonly resourceType: string;\n readonly resourceName: string;\n}\n\n/**\n * Usually, we deduce the names of the service and the resource type used to format the ARN from the CloudFormation resource type.\n * For a CFN type like AWS::Service::ResourceType, the second segment becomes the service name, and the third the resource type\n * (after converting both of them to lowercase).\n * However, some resource types break this simple convention, and we need to special-case them.\n * This map is for storing those cases.\n */\nconst RESOURCE_TYPE_SPECIAL_NAMES: {\n [type: string]: { resourceType: string };\n} = {\n 'AWS::Events::EventBus': {\n resourceType: 'event-bus',\n },\n};\n\nconst RESOURCE_TYPE_ATTRIBUTES_FORMATS: {\n [type: string]: { [attribute: string]: (parts: ArnParts) => string };\n} = {\n 'AWS::IAM::Role': { Arn: iamArnFmt },\n 'AWS::IAM::User': { Arn: iamArnFmt },\n 'AWS::IAM::Group': { Arn: iamArnFmt },\n 'AWS::S3::Bucket': { Arn: s3ArnFmt },\n 'AWS::Lambda::Function': { Arn: stdColonResourceArnFmt },\n 'AWS::Events::EventBus': {\n Arn: stdSlashResourceArnFmt,\n // the name attribute of the EventBus is the same as the Ref\n Name: (parts) => parts.resourceName,\n },\n 'AWS::DynamoDB::Table': { Arn: stdSlashResourceArnFmt },\n 'AWS::AppSync::GraphQLApi': { ApiId: appsyncGraphQlApiApiIdFmt },\n 'AWS::AppSync::FunctionConfiguration': {\n FunctionId: appsyncGraphQlFunctionIDFmt,\n },\n 'AWS::AppSync::DataSource': { Name: appsyncGraphQlDataSourceNameFmt },\n 'AWS::KMS::Key': { Arn: stdSlashResourceArnFmt },\n};\n\nfunction iamArnFmt(parts: ArnParts): string {\n // we skip region for IAM resources\n return `arn:${parts.partition}:${parts.service}::${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction s3ArnFmt(parts: ArnParts): string {\n // we skip account, region and resourceType for S3 resources\n return `arn:${parts.partition}:${parts.service}:::${parts.resourceName}`;\n}\n\nfunction stdColonResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType:resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}:${parts.resourceName}`;\n}\n\nfunction stdSlashResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType/resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction appsyncGraphQlApiApiIdFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>\n return parts.resourceName.split('/')[1];\n}\n\nfunction appsyncGraphQlFunctionIDFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/functions/<functionId>\n return parts.resourceName.split('/')[3];\n}\n\nfunction appsyncGraphQlDataSourceNameFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/datasources/<name>\n return parts.resourceName.split('/')[3];\n}\n\ninterface Intrinsic {\n readonly name: string;\n readonly args: any;\n}\n\nasync function asyncGlobalReplace(str: string, regex: RegExp, cb: (x: string) => Promise<string>): Promise<string> {\n if (!regex.global) {\n throw new ToolkitError('Regex must be created with /g flag');\n }\n\n const ret = new Array<string>();\n let start = 0;\n while (true) {\n const match = regex.exec(str);\n if (!match) {\n break;\n }\n\n ret.push(str.substring(start, match.index));\n ret.push(await cb(match[1]));\n\n start = regex.lastIndex;\n }\n ret.push(str.slice(start));\n\n return ret.join('');\n}\n", "import type { PropertyDifference, Resource } from '@aws-cdk/cloudformation-diff';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SDK } from '../aws-auth';\n\nexport const ICON = '\u2728';\n\nexport interface HotswappableChange {\n readonly hotswappable: true;\n readonly resourceType: string;\n readonly propsChanged: Array<string>;\n /**\n * The name of the service being hotswapped.\n * Used to set a custom User-Agent for SDK calls.\n */\n readonly service: string;\n\n /**\n * The names of the resources being hotswapped.\n */\n readonly resourceNames: string[];\n\n readonly apply: (sdk: SDK) => Promise<void>;\n}\n\nexport interface NonHotswappableChange {\n readonly hotswappable: false;\n readonly resourceType: string;\n readonly rejectedChanges: Array<string>;\n readonly logicalId: string;\n /**\n * Tells the user exactly why this change was deemed non-hotswappable and what its logical ID is.\n * If not specified, `reason` will be autofilled to state that the properties listed in `rejectedChanges` are not hotswappable.\n */\n readonly reason?: string;\n /**\n * Whether or not to show this change when listing non-hotswappable changes in HOTSWAP_ONLY mode. Does not affect\n * listing in FALL_BACK mode.\n *\n * @default true\n */\n readonly hotswapOnlyVisible?: boolean;\n}\n\nexport type ChangeHotswapResult = Array<HotswappableChange | NonHotswappableChange>;\n\nexport interface ClassifiedResourceChanges {\n hotswappableChanges: HotswappableChange[];\n nonHotswappableChanges: NonHotswappableChange[];\n}\n\nexport enum HotswapMode {\n /**\n * Will fall back to CloudFormation when a non-hotswappable change is detected\n */\n FALL_BACK = 'fall-back',\n\n /**\n * Will not fall back to CloudFormation when a non-hotswappable change is detected\n */\n HOTSWAP_ONLY = 'hotswap-only',\n\n /**\n * Will not attempt to hotswap anything and instead go straight to CloudFormation\n */\n FULL_DEPLOYMENT = 'full-deployment',\n}\n\n/**\n * Represents a change that can be hotswapped.\n */\nexport class HotswappableChangeCandidate {\n /**\n * The logical ID of the resource which is being changed\n */\n public readonly logicalId: string;\n\n /**\n * The value the resource is being updated from\n */\n public readonly oldValue: Resource;\n\n /**\n * The value the resource is being updated to\n */\n public readonly newValue: Resource;\n\n /**\n * The changes made to the resource properties\n */\n public readonly propertyUpdates: PropDiffs;\n\n public constructor(logicalId: string, oldValue: Resource, newValue: Resource, propertyUpdates: PropDiffs) {\n this.logicalId = logicalId;\n this.oldValue = oldValue;\n this.newValue = newValue;\n this.propertyUpdates = propertyUpdates;\n }\n}\n\ntype Exclude = { [key: string]: Exclude | true };\n\n/**\n * Represents configuration property overrides for hotswap deployments\n */\nexport class HotswapPropertyOverrides {\n // Each supported resource type will have its own properties. Currently this is ECS\n ecsHotswapProperties?: EcsHotswapProperties;\n\n public constructor (ecsHotswapProperties?: EcsHotswapProperties) {\n this.ecsHotswapProperties = ecsHotswapProperties;\n }\n}\n\n/**\n * Represents configuration properties for ECS hotswap deployments\n */\nexport class EcsHotswapProperties {\n // The lower limit on the number of your service's tasks that must remain in the RUNNING state during a deployment, as a percentage of the desiredCount\n readonly minimumHealthyPercent?: number;\n // The upper limit on the number of your service's tasks that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desiredCount\n readonly maximumHealthyPercent?: number;\n\n public constructor (minimumHealthyPercent?: number, maximumHealthyPercent?: number) {\n if (minimumHealthyPercent !== undefined && minimumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-minimum-healthy-percent can\\'t be a negative number');\n }\n if (maximumHealthyPercent !== undefined && maximumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-maximum-healthy-percent can\\'t be a negative number');\n }\n // In order to preserve the current behaviour, when minimumHealthyPercent is not defined, it will be set to the currently default value of 0\n if (minimumHealthyPercent == undefined) {\n this.minimumHealthyPercent = 0;\n } else {\n this.minimumHealthyPercent = minimumHealthyPercent;\n }\n this.maximumHealthyPercent = maximumHealthyPercent;\n }\n\n /**\n * Check if any hotswap properties are defined\n * @returns true if all properties are undefined, false otherwise\n */\n public isEmpty(): boolean {\n return this.minimumHealthyPercent === 0 && this.maximumHealthyPercent === undefined;\n }\n}\n\n/**\n * This function transforms all keys (recursively) in the provided `val` object.\n *\n * @param val The object whose keys need to be transformed.\n * @param transform The function that will be applied to each key.\n * @param exclude The keys that will not be transformed and copied to output directly\n * @returns A new object with the same values as `val`, but with all keys transformed according to `transform`.\n */\nexport function transformObjectKeys(val: any, transform: (str: string) => string, exclude: Exclude = {}): any {\n if (val == null || typeof val !== 'object') {\n return val;\n }\n if (Array.isArray(val)) {\n // For arrays we just pass parent's exclude object directly\n // since it makes no sense to specify different exclude options for each array element\n return val.map((input: any) => transformObjectKeys(input, transform, exclude));\n }\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(val)) {\n const childExclude = exclude[k];\n if (childExclude === true) {\n // we don't transform this object if the key is specified in exclude\n ret[transform(k)] = v;\n } else {\n ret[transform(k)] = transformObjectKeys(v, transform, childExclude);\n }\n }\n return ret;\n}\n\n/**\n * This function lower cases the first character of the string provided.\n */\nexport function lowerCaseFirstCharacter(str: string): string {\n return str.length > 0 ? `${str[0].toLowerCase()}${str.slice(1)}` : str;\n}\n\nexport type PropDiffs = Record<string, PropertyDifference<any>>;\n\nexport class ClassifiedChanges {\n public constructor(\n public readonly change: HotswappableChangeCandidate,\n public readonly hotswappableProps: PropDiffs,\n public readonly nonHotswappableProps: PropDiffs,\n ) {\n }\n\n public reportNonHotswappablePropertyChanges(ret: ChangeHotswapResult): void {\n const nonHotswappablePropNames = Object.keys(this.nonHotswappableProps);\n if (nonHotswappablePropNames.length > 0) {\n const tagOnlyChange = nonHotswappablePropNames.length === 1 && nonHotswappablePropNames[0] === 'Tags';\n reportNonHotswappableChange(\n ret,\n this.change,\n this.nonHotswappableProps,\n tagOnlyChange\n ? 'Tags are not hotswappable'\n : `resource properties '${nonHotswappablePropNames}' are not hotswappable on this resource type`,\n );\n }\n }\n\n public get namesOfHotswappableProps(): string[] {\n return Object.keys(this.hotswappableProps);\n }\n}\n\nexport function classifyChanges(xs: HotswappableChangeCandidate, hotswappablePropNames: string[]): ClassifiedChanges {\n const hotswappableProps: PropDiffs = {};\n const nonHotswappableProps: PropDiffs = {};\n\n for (const [name, propDiff] of Object.entries(xs.propertyUpdates)) {\n if (hotswappablePropNames.includes(name)) {\n hotswappableProps[name] = propDiff;\n } else {\n nonHotswappableProps[name] = propDiff;\n }\n }\n\n return new ClassifiedChanges(xs, hotswappableProps, nonHotswappableProps);\n}\n\nexport function reportNonHotswappableChange(\n ret: ChangeHotswapResult,\n change: HotswappableChangeCandidate,\n nonHotswappableProps?: PropDiffs,\n reason?: string,\n hotswapOnlyVisible?: boolean,\n): void {\n let hotswapOnlyVisibility = true;\n if (hotswapOnlyVisible === false) {\n hotswapOnlyVisibility = false;\n }\n ret.push({\n hotswappable: false,\n rejectedChanges: Object.keys(nonHotswappableProps ?? change.propertyUpdates),\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n reason,\n hotswapOnlyVisible: hotswapOnlyVisibility,\n });\n}\n\nexport function reportNonHotswappableResource(\n change: HotswappableChangeCandidate,\n reason?: string,\n): ChangeHotswapResult {\n return [\n {\n hotswappable: false,\n rejectedChanges: Object.keys(change.propertyUpdates),\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n reason,\n },\n ];\n}\n", "import type {\n GetSchemaCreationStatusCommandOutput,\n GetSchemaCreationStatusCommandInput,\n} from '@aws-sdk/client-appsync';\nimport {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n lowerCaseFirstCharacter,\n transformObjectKeys,\n} from './common';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SDK } from '../aws-auth';\n\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableAppSyncChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n const isResolver = change.newValue.Type === 'AWS::AppSync::Resolver';\n const isFunction = change.newValue.Type === 'AWS::AppSync::FunctionConfiguration';\n const isGraphQLSchema = change.newValue.Type === 'AWS::AppSync::GraphQLSchema';\n const isAPIKey = change.newValue.Type === 'AWS::AppSync::ApiKey';\n if (!isResolver && !isFunction && !isGraphQLSchema && !isAPIKey) {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n const classifiedChanges = classifyChanges(change, [\n 'RequestMappingTemplate',\n 'RequestMappingTemplateS3Location',\n 'ResponseMappingTemplate',\n 'ResponseMappingTemplateS3Location',\n 'Code',\n 'CodeS3Location',\n 'Definition',\n 'DefinitionS3Location',\n 'Expires',\n ]);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n let physicalName: string | undefined = undefined;\n const arn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n isFunction ? change.newValue.Properties?.Name : undefined,\n );\n if (isResolver) {\n const arnParts = arn?.split('/');\n physicalName = arnParts ? `${arnParts[3]}.${arnParts[5]}` : undefined;\n } else {\n physicalName = arn;\n }\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'appsync',\n resourceNames: [`${change.newValue.Type} '${physicalName}'`],\n apply: async (sdk: SDK) => {\n if (!physicalName) {\n return;\n }\n\n const sdkProperties: { [name: string]: any } = {\n ...change.oldValue.Properties,\n Definition: change.newValue.Properties?.Definition,\n DefinitionS3Location: change.newValue.Properties?.DefinitionS3Location,\n requestMappingTemplate: change.newValue.Properties?.RequestMappingTemplate,\n requestMappingTemplateS3Location: change.newValue.Properties?.RequestMappingTemplateS3Location,\n responseMappingTemplate: change.newValue.Properties?.ResponseMappingTemplate,\n responseMappingTemplateS3Location: change.newValue.Properties?.ResponseMappingTemplateS3Location,\n code: change.newValue.Properties?.Code,\n codeS3Location: change.newValue.Properties?.CodeS3Location,\n expires: change.newValue.Properties?.Expires,\n };\n const evaluatedResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression(sdkProperties);\n const sdkRequestObject = transformObjectKeys(evaluatedResourceProperties, lowerCaseFirstCharacter);\n\n // resolve s3 location files as SDK doesn't take in s3 location but inline code\n if (sdkRequestObject.requestMappingTemplateS3Location) {\n sdkRequestObject.requestMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.requestMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.requestMappingTemplateS3Location;\n }\n if (sdkRequestObject.responseMappingTemplateS3Location) {\n sdkRequestObject.responseMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.responseMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.responseMappingTemplateS3Location;\n }\n if (sdkRequestObject.definitionS3Location) {\n sdkRequestObject.definition = await fetchFileFromS3(sdkRequestObject.definitionS3Location, sdk);\n delete sdkRequestObject.definitionS3Location;\n }\n if (sdkRequestObject.codeS3Location) {\n sdkRequestObject.code = await fetchFileFromS3(sdkRequestObject.codeS3Location, sdk);\n delete sdkRequestObject.codeS3Location;\n }\n\n if (isResolver) {\n await sdk.appsync().updateResolver(sdkRequestObject);\n } else if (isFunction) {\n // Function version is only applicable when using VTL and mapping templates\n // Runtime only applicable when using code (JS mapping templates)\n if (sdkRequestObject.code) {\n delete sdkRequestObject.functionVersion;\n } else {\n delete sdkRequestObject.runtime;\n }\n\n const functions = await sdk.appsync().listFunctions({ apiId: sdkRequestObject.apiId });\n const { functionId } = functions.find((fn) => fn.name === physicalName) ?? {};\n // Updating multiple functions at the same time or along with graphql schema results in `ConcurrentModificationException`\n await exponentialBackOffRetry(\n () =>\n sdk.appsync().updateFunction({\n ...sdkRequestObject,\n functionId: functionId,\n }),\n 6,\n 1000,\n 'ConcurrentModificationException',\n );\n } else if (isGraphQLSchema) {\n let schemaCreationResponse: GetSchemaCreationStatusCommandOutput = await sdk\n .appsync()\n .startSchemaCreation(sdkRequestObject);\n while (\n schemaCreationResponse.status &&\n ['PROCESSING', 'DELETING'].some((status) => status === schemaCreationResponse.status)\n ) {\n await sleep(1000); // poll every second\n const getSchemaCreationStatusRequest: GetSchemaCreationStatusCommandInput = {\n apiId: sdkRequestObject.apiId,\n };\n schemaCreationResponse = await sdk.appsync().getSchemaCreationStatus(getSchemaCreationStatusRequest);\n }\n if (schemaCreationResponse.status === 'FAILED') {\n throw new ToolkitError(schemaCreationResponse.details ?? 'Schema creation has failed.');\n }\n } else {\n // isApiKey\n if (!sdkRequestObject.id) {\n // ApiKeyId is optional in CFN but required in SDK. Grab the KeyId from physicalArn if not available as part of CFN template\n const arnParts = physicalName?.split('/');\n if (arnParts && arnParts.length === 4) {\n sdkRequestObject.id = arnParts[3];\n }\n }\n await sdk.appsync().updateApiKey(sdkRequestObject);\n }\n },\n });\n }\n\n return ret;\n}\n\nasync function fetchFileFromS3(s3Url: string, sdk: SDK) {\n const s3PathParts = s3Url.split('/');\n const s3Bucket = s3PathParts[2]; // first two are \"s3:\" and \"\" due to s3://\n const s3Key = s3PathParts.splice(3).join('/'); // after removing first three we reconstruct the key\n return (await sdk.s3().getObject({ Bucket: s3Bucket, Key: s3Key })).Body?.transformToString();\n}\n\nasync function exponentialBackOffRetry(fn: () => Promise<any>, numOfRetries: number, backOff: number, errorCodeToRetry: string) {\n try {\n await fn();\n } catch (error: any) {\n if (error && error.name === errorCodeToRetry && numOfRetries > 0) {\n await sleep(backOff); // time to wait doubles everytime function fails, starts at 1 second\n await exponentialBackOffRetry(fn, numOfRetries - 1, backOff * 2, errorCodeToRetry);\n } else {\n throw error;\n }\n }\n}\n\nasync function sleep(ms: number) {\n return new Promise((ok) => setTimeout(ok, ms));\n}\n", "import type { UpdateProjectCommandInput } from '@aws-sdk/client-codebuild';\nimport {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n lowerCaseFirstCharacter,\n transformObjectKeys,\n} from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableCodeBuildProjectChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n if (change.newValue.Type !== 'AWS::CodeBuild::Project') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n const classifiedChanges = classifyChanges(change, ['Source', 'Environment', 'SourceVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n if (classifiedChanges.namesOfHotswappableProps.length > 0) {\n const updateProjectInput: UpdateProjectCommandInput = {\n name: '',\n };\n const projectName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.Name,\n );\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: classifiedChanges.namesOfHotswappableProps,\n service: 'codebuild',\n resourceNames: [`CodeBuild Project '${projectName}'`],\n apply: async (sdk: SDK) => {\n if (!projectName) {\n return;\n }\n updateProjectInput.name = projectName;\n\n for (const updatedPropName in change.propertyUpdates) {\n const updatedProp = change.propertyUpdates[updatedPropName];\n switch (updatedPropName) {\n case 'Source':\n updateProjectInput.source = transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n convertSourceCloudformationKeyToSdkKey,\n );\n break;\n case 'Environment':\n updateProjectInput.environment = await transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n lowerCaseFirstCharacter,\n );\n break;\n case 'SourceVersion':\n updateProjectInput.sourceVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n }\n }\n\n await sdk.codeBuild().updateProject(updateProjectInput);\n },\n });\n }\n\n return ret;\n}\n\nfunction convertSourceCloudformationKeyToSdkKey(key: string): string {\n if (key.toLowerCase() === 'buildspec') {\n return key.toLowerCase();\n }\n return lowerCaseFirstCharacter(key);\n}\n", "import {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n HotswapPropertyOverrides, lowerCaseFirstCharacter,\n reportNonHotswappableChange,\n transformObjectKeys,\n} from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableEcsServiceChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ChangeHotswapResult> {\n // the only resource change we can evaluate here is an ECS TaskDefinition\n if (change.newValue.Type !== 'AWS::ECS::TaskDefinition') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n // We only allow a change in the ContainerDefinitions of the TaskDefinition for now -\n // it contains the image and environment variables, so seems like a safe bet for now.\n // We might revisit this decision in the future though!\n const classifiedChanges = classifyChanges(change, ['ContainerDefinitions']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // find all ECS Services that reference the TaskDefinition that changed\n const resourcesReferencingTaskDef = evaluateCfnTemplate.findReferencesTo(logicalId);\n const ecsServiceResourcesReferencingTaskDef = resourcesReferencingTaskDef.filter(\n (r) => r.Type === 'AWS::ECS::Service',\n );\n const ecsServicesReferencingTaskDef = new Array<EcsService>();\n for (const ecsServiceResource of ecsServiceResourcesReferencingTaskDef) {\n const serviceArn = await evaluateCfnTemplate.findPhysicalNameFor(ecsServiceResource.LogicalId);\n if (serviceArn) {\n ecsServicesReferencingTaskDef.push({ serviceArn });\n }\n }\n if (ecsServicesReferencingTaskDef.length === 0) {\n // if there are no resources referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n reportNonHotswappableChange(ret, change, undefined, 'No ECS services reference the changed task definition', false);\n }\n if (resourcesReferencingTaskDef.length > ecsServicesReferencingTaskDef.length) {\n // if something besides an ECS Service is referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n const nonEcsServiceTaskDefRefs = resourcesReferencingTaskDef.filter((r) => r.Type !== 'AWS::ECS::Service');\n for (const taskRef of nonEcsServiceTaskDefRefs) {\n reportNonHotswappableChange(\n ret,\n change,\n undefined,\n `A resource '${taskRef.LogicalId}' with Type '${taskRef.Type}' that is not an ECS Service was found referencing the changed TaskDefinition '${logicalId}'`,\n );\n }\n }\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const taskDefinitionResource = await prepareTaskDefinitionChange(evaluateCfnTemplate, logicalId, change);\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'ecs-service',\n resourceNames: [\n `ECS Task Definition '${await taskDefinitionResource.Family}'`,\n ...ecsServicesReferencingTaskDef.map((ecsService) => `ECS Service '${ecsService.serviceArn.split('/')[2]}'`),\n ],\n apply: async (sdk: SDK) => {\n // Step 1 - update the changed TaskDefinition, creating a new TaskDefinition Revision\n // we need to lowercase the evaluated TaskDef from CloudFormation,\n // as the AWS SDK uses lowercase property names for these\n\n // The SDK requires more properties here than its worth doing explicit typing for\n // instead, just use all the old values in the diff to fill them in implicitly\n const lowercasedTaskDef = transformObjectKeys(taskDefinitionResource, lowerCaseFirstCharacter, {\n // All the properties that take arbitrary string as keys i.e. { \"string\" : \"string\" }\n // https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html#API_RegisterTaskDefinition_RequestSyntax\n ContainerDefinitions: {\n DockerLabels: true,\n FirelensConfiguration: {\n Options: true,\n },\n LogConfiguration: {\n Options: true,\n },\n },\n Volumes: {\n DockerVolumeConfiguration: {\n DriverOpts: true,\n Labels: true,\n },\n },\n });\n const registerTaskDefResponse = await sdk.ecs().registerTaskDefinition(lowercasedTaskDef);\n const taskDefRevArn = registerTaskDefResponse.taskDefinition?.taskDefinitionArn;\n\n let ecsHotswapProperties = hotswapPropertyOverrides.ecsHotswapProperties;\n let minimumHealthyPercent = ecsHotswapProperties?.minimumHealthyPercent;\n let maximumHealthyPercent = ecsHotswapProperties?.maximumHealthyPercent;\n\n // Step 2 - update the services using that TaskDefinition to point to the new TaskDefinition Revision\n // Forcing New Deployment and setting Minimum Healthy Percent to 0.\n // As CDK HotSwap is development only, this seems the most efficient way to ensure all tasks are replaced immediately, regardless of original amount\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(\n ecsServicesReferencingTaskDef.map(async (service) => {\n const cluster = service.serviceArn.split('/')[1];\n const update = await sdk.ecs().updateService({\n service: service.serviceArn,\n taskDefinition: taskDefRevArn,\n cluster,\n forceNewDeployment: true,\n deploymentConfiguration: {\n minimumHealthyPercent: minimumHealthyPercent !== undefined ? minimumHealthyPercent : 0,\n maximumPercent: maximumHealthyPercent !== undefined ? maximumHealthyPercent : undefined,\n },\n });\n\n await sdk.ecs().waitUntilServicesStable({\n cluster: update.service?.clusterArn,\n services: [service.serviceArn],\n });\n }),\n );\n },\n });\n }\n\n return ret;\n}\n\ninterface EcsService {\n readonly serviceArn: string;\n}\n\nasync function prepareTaskDefinitionChange(\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n logicalId: string,\n change: HotswappableChangeCandidate,\n) {\n const taskDefinitionResource: { [name: string]: any } = {\n ...change.oldValue.Properties,\n ContainerDefinitions: change.newValue.Properties?.ContainerDefinitions,\n };\n // first, let's get the name of the family\n const familyNameOrArn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n taskDefinitionResource?.Family,\n );\n if (!familyNameOrArn) {\n // if the Family property has not been provided, and we can't find it in the current Stack,\n // this means hotswapping is not possible\n return;\n }\n // the physical name of the Task Definition in CloudFormation includes its current revision number at the end,\n // remove it if needed\n const familyNameOrArnParts = familyNameOrArn.split(':');\n const family =\n familyNameOrArnParts.length > 1\n ? // familyNameOrArn is actually an ARN, of the format 'arn:aws:ecs:region:account:task-definition/<family-name>:<revision-nr>'\n // so, take the 6th element, at index 5, and split it on '/'\n familyNameOrArnParts[5].split('/')[1]\n : // otherwise, familyNameOrArn is just the simple name evaluated from the CloudFormation template\n familyNameOrArn;\n // then, let's evaluate the body of the remainder of the TaskDef (without the Family property)\n return {\n ...(await evaluateCfnTemplate.evaluateCfnExpression({\n ...(taskDefinitionResource ?? {}),\n Family: undefined,\n })),\n Family: family,\n };\n}\n", "import { Writable } from 'stream';\nimport { type FunctionConfiguration, type UpdateFunctionConfigurationCommandInput } from '@aws-sdk/client-lambda';\nimport { type ChangeHotswapResult, classifyChanges, type HotswappableChangeCandidate, PropDiffs } from './common';\nimport { ToolkitError } from '../../toolkit/error';\nimport { flatMap } from '../../util';\nimport type { ILambdaClient, SDK } from '../aws-auth';\nimport { CfnEvaluationException, type EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\n// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\nexport async function isHotswappableLambdaFunctionChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n // if the change is for a Lambda Version,\n // ignore it by returning an empty hotswap operation -\n // we will publish a new version when we get to hotswapping the actual Function this Version points to, below\n // (Versions can't be changed in CloudFormation anyway, they're immutable)\n if (change.newValue.Type === 'AWS::Lambda::Version') {\n return [\n {\n hotswappable: true,\n resourceType: 'AWS::Lambda::Version',\n resourceNames: [],\n propsChanged: [],\n service: 'lambda',\n apply: async (_sdk: SDK) => {\n },\n },\n ];\n }\n\n // we handle Aliases specially too\n if (change.newValue.Type === 'AWS::Lambda::Alias') {\n return classifyAliasChanges(change);\n }\n\n if (change.newValue.Type !== 'AWS::Lambda::Function') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['Code', 'Environment', 'Description']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const functionName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.FunctionName,\n );\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'lambda',\n resourceNames: [\n `Lambda Function '${functionName}'`,\n // add Version here if we're publishing a new one\n ...(await renderVersions(logicalId, evaluateCfnTemplate, [`Lambda Version for Function '${functionName}'`])),\n // add any Aliases that we are hotswapping here\n ...(await renderAliases(\n logicalId,\n evaluateCfnTemplate,\n async (alias) => `Lambda Alias '${alias}' for Function '${functionName}'`,\n )),\n ],\n apply: async (sdk: SDK) => {\n const lambdaCodeChange = await evaluateLambdaFunctionProps(\n classifiedChanges.hotswappableProps,\n change.newValue.Properties?.Runtime,\n evaluateCfnTemplate,\n );\n if (lambdaCodeChange === undefined) {\n return;\n }\n\n if (!functionName) {\n return;\n }\n\n const { versionsReferencingFunction, aliasesNames } = await versionsAndAliases(logicalId, evaluateCfnTemplate);\n const lambda = sdk.lambda();\n const operations: Promise<any>[] = [];\n\n if (lambdaCodeChange.code !== undefined || lambdaCodeChange.configurations !== undefined) {\n if (lambdaCodeChange.code !== undefined) {\n const updateFunctionCodeResponse = await lambda.updateFunctionCode({\n FunctionName: functionName,\n S3Bucket: lambdaCodeChange.code.s3Bucket,\n S3Key: lambdaCodeChange.code.s3Key,\n ImageUri: lambdaCodeChange.code.imageUri,\n ZipFile: lambdaCodeChange.code.functionCodeZip,\n S3ObjectVersion: lambdaCodeChange.code.s3ObjectVersion,\n });\n\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n if (lambdaCodeChange.configurations !== undefined) {\n const updateRequest: UpdateFunctionConfigurationCommandInput = {\n FunctionName: functionName,\n };\n if (lambdaCodeChange.configurations.description !== undefined) {\n updateRequest.Description = lambdaCodeChange.configurations.description;\n }\n if (lambdaCodeChange.configurations.environment !== undefined) {\n updateRequest.Environment = lambdaCodeChange.configurations.environment;\n }\n const updateFunctionCodeResponse = await lambda.updateFunctionConfiguration(updateRequest);\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n // only if the code changed is there any point in publishing a new Version\n if (versionsReferencingFunction.length > 0) {\n const publishVersionPromise = lambda.publishVersion({\n FunctionName: functionName,\n });\n\n if (aliasesNames.length > 0) {\n // we need to wait for the Version to finish publishing\n const versionUpdate = await publishVersionPromise;\n for (const alias of aliasesNames) {\n operations.push(\n lambda.updateAlias({\n FunctionName: functionName,\n Name: alias,\n FunctionVersion: versionUpdate.Version,\n }),\n );\n }\n } else {\n operations.push(publishVersionPromise);\n }\n }\n }\n\n // run all of our updates in parallel\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(operations);\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Determines which changes to this Alias are hotswappable or not\n */\nfunction classifyAliasChanges(change: HotswappableChangeCandidate): ChangeHotswapResult {\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['FunctionVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: [],\n service: 'lambda',\n resourceNames: [],\n apply: async (_sdk: SDK) => {\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Evaluates the hotswappable properties of an AWS::Lambda::Function and\n * Returns a `LambdaFunctionChange` if the change is hotswappable.\n * Returns `undefined` if the change is not hotswappable.\n */\nasync function evaluateLambdaFunctionProps(\n hotswappablePropChanges: PropDiffs,\n runtime: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<LambdaFunctionChange | undefined> {\n /*\n * At first glance, we would want to initialize these using the \"previous\" values (change.oldValue),\n * in case only one of them changed, like the key, and the Bucket stayed the same.\n * However, that actually fails for old-style synthesis, which uses CFN Parameters!\n * Because the names of the Parameters depend on the hash of the Asset,\n * the Parameters used for the \"old\" values no longer exist in `assetParams` at this point,\n * which means we don't have the correct values available to evaluate the CFN expression with.\n * Fortunately, the diff will always include both the s3Bucket and s3Key parts of the Lambda's Code property,\n * even if only one of them was actually changed,\n * which means we don't need the \"old\" values at all, and we can safely initialize these with just `''`.\n */\n let code: LambdaFunctionCode | undefined = undefined;\n let description: string | undefined = undefined;\n let environment: { [key: string]: string } | undefined = undefined;\n\n for (const updatedPropName in hotswappablePropChanges) {\n const updatedProp = hotswappablePropChanges[updatedPropName];\n\n switch (updatedPropName) {\n case 'Code':\n let s3Bucket, s3Key, s3ObjectVersion, imageUri, functionCodeZip;\n\n for (const newPropName in updatedProp.newValue) {\n switch (newPropName) {\n case 'S3Bucket':\n s3Bucket = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3Key':\n s3Key = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3ObjectVersion':\n s3ObjectVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ImageUri':\n imageUri = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ZipFile':\n // We must create a zip package containing a file with the inline code\n const functionCode = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n const functionRuntime = await evaluateCfnTemplate.evaluateCfnExpression(runtime);\n if (!functionRuntime) {\n return undefined;\n }\n // file extension must be chosen depending on the runtime\n const codeFileExt = determineCodeFileExtFromRuntime(functionRuntime);\n functionCodeZip = await zipString(`index.${codeFileExt}`, functionCode);\n break;\n }\n }\n code = {\n s3Bucket,\n s3Key,\n s3ObjectVersion,\n imageUri,\n functionCodeZip,\n };\n break;\n case 'Description':\n description = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n case 'Environment':\n environment = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n default:\n // we will never get here, but just in case we do throw an error\n throw new ToolkitError(\n 'while apply()ing, found a property that cannot be hotswapped. Please report this at github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n }\n\n const configurations = description || environment ? { description, environment } : undefined;\n return code || configurations ? { code, configurations } : undefined;\n}\n\ninterface LambdaFunctionCode {\n readonly s3Bucket?: string;\n readonly s3Key?: string;\n readonly s3ObjectVersion?: string;\n readonly imageUri?: string;\n readonly functionCodeZip?: Buffer;\n}\n\ninterface LambdaFunctionConfigurations {\n readonly description?: string;\n readonly environment?: { [key: string]: string };\n}\n\ninterface LambdaFunctionChange {\n readonly code?: LambdaFunctionCode;\n readonly configurations?: LambdaFunctionConfigurations;\n}\n\n/**\n * Compress a string as a file, returning a promise for the zip buffer\n * https://github.com/archiverjs/node-archiver/issues/342\n */\nfunction zipString(fileName: string, rawString: string): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const buffers: Buffer[] = [];\n\n const converter = new Writable();\n\n converter._write = (chunk: Buffer, _: string, callback: () => void) => {\n buffers.push(chunk);\n process.nextTick(callback);\n };\n\n converter.on('finish', () => {\n resolve(Buffer.concat(buffers));\n });\n\n const archive = archiver('zip');\n\n archive.on('error', (err: any) => {\n reject(err);\n });\n\n archive.pipe(converter);\n\n archive.append(rawString, {\n name: fileName,\n date: new Date('1980-01-01T00:00:00.000Z'), // Add date to make resulting zip file deterministic\n });\n\n void archive.finalize();\n });\n}\n\n/**\n * After a Lambda Function is updated, it cannot be updated again until the\n * `State=Active` and the `LastUpdateStatus=Successful`.\n *\n * Depending on the configuration of the Lambda Function this could happen relatively quickly\n * or very slowly. For example, Zip based functions _not_ in a VPC can take ~1 second whereas VPC\n * or Container functions can take ~25 seconds (and 'idle' VPC functions can take minutes).\n */\nasync function waitForLambdasPropertiesUpdateToFinish(\n currentFunctionConfiguration: FunctionConfiguration,\n lambda: ILambdaClient,\n functionName: string,\n): Promise<void> {\n const functionIsInVpcOrUsesDockerForCode =\n currentFunctionConfiguration.VpcConfig?.VpcId || currentFunctionConfiguration.PackageType === 'Image';\n\n // if the function is deployed in a VPC or if it is a container image function\n // then the update will take much longer and we can wait longer between checks\n // otherwise, the update will be quick, so a 1-second delay is fine\n const delaySeconds = functionIsInVpcOrUsesDockerForCode ? 5 : 1;\n\n await lambda.waitUntilFunctionUpdated(delaySeconds, {\n FunctionName: functionName,\n });\n}\n\n/**\n * Get file extension from Lambda runtime string.\n * We use this extension to create a deployment package from Lambda inline code.\n */\nfunction determineCodeFileExtFromRuntime(runtime: string): string {\n if (runtime.startsWith('node')) {\n return 'js';\n }\n if (runtime.startsWith('python')) {\n return 'py';\n }\n // Currently inline code only supports Node.js and Python, ignoring other runtimes.\n // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#aws-properties-lambda-function-code-properties\n throw new CfnEvaluationException(\n `runtime ${runtime} is unsupported, only node.js and python runtimes are currently supported.`,\n );\n}\n\n/**\n * Finds all Versions that reference an AWS::Lambda::Function with logical ID `logicalId`\n * and Aliases that reference those Versions.\n */\nasync function versionsAndAliases(logicalId: string, evaluateCfnTemplate: EvaluateCloudFormationTemplate) {\n // find all Lambda Versions that reference this Function\n const versionsReferencingFunction = evaluateCfnTemplate\n .findReferencesTo(logicalId)\n .filter((r) => r.Type === 'AWS::Lambda::Version');\n // find all Lambda Aliases that reference the above Versions\n const aliasesReferencingVersions = flatMap(versionsReferencingFunction, v =>\n evaluateCfnTemplate.findReferencesTo(v.LogicalId));\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const aliasesNames = await Promise.all(aliasesReferencingVersions.map(a =>\n evaluateCfnTemplate.evaluateCfnExpression(a.Properties?.Name)));\n\n return { versionsReferencingFunction, aliasesNames };\n}\n\n/**\n * Renders the string used in displaying Alias resource names that reference the specified Lambda Function\n */\nasync function renderAliases(\n logicalId: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n callbackfn: (value: any, index: number, array: any[]) => Promise<string>,\n): Promise<string[]> {\n const aliasesNames = (await versionsAndAliases(logicalId, evaluateCfnTemplate)).aliasesNames;\n\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(aliasesNames.map(callbackfn));\n}\n\n/**\n * Renders the string used in displaying Version resource names that reference the specified Lambda Function\n */\nasync function renderVersions(\n logicalId: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n versionString: string[],\n): Promise<string[]> {\n const versions = (await versionsAndAliases(logicalId, evaluateCfnTemplate)).versionsReferencingFunction;\n\n return versions.length > 0 ? versionString : [];\n}\n", "import { error } from 'console';\nimport { createWriteStream, promises as fs } from 'fs';\nimport * as path from 'path';\nimport * as glob from 'glob';\nimport { formatErrorMessage } from './format-error';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\n// Adapted from cdk-assets\nexport async function zipDirectory(directory: string, outputFile: string): Promise<void> {\n // We write to a temporary file and rename at the last moment. This is so that if we are\n // interrupted during this process, we don't leave a half-finished file in the target location.\n const temporaryOutputFile = `${outputFile}.${randomString()}._tmp`;\n await writeZipFile(directory, temporaryOutputFile);\n await moveIntoPlace(temporaryOutputFile, outputFile);\n}\n\nfunction writeZipFile(directory: string, outputFile: string): Promise<void> {\n return new Promise(async (ok, fail) => {\n // The below options are needed to support following symlinks when building zip files:\n // - nodir: This will prevent symlinks themselves from being copied into the zip.\n // - follow: This will follow symlinks and copy the files within.\n const globOptions = {\n dot: true,\n nodir: true,\n follow: true,\n cwd: directory,\n };\n const files = glob.sync('**', globOptions); // The output here is already sorted\n\n const output = createWriteStream(outputFile);\n\n const archive = archiver('zip');\n archive.on('warning', fail);\n archive.on('error', fail);\n\n // archive has been finalized and the output file descriptor has closed, resolve promise\n // this has to be done before calling `finalize` since the events may fire immediately after.\n // see https://www.npmjs.com/package/archiver\n output.once('close', ok);\n\n archive.pipe(output);\n\n // Append files serially to ensure file order\n for (const file of files) {\n const fullPath = path.resolve(directory, file);\n // Exactly 2 promises\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const [data, stat] = await Promise.all([fs.readFile(fullPath), fs.stat(fullPath)]);\n archive.append(data, {\n name: file,\n mode: stat.mode,\n });\n }\n\n await archive.finalize();\n });\n}\n\n/**\n * Rename the file to the target location, taking into account:\n *\n * - That we may see EPERM on Windows while an Antivirus scanner still has the\n * file open, so retry a couple of times.\n * - This same function may be called in parallel and be interrupted at any point.\n */\nasync function moveIntoPlace(source: string, target: string) {\n let delay = 100;\n let attempts = 5;\n while (true) {\n try {\n // 'rename' is guaranteed to overwrite an existing target, as long as it is a file (not a directory)\n await fs.rename(source, target);\n return;\n } catch (e: any) {\n if (e.code !== 'EPERM' || attempts-- <= 0) {\n throw e;\n }\n error(formatErrorMessage(e));\n await sleep(Math.floor(Math.random() * delay));\n delay *= 2;\n }\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise(ok => setTimeout(ok, ms));\n}\n\nfunction randomString() {\n return Math.random().toString(36).replace(/[^a-z0-9]+/g, '');\n}\n", "/**\n * Map a function over an array and concatenate the results\n */\nexport function flatMap<T, U>(xs: T[], fn: ((x: T, i: number) => U[])): U[] {\n return flatten(xs.map(fn));\n}\n\n/**\n * Flatten a list of lists into a list of elements\n */\nexport function flatten<T>(xs: T[][]): T[] {\n return Array.prototype.concat.apply([], xs);\n}\n\n/**\n * Partition a collection by removing and returning all elements that match a predicate\n *\n * Note: the input collection is modified in-place!\n */\nexport function partition<T>(collection: T[], pred: (x: T) => boolean): T[] {\n const ret: T[] = [];\n let i = 0;\n while (i < collection.length) {\n if (pred(collection[i])) {\n ret.push(collection.splice(i, 1)[0]);\n } else {\n i++;\n }\n }\n return ret;\n}\n", "/**\n * Validate SNS topic arn\n */\nexport function validateSnsTopicArn(arn: string): boolean {\n return /^arn:aws:sns:[a-z0-9\\-]+:[0-9]+:[a-z0-9\\-\\_]+$/i.test(arn);\n}\n", "/**\n * Run a number of promise generators with max parallelism\n *\n * Order is not maintained between the input and output.\n */\nexport async function parallelPromises<A>(n: number, promises: Array<() => Promise<A>>): Promise<Array<A>> {\n const ret = new Array<A>();\n let count = 0;\n let error: Error | undefined;\n const queue = [...promises];\n\n return new Promise((ok, ko) => {\n tick();\n\n function tick() {\n if (count === 0 && error) {\n ko(error);\n return;\n }\n if (count === 0 && queue.length === 0) {\n ok(ret);\n return;\n }\n\n while (count < n && queue.length > 0 && !error) {\n const next = queue.shift();\n if (next !== undefined) {\n start(next);\n }\n }\n }\n\n function start(fn: () => Promise<A>) {\n count += 1;\n fn()\n .then((result) => {\n ret.push(result);\n })\n .catch((e) => {\n error = e;\n })\n .finally(() => {\n count -= 1;\n tick();\n });\n }\n });\n}\n", "/**\n * Pad 's' on the left with 'char' until it is n characters wide\n */\nexport function leftPad(s: string, n: number, char: string) {\n const padding = Math.max(0, n - s.length);\n return char.repeat(padding) + s;\n}\n\n/**\n * Formats time in milliseconds (which we get from 'Date.getTime()')\n * to a human-readable time; returns time in seconds rounded to 2\n * decimal places.\n */\nexport function formatTime(num: number): number {\n return roundPercentage(millisecondsToSeconds(num));\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(100 * num) / 100;\n}\n\n/**\n * Given a time in milliseconds, return an equivalent amount in seconds.\n */\nfunction millisecondsToSeconds(num: number): number {\n return num / 1000;\n}\n", "import * as semver from 'semver';\nimport { ToolkitError } from '../toolkit/error';\n\n// bracket - https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN401\n// pep - https://www.python.org/dev/peps/pep-0440/#version-specifiers\nexport type RangeType = 'bracket' | 'pep'\n\nexport function rangeFromSemver(ver: string, targetType: RangeType) {\n const re = ver.match(/^([^\\d]*)([\\d.]*)$/);\n if (!re || !semver.valid(re[2])) {\n throw new ToolkitError('not a semver or unsupported range syntax');\n }\n const prefixPart = re[1];\n const verPart = re[2];\n\n switch (targetType) {\n case 'bracket':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return ver;\n case '^':\n return `[${verPart},${semver.major(verPart)+1}.0.0)`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n case 'pep':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return `==${ver}`;\n case '^':\n return `>=${verPart},<${semver.major(verPart)+1}.0.0`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n }\n}\n", "import type { ChangeHotswapResult, HotswappableChangeCandidate } from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\n/**\n * This means that the value is required to exist by CloudFormation's Custom Resource API (or our S3 Bucket Deployment Lambda's API)\n * but the actual value specified is irrelevant\n */\nexport const REQUIRED_BY_CFN = 'required-to-be-present-by-cfn';\n\nexport async function isHotswappableS3BucketDeploymentChange(\n _logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n // In old-style synthesis, the policy used by the lambda to copy assets Ref's the assets directly,\n // meaning that the changes made to the Policy are artifacts that can be safely ignored\n const ret: ChangeHotswapResult = [];\n\n if (change.newValue.Type !== 'Custom::CDKBucketDeployment') {\n return [];\n }\n\n // no classification to be done here; all the properties of this custom resource thing are hotswappable\n const customResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression({\n ...change.newValue.Properties,\n ServiceToken: undefined,\n });\n\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: ['*'],\n service: 'custom-s3-deployment',\n resourceNames: [`Contents of S3 Bucket '${customResourceProperties.DestinationBucketName}'`],\n apply: async (sdk: SDK) => {\n // note that this gives the ARN of the lambda, not the name. This is fine though, the invoke() sdk call will take either\n const functionName = await evaluateCfnTemplate.evaluateCfnExpression(change.newValue.Properties?.ServiceToken);\n if (!functionName) {\n return;\n }\n\n await sdk.lambda().invokeCommand({\n FunctionName: functionName,\n // Lambda refuses to take a direct JSON object and requires it to be stringify()'d\n Payload: JSON.stringify({\n RequestType: 'Update',\n ResponseURL: REQUIRED_BY_CFN,\n PhysicalResourceId: REQUIRED_BY_CFN,\n StackId: REQUIRED_BY_CFN,\n RequestId: REQUIRED_BY_CFN,\n LogicalResourceId: REQUIRED_BY_CFN,\n ResourceProperties: stringifyObject(customResourceProperties), // JSON.stringify() doesn't turn the actual objects to strings, but the lambda expects strings\n }),\n });\n },\n });\n\n return ret;\n}\n\nexport async function skipChangeForS3DeployCustomResourcePolicy(\n iamPolicyLogicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<boolean> {\n if (change.newValue.Type !== 'AWS::IAM::Policy') {\n return false;\n }\n const roles: string[] = change.newValue.Properties?.Roles;\n\n // If no roles are referenced, the policy is definitely not used for a S3Deployment\n if (!roles || !roles.length) {\n return false;\n }\n\n // Check if every role this policy is referenced by is only used for a S3Deployment\n for (const role of roles) {\n const roleArn = await evaluateCfnTemplate.evaluateCfnExpression(role);\n const roleLogicalId = await evaluateCfnTemplate.findLogicalIdForPhysicalName(roleArn);\n\n // We must assume this role is used for something else, because we can't check it\n if (!roleLogicalId) {\n return false;\n }\n\n // Find all interesting reference to the role\n const roleRefs = evaluateCfnTemplate\n .findReferencesTo(roleLogicalId)\n // we are not interested in the reference from the original policy - it always exists\n .filter((roleRef) => !(roleRef.Type == 'AWS::IAM::Policy' && roleRef.LogicalId === iamPolicyLogicalId));\n\n // Check if the role is only used for S3Deployment\n // We know this is the case, if S3Deployment -> Lambda -> Role is satisfied for every reference\n // And we have at least one reference.\n const isRoleOnlyForS3Deployment =\n roleRefs.length >= 1 &&\n roleRefs.every((roleRef) => {\n if (roleRef.Type === 'AWS::Lambda::Function') {\n const lambdaRefs = evaluateCfnTemplate.findReferencesTo(roleRef.LogicalId);\n // Every reference must be to the custom resource and at least one reference must be present\n return (\n lambdaRefs.length >= 1 && lambdaRefs.every((lambdaRef) => lambdaRef.Type === 'Custom::CDKBucketDeployment')\n );\n }\n return false;\n });\n\n // We have determined this role is used for something else, so we can't skip the change\n if (!isRoleOnlyForS3Deployment) {\n return false;\n }\n }\n\n // We have checked that any use of this policy is only for S3Deployment and we can safely skip it\n return true;\n}\n\nfunction stringifyObject(obj: any): any {\n if (obj == null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stringifyObject);\n }\n if (typeof obj !== 'object') {\n return obj.toString();\n }\n\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(obj)) {\n ret[k] = stringifyObject(v);\n }\n return ret;\n}\n", "import { type ChangeHotswapResult, classifyChanges, type HotswappableChangeCandidate } from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableStateMachineChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n if (change.newValue.Type !== 'AWS::StepFunctions::StateMachine') {\n return [];\n }\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['DefinitionString']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const stateMachineNameInCfnTemplate = change.newValue?.Properties?.StateMachineName;\n const stateMachineArn = stateMachineNameInCfnTemplate\n ? await evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::Sub':\n 'arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:' +\n stateMachineNameInCfnTemplate,\n })\n : await evaluateCfnTemplate.findPhysicalNameFor(logicalId);\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'stepfunctions-service',\n resourceNames: [`${change.newValue.Type} '${stateMachineArn?.split(':')[6]}'`],\n apply: async (sdk: SDK) => {\n if (!stateMachineArn) {\n return;\n }\n\n // not passing the optional properties leaves them unchanged\n await sdk.stepFunctions().updateStateMachine({\n stateMachineArn,\n definition: await evaluateCfnTemplate.evaluateCfnExpression(change.propertyUpdates.DefinitionString.newValue),\n });\n },\n });\n }\n\n return ret;\n}\n", "import { ClientRequest } from 'http';\nimport { RequestOptions } from 'https';\nimport * as https from 'node:https';\nimport * as path from 'path';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { SdkHttpOptions } from './api';\nimport { AwsCliCompatible } from './api/aws-auth/awscli-compatible';\nimport type { Context } from './api/context';\nimport { versionNumber } from './cli/version';\nimport { debug, info, warning, error } from './logging';\nimport { ToolkitError } from './toolkit/error';\nimport { ConstructTreeNode, loadTreeFromDir } from './tree';\nimport { cdkCacheDir } from './util/directories';\nimport { formatErrorMessage } from './util/format-error';\n\nconst CACHE_FILE_PATH = path.join(cdkCacheDir(), 'notices.json');\n\nexport interface NoticesProps {\n /**\n * CDK context\n */\n readonly context: Context;\n\n /**\n * Include notices that have already been acknowledged.\n *\n * @default false\n */\n readonly includeAcknowledged?: boolean;\n\n /**\n * Global CLI option for output directory for synthesized cloud assembly\n *\n * @default 'cdk.out'\n */\n readonly output?: string;\n\n /**\n * Global CLI option for whether we show notices\n *\n * @default true\n */\n readonly shouldDisplay?: boolean;\n\n /**\n * Options for the HTTP request\n */\n readonly httpOptions?: SdkHttpOptions;\n}\n\nexport interface NoticesPrintOptions {\n\n /**\n * Whether to append the total number of unacknowledged notices to the display.\n *\n * @default false\n */\n readonly showTotal?: boolean;\n}\n\nexport interface NoticesRefreshOptions {\n /**\n * Whether to force a cache refresh regardless of expiration time.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Data source for fetch notices from.\n *\n * @default - WebsiteNoticeDataSource\n */\n readonly dataSource?: NoticeDataSource;\n}\n\nexport interface NoticesFilterFilterOptions {\n readonly data: Notice[];\n readonly cliVersion: string;\n readonly outDir: string;\n readonly bootstrappedEnvironments: BootstrappedEnvironment[];\n}\n\nexport abstract class NoticesFilter {\n public static filter(options: NoticesFilterFilterOptions): FilteredNotice[] {\n const components = [\n ...NoticesFilter.constructTreeComponents(options.outDir),\n ...NoticesFilter.otherComponents(options),\n ];\n\n return NoticesFilter.findForNamedComponents(options.data, components);\n }\n\n /**\n * From a set of input options, return the notices components we are searching for\n */\n private static otherComponents(options: NoticesFilterFilterOptions): ActualComponent[] {\n return [\n // CLI\n {\n name: 'cli',\n version: options.cliVersion,\n },\n\n // Node version\n {\n name: 'node',\n version: process.version.replace(/^v/, ''), // remove the 'v' prefix.\n dynamicName: 'node',\n },\n\n // Bootstrap environments\n ...options.bootstrappedEnvironments.flatMap(env => {\n const semverBootstrapVersion = semver.coerce(env.bootstrapStackVersion);\n if (!semverBootstrapVersion) {\n // we don't throw because notices should never crash the cli.\n warning(`While filtering notices, could not coerce bootstrap version '${env.bootstrapStackVersion}' into semver`);\n return [];\n }\n\n return [{\n name: 'bootstrap',\n version: `${semverBootstrapVersion}`,\n dynamicName: 'ENVIRONMENTS',\n dynamicValue: env.environment.name,\n }];\n }),\n ];\n }\n\n /**\n * Based on a set of component names, find all notices that match one of the given components\n */\n private static findForNamedComponents(data: Notice[], actualComponents: ActualComponent[]): FilteredNotice[] {\n return data.flatMap(notice => {\n const ors = this.resolveAliases(normalizeComponents(notice.components));\n\n // Find the first set of the disjunctions of which all components match against the actual components.\n // Return the actual components we found so that we can inject their dynamic values. A single filter\n // component can match more than one actual component\n for (const ands of ors) {\n const matched = ands.map(affected => actualComponents.filter(actual =>\n NoticesFilter.componentNameMatches(affected, actual) && semver.satisfies(actual.version, affected.version)));\n\n // For every clause in the filter we matched one or more components\n if (matched.every(xs => xs.length > 0)) {\n const ret = new FilteredNotice(notice);\n NoticesFilter.addDynamicValues(matched.flatMap(x => x), ret);\n return [ret];\n }\n }\n\n return [];\n });\n }\n\n /**\n * Whether the given \"affected component\" name applies to the given actual component name.\n *\n * The name matches if the name is exactly the same, or the name in the notice\n * is a prefix of the node name when the query ends in '.'.\n */\n private static componentNameMatches(pattern: Component, actual: ActualComponent): boolean {\n return pattern.name.endsWith('.') ? actual.name.startsWith(pattern.name) : pattern.name === actual.name;\n }\n\n /**\n * Adds dynamic values from the given ActualComponents\n *\n * If there are multiple components with the same dynamic name, they are joined\n * by a comma.\n */\n private static addDynamicValues(comps: ActualComponent[], notice: FilteredNotice) {\n const dynamicValues: Record<string, string[]> = {};\n for (const comp of comps) {\n if (comp.dynamicName) {\n dynamicValues[comp.dynamicName] = dynamicValues[comp.dynamicName] ?? [];\n dynamicValues[comp.dynamicName].push(comp.dynamicValue ?? comp.version);\n }\n }\n for (const [key, values] of Object.entries(dynamicValues)) {\n notice.addDynamicValue(key, values.join(','));\n }\n }\n\n /**\n * Treat 'framework' as an alias for either `aws-cdk-lib.` or `@aws-cdk/core.`.\n *\n * Because it's EITHER `aws-cdk-lib` or `@aws-cdk/core`, we need to add multiple\n * arrays at the top level.\n */\n private static resolveAliases(ors: Component[][]): Component[][] {\n return ors.flatMap(ands => {\n const hasFramework = ands.find(c => c.name === 'framework');\n if (!hasFramework) {\n return [ands];\n }\n\n return [\n ands.map(c => c.name === 'framework' ? { ...c, name: '@aws-cdk/core.' } : c),\n ands.map(c => c.name === 'framework' ? { ...c, name: 'aws-cdk-lib.' } : c),\n ];\n });\n }\n\n /**\n * Load the construct tree from the given directory and return its components\n */\n private static constructTreeComponents(manifestDir: string): ActualComponent[] {\n const tree = loadTreeFromDir(manifestDir);\n if (!tree) {\n return [];\n }\n\n const ret: ActualComponent[] = [];\n recurse(tree);\n return ret;\n\n function recurse(x: ConstructTreeNode) {\n if (x.constructInfo?.fqn && x.constructInfo?.version) {\n ret.push({\n name: x.constructInfo?.fqn,\n version: x.constructInfo?.version,\n });\n }\n\n for (const child of Object.values(x.children ?? {})) {\n recurse(child);\n }\n }\n }\n}\n\ninterface ActualComponent {\n /**\n * Name of the component\n */\n readonly name: string;\n\n /**\n * Version of the component\n */\n readonly version: string;\n\n /**\n * If matched, under what name should it be added to the set of dynamic values\n *\n * These will be used to substitute placeholders in the message string, where\n * placeholders look like `{resolve:XYZ}`.\n *\n * If there is more than one component with the same dynamic name, they are\n * joined by ','.\n *\n * @default - Don't add to the set of dynamic values.\n */\n readonly dynamicName?: string;\n\n /**\n * If matched, what we should put in the set of dynamic values insstead of the version.\n *\n * Only used if `dynamicName` is set; by default we will add the actual version\n * of the component.\n *\n * @default - The version.\n */\n readonly dynamicValue?: string;\n}\n\n/**\n * Information about a bootstrapped environment.\n */\nexport interface BootstrappedEnvironment {\n readonly bootstrapStackVersion: number;\n readonly environment: Environment;\n}\n\n/**\n * Provides access to notices the CLI can display.\n */\nexport class Notices {\n /**\n * Create an instance. Note that this replaces the singleton.\n */\n public static create(props: NoticesProps): Notices {\n this._instance = new Notices(props);\n return this._instance;\n }\n\n /**\n * Get the singleton instance. May return `undefined` if `create` has not been called.\n */\n public static get(): Notices | undefined {\n return this._instance;\n }\n\n private static _instance: Notices | undefined;\n\n private readonly context: Context;\n private readonly output: string;\n private readonly shouldDisplay: boolean;\n private readonly acknowledgedIssueNumbers: Set<Number>;\n private readonly includeAcknowlegded: boolean;\n private readonly httpOptions: SdkHttpOptions;\n\n private data: Set<Notice> = new Set();\n\n // sets don't deduplicate interfaces, so we use a map.\n private readonly bootstrappedEnvironments: Map<string, BootstrappedEnvironment> = new Map();\n\n private constructor(props: NoticesProps) {\n this.context = props.context;\n this.acknowledgedIssueNumbers = new Set(this.context.get('acknowledged-issue-numbers') ?? []);\n this.includeAcknowlegded = props.includeAcknowledged ?? false;\n this.output = props.output ?? 'cdk.out';\n this.shouldDisplay = props.shouldDisplay ?? true;\n this.httpOptions = props.httpOptions ?? {};\n }\n\n /**\n * Add a bootstrap information to filter on. Can have multiple values\n * in case of multi-environment deployments.\n */\n public addBootstrappedEnvironment(bootstrapped: BootstrappedEnvironment) {\n const key = [\n bootstrapped.bootstrapStackVersion,\n bootstrapped.environment.account,\n bootstrapped.environment.region,\n bootstrapped.environment.name,\n ].join(':');\n this.bootstrappedEnvironments.set(key, bootstrapped);\n }\n\n /**\n * Refresh the list of notices this instance is aware of.\n * To make sure this never crashes the CLI process, all failures are caught and\n * silently logged.\n *\n * If context is configured to not display notices, this will no-op.\n */\n public async refresh(options: NoticesRefreshOptions = {}) {\n if (!this.shouldDisplay) {\n return;\n }\n\n try {\n const underlyingDataSource = options.dataSource ?? new WebsiteNoticeDataSource(this.httpOptions);\n const dataSource = new CachedDataSource(CACHE_FILE_PATH, underlyingDataSource, options.force ?? false);\n const notices = await dataSource.fetch();\n this.data = new Set(this.includeAcknowlegded ? notices : notices.filter(n => !this.acknowledgedIssueNumbers.has(n.issueNumber)));\n } catch (e: any) {\n debug(`Could not refresh notices: ${e}`);\n }\n }\n\n /**\n * Display the relevant notices (unless context dictates we shouldn't).\n */\n public display(options: NoticesPrintOptions = {}) {\n if (!this.shouldDisplay) {\n return;\n }\n\n const filteredNotices = NoticesFilter.filter({\n data: Array.from(this.data),\n cliVersion: versionNumber(),\n outDir: this.output,\n bootstrappedEnvironments: Array.from(this.bootstrappedEnvironments.values()),\n });\n\n if (filteredNotices.length > 0) {\n info('');\n info('NOTICES (What\\'s this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)');\n info('');\n for (const filtered of filteredNotices) {\n const formatted = filtered.format();\n switch (filtered.notice.severity) {\n case 'warning':\n warning(formatted);\n break;\n case 'error':\n error(formatted);\n break;\n default:\n info(formatted);\n }\n info('');\n }\n info(`If you don\u2019t want to see a notice anymore, use \"cdk acknowledge <id>\". For example, \"cdk acknowledge ${filteredNotices[0].notice.issueNumber}\".`);\n }\n\n if (options.showTotal ?? false) {\n info('');\n info(`There are ${filteredNotices.length} unacknowledged notice(s).`);\n }\n }\n}\n\nexport interface Component {\n name: string;\n\n /**\n * The range of affected versions\n */\n version: string;\n}\n\nexport interface Notice {\n title: string;\n issueNumber: number;\n overview: string;\n /**\n * A set of affected components\n *\n * The canonical form of a list of components is in Disjunctive Normal Form\n * (i.e., an OR of ANDs). This is the form when the list of components is a\n * doubly nested array: the notice matches if all components of at least one\n * of the top-level array matches.\n *\n * If the `components` is a single-level array, it is evaluated as an OR; it\n * matches if any of the components matches.\n */\n components: Array<Component | Component[]>;\n schemaVersion: string;\n severity?: string;\n}\n\n/**\n * Normalizes the given components structure into DNF form\n */\nfunction normalizeComponents(xs: Array<Component | Component[]>): Component[][] {\n return xs.map(x => Array.isArray(x) ? x : [x]);\n}\n\nfunction renderConjunction(xs: Component[]): string {\n return xs.map(c => `${c.name}: ${c.version}`).join(' AND ');\n}\n\n/**\n * Notice after passing the filter. A filter can augment a notice with\n * dynamic values as it has access to the dynamic matching data.\n */\nexport class FilteredNotice {\n private readonly dynamicValues: { [key: string]: string } = {};\n\n public constructor(public readonly notice: Notice) {\n }\n\n public addDynamicValue(key: string, value: string) {\n this.dynamicValues[`{resolve:${key}}`] = value;\n }\n\n public format(): string {\n const componentsValue = normalizeComponents(this.notice.components).map(renderConjunction).join(', ');\n return this.resolveDynamicValues([\n `${this.notice.issueNumber}\\t${this.notice.title}`,\n this.formatOverview(),\n `\\tAffected versions: ${componentsValue}`,\n `\\tMore information at: https://github.com/aws/aws-cdk/issues/${this.notice.issueNumber}`,\n ].join('\\n\\n') + '\\n');\n }\n\n private formatOverview() {\n const wrap = (s: string) => s.replace(/(?![^\\n]{1,60}$)([^\\n]{1,60})\\s/g, '$1\\n');\n\n const heading = 'Overview: ';\n const separator = `\\n\\t${' '.repeat(heading.length)}`;\n const content = wrap(this.notice.overview)\n .split('\\n')\n .join(separator);\n\n return '\\t' + heading + content;\n }\n\n private resolveDynamicValues(input: string): string {\n const pattern = new RegExp(Object.keys(this.dynamicValues).join('|'), 'g');\n return input.replace(pattern, (matched) => this.dynamicValues[matched] ?? matched);\n }\n}\n\nexport interface NoticeDataSource {\n fetch(): Promise<Notice[]>;\n}\n\nexport class WebsiteNoticeDataSource implements NoticeDataSource {\n private readonly options: SdkHttpOptions;\n\n constructor(options: SdkHttpOptions = {}) {\n this.options = options;\n }\n\n fetch(): Promise<Notice[]> {\n const timeout = 3000;\n return new Promise((resolve, reject) => {\n let req: ClientRequest | undefined;\n\n let timer = setTimeout(() => {\n if (req) {\n req.destroy(new ToolkitError('Request timed out'));\n }\n }, timeout);\n\n timer.unref();\n\n const options: RequestOptions = {\n agent: AwsCliCompatible.proxyAgent(this.options),\n };\n\n try {\n req = https.get('https://cli.cdk.dev-tools.aws.dev/notices.json',\n options,\n res => {\n if (res.statusCode === 200) {\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => {\n rawData += chunk;\n });\n res.on('end', () => {\n try {\n const data = JSON.parse(rawData).notices as Notice[];\n if (!data) {\n throw new ToolkitError(\"'notices' key is missing\");\n }\n debug('Notices refreshed');\n resolve(data ?? []);\n } catch (e: any) {\n reject(new ToolkitError(`Failed to parse notices: ${formatErrorMessage(e)}`));\n }\n });\n res.on('error', e => {\n reject(new ToolkitError(`Failed to fetch notices: ${formatErrorMessage(e)}`));\n });\n } else {\n reject(new ToolkitError(`Failed to fetch notices. Status code: ${res.statusCode}`));\n }\n });\n req.on('error', reject);\n } catch (e: any) {\n reject(new ToolkitError(`HTTPS 'get' call threw an error: ${formatErrorMessage(e)}`));\n }\n });\n }\n}\n\ninterface CachedNotices {\n expiration: number;\n notices: Notice[];\n}\n\nconst TIME_TO_LIVE_SUCCESS = 60 * 60 * 1000; // 1 hour\nconst TIME_TO_LIVE_ERROR = 1 * 60 * 1000; // 1 minute\n\nexport class CachedDataSource implements NoticeDataSource {\n constructor(\n private readonly fileName: string,\n private readonly dataSource: NoticeDataSource,\n private readonly skipCache?: boolean) {\n }\n\n async fetch(): Promise<Notice[]> {\n const cachedData = await this.load();\n const data = cachedData.notices;\n const expiration = cachedData.expiration ?? 0;\n\n if (Date.now() > expiration || this.skipCache) {\n const freshData = await this.fetchInner();\n await this.save(freshData);\n return freshData.notices;\n } else {\n debug(`Reading cached notices from ${this.fileName}`);\n return data;\n }\n }\n\n private async fetchInner(): Promise<CachedNotices> {\n try {\n return {\n expiration: Date.now() + TIME_TO_LIVE_SUCCESS,\n notices: await this.dataSource.fetch(),\n };\n } catch (e) {\n debug(`Could not refresh notices: ${e}`);\n return {\n expiration: Date.now() + TIME_TO_LIVE_ERROR,\n notices: [],\n };\n }\n }\n\n private async load(): Promise<CachedNotices> {\n const defaultValue = {\n expiration: 0,\n notices: [],\n };\n\n try {\n return fs.existsSync(this.fileName)\n ? await fs.readJSON(this.fileName) as CachedNotices\n : defaultValue;\n } catch (e) {\n debug(`Failed to load notices from cache: ${e}`);\n return defaultValue;\n }\n }\n\n private async save(cached: CachedNotices): Promise<void> {\n try {\n await fs.writeJSON(this.fileName, cached);\n } catch (e) {\n debug(`Failed to store notices in the cache: ${e}`);\n }\n }\n}\n", "/* istanbul ignore file */\nimport * as path from 'path';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { debug, info } from '../logging';\nimport { ToolkitError } from '../toolkit/error';\nimport { formatAsBanner } from './util/console-formatters';\nimport { cdkCacheDir, rootDir } from '../util/directories';\nimport { getLatestVersionFromNpm } from './util/npm';\n\nconst ONE_DAY_IN_SECONDS = 1 * 24 * 60 * 60;\n\nconst UPGRADE_DOCUMENTATION_LINKS: Record<number, string> = {\n 1: 'https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html',\n};\n\nexport function displayVersion() {\n return `${versionNumber()} (build ${commit()})`;\n}\n\nexport function isDeveloperBuild(): boolean {\n return versionNumber() === '0.0.0';\n}\n\nexport function versionNumber(): string {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require(path.join(rootDir(), 'package.json')).version.replace(/\\+[0-9a-f]+$/, '');\n}\n\nfunction commit(): string {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require(path.join(rootDir(), 'build-info.json')).commit;\n}\n\nexport class VersionCheckTTL {\n public static timestampFilePath(): string {\n // Using the same path from account-cache.ts\n return path.join(cdkCacheDir(), 'repo-version-ttl');\n }\n\n private readonly file: string;\n\n // File modify times are accurate only to the second\n private readonly ttlSecs: number;\n\n constructor(file?: string, ttlSecs?: number) {\n this.file = file || VersionCheckTTL.timestampFilePath();\n try {\n fs.mkdirsSync(path.dirname(this.file));\n fs.accessSync(path.dirname(this.file), fs.constants.W_OK);\n } catch {\n throw new ToolkitError(`Directory (${path.dirname(this.file)}) is not writable.`);\n }\n this.ttlSecs = ttlSecs || ONE_DAY_IN_SECONDS;\n }\n\n public async hasExpired(): Promise<boolean> {\n try {\n const lastCheckTime = (await fs.stat(this.file)).mtimeMs;\n const today = new Date().getTime();\n\n if ((today - lastCheckTime) / 1000 > this.ttlSecs) { // convert ms to sec\n return true;\n }\n return false;\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n return true;\n } else {\n throw err;\n }\n }\n }\n\n public async update(latestVersion?: string): Promise<void> {\n if (!latestVersion) {\n latestVersion = '';\n }\n await fs.writeFile(this.file, latestVersion);\n }\n}\n\n// Export for unit testing only.\n// Don't use directly, use displayVersionMessage() instead.\nexport async function latestVersionIfHigher(currentVersion: string, cacheFile: VersionCheckTTL): Promise<string|null> {\n if (!(await cacheFile.hasExpired())) {\n return null;\n }\n\n const latestVersion = await getLatestVersionFromNpm();\n const isNewer = semver.gt(latestVersion, currentVersion);\n await cacheFile.update(latestVersion);\n\n if (isNewer) {\n return latestVersion;\n } else {\n return null;\n }\n}\n\nfunction getMajorVersionUpgradeMessage(currentVersion: string): string | void {\n const currentMajorVersion = semver.major(currentVersion);\n if (UPGRADE_DOCUMENTATION_LINKS[currentMajorVersion]) {\n return `Information about upgrading from version ${currentMajorVersion}.x to version ${currentMajorVersion + 1}.x is available here: ${UPGRADE_DOCUMENTATION_LINKS[currentMajorVersion]}`;\n }\n}\n\nfunction getVersionMessage(currentVersion: string, laterVersion: string): string[] {\n return [\n `Newer version of CDK is available [${chalk.green(laterVersion as string)}]`,\n getMajorVersionUpgradeMessage(currentVersion),\n 'Upgrade recommended (npm install -g aws-cdk)',\n ].filter(Boolean) as string[];\n}\n\nexport async function displayVersionMessage(currentVersion = versionNumber(), versionCheckCache?: VersionCheckTTL): Promise<void> {\n if (!process.stdout.isTTY || process.env.CDK_DISABLE_VERSION_CHECK) {\n return;\n }\n\n try {\n const laterVersion = await latestVersionIfHigher(currentVersion, versionCheckCache ?? new VersionCheckTTL());\n if (laterVersion) {\n const bannerMsg = formatAsBanner(getVersionMessage(currentVersion, laterVersion));\n bannerMsg.forEach((e) => info(e));\n }\n } catch (err: any) {\n debug(`Could not run version check - ${err.message}`);\n }\n}\n", "// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst stripAnsi = require('strip-ansi');\n\n/**\n * Returns a set of strings when printed on the console produces a banner msg. The message is in the following format -\n * ********************\n * *** msg line x ***\n * *** msg line xyz ***\n * ********************\n *\n * Spec:\n * - The width of every line is equal, dictated by the longest message string\n * - The first and last lines are '*'s for the full length of the line\n * - Each line in between is prepended with '*** ' and appended with ' ***'\n * - The text is indented left, i.e. whitespace is right-padded when the length is shorter than the longest.\n *\n * @param msgs array of strings containing the message lines to be printed in the banner. Returns empty string if array\n * is empty.\n * @returns array of strings containing the message formatted as a banner\n */\nexport function formatAsBanner(msgs: string[]): string[] {\n const printLen = (str: string) => stripAnsi(str).length;\n\n if (msgs.length === 0) {\n return [];\n }\n\n const leftPad = '*** ';\n const rightPad = ' ***';\n const bannerWidth = printLen(leftPad) + printLen(rightPad) +\n msgs.reduce((acc, msg) => Math.max(acc, printLen(msg)), 0);\n\n const bannerLines: string[] = [];\n bannerLines.push('*'.repeat(bannerWidth));\n\n // Improvement: If any 'msg' is wider than the terminal width, wrap message across lines.\n msgs.forEach((msg) => {\n const padding = ' '.repeat(bannerWidth - (printLen(msg) + printLen(leftPad) + printLen(rightPad)));\n bannerLines.push(''.concat(leftPad, msg, padding, rightPad));\n });\n\n bannerLines.push('*'.repeat(bannerWidth));\n return bannerLines;\n}\n", "import { exec as _exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as semver from 'semver';\nimport { debug } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\n\nconst exec = promisify(_exec);\n\n/* istanbul ignore next: not called during unit tests */\nexport async function getLatestVersionFromNpm(): Promise<string> {\n const { stdout, stderr } = await exec('npm view aws-cdk version', { timeout: 3000 });\n if (stderr && stderr.trim().length > 0) {\n debug(`The 'npm view' command generated an error stream with content [${stderr.trim()}]`);\n }\n const latestVersion = stdout.trim();\n if (!semver.valid(latestVersion)) {\n throw new ToolkitError(`npm returned an invalid semver ${latestVersion}`);\n }\n\n return latestVersion;\n}\n", "import * as path from 'path';\nimport { CloudAssembly } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { trace } from './logging';\n\n/**\n * Source information on a construct (class fqn and version)\n */\nexport interface ConstructInfo {\n readonly fqn: string;\n readonly version: string;\n}\n\n/**\n * A node in the construct tree.\n */\nexport interface ConstructTreeNode {\n readonly id: string;\n readonly path: string;\n readonly children?: { [key: string]: ConstructTreeNode };\n readonly attributes?: { [key: string]: any };\n\n /**\n * Information on the construct class that led to this node, if available\n */\n readonly constructInfo?: ConstructInfo;\n}\n\n/**\n * Whether the provided predicate is true for at least one element in the construct (sub-)tree.\n */\nexport function some(node: ConstructTreeNode | undefined, predicate: (n: ConstructTreeNode) => boolean): boolean {\n return node != null && (predicate(node) || findInChildren());\n\n function findInChildren(): boolean {\n return Object.values(node?.children ?? {}).some(child => some(child, predicate));\n }\n}\n\nexport function loadTree(assembly: CloudAssembly): ConstructTreeNode | undefined {\n try {\n const outdir = assembly.directory;\n const fileName = assembly.tree()?.file;\n return fileName ? fs.readJSONSync(path.join(outdir, fileName)).tree : {};\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n\nexport function loadTreeFromDir(outdir: string): ConstructTreeNode | undefined {\n try {\n return fs.readJSONSync(path.join(outdir, 'tree.json')).tree;\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { SDK } from './aws-auth';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BUCKET_DOMAIN_NAME_OUTPUT,\n BUCKET_NAME_OUTPUT,\n DEFAULT_BOOTSTRAP_VARIANT,\n REPOSITORY_NAME_OUTPUT,\n} from './bootstrap/bootstrap-props';\nimport { type CloudFormationStack, stabilizeStack } from './deployments/cloudformation';\nimport { debug } from '../cli/messages';\nimport { IoMessaging } from '../toolkit/cli-io-host';\nimport { ToolkitError } from '../toolkit/error';\n\nexport const DEFAULT_TOOLKIT_STACK_NAME = 'CDKToolkit';\n\n/**\n * Information on the Bootstrap stack of the environment we're deploying to.\n *\n * This class serves to:\n *\n * - Inspect the bootstrap stack, and return various properties of it for successful\n * asset deployment (in case of legacy-synthesized stacks).\n * - Validate the version of the target environment, and nothing else (in case of\n * default-synthesized stacks).\n *\n * An object of this type might represent a bootstrap stack that could not be found.\n * This is not an issue unless any members are used that require the bootstrap stack\n * to have been found, in which case an error is thrown (default-synthesized stacks\n * should never run into this as they don't need information from the bootstrap\n * stack, all information is already encoded into the Cloud Assembly Manifest).\n *\n * Nevertheless, an instance of this class exists to serve as a cache for SSM\n * parameter lookups (otherwise, the \"bootstrap stack version\" parameter would\n * need to be read repeatedly).\n *\n * Called \"ToolkitInfo\" for historical reasons.\n *\n */\nexport abstract class ToolkitInfo {\n public static determineName(overrideName?: string) {\n return overrideName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n public static async lookup(\n environment: cxapi.Environment,\n sdk: SDK,\n { ioHost, action }: IoMessaging,\n stackName: string | undefined,\n ): Promise<ToolkitInfo> {\n const cfn = sdk.cloudFormation();\n stackName = ToolkitInfo.determineName(stackName);\n try {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n await ioHost.notify(debug(\n action,\n format(\n \"The environment %s doesn't have the CDK toolkit stack (%s) installed. Use %s to setup your environment for use with the toolkit.\",\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n if (stack.stackStatus.isCreationFailure) {\n // Treat a \"failed to create\" bootstrap stack as an absent one.\n await ioHost.notify(debug(\n action,\n format(\n 'The environment %s has a CDK toolkit stack (%s) that failed to create. Use %s to try provisioning it again.',\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n\n return new ExistingToolkitInfo(stack);\n } catch (e: any) {\n return ToolkitInfo.bootstrapStackLookupError(stackName, e);\n }\n }\n\n public static fromStack(stack: CloudFormationStack): ToolkitInfo {\n return new ExistingToolkitInfo(stack);\n }\n\n public static bootstrapStackNotFoundInfo(stackName: string): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n \"This deployment requires a bootstrap stack with a known name; pass '--toolkit-stack-name' or switch to using the 'DefaultStackSynthesizer' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)\",\n );\n }\n\n public static bootstrapStackLookupError(stackName: string, e: Error): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n `This deployment requires a bootstrap stack with a known name, but during its lookup the following error occurred: ${e}; pass \\'--toolkit-stack-name\\' or switch to using the \\'DefaultStackSynthesizer\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n\n public abstract readonly found: boolean;\n public abstract readonly bucketUrl: string;\n public abstract readonly bucketName: string;\n public abstract readonly repositoryName: string;\n public abstract readonly version: number;\n public abstract readonly variant: string;\n public abstract readonly bootstrapStack: CloudFormationStack;\n public abstract readonly stackName: string;\n\n constructor() {\n }\n}\n\n/**\n * Returned when a bootstrap stack is found\n */\nclass ExistingToolkitInfo extends ToolkitInfo {\n public readonly found = true;\n\n constructor(public readonly bootstrapStack: CloudFormationStack) {\n super();\n }\n\n public get bucketUrl() {\n return `https://${this.requireOutput(BUCKET_DOMAIN_NAME_OUTPUT)}`;\n }\n\n public get bucketName() {\n return this.requireOutput(BUCKET_NAME_OUTPUT);\n }\n\n public get repositoryName() {\n return this.requireOutput(REPOSITORY_NAME_OUTPUT);\n }\n\n public get version() {\n return parseInt(this.bootstrapStack.outputs[BOOTSTRAP_VERSION_OUTPUT] ?? '0', 10);\n }\n\n public get variant() {\n return this.bootstrapStack.parameters[BOOTSTRAP_VARIANT_PARAMETER] ?? DEFAULT_BOOTSTRAP_VARIANT;\n }\n\n public get parameters(): Record<string, string> {\n return this.bootstrapStack.parameters ?? {};\n }\n\n public get terminationProtection(): boolean {\n return this.bootstrapStack.terminationProtection ?? false;\n }\n\n public get stackName(): string {\n return this.bootstrapStack.stackName;\n }\n\n /**\n * Prepare an ECR repository for uploading to using Docker\n *\n */\n private requireOutput(output: string): string {\n if (!(output in this.bootstrapStack.outputs)) {\n throw new ToolkitError(\n `The CDK toolkit stack (${this.bootstrapStack.stackName}) does not have an output named ${output}. Use 'cdk bootstrap' to correct this.`,\n );\n }\n return this.bootstrapStack.outputs[output];\n }\n}\n\n/**\n * Returned when a bootstrap stack could not be found\n *\n * This is not an error in principle, UNTIL one of the members is called that requires\n * the bootstrap stack to have been found, in which case the lookup error is still thrown\n * belatedly.\n *\n * The errors below serve as a last stop-gap message--normally calling code should have\n * checked `toolkit.found` and produced an appropriate error message.\n */\nclass BootstrapStackNotFoundInfo extends ToolkitInfo {\n public readonly found = false;\n\n constructor(\n public readonly stackName: string,\n private readonly errorMessage: string,\n ) {\n super();\n }\n\n public get bootstrapStack(): CloudFormationStack {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketUrl(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get repositoryName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get version(): number {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get variant(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public prepareEcrRepository(): Promise<EcrRepositoryInfo> {\n throw new ToolkitError(this.errorMessage);\n }\n}\n\nexport interface EcrRepositoryInfo {\n repositoryUri: string;\n}\n\nexport interface EcrCredentials {\n username: string;\n password: string;\n endpoint: string;\n}\n", "import { BootstrapSource } from './bootstrap-environment';\nimport { Tag } from '../tags';\nimport { StringWithoutPlaceholders } from '../util/placeholders';\n\nexport const BUCKET_NAME_OUTPUT = 'BucketName';\nexport const REPOSITORY_NAME_OUTPUT = 'ImageRepositoryName';\nexport const BUCKET_DOMAIN_NAME_OUTPUT = 'BucketDomainName';\nexport const BOOTSTRAP_VERSION_OUTPUT = 'BootstrapVersion';\nexport const BOOTSTRAP_VERSION_RESOURCE = 'CdkBootstrapVersion';\nexport const BOOTSTRAP_VARIANT_PARAMETER = 'BootstrapVariant';\n\n/**\n * The assumed vendor of a template in case it is not set\n */\nexport const DEFAULT_BOOTSTRAP_VARIANT = 'AWS CDK: Default Resources';\n\n/**\n * Options for the bootstrapEnvironment operation(s)\n */\nexport interface BootstrapEnvironmentOptions {\n readonly toolkitStackName?: string;\n readonly roleArn?: StringWithoutPlaceholders;\n readonly parameters?: BootstrappingParameters;\n readonly force?: boolean;\n\n /**\n * The source of the bootstrap stack\n *\n * @default - modern v2-style bootstrapping\n */\n readonly source?: BootstrapSource;\n\n /**\n * Whether to execute the changeset or only create it and leave it in review.\n * @default true\n */\n readonly execute?: boolean;\n\n /**\n * Tags for cdktoolkit stack.\n *\n * @default - None.\n */\n readonly tags?: Tag[];\n\n /**\n * Whether the stacks created by the bootstrap process should be protected from termination.\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html\n * @default true\n */\n readonly terminationProtection?: boolean;\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n usePreviousParameters?: boolean;\n}\n\n/**\n * Parameters for the bootstrapping template\n */\nexport interface BootstrappingParameters {\n /**\n * The name to be given to the CDK Bootstrap bucket.\n *\n * @default - a name is generated by CloudFormation.\n */\n readonly bucketName?: string;\n\n /**\n * The ID of an existing KMS key to be used for encrypting items in the bucket.\n *\n * @default - use the default KMS key or create a custom one\n */\n readonly kmsKeyId?: string;\n\n /**\n * Whether or not to create a new customer master key (CMK)\n *\n * Only applies to modern bootstrapping. Legacy bootstrapping will never create\n * a CMK, only use the default S3 key.\n *\n * @default false\n */\n readonly createCustomerMasterKey?: boolean;\n\n /**\n * The list of AWS account IDs that are trusted to deploy into the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can deploy into this environment\n */\n readonly trustedAccounts?: string[];\n\n /**\n * The list of AWS account IDs that are trusted to look up values in the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can look up values in this environment\n */\n readonly trustedAccountsForLookup?: string[];\n\n /**\n * The list of AWS account IDs that should not be trusted by the bootstrapped environment.\n * If these accounts are already trusted, they will be removed on bootstrapping.\n *\n * @default - no account will be untrusted.\n */\n readonly untrustedAccounts?: string[];\n\n /**\n * The ARNs of the IAM managed policies that should be attached to the role performing CloudFormation deployments.\n * In most cases, this will be the AdministratorAccess policy.\n * At least one policy is required if `trustedAccounts` were passed.\n *\n * @default - the role will have no policies attached\n */\n readonly cloudFormationExecutionPolicies?: string[];\n\n /**\n * Identifier to distinguish multiple bootstrapped environments\n *\n * @default - Default qualifier\n */\n readonly qualifier?: string;\n\n /**\n * Whether or not to enable S3 Staging Bucket Public Access Block Configuration\n *\n * @default true\n */\n readonly publicAccessBlockConfiguration?: boolean;\n\n /**\n * Flag for using the default permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly examplePermissionsBoundary?: boolean;\n\n /**\n * Name for the customer's custom permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly customPermissionsBoundary?: string;\n}\n", "import type { Environment } from '@aws-cdk/cx-api';\nimport { debug, warn } from '../../cli/messages';\nimport { Notices } from '../../notices';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK } from '../aws-auth';\nimport { type EcrRepositoryInfo, ToolkitInfo } from '../toolkit-info';\n\n/**\n * Registry class for `EnvironmentResources`.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResourcesRegistry {\n private readonly cache = new Map<string, EnvironmentCache>();\n\n constructor(private readonly toolkitStackName?: string) {\n }\n\n public for(resolvedEnvironment: Environment, sdk: SDK, msg: IoMessaging) {\n const key = `${resolvedEnvironment.account}:${resolvedEnvironment.region}`;\n let envCache = this.cache.get(key);\n if (!envCache) {\n envCache = emptyCache();\n this.cache.set(key, envCache);\n }\n return new EnvironmentResources(resolvedEnvironment, sdk, msg, envCache, this.toolkitStackName);\n }\n}\n\n/**\n * Interface with the account and region we're deploying into\n *\n * Manages lookups for bootstrapped resources, falling back to the legacy \"CDK Toolkit\"\n * original bootstrap stack if necessary.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResources {\n constructor(\n public readonly environment: Environment,\n private readonly sdk: SDK,\n private readonly msg: IoMessaging,\n private readonly cache: EnvironmentCache,\n private readonly toolkitStackName?: string,\n ) {\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit() {\n if (!this.cache.toolkitInfo) {\n this.cache.toolkitInfo = await ToolkitInfo.lookup(this.environment, this.sdk, this.msg, this.toolkitStackName);\n }\n return this.cache.toolkitInfo;\n }\n\n /**\n * Validate that the bootstrap stack version matches or exceeds the expected version\n *\n * Use the SSM parameter name to read the version number if given, otherwise use the version\n * discovered on the bootstrap stack.\n *\n * Pass in the SSM parameter name so we can cache the lookups an don't need to do the same\n * lookup again and again for every artifact.\n */\n public async validateVersion(expectedVersion: number | undefined, ssmParameterName: string | undefined) {\n if (expectedVersion === undefined) {\n // No requirement\n return;\n }\n const defExpectedVersion = expectedVersion;\n\n if (ssmParameterName !== undefined) {\n try {\n doValidate(await this.versionFromSsmParameter(ssmParameterName), this.environment);\n return;\n } catch (e: any) {\n if (e.name !== 'AccessDeniedException') {\n throw e;\n }\n\n // This is a fallback! The bootstrap template that goes along with this change introduces\n // a new 'ssm:GetParameter' permission, but when run using the previous bootstrap template we\n // won't have the permissions yet to read the version, so we won't be able to show the\n // message telling the user they need to update! When we see an AccessDeniedException, fall\n // back to the version we read from Stack Outputs; but ONLY if the version we discovered via\n // outputs is legitimately an old version. If it's newer than that, something else must be broken,\n // so let it fail as it would if we didn't have this fallback.\n const bootstrapStack = await this.lookupToolkit();\n if (bootstrapStack.found && bootstrapStack.version < BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER) {\n await this.msg.ioHost.notify(warn(\n this.msg.action,\n `Could not read SSM parameter ${ssmParameterName}: ${formatErrorMessage(e)}, falling back to version from ${bootstrapStack}`,\n ));\n doValidate(bootstrapStack.version, this.environment);\n return;\n }\n\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', but during the confirmation via SSM parameter ${ssmParameterName} the following error occurred: ${e}`,\n );\n }\n }\n\n // No SSM parameter\n const bootstrapStack = await this.lookupToolkit();\n doValidate(bootstrapStack.version, this.environment);\n\n function doValidate(version: number, environment: Environment) {\n const notices = Notices.get();\n if (notices) {\n // if `Notices` hasn't been initialized there is probably a good\n // reason for it. handle gracefully.\n notices.addBootstrappedEnvironment({ bootstrapStackVersion: version, environment });\n }\n if (defExpectedVersion > version) {\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', found '${version}'. Please run 'cdk bootstrap'.`,\n );\n }\n }\n }\n\n /**\n * Read a version from an SSM parameter, cached\n */\n public async versionFromSsmParameter(parameterName: string): Promise<number> {\n const existing = this.cache.ssmParameters.get(parameterName);\n if (existing !== undefined) {\n return existing;\n }\n\n const ssm = this.sdk.ssm();\n\n try {\n const result = await ssm.getParameter({ Name: parameterName });\n\n const asNumber = parseInt(`${result.Parameter?.Value}`, 10);\n if (isNaN(asNumber)) {\n throw new ToolkitError(`SSM parameter ${parameterName} not a number: ${result.Parameter?.Value}`);\n }\n\n this.cache.ssmParameters.set(parameterName, asNumber);\n return asNumber;\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n throw new ToolkitError(\n `SSM parameter ${parameterName} not found. Has the environment been bootstrapped? Please run \\'cdk bootstrap\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n throw e;\n }\n }\n\n public async prepareEcrRepository(repositoryName: string): Promise<EcrRepositoryInfo> {\n if (!this.sdk) {\n throw new ToolkitError('ToolkitInfo needs to have been initialized with an sdk to call prepareEcrRepository');\n }\n const ecr = this.sdk.ecr();\n\n // check if repo already exists\n try {\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: checking if ECR repository already exists`));\n const describeResponse = await ecr.describeRepositories({\n repositoryNames: [repositoryName],\n });\n const existingRepositoryUri = describeResponse.repositories![0]?.repositoryUri;\n if (existingRepositoryUri) {\n return { repositoryUri: existingRepositoryUri };\n }\n } catch (e: any) {\n if (e.name !== 'RepositoryNotFoundException') {\n throw e;\n }\n }\n\n // create the repo (tag it so it will be easier to garbage collect in the future)\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: creating ECR repository`));\n const assetTag = { Key: 'awscdk:asset', Value: 'true' };\n const response = await ecr.createRepository({\n repositoryName,\n tags: [assetTag],\n });\n const repositoryUri = response.repository?.repositoryUri;\n if (!repositoryUri) {\n throw new ToolkitError(`CreateRepository did not return a repository URI for ${repositoryUri}`);\n }\n\n // configure image scanning on push (helps in identifying software vulnerabilities, no additional charge)\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: enable image scanning`));\n await ecr.putImageScanningConfiguration({\n repositoryName,\n imageScanningConfiguration: { scanOnPush: true },\n });\n\n return { repositoryUri };\n }\n}\n\nexport class NoBootstrapStackEnvironmentResources extends EnvironmentResources {\n constructor(environment: Environment, sdk: SDK, msg: IoMessaging) {\n super(environment, sdk, msg, emptyCache());\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit(): Promise<ToolkitInfo> {\n throw new ToolkitError(\n 'Trying to perform an operation that requires a bootstrap stack; you should not see this error, this is a bug in the CDK CLI.',\n );\n }\n}\n\n/**\n * Data that is cached on a per-environment level\n *\n * This cache may be shared between different instances of the `EnvironmentResources` class.\n */\ninterface EnvironmentCache {\n readonly ssmParameters: Map<string, number>;\n toolkitInfo?: ToolkitInfo;\n}\n\nfunction emptyCache(): EnvironmentCache {\n return {\n ssmParameters: new Map(),\n toolkitInfo: undefined,\n };\n}\n\n/**\n * The bootstrap template version that introduced ssm:GetParameter\n */\nconst BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER = 5;\n", "import { type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { Branded } from '../../util/type-brands';\nimport type { SdkProvider } from '../aws-auth/sdk-provider';\nimport { Mode } from '../plugin/mode';\n\n/**\n * Replace the {ACCOUNT} and {REGION} placeholders in all strings found in a complex object.\n */\nexport async function replaceEnvPlaceholders<A extends Record<string, string | undefined>>(\n object: A,\n env: Environment,\n sdkProvider: SdkProvider,\n): Promise<{[k in keyof A]: StringWithoutPlaceholders | undefined}> {\n return EnvironmentPlaceholders.replaceAsync(object, {\n accountId: () => Promise.resolve(env.account),\n region: () => Promise.resolve(env.region),\n partition: async () => {\n // There's no good way to get the partition!\n // We should have had it already, except we don't.\n //\n // Best we can do is ask the \"base credentials\" for this environment for their partition. Cross-partition\n // AssumeRole'ing will never work anyway, so this answer won't be wrong (it will just be slow!)\n return (await sdkProvider.baseCredentialsPartition(env, Mode.ForReading)) ?? 'aws';\n },\n });\n}\n\nexport type StringWithoutPlaceholders = Branded<string, 'NoPlaceholders'>;\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { SDK } from '../aws-auth';\nimport { EnvironmentResources, EnvironmentResourcesRegistry } from './environment-resources';\nimport { warn } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { CredentialsOptions, SdkForEnvironment, SdkProvider } from '../aws-auth/sdk-provider';\nimport { Mode } from '../plugin/mode';\nimport { replaceEnvPlaceholders, StringWithoutPlaceholders } from '../util/placeholders';\n\n/**\n * Access particular AWS resources, based on information from the CX manifest\n *\n * It is not possible to grab direct access to AWS credentials; 9 times out of 10\n * we have to allow for role assumption, and role assumption can only work if\n * there is a CX Manifest that contains a role ARN.\n *\n * This class exists so new code isn't tempted to go and get SDK credentials directly.\n */\nexport class EnvironmentAccess {\n private readonly sdkCache = new Map<string, SdkForEnvironment>();\n private readonly environmentResources: EnvironmentResourcesRegistry;\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n constructor(private readonly sdkProvider: SdkProvider, toolkitStackName: string, { ioHost, action }: IoMessaging) {\n this.environmentResources = new EnvironmentResourcesRegistry(toolkitStackName);\n this.ioHost = ioHost;\n this.action = action;\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveStackEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.sdkProvider.resolveEnvironment(stack.environment);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for readonly credentials if available, use the default\n * AWS credentials if not.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForReadOnlyStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for mutating credentials if available, use the default AWS\n * credentials if not. The `mode` parameter is only used for querying\n * plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForMutableStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForWriting);\n }\n\n /**\n * Get an SDK to access the given stack's environment for environmental lookups\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the lookup role if configured on the stack. Check the default `lookup-role`\n * policies to see what you can do with this role. It can generally read everything\n * in the account that does not require KMS access.\n *\n * ---\n *\n * For backwards compatibility reasons, there are some scenarios that are handled here:\n *\n * 1. The lookup role may not exist (it was added in bootstrap stack version 7). If so:\n * a. Return the default credentials if the default credentials are for the stack account\n * (you will notice this as `isFallbackCredentials=true`).\n * b. Throw an error if the default credentials are not for the stack account.\n *\n * 2. The lookup role may not have the correct permissions (for example, ReadOnlyAccess was added in\n * bootstrap stack version 8); the stack will have a minimum version number on it.\n * a. If it does not we throw an error which should be handled in the calling\n * function (and fallback to use a different role, etc)\n *\n * Upon success, caller will have an SDK for the right account, which may or may not have\n * the right permissions.\n */\n public async accessStackForLookup(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n const lookupEnv = await this.prepareSdk({\n environment: stack.environment,\n mode: Mode.ForReading,\n assumeRoleArn: stack.lookupRole?.arn,\n assumeRoleExternalId: stack.lookupRole?.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.lookupRole?.assumeRoleAdditionalOptions,\n });\n\n // if we succeed in assuming the lookup role, make sure we have the correct bootstrap stack version\n if (lookupEnv.didAssumeRole && stack.lookupRole?.bootstrapStackVersionSsmParameter && stack.lookupRole.requiresBootstrapStackVersion) {\n const version = await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);\n if (version < stack.lookupRole.requiresBootstrapStackVersion) {\n throw new ToolkitError(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`);\n }\n }\n if (lookupEnv.isFallbackCredentials) {\n const arn = await lookupEnv.replacePlaceholders(stack.lookupRole?.arn);\n await this.ioHost.notify(warn(this.action, `Lookup role ${arn} was not assumed. Proceeding with default credentials.`));\n }\n return lookupEnv;\n }\n\n /**\n * Get an SDK to access the given stack's environment for reading stack attributes\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will try to assume the lookup role if given, will use the regular stack operations\n * access (deploy-role) otherwise. When calling this, you should assume that you will get\n * the least privileged role, so don't try to use it for anything the `deploy-role`\n * wouldn't be able to do. Also you cannot rely on being able to read encrypted anything.\n */\n public async accessStackForLookupBestEffort(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n try {\n return await this.accessStackForLookup(stack);\n } catch (e: any) {\n await this.ioHost.notify(warn(this.action, `${formatErrorMessage(e)}`));\n }\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n private async accessStackForStackOperations(stack: cxapi.CloudFormationStackArtifact, mode: Mode): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n return this.prepareSdk({\n environment: stack.environment,\n mode,\n assumeRoleArn: stack.assumeRoleArn,\n assumeRoleExternalId: stack.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.assumeRoleAdditionalOptions,\n });\n }\n\n /**\n * Prepare an SDK for use in the given environment and optionally with a role assumed.\n */\n private async prepareSdk(\n options: PrepareSdkRoleOptions,\n ): Promise<TargetEnvironment> {\n const resolvedEnvironment = await this.sdkProvider.resolveEnvironment(options.environment);\n\n // Substitute any placeholders with information about the current environment\n const { assumeRoleArn } = await replaceEnvPlaceholders({\n assumeRoleArn: options.assumeRoleArn,\n }, resolvedEnvironment, this.sdkProvider);\n\n const stackSdk = await this.cachedSdkForEnvironment(resolvedEnvironment, options.mode, {\n assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n });\n\n return {\n sdk: stackSdk.sdk,\n resolvedEnvironment,\n resources: this.environmentResources.for(resolvedEnvironment, stackSdk.sdk, { ioHost: this.ioHost, action: this.action }),\n // If we asked for a role, did not successfully assume it, and yet got here without an exception: that\n // means we must have fallback credentials.\n isFallbackCredentials: !stackSdk.didAssumeRole && !!assumeRoleArn,\n didAssumeRole: stackSdk.didAssumeRole,\n replacePlaceholders: async <A extends string | undefined>(str: A) => {\n const ret = await replaceEnvPlaceholders({ str }, resolvedEnvironment, this.sdkProvider);\n return ret.str;\n },\n };\n }\n\n private async cachedSdkForEnvironment(\n environment: cxapi.Environment,\n mode: Mode,\n options?: CredentialsOptions,\n ) {\n const cacheKeyElements = [\n environment.account,\n environment.region,\n `${mode}`,\n options?.assumeRoleArn ?? '',\n options?.assumeRoleExternalId ?? '',\n ];\n\n if (options?.assumeRoleAdditionalOptions) {\n cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions));\n }\n\n const cacheKey = cacheKeyElements.join(':');\n const existing = this.sdkCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n const ret = await this.sdkProvider.forEnvironment(environment, mode, options);\n this.sdkCache.set(cacheKey, ret);\n return ret;\n }\n}\n\n/**\n * SDK obtained by assuming the deploy role\n * for a given environment\n */\nexport interface TargetEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The resolved environment for the stack\n * (no more 'unknown-account/unknown-region')\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * Access class for environmental resources to help the deployment\n */\n readonly resources: EnvironmentResources;\n\n /**\n * Whether or not we assumed a role in the process of getting these credentials\n */\n readonly didAssumeRole: boolean;\n\n /**\n * Whether or not these are fallback credentials\n *\n * Fallback credentials means that assuming the intended role failed, but the\n * base credentials happen to be for the right account so we just picked those\n * and hope the future SDK calls succeed.\n *\n * This is a backwards compatibility mechanism from around the time we introduced\n * deployment roles.\n */\n readonly isFallbackCredentials: boolean;\n\n /**\n * Replace environment placeholders according to the current environment\n */\n replacePlaceholders(x: string | undefined): Promise<StringWithoutPlaceholders | undefined>;\n}\n\ninterface PrepareSdkRoleOptions {\n readonly environment: cxapi.Environment;\n readonly mode: Mode;\n readonly assumeRoleArn?: string;\n readonly assumeRoleExternalId?: string;\n readonly assumeRoleAdditionalOptions?: { [key: string]: any };\n}\n", "import { ToolkitError } from '../../toolkit/error';\n\nexport type DeployStackResult =\n | SuccessfulDeployStackResult\n | NeedRollbackFirstDeployStackResult\n | ReplacementRequiresRollbackStackResult\n ;\n\n/** Successfully deployed a stack */\nexport interface SuccessfulDeployStackResult {\n readonly type: 'did-deploy-stack';\n readonly noOp: boolean;\n readonly outputs: { [name: string]: string };\n readonly stackArn: string;\n}\n\n/** The stack is currently in a failpaused state, and needs to be rolled back before the deployment */\nexport interface NeedRollbackFirstDeployStackResult {\n readonly type: 'failpaused-need-rollback-first';\n readonly reason: 'not-norollback' | 'replacement';\n readonly status: string;\n}\n\n/** The upcoming change has a replacement, which requires deploying with --rollback */\nexport interface ReplacementRequiresRollbackStackResult {\n readonly type: 'replacement-requires-rollback';\n}\n\nexport function assertIsSuccessfulDeployStackResult(x: DeployStackResult): asserts x is SuccessfulDeployStackResult {\n if (x.type !== 'did-deploy-stack') {\n throw new ToolkitError(`Unexpected deployStack result. This should not happen: ${JSON.stringify(x)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose.`);\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\n/**\n * @returns an array with the tags available in the stack metadata.\n */\nexport function tagsForStack(stack: cxapi.CloudFormationStackArtifact): Tag[] {\n return Object.entries(stack.tags).map(([Key, Value]) => ({ Key, Value }));\n}\n\nexport interface Tag {\n readonly Key: string;\n readonly Value: string;\n}\n", "import { format } from 'util';\nimport * as cfnDiff from '@aws-cdk/cloudformation-diff';\nimport { ResourceDifference } from '@aws-cdk/cloudformation-diff';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as promptly from 'promptly';\nimport { error, info, warn } from '../../cli/messages';\nimport { IIoHost, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { assertIsSuccessfulDeployStackResult, type Deployments, DeploymentMethod, ResourceIdentifierProperties, ResourcesToImport } from '../deployments';\nimport type { StackActivityProgress } from '../stack-events';\nimport type { Tag } from '../tags';\n\nexport interface ResourceImporterProps {\n deployments: Deployments;\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\nexport interface ImportDeploymentOptions {\n /**\n * Role to pass to CloudFormation for deployment\n *\n * @default - Default stack role\n */\n readonly roleArn?: string;\n\n /**\n * Deployment method\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Stack tags (pass through to CloudFormation)\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Display mode for stack deployment progress.\n *\n * @default - StackActivityProgress.Bar - stack events will be displayed for\n * the resource currently being deployed.\n */\n readonly progress?: StackActivityProgress;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n}\n\n/**\n * Set of parameters that uniquely identify a physical resource of a given type\n * for the import operation, example:\n *\n * ```\n * {\n * \"AWS::S3::Bucket\": [[\"BucketName\"]],\n * \"AWS::DynamoDB::GlobalTable\": [[\"TableName\"], [\"TableArn\"], [\"TableStreamArn\"]],\n * \"AWS::Route53::KeySigningKey\": [[\"HostedZoneId\", \"Name\"]],\n * }\n * ```\n */\nexport type ResourceIdentifiers = { [resourceType: string]: string[][] };\n\n/**\n * Mapping of CDK resources (L1 constructs) to physical resources to be imported\n * in their place, example:\n *\n * ```\n * {\n * \"MyStack/MyS3Bucket/Resource\": {\n * \"BucketName\": \"my-manually-created-s3-bucket\"\n * },\n * \"MyStack/MyVpc/Resource\": {\n * \"VpcId\": \"vpc-123456789\"\n * }\n * }\n * ```\n */\nexport type ResourceMap = { [logicalResource: string]: ResourceIdentifierProperties };\n\n/**\n * Resource importing utility class\n *\n * - Determines the resources added to a template (compared to the deployed version)\n * - Look up the identification information\n * - Load them from a file, or\n * - Ask the user, based on information supplied to us by CloudFormation's GetTemplateSummary\n * - Translate the input to a structure expected by CloudFormation, update the template to add the\n * importable resources, then run an IMPORT changeset.\n */\nexport class ResourceImporter {\n private _currentTemplate: any;\n\n private readonly stack: cxapi.CloudFormationStackArtifact;\n private readonly cfn: Deployments;\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n constructor(\n stack: cxapi.CloudFormationStackArtifact,\n props: ResourceImporterProps,\n ) {\n this.stack = stack;\n this.cfn = props.deployments;\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n /**\n * Ask the user for resources to import\n */\n public async askForResourceIdentifiers(available: ImportableResource[]): Promise<ImportMap> {\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n const resourceIdentifiers = await this.resourceIdentifiers();\n\n for (const resource of available) {\n const identifier = await this.askForResourceIdentifier(resourceIdentifiers, resource);\n if (!identifier) {\n continue;\n }\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = identifier;\n }\n\n return ret;\n }\n\n /**\n * Load the resources to import from a file\n */\n public async loadResourceIdentifiers(available: ImportableResource[], filename: string): Promise<ImportMap> {\n const contents = await fs.readJson(filename);\n\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n for (const resource of available) {\n const descr = this.describeResource(resource.logicalId);\n const idProps = contents[resource.logicalId];\n if (idProps) {\n await this.ioHost.notify(info(this.action, format('%s: importing using %s', chalk.blue(descr), chalk.blue(fmtdict(idProps)))));\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = idProps;\n delete contents[resource.logicalId];\n } else {\n await this.ioHost.notify(info(this.action, format('%s: skipping', chalk.blue(descr))));\n }\n }\n\n const unknown = Object.keys(contents);\n if (unknown.length > 0) {\n await this.ioHost.notify(warn(this.action, `Unrecognized resource identifiers in mapping file: ${unknown.join(', ')}`));\n }\n\n return ret;\n }\n\n /**\n * Based on the provided resource mapping, prepare CFN structures for import (template,\n * ResourcesToImport structure) and perform the import operation (CloudFormation deployment)\n *\n * @param importMap Mapping from CDK construct tree path to physical resource import identifiers\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMap(importMap: ImportMap, options: ImportDeploymentOptions = {}) {\n const resourcesToImport: ResourcesToImport = await this.makeResourcesToImport(importMap);\n const updatedTemplate = await this.currentTemplateWithAdditions(importMap.importResources);\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n /**\n * Based on the app and resources file generated by cdk migrate. Removes all items from the template that\n * cannot be included in an import change-set for new stacks and performs the import operation,\n * creating the new stack.\n *\n * @param resourcesToImport The mapping created by cdk migrate\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMigrate(resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions = {}) {\n const updatedTemplate = this.removeNonImportResources();\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n private async importResources(overrideTemplate: any, resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions) {\n try {\n const result = await this.cfn.deployStack({\n stack: this.stack,\n deployName: this.stack.stackName,\n ...options,\n overrideTemplate,\n resourcesToImport,\n });\n\n assertIsSuccessfulDeployStackResult(result);\n\n const message = result.noOp\n ? ' \u2705 %s (no changes)'\n : ' \u2705 %s';\n\n await this.ioHost.notify(info(this.action, '\\n' + chalk.green(format(message, this.stack.displayName))));\n } catch (e) {\n await this.ioHost.notify(error(this.action, format('\\n \u274C %s failed: %s', chalk.bold(this.stack.displayName), e), 'CDK_TOOLKIT_E3900'));\n throw e;\n }\n }\n\n /**\n * Perform a diff between the currently running and the new template, ensure that it is valid\n * for importing and return a list of resources that are being added in the new version\n *\n * @return mapping logicalResourceId -> resourceDifference\n */\n public async discoverImportableResources(allowNonAdditions = false): Promise<DiscoverImportableResourcesResult> {\n const currentTemplate = await this.currentTemplate();\n\n const diff = cfnDiff.fullDiff(currentTemplate, this.stack.template);\n\n // Ignore changes to CDKMetadata\n const resourceChanges = Object.entries(diff.resources.changes)\n .filter(([logicalId, _]) => logicalId !== 'CDKMetadata');\n\n // Split the changes into additions and non-additions. Imports only make sense\n // for newly-added resources.\n const nonAdditions = resourceChanges.filter(([_, dif]) => !dif.isAddition);\n const additions = resourceChanges.filter(([_, dif]) => dif.isAddition);\n\n if (nonAdditions.length) {\n const offendingResources = nonAdditions.map(([logId, _]) => this.describeResource(logId));\n\n if (allowNonAdditions) {\n await this.ioHost.notify(warn(this.action, `Ignoring updated/deleted resources (--force): ${offendingResources.join(', ')}`));\n } else {\n throw new ToolkitError('No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes ' +\n `to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(', ')} (--force to override)`);\n }\n }\n\n // Resources in the new template, that are not present in the current template, are a potential import candidates\n return {\n additions: additions.map(([logicalId, resourceDiff]) => ({\n logicalId,\n resourceDiff,\n resourceDefinition: addDefaultDeletionPolicy(this.stack.template?.Resources?.[logicalId] ?? {}),\n })),\n hasNonAdditions: nonAdditions.length > 0,\n };\n }\n\n /**\n * Resolves the environment of a stack.\n */\n public async resolveEnvironment(): Promise<cxapi.Environment> {\n return this.cfn.resolveEnvironment(this.stack);\n }\n\n /**\n * Get currently deployed template of the given stack (SINGLETON)\n *\n * @returns Currently deployed CloudFormation template\n */\n private async currentTemplate(): Promise<any> {\n if (!this._currentTemplate) {\n this._currentTemplate = await this.cfn.readCurrentTemplate(this.stack);\n }\n return this._currentTemplate;\n }\n\n /**\n * Return the current template, with the given resources added to it\n */\n private async currentTemplateWithAdditions(additions: ImportableResource[]): Promise<any> {\n const template = await this.currentTemplate();\n if (!template.Resources) {\n template.Resources = {};\n }\n\n for (const add of additions) {\n template.Resources[add.logicalId] = add.resourceDefinition;\n }\n\n return template;\n }\n\n /**\n * Get a list of import identifiers for all resource types used in the given\n * template that do support the import operation (SINGLETON)\n *\n * @returns a mapping from a resource type to a list of property names that together identify the resource for import\n */\n private async resourceIdentifiers(): Promise<ResourceIdentifiers> {\n const ret: ResourceIdentifiers = {};\n const resourceIdentifierSummaries = await this.cfn.resourceIdentifierSummaries(this.stack);\n for (const summary of resourceIdentifierSummaries) {\n if ('ResourceType' in summary && summary.ResourceType && 'ResourceIdentifiers' in summary && summary.ResourceIdentifiers) {\n ret[summary.ResourceType] = (summary.ResourceIdentifiers ?? [])?.map(x => x.split(','));\n }\n }\n return ret;\n }\n\n /**\n * Ask for the importable identifier for the given resource\n *\n * There may be more than one identifier under which a resource can be imported. The `import`\n * operation needs exactly one of them.\n *\n * - If we can get one from the template, we will use one.\n * - Otherwise, we will ask the user for one of them.\n */\n private async askForResourceIdentifier(\n resourceIdentifiers: ResourceIdentifiers,\n chg: ImportableResource,\n ): Promise<ResourceIdentifierProperties | undefined> {\n const resourceName = this.describeResource(chg.logicalId);\n\n // Skip resources that do not support importing\n const resourceType = chg.resourceDiff.newResourceType;\n if (resourceType === undefined || !(resourceType in resourceIdentifiers)) {\n await this.ioHost.notify(warn(this.action, `${resourceName}: unsupported resource type ${resourceType}, skipping import.`));\n return undefined;\n }\n\n const idPropSets = resourceIdentifiers[resourceType];\n\n // Retain only literal strings: strip potential CFN intrinsics\n const resourceProps = Object.fromEntries(Object.entries(chg.resourceDefinition.Properties ?? {})\n .filter(([_, v]) => typeof v === 'string')) as Record<string, string>;\n\n // Find property sets that are fully satisfied in the template, ask the user to confirm them\n const satisfiedPropSets = idPropSets.filter(ps => ps.every(p => resourceProps[p]));\n for (const satisfiedPropSet of satisfiedPropSets) {\n const candidateProps = Object.fromEntries(satisfiedPropSet.map(p => [p, resourceProps[p]]));\n const displayCandidateProps = fmtdict(candidateProps);\n\n if (await promptly.confirm(\n `${chalk.blue(resourceName)} (${resourceType}): import with ${chalk.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,\n { default: 'yes' },\n )) {\n return candidateProps;\n }\n }\n\n // If we got here and the user rejected any available identifiers, then apparently they don't want the resource at all\n if (satisfiedPropSets.length > 0) {\n await this.ioHost.notify(info(this.action, chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n // We cannot auto-import this, ask the user for one of the props\n // The only difference between these cases is what we print: for multiple properties, we print a preamble\n const prefix = `${chalk.blue(resourceName)} (${resourceType})`;\n let preamble;\n let promptPattern;\n if (idPropSets.length > 1) {\n preamble = `${prefix}: enter one of ${idPropSets.map(x => chalk.blue(x.join('+'))).join(', ')} to import (all empty to skip)`;\n promptPattern = `${prefix}: enter %`;\n } else {\n promptPattern = `${prefix}: enter %`;\n }\n\n // Do the input loop here\n if (preamble) {\n await this.ioHost.notify(info(this.action, preamble));\n }\n for (const idProps of idPropSets) {\n const input: Record<string, string> = {};\n for (const idProp of idProps) {\n // If we have a value from the template, use it as default. This will only be a partial\n // identifier if present, otherwise we would have done the import already above.\n const defaultValue = resourceProps[idProp] ?? '';\n\n const prompt = [\n promptPattern.replace(/%/g, chalk.blue(idProp)),\n defaultValue\n ? `[${defaultValue}]`\n : '(empty to skip)',\n ].join(' ') + ':';\n const response = await promptly.prompt(prompt,\n { default: defaultValue, trim: true },\n );\n\n if (!response) {\n break;\n }\n\n input[idProp] = response;\n // Also stick this property into 'resourceProps', so that it may be reused by a subsequent question\n // (for a different compound identifier that involves the same property). Just a small UX enhancement.\n resourceProps[idProp] = response;\n }\n\n // If the user gave inputs for all values, we are complete\n if (Object.keys(input).length === idProps.length) {\n return input;\n }\n }\n\n await this.ioHost.notify(info(this.action, chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n /**\n * Convert the internal \"resource mapping\" structure to CloudFormation accepted \"ResourcesToImport\" structure\n */\n private async makeResourcesToImport(resourceMap: ImportMap): Promise<ResourcesToImport> {\n return resourceMap.importResources.map(res => ({\n LogicalResourceId: res.logicalId,\n ResourceType: res.resourceDiff.newResourceType!,\n ResourceIdentifier: resourceMap.resourceMap[res.logicalId],\n }));\n }\n\n /**\n * Convert CloudFormation logical resource ID to CDK construct tree path\n *\n * @param logicalId CloudFormation logical ID of the resource (the key in the template's Resources section)\n * @returns Forward-slash separated path of the resource in CDK construct tree, e.g. MyStack/MyBucket/Resource\n */\n private describeResource(logicalId: string): string {\n return this.stack.template?.Resources?.[logicalId]?.Metadata?.['aws:cdk:path'] ?? logicalId;\n }\n\n /**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\n private removeNonImportResources() {\n return removeNonImportResources(this.stack);\n }\n}\n\n/**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\nexport function removeNonImportResources(stack: cxapi.CloudFormationStackArtifact) {\n const template = stack.template;\n delete template.Resources.CDKMetadata;\n delete template.Outputs;\n return template;\n}\n\n/**\n * Information about a resource in the template that is importable\n */\nexport interface ImportableResource {\n /**\n * The logical ID of the resource\n */\n readonly logicalId: string;\n\n /**\n * The resource definition in the new template\n */\n readonly resourceDefinition: any;\n\n /**\n * The diff as reported by `cloudformation-diff`.\n */\n readonly resourceDiff: ResourceDifference;\n}\n\n/**\n * The information necessary to execute an import operation\n */\nexport interface ImportMap {\n /**\n * Mapping logical IDs to physical names\n */\n readonly resourceMap: ResourceMap;\n\n /**\n * The selection of resources we are actually importing\n *\n * For each of the resources in this list, there is a corresponding entry in\n * the `resourceMap` map.\n */\n readonly importResources: ImportableResource[];\n}\n\nfunction fmtdict<A>(xs: Record<string, A>) {\n return Object.entries(xs).map(([k, v]) => `${k}=${v}`).join(', ');\n}\n\n/**\n * Add a default `DeletionPolicy` policy.\n * The default value is set to 'Retain', to lower risk of unintentionally\n * deleting stateful resources in the process of importing to CDK.\n */\nfunction addDefaultDeletionPolicy(resource: any): any {\n if (resource.DeletionPolicy) {\n return resource;\n }\n\n return {\n ...resource,\n DeletionPolicy: 'Retain',\n };\n}\n\nexport interface DiscoverImportableResourcesResult {\n readonly additions: ImportableResource[];\n readonly hasNonAdditions: boolean;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport { ImportDeploymentOptions, ResourceImporter } from './importer';\nimport { info } from '../../cli/messages';\nimport type { IIoHost, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { formatTime } from '../../util/string-manipulation';\nimport { StackCollection } from '../cxapp/cloud-assembly';\nimport type { Deployments, ResourcesToImport } from '../deployments';\n\nexport interface ResourceMigratorProps {\n deployments: Deployments;\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\nexport class ResourceMigrator {\n private readonly props: ResourceMigratorProps;\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n public constructor(props: ResourceMigratorProps) {\n this.props = props;\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n /**\n * Checks to see if a migrate.json file exists. If it does and the source is either `filepath` or\n * is in the same environment as the stack deployment, a new stack is created and the resources are\n * migrated to the stack using an IMPORT changeset. The normal deployment will resume after this is complete\n * to add back in any outputs and the CDKMetadata.\n */\n public async tryMigrateResources(stacks: StackCollection, options: ImportDeploymentOptions): Promise<void> {\n const stack = stacks.stackArtifacts[0];\n const migrateDeployment = new ResourceImporter(stack, {\n deployments: this.props.deployments,\n ioHost: this.ioHost,\n action: this.action,\n });\n const resourcesToImport = await this.tryGetResources(await migrateDeployment.resolveEnvironment());\n\n if (resourcesToImport) {\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: creating stack for resource migration...`));\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: importing resources into stack...`));\n\n await this.performResourceMigration(migrateDeployment, resourcesToImport, options);\n\n fs.rmSync('migrate.json');\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: applying CDKMetadata and Outputs to stack (if applicable)...`));\n }\n }\n\n /**\n * Creates a new stack with just the resources to be migrated\n */\n private async performResourceMigration(\n migrateDeployment: ResourceImporter,\n resourcesToImport: ResourcesToImport,\n options: ImportDeploymentOptions,\n ) {\n const startDeployTime = new Date().getTime();\n let elapsedDeployTime = 0;\n\n // Initial Deployment\n await migrateDeployment.importResourcesFromMigrate(resourcesToImport, {\n roleArn: options.roleArn,\n deploymentMethod: options.deploymentMethod,\n usePreviousParameters: true,\n progress: options.progress,\n rollback: options.rollback,\n });\n\n elapsedDeployTime = new Date().getTime() - startDeployTime;\n await this.ioHost.notify(info(this.action, `'\\n\u2728 Resource migration time: ${formatTime(elapsedDeployTime)}s\\n'`, 'CDK_TOOLKIT_I5002', {\n duration: elapsedDeployTime,\n }));\n }\n\n public async tryGetResources(environment: cxapi.Environment): Promise<ResourcesToImport | undefined> {\n try {\n const migrateFile = fs.readJsonSync('migrate.json', {\n encoding: 'utf-8',\n });\n const sourceEnv = (migrateFile.Source as string).split(':');\n if (\n sourceEnv[0] === 'localfile' ||\n (sourceEnv[4] === environment.account && sourceEnv[3] === environment.region)\n ) {\n return migrateFile.Resources;\n }\n } catch (e) {\n // Nothing to do\n }\n\n return undefined;\n }\n}\n\n", "import * as util from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { info, error } from '../../logging';\nimport { flatten } from '../../util/arrays';\nimport type { SDK } from '../aws-auth';\n\n/**\n * After reading events from all CloudWatch log groups\n * how long should we wait to read more events.\n *\n * If there is some error with reading events (i.e. Throttle)\n * then this is also how long we wait until we try again\n */\nconst SLEEP = 2_000;\n\n/**\n * Represents a CloudWatch Log Event that will be\n * printed to the terminal\n */\ninterface CloudWatchLogEvent {\n /**\n * The log event message\n */\n readonly message: string;\n\n /**\n * The name of the log group\n */\n readonly logGroupName: string;\n\n /**\n * The time at which the event occurred\n */\n readonly timestamp: Date;\n}\n\n/**\n * Configuration tracking information on the log groups that are\n * being monitored\n */\ninterface LogGroupsAccessSettings {\n /**\n * The SDK for a given environment (account/region)\n */\n readonly sdk: SDK;\n\n /**\n * A map of log groups and associated startTime in a given account.\n *\n * The monitor will read events from the log group starting at the\n * associated startTime\n */\n readonly logGroupsStartTimes: { [logGroupName: string]: number };\n}\n\nexport class CloudWatchLogEventMonitor {\n /**\n * Determines which events not to display\n */\n private startTime: number;\n\n /**\n * Map of environment (account:region) to LogGroupsAccessSettings\n */\n private readonly envsLogGroupsAccessSettings = new Map<string, LogGroupsAccessSettings>();\n\n private active = false;\n\n constructor(startTime?: Date) {\n this.startTime = startTime?.getTime() ?? Date.now();\n }\n\n /**\n * resume reading/printing events\n */\n public activate(): void {\n this.active = true;\n this.scheduleNextTick(0);\n }\n\n /**\n * deactivates the monitor so no new events are read\n * use case for this is when we are in the middle of performing a deployment\n * and don't want to interweave all the logs together with the CFN\n * deployment logs\n *\n * Also resets the start time to be when the new deployment was triggered\n * and clears the list of tracked log groups\n */\n public deactivate(): void {\n this.active = false;\n this.startTime = Date.now();\n this.envsLogGroupsAccessSettings.clear();\n }\n\n /**\n * Adds CloudWatch log groups to read log events from.\n * Since we could be watching multiple stacks that deploy to\n * multiple environments (account+region), we need to store a list of log groups\n * per env along with the SDK object that has access to read from\n * that environment.\n */\n public addLogGroups(env: cxapi.Environment, sdk: SDK, logGroupNames: string[]): void {\n const awsEnv = `${env.account}:${env.region}`;\n const logGroupsStartTimes = logGroupNames.reduce(\n (acc, groupName) => {\n acc[groupName] = this.startTime;\n return acc;\n },\n {} as { [logGroupName: string]: number },\n );\n this.envsLogGroupsAccessSettings.set(awsEnv, {\n sdk,\n logGroupsStartTimes: {\n ...this.envsLogGroupsAccessSettings.get(awsEnv)?.logGroupsStartTimes,\n ...logGroupsStartTimes,\n },\n });\n }\n\n private scheduleNextTick(sleep: number): void {\n setTimeout(() => void this.tick(), sleep);\n }\n\n private async tick(): Promise<void> {\n // excluding from codecoverage because this\n // doesn't always run (depends on timing)\n /* istanbul ignore next */\n if (!this.active) {\n return;\n }\n try {\n const events = flatten(await this.readNewEvents());\n events.forEach((event) => {\n this.print(event);\n });\n } catch (e) {\n error('Error occurred while monitoring logs: %s', e);\n }\n\n this.scheduleNextTick(SLEEP);\n }\n\n /**\n * Reads all new log events from a set of CloudWatch Log Groups\n * in parallel\n */\n private async readNewEvents(): Promise<Array<Array<CloudWatchLogEvent>>> {\n const promises: Array<Promise<Array<CloudWatchLogEvent>>> = [];\n for (const settings of this.envsLogGroupsAccessSettings.values()) {\n for (const group of Object.keys(settings.logGroupsStartTimes)) {\n promises.push(this.readEventsFromLogGroup(settings, group));\n }\n }\n // Limited set of log groups\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(promises);\n }\n\n /**\n * Print out a cloudwatch event\n */\n private print(event: CloudWatchLogEvent): void {\n info(\n util.format(\n '[%s] %s %s',\n chalk.blue(event.logGroupName),\n chalk.yellow(event.timestamp.toLocaleTimeString()),\n event.message.trim(),\n ),\n );\n }\n\n /**\n * Reads all new log events from a CloudWatch Log Group\n * starting at either the time the hotswap was triggered or\n * when the last event was read on the previous tick\n */\n private async readEventsFromLogGroup(\n logGroupsAccessSettings: LogGroupsAccessSettings,\n logGroupName: string,\n ): Promise<Array<CloudWatchLogEvent>> {\n const events: CloudWatchLogEvent[] = [];\n\n // log events from some service are ingested faster than others\n // so we need to track the start/end time for each log group individually\n // to make sure that we process all events from each log group\n const startTime = logGroupsAccessSettings.logGroupsStartTimes[logGroupName] ?? this.startTime;\n let endTime = startTime;\n try {\n const response = await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({\n logGroupName: logGroupName,\n limit: 100,\n startTime: startTime,\n });\n const filteredEvents = response.events ?? [];\n\n for (const event of filteredEvents) {\n if (event.message) {\n events.push({\n message: event.message,\n logGroupName,\n timestamp: event.timestamp ? new Date(event.timestamp) : new Date(),\n });\n\n if (event.timestamp && endTime < event.timestamp) {\n endTime = event.timestamp;\n }\n }\n }\n // As long as there are _any_ events in the log group `filterLogEvents` will return a nextToken.\n // This is true even if these events are before `startTime`. So if we have 100 events and a nextToken\n // then assume that we have hit the limit and let the user know some messages have been suppressed.\n // We are essentially showing them a sampling (10000 events printed out is not very useful)\n if (filteredEvents.length === 100 && response.nextToken) {\n events.push({\n message: '>>> `watch` shows only the first 100 log messages - the rest have been truncated...',\n logGroupName,\n timestamp: new Date(endTime),\n });\n }\n } catch (e: any) {\n // with Lambda functions the CloudWatch is not created\n // until something is logged, so just keep polling until\n // there is somthing to find\n if (e.name === 'ResourceNotFoundException') {\n return [];\n }\n throw e;\n }\n logGroupsAccessSettings.logGroupsStartTimes[logGroupName] = endTime + 1;\n return events;\n }\n}\n", "import type { CloudFormationStackArtifact, Environment } from '@aws-cdk/cx-api';\nimport type { StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport { debug } from '../../logging';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport { EnvironmentAccess } from '../environment';\nimport { EvaluateCloudFormationTemplate, LazyListStackResources } from '../evaluate-cloudformation-template';\nimport { Mode } from '../plugin/mode';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\n// resource types that have associated CloudWatch Log Groups that should _not_ be monitored\nconst IGNORE_LOGS_RESOURCE_TYPES = ['AWS::EC2::FlowLog', 'AWS::CloudTrail::Trail', 'AWS::CodeBuild::Project'];\n\n/**\n * Configuration needed to monitor CloudWatch Log Groups\n * found in a given CloudFormation Stack\n */\nexport interface FoundLogGroupsResult {\n /**\n * The resolved environment (account/region) that the log\n * groups are deployed in\n */\n readonly env: Environment;\n\n /**\n * The SDK that can be used to read events from the CloudWatch\n * Log Groups in the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The names of the relevant CloudWatch Log Groups\n * in the given CloudFormation template\n */\n readonly logGroupNames: string[];\n}\n\nexport async function findCloudWatchLogGroups(\n sdkProvider: SdkProvider,\n msg: IoMessaging,\n stackArtifact: CloudFormationStackArtifact,\n): Promise<FoundLogGroupsResult> {\n let sdk: SDK;\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // try to assume the lookup role and fallback to the default credentials\n try {\n sdk = (await new EnvironmentAccess(sdkProvider, DEFAULT_TOOLKIT_STACK_NAME, msg).accessStackForLookup(stackArtifact)).sdk;\n } catch (e: any) {\n debug(`Failed to access SDK environment: ${formatErrorMessage(e)}`);\n sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForReading)).sdk;\n }\n\n const listStackResources = new LazyListStackResources(sdk, stackArtifact.stackName);\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackName: stackArtifact.stackName,\n template: stackArtifact.template,\n parameters: {},\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n });\n\n const stackResources = await listStackResources.listStackResources();\n const logGroupNames = findAllLogGroupNames(stackResources, evaluateCfnTemplate);\n\n return {\n env: resolvedEnv,\n sdk,\n logGroupNames,\n };\n}\n\n/**\n * Determine if a CloudWatch Log Group is associated\n * with an ignored resource\n */\nfunction isReferencedFromIgnoredResource(\n logGroupResource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): boolean {\n const resourcesReferencingLogGroup = evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId!);\n return resourcesReferencingLogGroup.some((reference) => {\n return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type);\n });\n}\n\ntype CloudWatchLogsResolver = (\n resource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n) => string | undefined;\n\nconst cloudWatchLogsResolvers: Record<string, CloudWatchLogsResolver> = {\n 'AWS::Logs::LogGroup': (resource, evaluateCfnTemplate) => {\n if (isReferencedFromIgnoredResource(resource, evaluateCfnTemplate)) {\n return undefined;\n }\n return resource.PhysicalResourceId?.toString();\n },\n\n // Resource types that will create a CloudWatch log group with a specific name if one is not provided.\n // The keys are CFN resource types, and the values are the name of the physical name property of that resource\n // and the service name that is used in the automatically created CloudWatch log group.\n 'AWS::Lambda::Function': (resource, evaluateCfnTemplate) => {\n const loggingConfig = evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId!, 'LoggingConfig');\n if (loggingConfig?.LogGroup) {\n // if LogGroup is a string then use it as the LogGroupName as it is referred by LogGroup.fromLogGroupArn in CDK\n if (typeof loggingConfig.LogGroup === 'string') {\n return loggingConfig.LogGroup;\n }\n\n // if { Ref: '...' } is used then try to resolve the LogGroupName from the referenced resource in the template\n if (typeof loggingConfig.LogGroup === 'object') {\n if (loggingConfig.LogGroup.Ref) {\n return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref, 'LogGroupName');\n }\n }\n }\n\n return `/aws/lambda/${resource.PhysicalResourceId}`;\n },\n};\n\n/**\n * Find all CloudWatch Log Groups in the deployed template.\n * This will find both explicitly created Log Groups (excluding those associated with ignored resources)\n * and Log Groups created implicitly (i.e. Lambda Functions)\n */\nfunction findAllLogGroupNames(\n stackResources: StackResourceSummary[],\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): string[] {\n const logGroupNames: string[] = [];\n\n for (const resource of stackResources) {\n const logGroupResolver = cloudWatchLogsResolvers[resource.ResourceType!];\n if (logGroupResolver) {\n const logGroupName = logGroupResolver(resource, evaluateCfnTemplate);\n if (logGroupName) {\n logGroupNames.push(logGroupName);\n }\n }\n }\n\n return logGroupNames;\n}\n", "import { WorkNode, DeploymentState, StackNode, AssetBuildNode, AssetPublishNode } from './work-graph-types';\nimport { debug, trace } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { parallelPromises } from '../../util/parallel';\n\nexport type Concurrency = number | Record<WorkNode['type'], number>;\n\nexport interface WorkGraphProps {\n ioHost: IoMessaging['ioHost'];\n action: IoMessaging['action'];\n}\n\nexport class WorkGraph {\n public readonly nodes: Record<string, WorkNode>;\n private readonly readyPool: Array<WorkNode> = [];\n private readonly lazyDependencies = new Map<string, string[]>();\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n public error?: Error;\n\n public constructor(nodes: Record<string, WorkNode>, props: WorkGraphProps) {\n this.nodes = { ...nodes };\n\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n public addNodes(...nodes: WorkNode[]) {\n for (const node of nodes) {\n if (this.nodes[node.id]) {\n throw new ToolkitError(`Duplicate use of node id: ${node.id}`);\n }\n\n const ld = this.lazyDependencies.get(node.id);\n if (ld) {\n for (const x of ld) {\n node.dependencies.add(x);\n }\n this.lazyDependencies.delete(node.id);\n }\n\n this.nodes[node.id] = node;\n }\n }\n\n public removeNode(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n const removedNode = this.nodes[id];\n\n this.lazyDependencies.delete(id);\n delete this.nodes[id];\n\n if (removedNode) {\n for (const node of Object.values(this.nodes)) {\n node.dependencies.delete(removedNode.id);\n }\n }\n }\n\n /**\n * Return all nodes of a given type\n */\n public nodesOfType<T extends WorkNode['type']>(type: T): Extract<WorkNode, { type: T }>[] {\n return Object.values(this.nodes).filter(n => n.type === type) as any;\n }\n\n /**\n * Return all nodes that depend on a given node\n */\n public dependees(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n return Object.values(this.nodes).filter(n => n.dependencies.has(id));\n }\n\n /**\n * Add a dependency, that may come before or after the nodes involved\n */\n public addDependency(fromId: string, toId: string) {\n const node = this.nodes[fromId];\n if (node) {\n node.dependencies.add(toId);\n return;\n }\n let lazyDeps = this.lazyDependencies.get(fromId);\n if (!lazyDeps) {\n lazyDeps = [];\n this.lazyDependencies.set(fromId, lazyDeps);\n }\n lazyDeps.push(toId);\n }\n\n public tryGetNode(id: string): WorkNode | undefined {\n return this.nodes[id];\n }\n\n public node(id: string) {\n const ret = this.nodes[id];\n if (!ret) {\n throw new ToolkitError(`No node with id ${id} among ${Object.keys(this.nodes)}`);\n }\n return ret;\n }\n\n public absorb(graph: WorkGraph) {\n this.addNodes(...Object.values(graph.nodes));\n }\n\n private hasFailed(): boolean {\n return Object.values(this.nodes).some((n) => n.deploymentState === DeploymentState.FAILED);\n }\n\n public doParallel(concurrency: Concurrency, actions: WorkGraphActions) {\n return this.forAllArtifacts(concurrency, async (x: WorkNode) => {\n switch (x.type) {\n case 'stack':\n await actions.deployStack(x);\n break;\n case 'asset-build':\n await actions.buildAsset(x);\n break;\n case 'asset-publish':\n await actions.publishAsset(x);\n break;\n }\n });\n }\n\n /**\n * Return the set of unblocked nodes\n */\n public async ready(): Promise<ReadonlyArray<WorkNode>> {\n await this.updateReadyPool();\n return this.readyPool;\n }\n\n private forAllArtifacts(n: Concurrency, fn: (x: WorkNode) => Promise<void>): Promise<void> {\n const graph = this;\n\n // If 'n' is a number, we limit all concurrency equally (effectively we will be using totalMax)\n // If 'n' is a record, we limit each job independently (effectively we will be using max)\n const max: Record<WorkNode['type'], number> = typeof n === 'number' ?\n {\n 'asset-build': n,\n 'asset-publish': n,\n 'stack': n,\n } : n;\n const totalMax = typeof n === 'number' ? n : sum(Object.values(n));\n\n return new Promise((ok, fail) => {\n let active: Record<WorkNode['type'], number> = {\n 'asset-build': 0,\n 'asset-publish': 0,\n 'stack': 0,\n };\n function totalActive() {\n return sum(Object.values(active));\n }\n\n start();\n\n function start() {\n graph.updateReadyPool().then(() => {\n for (let i = 0; i < graph.readyPool.length; ) {\n const node = graph.readyPool[i];\n\n if (active[node.type] < max[node.type] && totalActive() < totalMax) {\n graph.readyPool.splice(i, 1);\n startOne(node);\n } else {\n i += 1;\n }\n }\n\n if (totalActive() === 0) {\n if (graph.done()) {\n ok();\n }\n // wait for other active deploys to finish before failing\n if (graph.hasFailed()) {\n fail(graph.error);\n }\n }\n }).catch((e) => {\n fail(e);\n });\n }\n\n function startOne(x: WorkNode) {\n x.deploymentState = DeploymentState.DEPLOYING;\n active[x.type]++;\n void fn(x)\n .finally(() => {\n active[x.type]--;\n })\n .then(() => {\n graph.deployed(x);\n start();\n }).catch((err) => {\n // By recording the failure immediately as the queued task exits, we prevent the next\n // queued task from starting.\n graph.failed(x, err);\n start();\n });\n }\n });\n }\n\n private done(): boolean {\n return Object.values(this.nodes).every((n) => DeploymentState.COMPLETED === n.deploymentState);\n }\n\n private deployed(node: WorkNode) {\n node.deploymentState = DeploymentState.COMPLETED;\n }\n\n private failed(node: WorkNode, error?: Error) {\n this.error = error;\n node.deploymentState = DeploymentState.FAILED;\n this.skipRest();\n this.readyPool.splice(0);\n }\n\n public toString() {\n return [\n 'digraph D {',\n ...Object.entries(this.nodes).flatMap(([id, node]) => renderNode(id, node)),\n '}',\n ].join('\\n');\n\n function renderNode(id: string, node: WorkNode): string[] {\n const ret = [];\n if (node.deploymentState === DeploymentState.COMPLETED) {\n ret.push(` ${gv(id, { style: 'filled', fillcolor: 'yellow', comment: node.note })};`);\n } else {\n ret.push(` ${gv(id, { comment: node.note })};`);\n }\n for (const dep of node.dependencies) {\n ret.push(` ${gv(id)} -> ${gv(dep)};`);\n }\n return ret;\n }\n }\n\n /**\n * Ensure all dependencies actually exist. This protects against scenarios such as the following:\n * StackA depends on StackB, but StackB is not selected to deploy. The dependency is redundant\n * and will be dropped.\n * This assumes the manifest comes uncorrupted so we will not fail if a dependency is not found.\n */\n public removeUnavailableDependencies() {\n for (const node of Object.values(this.nodes)) {\n const removeDeps = Array.from(node.dependencies).filter((dep) => this.nodes[dep] === undefined);\n\n removeDeps.forEach((d) => {\n node.dependencies.delete(d);\n });\n }\n }\n\n /**\n * Remove all asset publishing steps for assets that are already published, and then build\n * that aren't used anymore.\n *\n * Do this in parallel, because there may be a lot of assets in an application (seen in practice: >100 assets)\n */\n public async removeUnnecessaryAssets(isUnnecessary: (x: AssetPublishNode) => Promise<boolean>) {\n await this.ioHost.notify(debug(this.action, 'Checking for previously published assets'));\n\n const publishes = this.nodesOfType('asset-publish');\n\n const classifiedNodes = await parallelPromises(\n 8,\n publishes.map((assetNode) => async() => [assetNode, await isUnnecessary(assetNode)] as const));\n\n const alreadyPublished = classifiedNodes.filter(([_, unnecessary]) => unnecessary).map(([assetNode, _]) => assetNode);\n for (const assetNode of alreadyPublished) {\n this.removeNode(assetNode);\n }\n\n await this.ioHost.notify(debug(this.action, `${publishes.length} total assets, ${publishes.length - alreadyPublished.length} still need to be published`));\n\n // Now also remove any asset build steps that don't have any dependencies on them anymore\n const unusedBuilds = this.nodesOfType('asset-build').filter(build => this.dependees(build).length === 0);\n for (const unusedBuild of unusedBuilds) {\n this.removeNode(unusedBuild);\n }\n }\n\n private async updateReadyPool() {\n const activeCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.DEPLOYING).length;\n const pendingCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.PENDING).length;\n\n const newlyReady = Object.values(this.nodes).filter((x) =>\n x.deploymentState === DeploymentState.PENDING &&\n Array.from(x.dependencies).every((id) => this.node(id).deploymentState === DeploymentState.COMPLETED));\n\n // Add newly available nodes to the ready pool\n for (const node of newlyReady) {\n node.deploymentState = DeploymentState.QUEUED;\n this.readyPool.push(node);\n }\n\n // Remove nodes from the ready pool that have already started deploying\n retainOnly(this.readyPool, (node) => node.deploymentState === DeploymentState.QUEUED);\n\n // Sort by reverse priority\n this.readyPool.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n if (this.readyPool.length === 0 && activeCount === 0 && pendingCount > 0) {\n const cycle = this.findCycle() ?? ['No cycle found!'];\n await this.ioHost.notify(trace(this.action, `Cycle ${cycle.join(' -> ')} in graph ${this}`));\n throw new ToolkitError(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(' -> ')} (run with -vv for full graph)`);\n }\n }\n\n private skipRest() {\n for (const node of Object.values(this.nodes)) {\n if ([DeploymentState.QUEUED, DeploymentState.PENDING].includes(node.deploymentState)) {\n node.deploymentState = DeploymentState.SKIPPED;\n }\n }\n }\n\n /**\n * Find cycles in a graph\n *\n * Not the fastest, but effective and should be rare\n */\n public findCycle(): string[] | undefined {\n const seen = new Set<string>();\n const self = this;\n for (const nodeId of Object.keys(this.nodes)) {\n const cycle = recurse(nodeId, [nodeId]);\n if (cycle) {\n return cycle;\n }\n }\n return undefined;\n\n function recurse(nodeId: string, path: string[]): string[] | undefined {\n if (seen.has(nodeId)) {\n return undefined;\n }\n try {\n for (const dep of self.nodes[nodeId].dependencies ?? []) {\n const index = path.indexOf(dep);\n if (index > -1) {\n return [...path.slice(index), dep];\n }\n\n const cycle = recurse(dep, [...path, dep]);\n if (cycle) {\n return cycle;\n }\n }\n\n return undefined;\n } finally {\n seen.add(nodeId);\n }\n }\n }\n\n /**\n * Whether the `end` node is reachable from the `start` node, following the dependency arrows\n */\n public reachable(start: string, end: string): boolean {\n const seen = new Set<string>();\n const self = this;\n return recurse(start);\n\n function recurse(current: string) {\n if (seen.has(current)) {\n return false;\n }\n seen.add(current);\n\n if (current === end) {\n return true;\n }\n for (const dep of self.nodes[current].dependencies) {\n if (recurse(dep)) {\n return true;\n }\n }\n return false;\n }\n }\n}\n\nexport interface WorkGraphActions {\n deployStack: (stackNode: StackNode) => Promise<void>;\n buildAsset: (assetNode: AssetBuildNode) => Promise<void>;\n publishAsset: (assetNode: AssetPublishNode) => Promise<void>;\n}\n\nfunction sum(xs: number[]) {\n let ret = 0;\n for (const x of xs) {\n ret += x;\n }\n return ret;\n}\n\nfunction retainOnly<A>(xs: A[], pred: (x: A) => boolean) {\n xs.splice(0, xs.length, ...xs.filter(pred));\n}\n\nfunction gv(id: string, attrs?: Record<string, string | undefined>) {\n const attrString = Object.entries(attrs ?? {}).flatMap(([k, v]) => v !== undefined ? [`${k}=\"${v}\"`] : []).join(',');\n\n return attrString ? `\"${simplifyId(id)}\" [${attrString}]` : `\"${simplifyId(id)}\"`;\n}\n\nfunction simplifyId(id: string) {\n return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g, '$1');\n}\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { AssetManifest, type IManifestEntry } from 'cdk-assets';\nimport { WorkGraph } from './work-graph';\nimport { DeploymentState, AssetBuildNode, WorkNode } from './work-graph-types';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { contentHashAny } from '../../util/content-hash';\n\nexport class WorkGraphBuilder {\n /**\n * Default priorities for nodes\n *\n * Assets builds have higher priority than the other two operations, to make good on our promise that\n * '--prebuild-assets' will actually do assets before stacks (if it can). Unfortunately it is the\n * default :(\n *\n * But between stack dependencies and publish dependencies, stack dependencies go first\n */\n public static PRIORITIES: Record<WorkNode['type'], number> = {\n 'asset-build': 10,\n 'asset-publish': 0,\n 'stack': 5,\n };\n private readonly graph: WorkGraph;\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n constructor(\n { ioHost, action }: IoMessaging,\n private readonly prebuildAssets: boolean,\n private readonly idPrefix = '',\n ) {\n this.graph = new WorkGraph({}, { ioHost, action });\n this.ioHost = ioHost;\n this.action = action;\n }\n\n private addStack(artifact: cxapi.CloudFormationStackArtifact) {\n this.graph.addNodes({\n type: 'stack',\n id: `${this.idPrefix}${artifact.id}`,\n dependencies: new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),\n stack: artifact,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES.stack,\n });\n }\n\n /**\n * Oof, see this parameter list\n */\n // eslint-disable-next-line max-len\n private addAsset(parentStack: cxapi.CloudFormationStackArtifact, assetManifestArtifact: cxapi.AssetManifestArtifact, assetManifest: AssetManifest, asset: IManifestEntry) {\n // Just the artifact identifier\n const assetId = asset.id.assetId;\n\n const buildId = `build-${assetId}-${contentHashAny([assetId, asset.genericSource]).substring(0, 10)}`;\n const publishId = `publish-${assetId}-${contentHashAny([assetId, asset.genericDestination]).substring(0, 10)}`;\n\n // Build node only gets added once because they are all the same\n if (!this.graph.tryGetNode(buildId)) {\n const node: AssetBuildNode = {\n type: 'asset-build',\n id: buildId,\n note: assetId,\n dependencies: new Set([\n ...this.stackArtifactIds(assetManifestArtifact.dependencies),\n // If we disable prebuild, then assets inherit (stack) dependencies from their parent stack\n ...!this.prebuildAssets ? this.stackArtifactIds(onlyStacks(parentStack.dependencies)) : [],\n ]),\n parentStack: parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-build'],\n };\n this.graph.addNodes(node);\n }\n\n const publishNode = this.graph.tryGetNode(publishId);\n if (!publishNode) {\n this.graph.addNodes({\n type: 'asset-publish',\n id: publishId,\n note: `${asset.id}`,\n dependencies: new Set([\n buildId,\n ]),\n parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-publish'],\n });\n }\n\n for (const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))) {\n // The asset publish step also depends on the stacks that the parent depends on.\n // This is purely cosmetic: if we don't do this, the progress printing of asset publishing\n // is going to interfere with the progress bar of the stack deployment. We could remove this\n // for overall faster deployments if we ever have a better method of progress displaying.\n // Note: this may introduce a cycle if one of the parent's dependencies is another stack that\n // depends on this asset. To workaround this we remove these cycles once all nodes have\n // been added to the graph.\n this.graph.addDependency(publishId, inheritedDep);\n }\n\n // This will work whether the stack node has been added yet or not\n this.graph.addDependency(`${this.idPrefix}${parentStack.id}`, publishId);\n }\n\n public build(artifacts: cxapi.CloudArtifact[]): WorkGraph {\n const parentStacks = stacksFromAssets(artifacts);\n\n for (const artifact of artifacts) {\n if (cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n this.addStack(artifact);\n } else if (cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n const manifest = AssetManifest.fromFile(artifact.file);\n\n for (const entry of manifest.entries) {\n const parentStack = parentStacks.get(artifact);\n if (parentStack === undefined) {\n throw new ToolkitError('Found an asset manifest that is not associated with a stack');\n }\n this.addAsset(parentStack, artifact, manifest, entry);\n }\n } else if (cxapi.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)) {\n const assembly = new cxapi.CloudAssembly(artifact.fullPath, { topoSort: false });\n const nestedGraph = new WorkGraphBuilder(\n { ioHost: this.ioHost, action: this.action },\n this.prebuildAssets,\n `${this.idPrefix}${artifact.id}.`,\n ).build(assembly.artifacts);\n this.graph.absorb(nestedGraph);\n } else {\n // Ignore whatever else\n }\n }\n\n this.graph.removeUnavailableDependencies();\n\n // Remove any potentially introduced cycles between asset publishing and the stacks that depend on them.\n this.removeStackPublishCycles();\n\n return this.graph;\n }\n\n private stackArtifactIds(deps: cxapi.CloudArtifact[]): string[] {\n return deps.flatMap((d) => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(d) ? [this.stackArtifactId(d)] : []);\n }\n\n private stackArtifactId(artifact: cxapi.CloudArtifact): string {\n if (!cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n throw new ToolkitError(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`);\n }\n return `${this.idPrefix}${artifact.id}`;\n }\n\n /**\n * We may have accidentally introduced cycles in an attempt to make the messages printed to the\n * console not interfere with each other too much. Remove them again.\n */\n private removeStackPublishCycles() {\n const publishSteps = this.graph.nodesOfType('asset-publish');\n for (const publishStep of publishSteps) {\n for (const dep of publishStep.dependencies) {\n if (this.graph.reachable(dep, publishStep.id)) {\n publishStep.dependencies.delete(dep);\n }\n }\n }\n }\n}\n\nfunction stacksFromAssets(artifacts: cxapi.CloudArtifact[]) {\n const ret = new Map<cxapi.AssetManifestArtifact, cxapi.CloudFormationStackArtifact>();\n for (const stack of artifacts.filter(cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact)) {\n const assetArtifacts = stack.dependencies.filter(cxapi.AssetManifestArtifact.isAssetManifestArtifact);\n for (const art of assetArtifacts) {\n ret.set(art, stack);\n }\n }\n\n return ret;\n}\n\nfunction onlyStacks(artifacts: cxapi.CloudArtifact[]) {\n return artifacts.filter(cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact);\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { AmiContextProviderPlugin } from './ami';\nimport { AZContextProviderPlugin } from './availability-zones';\nimport { CcApiContextProviderPlugin } from './cc-api-provider';\nimport { EndpointServiceAZContextProviderPlugin } from './endpoint-service-availability-zones';\nimport { HostedZoneContextProviderPlugin } from './hosted-zones';\nimport { KeyContextProviderPlugin } from './keys';\nimport { LoadBalancerContextProviderPlugin, LoadBalancerListenerContextProviderPlugin } from './load-balancers';\nimport { SecurityGroupContextProviderPlugin } from './security-groups';\nimport { SSMContextProviderPlugin } from './ssm-parameters';\nimport { VpcNetworkContextProviderPlugin } from './vpcs';\nimport { SdkProvider } from '../api';\nimport { Context, TRANSIENT_CONTEXT_KEY } from '../api/context';\nimport { PluginHost } from '../api/plugin';\nimport { ContextProviderPlugin } from '../api/plugin/context-provider-plugin';\nimport { replaceEnvPlaceholders } from '../api/util/placeholders';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\nimport { formatErrorMessage } from '../util/format-error';\n\nexport type ContextProviderFactory = ((sdk: SdkProvider) => ContextProviderPlugin);\nexport type ProviderMap = {[name: string]: ContextProviderFactory};\n\nconst PLUGIN_PROVIDER_PREFIX = 'plugin';\n\n/**\n * Iterate over the list of missing context values and invoke the appropriate providers from the map to retrieve them\n */\nexport async function provideContextValues(\n missingValues: cxschema.MissingContext[],\n context: Context,\n sdk: SdkProvider) {\n for (const missingContext of missingValues) {\n const key = missingContext.key;\n\n const providerName = missingContext.provider === cxschema.ContextProvider.PLUGIN\n ? `${PLUGIN_PROVIDER_PREFIX}:${(missingContext.props as cxschema.PluginContextQuery).pluginName}`\n : missingContext.provider;\n\n let factory;\n if (providerName.startsWith(`${PLUGIN_PROVIDER_PREFIX}:`)) {\n const plugin = PluginHost.instance.contextProviderPlugins[providerName.substring(PLUGIN_PROVIDER_PREFIX.length + 1)];\n if (!plugin) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized plugin context provider name: ${missingContext.provider}.`);\n }\n factory = () => plugin;\n } else {\n factory = availableContextProviders[providerName];\n if (!factory) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized context provider name: ${missingContext.provider}. You might need to update the toolkit to match the version of the construct library.`);\n }\n }\n\n const provider = factory(sdk);\n\n let value;\n try {\n const environment = missingContext.props.account && missingContext.props.region\n ? cxapi.EnvironmentUtils.make(missingContext.props.account, missingContext.props.region)\n : undefined;\n\n const resolvedEnvironment: cxapi.Environment = environment\n ? await sdk.resolveEnvironment(environment)\n : { account: '?', region: '?', name: '?' };\n\n const arns = await replaceEnvPlaceholders({\n lookupRoleArn: missingContext.props.lookupRoleArn,\n }, resolvedEnvironment, sdk);\n\n value = await provider.getValue({ ...missingContext.props, lookupRoleArn: arns.lookupRoleArn });\n } catch (e: any) {\n // Set a specially formatted provider value which will be interpreted\n // as a lookup failure in the toolkit.\n value = { [cxapi.PROVIDER_ERROR_KEY]: formatErrorMessage(e), [TRANSIENT_CONTEXT_KEY]: true };\n }\n context.set(key, value);\n debug(`Setting \"${key}\" context to ${JSON.stringify(value)}`);\n }\n}\n\n/**\n * Register a context provider\n *\n * A context provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerContextProvider(name: string, provider: ContextProviderPlugin) {\n availableContextProviders[name] = () => provider;\n}\n\n/**\n * Register a plugin context provider\n *\n * A plugin provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerPluginContextProvider(name: string, provider: ContextProviderPlugin) {\n registerContextProvider(`${PLUGIN_PROVIDER_PREFIX}:${name}`, provider);\n}\n\n/**\n * Register a context provider factory\n *\n * A context provider factory takes an SdkProvider and returns the context provider plugin.\n */\nexport function registerContextProviderFactory(name: string, provider: ContextProviderFactory) {\n availableContextProviders[name] = provider;\n}\n\nconst availableContextProviders: ProviderMap = {\n [cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER]: (s) => new AZContextProviderPlugin(s),\n [cxschema.ContextProvider.SSM_PARAMETER_PROVIDER]: (s) => new SSMContextProviderPlugin(s),\n [cxschema.ContextProvider.HOSTED_ZONE_PROVIDER]: (s) => new HostedZoneContextProviderPlugin(s),\n [cxschema.ContextProvider.VPC_PROVIDER]: (s) => new VpcNetworkContextProviderPlugin(s),\n [cxschema.ContextProvider.AMI_PROVIDER]: (s) => new AmiContextProviderPlugin(s),\n [cxschema.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]: (s) => new EndpointServiceAZContextProviderPlugin(s),\n [cxschema.ContextProvider.SECURITY_GROUP_PROVIDER]: (s) => new SecurityGroupContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_PROVIDER]: (s) => new LoadBalancerContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_LISTENER_PROVIDER]: (s) => new LoadBalancerListenerContextProviderPlugin(s),\n [cxschema.ContextProvider.KEY_PROVIDER]: (s) => new KeyContextProviderPlugin(s),\n [cxschema.ContextProvider.CC_API_PROVIDER]: (s) => new CcApiContextProviderPlugin(s),\n};\n", "import type { AmiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug, info } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Plugin to search AMIs for the current account\n */\nexport class AmiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: AmiContextQuery) {\n const region = args.region;\n const account = args.account;\n\n // Normally we'd do this only as 'debug', but searching AMIs typically takes dozens\n // of seconds, so be little more verbose about it so users know what is going on.\n info(`Searching for AMI in ${account}:${region}`);\n debug(`AMI search parameters: ${JSON.stringify(args)}`);\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeImages({\n Owners: args.owners,\n Filters: Object.entries(args.filters).map(([key, values]) => ({\n Name: key,\n Values: values,\n })),\n });\n\n const images = [...(response.Images || [])].filter((i) => i.ImageId !== undefined);\n\n if (images.length === 0) {\n throw new ContextProviderError('No AMI found that matched the search criteria');\n }\n\n // Return the most recent one\n // Note: Date.parse() is not going to respect the timezone of the string,\n // but since we only care about the relative values that is okay.\n images.sort(descending((i) => Date.parse(i.CreationDate || '1970')));\n\n debug(`Selected image '${images[0].ImageId}' created at '${images[0].CreationDate}'`);\n return images[0].ImageId!;\n }\n}\n\n/**\n * Make a comparator that sorts in descending order given a sort key extractor\n */\nfunction descending<A>(valueOf: (x: A) => number) {\n return (a: A, b: A) => {\n return valueOf(b) - valueOf(a);\n };\n}\n", "import type { AvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { AvailabilityZone } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\n\n/**\n * Plugin to retrieve the Availability Zones for the current account\n */\nexport class AZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: AvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n debug(`Reading AZs for ${account}:${region}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeAvailabilityZones({});\n if (!response.AvailabilityZones) {\n return [];\n }\n const azs = response.AvailabilityZones.filter((zone: AvailabilityZone) => zone.State === 'available').map(\n (zone: AvailabilityZone) => zone.ZoneName,\n );\n return azs;\n }\n}\n", "/**\n * This gets the values of the jsonObject at the paths specified in propertiesToReturn.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * propertiesToReturn = ['key1', 'key2.foo'];\n *\n * The returned object is:\n *\n * ```\n * {\n * key1: 'abc',\n * 'key2.foo': 'qwerty',\n * Identifier: identifier\n * }\n * ```\n */\nexport function getResultObj(jsonObject: any, identifier: string, propertiesToReturn: string[]): {[key: string]: any} {\n const propsObj = {};\n propertiesToReturn.forEach((propName) => {\n Object.assign(propsObj, { [propName]: findJsonValue(jsonObject, propName) });\n });\n Object.assign(propsObj, { ['Identifier']: identifier });\n return propsObj;\n}\n\n/**\n * This finds the value of the jsonObject at the path. Path is delimited by '.'.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * If path is 'key1', then it will return 'abc'.\n * If path is 'key2.foo', then it will return 'qwerty'.\n * If path is 'key2', then it will return the object:\n * {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n *\n * If the path is not found, an Error will be thrown stating which token is missing.\n */\nexport function findJsonValue(jsonObject: any, path: string): any {\n const paths = path.split('.');\n let obj = jsonObject;\n paths.forEach(p => {\n obj = obj[p];\n if (obj === undefined) {\n throw new TypeError(`Cannot read field ${path}. ${p} is not found.`);\n }\n });\n return obj;\n}\n", "import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { ICloudControlClient } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\nimport { findJsonValue, getResultObj } from '../util/json';\n\nexport class CcApiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n /**\n * This returns a data object with the value from CloudControl API result.\n * args.typeName - see https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/supported-resources.html\n * args.exactIdentifier - use CC API getResource.\n * args.propertyMatch - use CCP API listResources to get resources and propertyMatch to search through the list.\n * args.propertiesToReturn - Properties from CC API to return.\n */\n public async getValue(args: CcApiContextQuery) {\n const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl();\n\n const result = await this.findResources(cloudControl, args);\n return result;\n }\n\n private async findResources(cc: ICloudControlClient, args: CcApiContextQuery): Promise<{[key: string]: any} []> {\n if (args.exactIdentifier && args.propertyMatch) {\n throw new ContextProviderError(`Specify either exactIdentifier or propertyMatch, but not both. Failed to find resources using CC API for type ${args.typeName}.`);\n }\n if (!args.exactIdentifier && !args.propertyMatch) {\n throw new ContextProviderError(`Neither exactIdentifier nor propertyMatch is specified. Failed to find resources using CC API for type ${args.typeName}.`);\n }\n\n if (args.exactIdentifier) {\n // use getResource to get the exact indentifier\n return this.getResource(cc, args.typeName, args.exactIdentifier, args.propertiesToReturn);\n } else {\n // use listResource\n return this.listResources(cc, args.typeName, args.propertyMatch!, args.propertiesToReturn);\n }\n }\n\n /**\n * Calls getResource from CC API to get the resource.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/get-resource.html\n *\n * If the exactIdentifier is not found, then an empty map is returned.\n * If the resource is found, then a map of the identifier to a map of property values is returned.\n */\n private async getResource(\n cc: ICloudControlClient,\n typeName: string,\n exactIdentifier: string,\n propertiesToReturn: string[],\n ): Promise<{[key: string]: any}[]> {\n const resultObjs: {[key: string]: any}[] = [];\n try {\n const result = await cc.getResource({\n TypeName: typeName,\n Identifier: exactIdentifier,\n });\n const id = result.ResourceDescription?.Identifier ?? '';\n if (id !== '') {\n const propsObject = JSON.parse(result.ResourceDescription?.Properties ?? '');\n const propsObj = getResultObj(propsObject, result.ResourceDescription?.Identifier!, propertiesToReturn);\n resultObjs.push(propsObj);\n } else {\n throw new ContextProviderError(`Could not get resource ${exactIdentifier}.`);\n }\n } catch (err) {\n throw new ContextProviderError(`Encountered CC API error while getting resource ${exactIdentifier}. Error: ${err}`);\n }\n return resultObjs;\n }\n\n /**\n * Calls listResources from CC API to get the resources and apply args.propertyMatch to find the resources.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/list-resources.html\n *\n * Since exactIdentifier is not specified, propertyMatch must be specified.\n * This returns an object where the ids are object keys and values are objects with keys of args.propertiesToReturn.\n */\n private async listResources(\n cc: ICloudControlClient,\n typeName: string,\n propertyMatch: Record<string, unknown>,\n propertiesToReturn: string[],\n ): Promise<{[key: string]: any}[]> {\n const resultObjs: {[key: string]: any}[] = [];\n\n try {\n const result = await cc.listResources({\n TypeName: typeName,\n });\n result.ResourceDescriptions?.forEach((resource) => {\n const id = resource.Identifier ?? '';\n if (id !== '') {\n const propsObject = JSON.parse(resource.Properties ?? '');\n\n const filters = Object.entries(propertyMatch);\n let match = false;\n if (filters) {\n match = filters.every((record, _index, _arr) => {\n const key = record[0];\n const expected = record[1];\n const actual = findJsonValue(propsObject, key);\n return propertyMatchesFilter(actual, expected);\n });\n\n function propertyMatchesFilter(actual: any, expected: unknown) {\n // For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later\n return expected === actual;\n }\n }\n\n if (match) {\n const propsObj = getResultObj(propsObject, resource.Identifier!, propertiesToReturn);\n resultObjs.push(propsObj);\n }\n }\n });\n } catch (err) {\n throw new ContextProviderError(`Could not get resources ${propertyMatch}. Error: ${err}`);\n }\n return resultObjs;\n }\n}\n", "import type { EndpointServiceAvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\n\n/**\n * Plugin to retrieve the Availability Zones for an endpoint service\n */\nexport class EndpointServiceAZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: EndpointServiceAvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n const serviceName = args.serviceName;\n debug(`Reading AZs for ${account}:${region}:${serviceName}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeVpcEndpointServices({\n ServiceNames: [serviceName],\n });\n\n // expect a service in the response\n if (!response.ServiceDetails || response.ServiceDetails.length === 0) {\n debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);\n return [];\n }\n const azs = response.ServiceDetails[0].AvailabilityZones;\n debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);\n return azs;\n }\n}\n", "import { HostedZoneContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { HostedZone } from '@aws-sdk/client-route-53';\nimport type { IRoute53Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class HostedZoneContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: HostedZoneContextQuery): Promise<object> {\n const account = args.account;\n const region = args.region;\n if (!this.isHostedZoneQuery(args)) {\n throw new ContextProviderError(`HostedZoneProvider requires domainName property to be set in ${args}`);\n }\n const domainName = args.domainName;\n debug(`Reading hosted zone ${account}:${region}:${domainName}`);\n const r53 = (await initContextProviderSdk(this.aws, args)).route53();\n const response = await r53.listHostedZonesByName({ DNSName: domainName });\n if (!response.HostedZones) {\n throw new ContextProviderError(`Hosted Zone not found in account ${account}, region ${region}: ${domainName}`);\n }\n const candidateZones = await this.filterZones(r53, response.HostedZones, args);\n if (candidateZones.length !== 1) {\n const filteProps = `dns:${domainName}, privateZone:${args.privateZone}, vpcId:${args.vpcId}`;\n throw new ContextProviderError(`Found zones: ${JSON.stringify(candidateZones)} for ${filteProps}, but wanted exactly 1 zone`);\n }\n\n return {\n Id: candidateZones[0].Id,\n Name: candidateZones[0].Name,\n };\n }\n\n private async filterZones(\n r53: IRoute53Client,\n zones: HostedZone[],\n props: HostedZoneContextQuery,\n ): Promise<HostedZone[]> {\n let candidates: HostedZone[] = [];\n const domainName = props.domainName.endsWith('.') ? props.domainName : `${props.domainName}.`;\n debug(`Found the following zones ${JSON.stringify(zones)}`);\n candidates = zones.filter((zone) => zone.Name === domainName);\n debug(`Found the following matched name zones ${JSON.stringify(candidates)}`);\n if (props.privateZone) {\n candidates = candidates.filter((zone) => zone.Config && zone.Config.PrivateZone);\n } else {\n candidates = candidates.filter((zone) => !zone.Config || !zone.Config.PrivateZone);\n }\n if (props.vpcId) {\n const vpcZones: HostedZone[] = [];\n for (const zone of candidates) {\n const data = await r53.getHostedZone({ Id: zone.Id });\n if (!data.VPCs) {\n debug(`Expected VPC for private zone but no VPC found ${zone.Id}`);\n continue;\n }\n if (data.VPCs.map((vpc) => vpc.VPCId).includes(props.vpcId)) {\n vpcZones.push(zone);\n }\n }\n return vpcZones;\n }\n return candidates;\n }\n\n private isHostedZoneQuery(props: HostedZoneContextQuery | any): props is HostedZoneContextQuery {\n return (props as HostedZoneContextQuery).domainName !== undefined;\n }\n}\n", "import type { KeyContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { KeyContextResponse } from '@aws-cdk/cx-api';\nimport type { AliasListEntry, ListAliasesCommandOutput } from '@aws-sdk/client-kms';\nimport type { IKMSClient } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class KeyContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: KeyContextQuery) {\n const kms = (await initContextProviderSdk(this.aws, args)).kms();\n\n const aliasListEntry = await this.findKey(kms, args);\n\n return this.readKeyProps(aliasListEntry, args);\n }\n\n // TODO: use paginator function\n private async findKey(kms: IKMSClient, args: KeyContextQuery): Promise<AliasListEntry> {\n debug(`Listing keys in ${args.account}:${args.region}`);\n\n let response: ListAliasesCommandOutput;\n let nextMarker: string | undefined;\n do {\n response = await kms.listAliases({\n Marker: nextMarker,\n });\n\n const aliases = response.Aliases || [];\n for (const alias of aliases) {\n if (alias.AliasName == args.aliasName) {\n return alias;\n }\n }\n\n nextMarker = response.NextMarker;\n } while (nextMarker);\n\n const suppressError = 'ignoreErrorOnMissingContext' in args && args.ignoreErrorOnMissingContext as boolean;\n const hasDummyKeyId = 'dummyValue' in args && typeof args.dummyValue === 'object' && args.dummyValue !== null && 'keyId' in args.dummyValue;\n if (suppressError && hasDummyKeyId) {\n const keyId = (args.dummyValue as { keyId: string }).keyId;\n return { TargetKeyId: keyId };\n }\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n private async readKeyProps(alias: AliasListEntry, args: KeyContextQuery): Promise<KeyContextResponse> {\n if (!alias.TargetKeyId) {\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n debug(`Key found ${alias.TargetKeyId}`);\n\n return {\n keyId: alias.TargetKeyId,\n };\n }\n}\n", "import { LoadBalancerContextQuery, LoadBalancerListenerContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport {\n LoadBalancerContextResponse,\n LoadBalancerIpAddressType,\n LoadBalancerListenerContextResponse,\n} from '@aws-cdk/cx-api';\nimport { type Listener, LoadBalancer, type TagDescription } from '@aws-sdk/client-elastic-load-balancing-v2';\nimport type { IElasticLoadBalancingV2Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Provides load balancer context information.\n */\nexport class LoadBalancerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerContextQuery): Promise<LoadBalancerContextResponse> {\n if (!query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError('The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`');\n }\n\n const loadBalancer = await (await LoadBalancerProvider.getClient(this.aws, query)).getLoadBalancer();\n\n const ipAddressType =\n loadBalancer.IpAddressType === 'ipv4' ? LoadBalancerIpAddressType.IPV4 : LoadBalancerIpAddressType.DUAL_STACK;\n\n return {\n loadBalancerArn: loadBalancer.LoadBalancerArn!,\n loadBalancerCanonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!,\n loadBalancerDnsName: loadBalancer.DNSName!,\n vpcId: loadBalancer.VpcId!,\n securityGroupIds: loadBalancer.SecurityGroups ?? [],\n ipAddressType: ipAddressType,\n };\n }\n}\n\n/**\n * Provides load balancer listener context information\n */\nexport class LoadBalancerListenerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerListenerContextQuery): Promise<LoadBalancerListenerContextResponse> {\n if (!query.listenerArn && !query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError(\n 'The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`',\n );\n }\n\n return (await LoadBalancerProvider.getClient(this.aws, query)).getListener();\n }\n}\n\nclass LoadBalancerProvider {\n public static async getClient(\n aws: SdkProvider,\n query: LoadBalancerListenerContextQuery,\n ): Promise<LoadBalancerProvider> {\n const client = (await initContextProviderSdk(aws, query)).elbv2();\n\n try {\n const listener = query.listenerArn\n ? // Assert we're sure there's at least one so it throws if not\n (await client.describeListeners({ ListenerArns: [query.listenerArn] })).Listeners![0]!\n : undefined;\n return new LoadBalancerProvider(\n client,\n { ...query, loadBalancerArn: listener?.LoadBalancerArn || query.loadBalancerArn },\n listener,\n );\n } catch (err) {\n throw new ContextProviderError(`No load balancer listeners found matching arn ${query.listenerArn}`);\n }\n }\n\n constructor(\n private readonly client: IElasticLoadBalancingV2Client,\n private readonly filter: LoadBalancerListenerContextQuery,\n private readonly listener?: Listener,\n ) {\n }\n\n public async getLoadBalancer(): Promise<LoadBalancer> {\n const loadBalancers = await this.getLoadBalancers();\n\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(`No load balancers found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (loadBalancers.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancers found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return loadBalancers[0];\n }\n\n public async getListener(): Promise<LoadBalancerListenerContextResponse> {\n if (this.listener) {\n try {\n const loadBalancer = await this.getLoadBalancer();\n return {\n listenerArn: this.listener.ListenerArn!,\n listenerPort: this.listener.Port!,\n securityGroupIds: loadBalancer.SecurityGroups || [],\n };\n } catch (err) {\n throw new ContextProviderError(`No associated load balancer found for listener arn ${this.filter.listenerArn}`);\n }\n }\n\n const loadBalancers = await this.getLoadBalancers();\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(\n `No associated load balancers found for load balancer listener query ${JSON.stringify(this.filter)}`,\n );\n }\n\n const listeners = (await this.getListenersForLoadBalancers(loadBalancers)).filter((listener) => {\n return (\n (!this.filter.listenerPort || listener.Port === this.filter.listenerPort) &&\n (!this.filter.listenerProtocol || listener.Protocol === this.filter.listenerProtocol)\n );\n });\n\n if (listeners.length === 0) {\n throw new ContextProviderError(`No load balancer listeners found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (listeners.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancer listeners found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return {\n listenerArn: listeners[0].ListenerArn!,\n listenerPort: listeners[0].Port!,\n securityGroupIds:\n loadBalancers.find((lb) => listeners[0].LoadBalancerArn === lb.LoadBalancerArn)?.SecurityGroups || [],\n };\n }\n\n private async getLoadBalancers() {\n const loadBalancerArns = this.filter.loadBalancerArn ? [this.filter.loadBalancerArn] : undefined;\n const loadBalancers = (\n await this.client.paginateDescribeLoadBalancers({\n LoadBalancerArns: loadBalancerArns,\n })\n ).filter((lb) => lb.Type === this.filter.loadBalancerType);\n\n return this.filterByTags(loadBalancers);\n }\n\n private async filterByTags(loadBalancers: LoadBalancer[]): Promise<LoadBalancer[]> {\n if (!this.filter.loadBalancerTags) {\n return loadBalancers;\n }\n return (await this.describeTags(loadBalancers.map((lb) => lb.LoadBalancerArn!)))\n .filter((tagDescription) => {\n // For every tag in the filter, there is some tag in the LB that matches it.\n // In other words, the set of tags in the filter is a subset of the set of tags in the LB.\n return this.filter.loadBalancerTags!.every((filter) => {\n return tagDescription.Tags?.some((tag) =>\n filter.key === tag.Key && filter.value === tag.Value);\n });\n })\n .flatMap((tag) => loadBalancers.filter((loadBalancer) => tag.ResourceArn === loadBalancer.LoadBalancerArn));\n }\n\n /**\n * Returns tag descriptions associated with the resources. The API doesn't support\n * pagination, so this function breaks the resource list into chunks and issues\n * the appropriate requests.\n */\n private async describeTags(resourceArns: string[]): Promise<TagDescription[]> {\n // Max of 20 resource arns per request.\n const chunkSize = 20;\n const tags = Array<TagDescription>();\n for (let i = 0; i < resourceArns.length; i += chunkSize) {\n const chunk = resourceArns.slice(i, Math.min(i + chunkSize, resourceArns.length));\n const chunkTags = await this.client.describeTags({\n ResourceArns: chunk,\n });\n\n tags.push(...(chunkTags.TagDescriptions || []));\n }\n return tags;\n }\n\n private async getListenersForLoadBalancers(loadBalancers: LoadBalancer[]): Promise<Listener[]> {\n const listeners: Listener[] = [];\n for (const loadBalancer of loadBalancers.map((lb) => lb.LoadBalancerArn)) {\n listeners.push(...(await this.client.paginateDescribeListeners({ LoadBalancerArn: loadBalancer })));\n }\n return listeners;\n }\n}\n", "import type { SecurityGroupContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { SecurityGroupContextResponse } from '@aws-cdk/cx-api';\nimport type { Filter, SecurityGroup } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class SecurityGroupContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(args: SecurityGroupContextQuery): Promise<SecurityGroupContextResponse> {\n if (args.securityGroupId && args.securityGroupName) {\n throw new ContextProviderError(\n \"'securityGroupId' and 'securityGroupName' can not be specified both when looking up a security group\",\n );\n }\n\n if (!args.securityGroupId && !args.securityGroupName) {\n throw new ContextProviderError(\"'securityGroupId' or 'securityGroupName' must be specified to look up a security group\");\n }\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const filters: Filter[] = [];\n if (args.vpcId) {\n filters.push({\n Name: 'vpc-id',\n Values: [args.vpcId],\n });\n }\n if (args.securityGroupName) {\n filters.push({\n Name: 'group-name',\n Values: [args.securityGroupName],\n });\n }\n\n const response = await ec2.describeSecurityGroups({\n GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined,\n Filters: filters.length > 0 ? filters : undefined,\n });\n\n const securityGroups = response.SecurityGroups ?? [];\n if (securityGroups.length === 0) {\n throw new ContextProviderError(`No security groups found matching ${JSON.stringify(args)}`);\n }\n\n if (securityGroups.length > 1) {\n throw new ContextProviderError(`More than one security groups found matching ${JSON.stringify(args)}`);\n }\n\n const [securityGroup] = securityGroups;\n\n return {\n securityGroupId: securityGroup.GroupId!,\n allowAllOutbound: hasAllTrafficEgress(securityGroup),\n };\n }\n}\n\n/**\n * @internal\n */\nexport function hasAllTrafficEgress(securityGroup: SecurityGroup) {\n let hasAllTrafficCidrV4 = false;\n let hasAllTrafficCidrV6 = false;\n\n for (const ipPermission of securityGroup.IpPermissionsEgress ?? []) {\n const isAllProtocols = ipPermission.IpProtocol === '-1';\n\n if (isAllProtocols && ipPermission.IpRanges?.some((m) => m.CidrIp === '0.0.0.0/0')) {\n hasAllTrafficCidrV4 = true;\n }\n\n if (isAllProtocols && ipPermission.Ipv6Ranges?.some((m) => m.CidrIpv6 === '::/0')) {\n hasAllTrafficCidrV6 = true;\n }\n }\n\n return hasAllTrafficCidrV4 && hasAllTrafficCidrV6;\n}\n", "import type { SSMParameterContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { GetParameterCommandOutput } from '@aws-sdk/client-ssm';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Plugin to read arbitrary SSM parameter names\n */\nexport class SSMContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: SSMParameterContextQuery) {\n const region = args.region;\n const account = args.account;\n\n if (!('parameterName' in args)) {\n throw new ContextProviderError('parameterName must be provided in props for SSMContextProviderPlugin');\n }\n const parameterName = args.parameterName;\n debug(`Reading SSM parameter ${account}:${region}:${parameterName}`);\n\n const response = await this.getSsmParameterValue(args);\n const parameterNotFound: boolean = !response.Parameter || response.Parameter.Value === undefined;\n const suppressError = 'ignoreErrorOnMissingContext' in args && (args.ignoreErrorOnMissingContext as boolean);\n if (parameterNotFound && suppressError && 'dummyValue' in args) {\n return args.dummyValue;\n }\n if (parameterNotFound) {\n throw new ContextProviderError(`SSM parameter not available in account ${account}, region ${region}: ${parameterName}`);\n }\n // will not be undefined because we've handled undefined cases above\n return response.Parameter!.Value;\n }\n\n /**\n * Gets the value of an SSM Parameter, while not throwin if the parameter does not exist.\n * @param account the account in which the SSM Parameter is expected to be.\n * @param region the region in which the SSM Parameter is expected to be.\n * @param parameterName the name of the SSM Parameter\n * @param lookupRoleArn the ARN of the lookup role.\n *\n * @returns the result of the ``GetParameter`` operation.\n *\n * @throws Error if a service error (other than ``ParameterNotFound``) occurs.\n */\n private async getSsmParameterValue(args: SSMParameterContextQuery): Promise<GetParameterCommandOutput> {\n const ssm = (await initContextProviderSdk(this.aws, args)).ssm();\n try {\n return await ssm.getParameter({ Name: args.parameterName });\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n return { $metadata: {} };\n }\n throw e;\n }\n }\n}\n", "import type { VpcContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type VpcContextResponse, type VpcSubnetGroup, VpcSubnetGroupType } from '@aws-cdk/cx-api';\nimport type { Filter, RouteTable, Tag, Vpc } from '@aws-sdk/client-ec2';\nimport type { IEC2Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\nexport class VpcNetworkContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: VpcContextQuery) {\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const vpcId = await this.findVpc(ec2, args);\n\n return this.readVpcProps(ec2, vpcId, args);\n }\n\n private async findVpc(ec2: IEC2Client, args: VpcContextQuery): Promise<Vpc> {\n // Build request filter (map { Name -> Value } to list of [{ Name, Values }])\n const filters: Filter[] = Object.entries(args.filter).map(([tag, value]) => ({ Name: tag, Values: [value] }));\n\n debug(`Listing VPCs in ${args.account}:${args.region}`);\n const response = await ec2.describeVpcs({ Filters: filters });\n\n const vpcs = response.Vpcs || [];\n if (vpcs.length === 0) {\n throw new ContextProviderError(`Could not find any VPCs matching ${JSON.stringify(args)}`);\n }\n if (vpcs.length > 1) {\n throw new ContextProviderError(`Found ${vpcs.length} VPCs matching ${JSON.stringify(args)}; please narrow the search criteria`);\n }\n\n return vpcs[0];\n }\n\n private async readVpcProps(ec2: IEC2Client, vpc: Vpc, args: VpcContextQuery): Promise<VpcContextResponse> {\n const vpcId = vpc.VpcId!;\n\n debug(`Describing VPC ${vpcId}`);\n\n const filters = { Filters: [{ Name: 'vpc-id', Values: [vpcId] }] };\n\n const subnetsResponse = await ec2.describeSubnets(filters);\n const listedSubnets = subnetsResponse.Subnets || [];\n\n const routeTablesResponse = await ec2.describeRouteTables(filters);\n const routeTables = new RouteTables(routeTablesResponse.RouteTables || []);\n\n // Now comes our job to separate these subnets out into AZs and subnet groups (Public, Private, Isolated)\n // We have the following attributes to go on:\n // - Type tag, we tag subnets with their type. In absence of this tag, we\n // determine the subnet must be Public if either:\n // a) it has the property MapPublicIpOnLaunch\n // b) it has a route to an Internet Gateway\n // If both of the above is false but the subnet has a route to a NAT Gateway\n // and the destination CIDR block is \"0.0.0.0/0\", we assume it to be a Private subnet.\n // Anything else is considered Isolated.\n // - Name tag, we tag subnets with their subnet group name. In absence of this tag,\n // we use the type as the name.\n\n const azs = Array.from(new Set<string>(listedSubnets.map((s) => s.AvailabilityZone!)));\n azs.sort();\n\n const subnets: Subnet[] = listedSubnets.map((subnet) => {\n let type = getTag('aws-cdk:subnet-type', subnet.Tags);\n if (type === undefined && subnet.MapPublicIpOnLaunch) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToIgw(subnet.SubnetId)) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToNatGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined && routeTables.hasRouteToTransitGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined) {\n type = SubnetType.Isolated;\n }\n\n if (!isValidSubnetType(type)) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} has invalid subnet type ${type} (must be ${SubnetType.Public}, ${SubnetType.Private} or ${SubnetType.Isolated})`,\n );\n }\n\n if (args.subnetGroupNameTag && !getTag(args.subnetGroupNameTag, subnet.Tags)) {\n throw new ContextProviderError(\n `Invalid subnetGroupNameTag: Subnet ${subnet.SubnetArn} does not have an associated tag with Key='${args.subnetGroupNameTag}'`,\n );\n }\n\n const name = getTag(args.subnetGroupNameTag || 'aws-cdk:subnet-name', subnet.Tags) || type;\n const routeTableId = routeTables.routeTableIdForSubnetId(subnet.SubnetId);\n\n if (!routeTableId) {\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} does not have an associated route table (and there is no \"main\" table)`,\n );\n }\n\n return {\n az: subnet.AvailabilityZone!,\n cidr: subnet.CidrBlock!,\n type,\n name,\n subnetId: subnet.SubnetId!,\n routeTableId,\n };\n });\n\n let grouped: SubnetGroups;\n let assymetricSubnetGroups: VpcSubnetGroup[] | undefined;\n if (args.returnAsymmetricSubnets) {\n grouped = { azs: [], groups: [] };\n assymetricSubnetGroups = groupAsymmetricSubnets(subnets);\n } else {\n grouped = groupSubnets(subnets);\n assymetricSubnetGroups = undefined;\n }\n\n // Find attached+available VPN gateway for this VPC\n const vpnGatewayResponse =\n (args.returnVpnGateways ?? true)\n ? await ec2.describeVpnGateways({\n Filters: [\n {\n Name: 'attachment.vpc-id',\n Values: [vpcId],\n },\n {\n Name: 'attachment.state',\n Values: ['attached'],\n },\n {\n Name: 'state',\n Values: ['available'],\n },\n ],\n })\n : undefined;\n const vpnGatewayId =\n vpnGatewayResponse?.VpnGateways?.length === 1 ? vpnGatewayResponse.VpnGateways[0].VpnGatewayId : undefined;\n\n return {\n vpcId,\n vpcCidrBlock: vpc.CidrBlock!,\n ownerAccountId: vpc.OwnerId,\n availabilityZones: grouped.azs,\n isolatedSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n isolatedSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n isolatedSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n privateSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n privateSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n privateSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n publicSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n publicSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n publicSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n vpnGatewayId,\n subnetGroups: assymetricSubnetGroups,\n };\n }\n}\n\nclass RouteTables {\n public readonly mainRouteTable?: RouteTable;\n\n constructor(private readonly tables: RouteTable[]) {\n this.mainRouteTable = this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => !!assoc.Main),\n );\n }\n\n public routeTableIdForSubnetId(subnetId: string | undefined): string | undefined {\n const table = this.tableForSubnet(subnetId);\n return (table && table.RouteTableId) || (this.mainRouteTable && this.mainRouteTable.RouteTableId);\n }\n\n /**\n * Whether the given subnet has a route to a NAT Gateway\n */\n public hasRouteToNatGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.NatGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to a Transit Gateway\n */\n public hasRouteToTransitGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.TransitGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to an IGW\n */\n public hasRouteToIgw(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table && !!table.Routes && table.Routes.some((route) => !!route.GatewayId && route.GatewayId.startsWith('igw-'))\n );\n }\n\n public tableForSubnet(subnetId: string | undefined) {\n return this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => assoc.SubnetId === subnetId),\n );\n }\n}\n\n/**\n * Return the value of a tag from a set of tags\n */\nfunction getTag(name: string, tags?: Tag[]): string | undefined {\n for (const tag of tags || []) {\n if (tag.Key === name) {\n return tag.Value;\n }\n }\n return undefined;\n}\n\n/**\n * Group subnets of the same type together, and order by AZ\n */\nfunction groupSubnets(subnets: Subnet[]): SubnetGroups {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n const groups = Object.values(grouping).map((sns) => {\n sns.sort((a: Subnet, b: Subnet) => a.az.localeCompare(b.az));\n return {\n type: sns[0].type,\n name: sns[0].name,\n subnets: sns,\n };\n });\n\n const azs = groups[0].subnets.map((s) => s.az);\n\n for (const group of groups) {\n const groupAZs = group.subnets.map((s) => s.az);\n if (!arraysEqual(groupAZs, azs)) {\n throw new ContextProviderError(`Not all subnets in VPC have the same AZs: ${groupAZs} vs ${azs}`);\n }\n }\n\n return { azs, groups };\n}\n\nfunction groupAsymmetricSubnets(subnets: Subnet[]): VpcSubnetGroup[] {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n return Object.values(grouping).map((subnetArray) => {\n subnetArray.sort((subnet1: Subnet, subnet2: Subnet) => subnet1.az.localeCompare(subnet2.az));\n\n return {\n name: subnetArray[0].name,\n type: subnetTypeToVpcSubnetType(subnetArray[0].type),\n subnets: subnetArray.map((subnet) => ({\n subnetId: subnet.subnetId,\n cidr: subnet.cidr,\n availabilityZone: subnet.az,\n routeTableId: subnet.routeTableId,\n })),\n };\n });\n}\n\nfunction subnetTypeToVpcSubnetType(type: SubnetType): VpcSubnetGroupType {\n switch (type) {\n case SubnetType.Isolated:\n return VpcSubnetGroupType.ISOLATED;\n case SubnetType.Private:\n return VpcSubnetGroupType.PRIVATE;\n case SubnetType.Public:\n return VpcSubnetGroupType.PUBLIC;\n }\n}\n\nenum SubnetType {\n Public = 'Public',\n Private = 'Private',\n Isolated = 'Isolated',\n}\n\nfunction isValidSubnetType(val: string): val is SubnetType {\n return val === SubnetType.Public || val === SubnetType.Private || val === SubnetType.Isolated;\n}\n\ninterface Subnet {\n az: string;\n cidr: string;\n type: SubnetType;\n name: string;\n routeTableId: string;\n subnetId: string;\n}\n\ninterface SubnetGroup {\n type: SubnetType;\n name: string;\n subnets: Subnet[];\n}\n\ninterface SubnetGroups {\n azs: string[];\n groups: SubnetGroup[];\n}\n\nfunction arraysEqual(as: string[], bs: string[]): boolean {\n if (as.length !== bs.length) {\n return false;\n }\n\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction findGroups(type: SubnetType, groups: SubnetGroups): SubnetGroup[] {\n return groups.groups.filter((g) => g.type === type);\n}\n\nfunction flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[] {\n const ret = new Array<U>();\n for (const x of xs) {\n ret.push(...fn(x));\n }\n return ret;\n}\n\nfunction collapse<T>(xs: T[]): T[] | undefined {\n if (xs.length > 0) {\n return xs;\n }\n return undefined;\n}\n", "import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { ToolkitError } from '../../toolkit/error';\n\n/**\n * A single-writer/multi-reader lock on a directory\n *\n * It uses marker files with PIDs in them as a locking marker; the PIDs will be\n * checked for liveness, so that if the process exits without cleaning up the\n * files the lock is implicitly released.\n *\n * This class is not 100% race safe, but in practice it should be a lot\n * better than the 0 protection we have today.\n */\n/* istanbul ignore next: code paths are unpredictable */\nexport class RWLock {\n private readonly pidString: string;\n private readonly writerFile: string;\n private readCounter = 0;\n\n constructor(public readonly directory: string) {\n this.pidString = `${process.pid}`;\n\n this.writerFile = path.join(this.directory, 'synth.lock');\n }\n\n /**\n * Acquire a writer lock.\n *\n * No other readers or writers must exist for the given directory.\n */\n public async acquireWrite(): Promise<IWriterLock> {\n await this.assertNoOtherWriters();\n\n const readers = await this.currentReaders();\n if (readers.length > 0) {\n throw new ToolkitError(`Other CLIs (PID=${readers}) are currently reading from ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n\n await writeFileAtomic(this.writerFile, this.pidString);\n\n return {\n release: async () => {\n await deleteFile(this.writerFile);\n },\n convertToReaderLock: async () => {\n // Acquire the read lock before releasing the write lock. Slightly less\n // chance of racing!\n const ret = await this.doAcquireRead();\n await deleteFile(this.writerFile);\n return ret;\n },\n };\n }\n\n /**\n * Acquire a read lock\n *\n * Will fail if there are any writers.\n */\n public async acquireRead(): Promise<ILock> {\n await this.assertNoOtherWriters();\n return this.doAcquireRead();\n }\n\n /**\n * Obtains the name fo a (new) `readerFile` to use. This includes a counter so\n * that if multiple threads of the same PID attempt to concurrently acquire\n * the same lock, they're guaranteed to use a different reader file name (only\n * one thread will ever execute JS code at once, guaranteeing the readCounter\n * is incremented \"atomically\" from the point of view of this PID.).\n */\n private readerFile(): string {\n return path.join(this.directory, `read.${this.pidString}.${++this.readCounter}.lock`);\n }\n\n /**\n * Do the actual acquiring of a read lock.\n */\n private async doAcquireRead(): Promise<ILock> {\n const readerFile = this.readerFile();\n await writeFileAtomic(readerFile, this.pidString);\n return {\n release: async () => {\n await deleteFile(readerFile);\n },\n };\n }\n\n private async assertNoOtherWriters() {\n const writer = await this.currentWriter();\n if (writer) {\n throw new ToolkitError(`Another CLI (PID=${writer}) is currently synthing to ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n }\n\n /**\n * Check the current writer (if any)\n */\n private async currentWriter(): Promise<number | undefined> {\n const contents = await readFileIfExists(this.writerFile);\n if (!contents) {\n return undefined;\n }\n\n const pid = parseInt(contents, 10);\n if (!processExists(pid)) {\n // Do cleanup of a stray file now\n await deleteFile(this.writerFile);\n return undefined;\n }\n\n return pid;\n }\n\n /**\n * Check the current readers (if any)\n */\n private async currentReaders(): Promise<number[]> {\n const re = /^read\\.([^.]+)\\.[^.]+\\.lock$/;\n const ret = new Array<number>();\n\n let children;\n try {\n children = await fs.readdir(this.directory, { encoding: 'utf-8' });\n } catch (e: any) {\n // Can't be locked if the directory doesn't exist\n if (e.code === 'ENOENT') {\n return [];\n }\n throw e;\n }\n\n for (const fname of children) {\n const m = fname.match(re);\n if (m) {\n const pid = parseInt(m[1], 10);\n if (processExists(pid)) {\n ret.push(pid);\n } else {\n // Do cleanup of a stray file now\n await deleteFile(path.join(this.directory, fname));\n }\n }\n }\n return ret;\n }\n}\n\n/**\n * An acquired lock\n */\nexport interface ILock {\n release(): Promise<void>;\n}\n\n/**\n * An acquired writer lock\n */\nexport interface IWriterLock extends ILock {\n /**\n * Convert the writer lock to a reader lock\n */\n convertToReaderLock(): Promise<ILock>;\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nasync function readFileIfExists(filename: string): Promise<string | undefined> {\n try {\n return await fs.readFile(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return undefined;\n }\n throw e;\n }\n}\n\nlet tmpCounter = 0;\n/* istanbul ignore next: code paths are unpredictable */\nasync function writeFileAtomic(filename: string, contents: string): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n const tmpFile = `${filename}.${process.pid}_${++tmpCounter}`;\n await fs.writeFile(tmpFile, contents, { encoding: 'utf-8' });\n await fs.rename(tmpFile, filename);\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nasync function deleteFile(filename: string) {\n try {\n await fs.unlink(filename);\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nfunction processExists(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return false;\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { SynthesisMessageLevel } from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { minimatch } from 'minimatch';\nimport * as semver from 'semver';\nimport { info } from '../../logging';\nimport { AssemblyError, ToolkitError } from '../../toolkit/error';\nimport { flatten } from '../../util';\n\nexport enum DefaultSelection {\n /**\n * Returns an empty selection in case there are no selectors.\n */\n None = 'none',\n\n /**\n * If the app includes a single stack, returns it. Otherwise throws an exception.\n * This behavior is used by \"deploy\".\n */\n OnlySingle = 'single',\n\n /**\n * Returns all stacks in the main (top level) assembly only.\n */\n MainAssembly = 'main',\n\n /**\n * If no selectors are provided, returns all stacks in the app,\n * including stacks inside nested assemblies.\n */\n AllStacks = 'all',\n}\n\nexport interface SelectStacksOptions {\n /**\n * Extend the selection to upstread/downstream stacks\n * @default ExtendedStackSelection.None only select the specified stacks.\n */\n extend?: ExtendedStackSelection;\n\n /**\n * The behavior if no selectors are provided.\n */\n defaultBehavior: DefaultSelection;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @default false\n */\n ignoreNoStacks?: boolean;\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExtendedStackSelection {\n /**\n * Don't select any extra stacks\n */\n None,\n\n /**\n * Include stacks that this stack depends on\n */\n Upstream,\n\n /**\n * Include stacks that depend on this stack\n */\n Downstream,\n}\n\n/**\n * A specification of which stacks should be selected\n */\nexport interface StackSelector {\n /**\n * Whether all stacks at the top level assembly should\n * be selected and nothing else\n */\n allTopLevel?: boolean;\n\n /**\n * A list of patterns to match the stack hierarchical ids\n */\n patterns: string[];\n}\n\n/**\n * A single Cloud Assembly and the operations we do on it to deploy the artifacts inside\n */\nexport class CloudAssembly {\n /**\n * The directory this CloudAssembly was read from\n */\n public readonly directory: string;\n\n constructor(public readonly assembly: cxapi.CloudAssembly) {\n this.directory = assembly.directory;\n }\n\n public async selectStacks(selector: StackSelector, options: SelectStacksOptions): Promise<StackCollection> {\n const asm = this.assembly;\n const topLevelStacks = asm.stacks;\n const stacks = semver.major(asm.version) < 10 ? asm.stacks : asm.stacksRecursively;\n const allTopLevel = selector.allTopLevel ?? false;\n const patterns = sanitizePatterns(selector.patterns);\n\n if (stacks.length === 0) {\n if (options.ignoreNoStacks) {\n return new StackCollection(this, []);\n }\n throw new ToolkitError('This app contains no stacks');\n }\n\n if (allTopLevel) {\n return this.selectTopLevelStacks(stacks, topLevelStacks, options.extend);\n } else if (patterns.length > 0) {\n return this.selectMatchingStacks(stacks, patterns, options.extend);\n } else {\n return this.selectDefaultStacks(stacks, topLevelStacks, options.defaultBehavior);\n }\n }\n\n private selectTopLevelStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n topLevelStacks: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): StackCollection {\n if (topLevelStacks.length > 0) {\n return this.extendStacks(topLevelStacks, stacks, extend);\n } else {\n throw new ToolkitError('No stack found in the main cloud assembly. Use \"list\" to print manifest');\n }\n }\n\n protected selectMatchingStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n patterns: string[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): StackCollection {\n const matchingPattern = (pattern: string) => (stack: cxapi.CloudFormationStackArtifact) => minimatch(stack.hierarchicalId, pattern);\n const matchedStacks = flatten(patterns.map(pattern => stacks.filter(matchingPattern(pattern))));\n\n return this.extendStacks(matchedStacks, stacks, extend);\n }\n\n private selectDefaultStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n topLevelStacks: cxapi.CloudFormationStackArtifact[],\n defaultSelection: DefaultSelection,\n ) {\n switch (defaultSelection) {\n case DefaultSelection.MainAssembly:\n return new StackCollection(this, topLevelStacks);\n case DefaultSelection.AllStacks:\n return new StackCollection(this, stacks);\n case DefaultSelection.None:\n return new StackCollection(this, []);\n case DefaultSelection.OnlySingle:\n if (topLevelStacks.length === 1) {\n return new StackCollection(this, topLevelStacks);\n } else {\n throw new ToolkitError('Since this app includes more than a single stack, specify which stacks to use (wildcards are supported) or specify `--all`\\n' +\n `Stacks: ${stacks.map(x => x.hierarchicalId).join(' \u00B7 ')}`);\n }\n default:\n throw new ToolkitError(`invalid default behavior: ${defaultSelection}`);\n }\n }\n\n protected extendStacks(\n matched: cxapi.CloudFormationStackArtifact[],\n all: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ) {\n const allStacks = new Map<string, cxapi.CloudFormationStackArtifact>();\n for (const stack of all) {\n allStacks.set(stack.hierarchicalId, stack);\n }\n\n const index = indexByHierarchicalId(matched);\n\n switch (extend) {\n case ExtendedStackSelection.Downstream:\n includeDownstreamStacks(index, allStacks);\n break;\n case ExtendedStackSelection.Upstream:\n includeUpstreamStacks(index, allStacks);\n break;\n }\n\n // Filter original array because it is in the right order\n const selectedList = all.filter(s => index.has(s.hierarchicalId));\n\n return new StackCollection(this, selectedList);\n }\n\n /**\n * Select a single stack by its ID\n */\n public stackById(stackId: string) {\n return new StackCollection(this, [this.assembly.getStackArtifact(stackId)]);\n }\n}\n\n/**\n * The dependencies of a stack.\n */\nexport type StackDependency = {\n id: string;\n dependencies: StackDependency[];\n};\n\n/**\n * Details of a stack.\n */\nexport type StackDetails = {\n id: string;\n name: string;\n environment: cxapi.Environment;\n dependencies: StackDependency[];\n};\n\n/**\n * A collection of stacks and related artifacts\n *\n * In practice, not all artifacts in the CloudAssembly are created equal;\n * stacks can be selected independently, but other artifacts such as asset\n * bundles cannot.\n */\nexport class StackCollection {\n constructor(public readonly assembly: CloudAssembly, public readonly stackArtifacts: cxapi.CloudFormationStackArtifact[]) {\n }\n\n public get stackCount() {\n return this.stackArtifacts.length;\n }\n\n public get firstStack() {\n if (this.stackCount < 1) {\n throw new ToolkitError('StackCollection contains no stack artifacts (trying to access the first one)');\n }\n return this.stackArtifacts[0];\n }\n\n public get stackIds(): string[] {\n return this.stackArtifacts.map(s => s.id);\n }\n\n public get hierarchicalIds(): string[] {\n return this.stackArtifacts.map(s => s.hierarchicalId);\n }\n\n public withDependencies(): StackDetails[] {\n const allData: StackDetails[] = [];\n\n for (const stack of this.stackArtifacts) {\n const data: StackDetails = {\n id: stack.displayName ?? stack.id,\n name: stack.stackName,\n environment: stack.environment,\n dependencies: [],\n };\n\n for (const dependencyId of stack.dependencies.map(x => x.id)) {\n if (dependencyId.includes('.assets')) {\n continue;\n }\n\n const depStack = this.assembly.stackById(dependencyId);\n\n if (depStack.firstStack.dependencies.filter((dep) => !(dep.id).includes('.assets')).length > 0) {\n for (const stackDetail of depStack.withDependencies()) {\n data.dependencies.push({\n id: stackDetail.id,\n dependencies: stackDetail.dependencies,\n });\n }\n } else {\n data.dependencies.push({\n id: depStack.firstStack.displayName ?? depStack.firstStack.id,\n dependencies: [],\n });\n }\n }\n\n allData.push(data);\n }\n\n return allData;\n }\n\n public reversed() {\n const arts = [...this.stackArtifacts];\n arts.reverse();\n return new StackCollection(this.assembly, arts);\n }\n\n public filter(predicate: (art: cxapi.CloudFormationStackArtifact) => boolean): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.filter(predicate));\n }\n\n public concat(...others: StackCollection[]): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.concat(...others.map(o => o.stackArtifacts)));\n }\n\n /**\n * Extracts 'aws:cdk:warning|info|error' metadata entries from the stack synthesis\n */\n public async validateMetadata(\n failAt: 'warn' | 'error' | 'none' = 'error',\n logger: (level: 'info' | 'error' | 'warn', msg: cxapi.SynthesisMessage) => Promise<void> = async () => {\n },\n ) {\n let warnings = false;\n let errors = false;\n\n for (const stack of this.stackArtifacts) {\n for (const message of stack.messages) {\n switch (message.level) {\n case SynthesisMessageLevel.WARNING:\n warnings = true;\n await logger('warn', message);\n break;\n case SynthesisMessageLevel.ERROR:\n errors = true;\n await logger('error', message);\n break;\n case SynthesisMessageLevel.INFO:\n await logger('info', message);\n break;\n }\n }\n }\n\n if (errors && failAt != 'none') {\n throw new AssemblyError('Found errors');\n }\n\n if (warnings && failAt === 'warn') {\n throw new AssemblyError('Found warnings (--strict mode)');\n }\n }\n}\n\nexport interface MetadataMessageOptions {\n /**\n * Whether to be verbose\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Don't stop on error metadata\n *\n * @default false\n */\n ignoreErrors?: boolean;\n\n /**\n * Treat warnings in metadata as errors\n *\n * @default false\n */\n strict?: boolean;\n}\n\nfunction indexByHierarchicalId(stacks: cxapi.CloudFormationStackArtifact[]): Map<string, cxapi.CloudFormationStackArtifact> {\n const result = new Map<string, cxapi.CloudFormationStackArtifact>();\n\n for (const stack of stacks) {\n result.set(stack.hierarchicalId, stack);\n }\n\n return result;\n}\n\n/**\n * Calculate the transitive closure of stack dependents.\n *\n * Modifies `selectedStacks` in-place.\n */\nfunction includeDownstreamStacks(\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>) {\n const added = new Array<string>();\n\n let madeProgress;\n do {\n madeProgress = false;\n\n for (const [id, stack] of allStacks) {\n // Select this stack if it's not selected yet AND it depends on a stack that's in the selected set\n if (!selectedStacks.has(id) && (stack.dependencies || []).some(dep => selectedStacks.has(dep.id))) {\n selectedStacks.set(id, stack);\n added.push(id);\n madeProgress = true;\n }\n }\n } while (madeProgress);\n\n if (added.length > 0) {\n info('Including depending stacks: %s', chalk.bold(added.join(', ')));\n }\n}\n\n/**\n * Calculate the transitive closure of stack dependencies.\n *\n * Modifies `selectedStacks` in-place.\n */\nfunction includeUpstreamStacks(\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>) {\n const added = new Array<string>();\n let madeProgress = true;\n while (madeProgress) {\n madeProgress = false;\n\n for (const stack of selectedStacks.values()) {\n // Select an additional stack if it's not selected yet and a dependency of a selected stack (and exists, obviously)\n for (const dependencyId of stack.dependencies.map(x => x.manifest.displayName ?? x.id)) {\n if (!selectedStacks.has(dependencyId) && allStacks.has(dependencyId)) {\n added.push(dependencyId);\n selectedStacks.set(dependencyId, allStacks.get(dependencyId)!);\n madeProgress = true;\n }\n }\n }\n }\n\n if (added.length > 0) {\n info('Including dependency stacks: %s', chalk.bold(added.join(', ')));\n }\n}\n\nexport function sanitizePatterns(patterns: string[]): string[] {\n let sanitized = patterns.filter(s => s != null); // filter null/undefined\n sanitized = [...new Set(sanitized)]; // make them unique\n return sanitized;\n}\n", "import * as childProcess from 'child_process';\nimport * as os from 'os';\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { Configuration, PROJECT_CONFIG, USER_DEFAULTS } from '../../cli/user-configuration';\nimport { versionNumber } from '../../cli/version';\nimport { debug, warning } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\nimport { loadTree, some } from '../../tree';\nimport { splitBySize } from '../../util/objects';\nimport { SdkProvider } from '../aws-auth';\nimport { Settings } from '../settings';\nimport { RWLock, ILock } from '../util/rwlock';\n\nexport interface ExecProgramResult {\n readonly assembly: cxapi.CloudAssembly;\n readonly lock: ILock;\n}\n\n/** Invokes the cloud executable and returns JSON output */\nexport async function execProgram(aws: SdkProvider, config: Configuration): Promise<ExecProgramResult> {\n const env = await prepareDefaultEnvironment(aws);\n const context = await prepareContext(config.settings, config.context.all, env);\n\n const build = config.settings.get(['build']);\n if (build) {\n await exec(build);\n }\n\n const app = config.settings.get(['app']);\n if (!app) {\n throw new ToolkitError(`--app is required either in command-line, in ${PROJECT_CONFIG} or in ${USER_DEFAULTS}`);\n }\n\n // bypass \"synth\" if app points to a cloud assembly\n if (await fs.pathExists(app) && (await fs.stat(app)).isDirectory()) {\n debug('--app points to a cloud assembly, so we bypass synth');\n\n // Acquire a read lock on this directory\n const lock = await new RWLock(app).acquireRead();\n\n return { assembly: createAssembly(app), lock };\n }\n\n const commandLine = await guessExecutable(app);\n\n const outdir = config.settings.get(['output']);\n if (!outdir) {\n throw new ToolkitError('unexpected: --output is required');\n }\n if (typeof outdir !== 'string') {\n throw new ToolkitError(`--output takes a string, got ${JSON.stringify(outdir)}`);\n }\n try {\n await fs.mkdirp(outdir);\n } catch (error: any) {\n throw new ToolkitError(`Could not create output directory ${outdir} (${error.message})`);\n }\n\n debug('outdir:', outdir);\n env[cxapi.OUTDIR_ENV] = outdir;\n\n // Acquire a lock on the output directory\n const writerLock = await new RWLock(outdir).acquireWrite();\n\n try {\n // Send version information\n env[cxapi.CLI_ASM_VERSION_ENV] = cxschema.Manifest.version();\n env[cxapi.CLI_VERSION_ENV] = versionNumber();\n\n debug('env:', env);\n\n const envVariableSizeLimit = os.platform() === 'win32' ? 32760 : 131072;\n const [smallContext, overflow] = splitBySize(context, spaceAvailableForContext(env, envVariableSizeLimit));\n\n // Store the safe part in the environment variable\n env[cxapi.CONTEXT_ENV] = JSON.stringify(smallContext);\n\n // If there was any overflow, write it to a temporary file\n let contextOverflowLocation;\n if (Object.keys(overflow ?? {}).length > 0) {\n const contextDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-context'));\n contextOverflowLocation = path.join(contextDir, 'context-overflow.json');\n fs.writeJSONSync(contextOverflowLocation, overflow);\n env[cxapi.CONTEXT_OVERFLOW_LOCATION_ENV] = contextOverflowLocation;\n }\n\n await exec(commandLine.join(' '));\n\n const assembly = createAssembly(outdir);\n\n contextOverflowCleanup(contextOverflowLocation, assembly);\n\n return { assembly, lock: await writerLock.convertToReaderLock() };\n } catch (e) {\n await writerLock.release();\n throw e;\n }\n\n async function exec(commandAndArgs: string) {\n return new Promise<void>((ok, fail) => {\n // We use a slightly lower-level interface to:\n //\n // - Pass arguments in an array instead of a string, to get around a\n // number of quoting issues introduced by the intermediate shell layer\n // (which would be different between Linux and Windows).\n //\n // - Inherit stderr from controlling terminal. We don't use the captured value\n // anyway, and if the subprocess is printing to it for debugging purposes the\n // user gets to see it sooner. Plus, capturing doesn't interact nicely with some\n // processes like Maven.\n const proc = childProcess.spawn(commandAndArgs, {\n stdio: ['ignore', 'inherit', 'inherit'],\n detached: false,\n shell: true,\n env: {\n ...process.env,\n ...env,\n },\n });\n\n proc.on('error', fail);\n\n proc.on('exit', code => {\n if (code === 0) {\n return ok();\n } else {\n debug('failed command:', commandAndArgs);\n return fail(new ToolkitError(`Subprocess exited with error ${code}`));\n }\n });\n });\n }\n}\n\n/**\n * Creates an assembly with error handling\n */\nexport function createAssembly(appDir: string) {\n try {\n return new cxapi.CloudAssembly(appDir, {\n // We sort as we deploy\n topoSort: false,\n });\n } catch (error: any) {\n if (error.message.includes(cxschema.VERSION_MISMATCH)) {\n // this means the CLI version is too old.\n // we instruct the user to upgrade.\n throw new ToolkitError(`This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.\\n(${error.message})`);\n }\n throw error;\n }\n}\n\n/**\n * If we don't have region/account defined in context, we fall back to the default SDK behavior\n * where region is retrieved from ~/.aws/config and account is based on default credentials provider\n * chain and then STS is queried.\n *\n * This is done opportunistically: for example, if we can't access STS for some reason or the region\n * is not configured, the context value will be 'null' and there could failures down the line. In\n * some cases, synthesis does not require region/account information at all, so that might be perfectly\n * fine in certain scenarios.\n *\n * @param context The context key/value bash.\n */\nexport async function prepareDefaultEnvironment(\n aws: SdkProvider,\n logFn: (msg: string, ...args: any) => any = debug,\n): Promise<{ [key: string]: string }> {\n const env: { [key: string]: string } = { };\n\n env[cxapi.DEFAULT_REGION_ENV] = aws.defaultRegion;\n await logFn(`Setting \"${cxapi.DEFAULT_REGION_ENV}\" environment variable to`, env[cxapi.DEFAULT_REGION_ENV]);\n\n const accountId = (await aws.defaultAccount())?.accountId;\n if (accountId) {\n env[cxapi.DEFAULT_ACCOUNT_ENV] = accountId;\n await logFn(`Setting \"${cxapi.DEFAULT_ACCOUNT_ENV}\" environment variable to`, env[cxapi.DEFAULT_ACCOUNT_ENV]);\n }\n\n return env;\n}\n\n/**\n * Settings related to synthesis are read from context.\n * The merging of various configuration sources like cli args or cdk.json has already happened.\n * We now need to set the final values to the context.\n */\nexport async function prepareContext(settings: Settings, context: {[key: string]: any}, env: { [key: string]: string | undefined}) {\n const debugMode: boolean = settings.get(['debug']) ?? true;\n if (debugMode) {\n env.CDK_DEBUG = 'true';\n }\n\n const pathMetadata: boolean = settings.get(['pathMetadata']) ?? true;\n if (pathMetadata) {\n context[cxapi.PATH_METADATA_ENABLE_CONTEXT] = true;\n }\n\n const assetMetadata: boolean = settings.get(['assetMetadata']) ?? true;\n if (assetMetadata) {\n context[cxapi.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT] = true;\n }\n\n const versionReporting: boolean = settings.get(['versionReporting']) ?? true;\n if (versionReporting) {\n context[cxapi.ANALYTICS_REPORTING_ENABLED_CONTEXT] = true;\n }\n // We need to keep on doing this for framework version from before this flag was deprecated.\n if (!versionReporting) {\n context['aws:cdk:disable-version-reporting'] = true;\n }\n\n const stagingEnabled = settings.get(['staging']) ?? true;\n if (!stagingEnabled) {\n context[cxapi.DISABLE_ASSET_STAGING_CONTEXT] = true;\n }\n\n const bundlingStacks = settings.get(['bundlingStacks']) ?? ['**'];\n context[cxapi.BUNDLING_STACKS] = bundlingStacks;\n\n debug('context:', context);\n\n return context;\n}\n\n/**\n * Make sure the 'app' is an array\n *\n * If it's a string, split on spaces as a trivial way of tokenizing the command line.\n */\nfunction appToArray(app: any) {\n return typeof app === 'string' ? app.split(' ') : app;\n}\n\ntype CommandGenerator = (file: string) => string[];\n\n/**\n * Execute the given file with the same 'node' process as is running the current process\n */\nfunction executeNode(scriptFile: string): string[] {\n return [process.execPath, scriptFile];\n}\n\n/**\n * Mapping of extensions to command-line generators\n */\nconst EXTENSION_MAP = new Map<string, CommandGenerator>([\n ['.js', executeNode],\n]);\n\n/**\n * Guess the executable from the command-line argument\n *\n * Only do this if the file is NOT marked as executable. If it is,\n * we'll defer to the shebang inside the file itself.\n *\n * If we're on Windows, we ALWAYS take the handler, since it's hard to\n * verify if registry associations have or have not been set up for this\n * file type, so we'll assume the worst and take control.\n */\nexport async function guessExecutable(app: string) {\n const commandLine = appToArray(app);\n if (commandLine.length === 1) {\n let fstat;\n\n try {\n fstat = await fs.stat(commandLine[0]);\n } catch {\n debug(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);\n return commandLine;\n }\n\n // eslint-disable-next-line no-bitwise\n const isExecutable = (fstat.mode & fs.constants.X_OK) !== 0;\n const isWindows = process.platform === 'win32';\n\n const handler = EXTENSION_MAP.get(path.extname(commandLine[0]));\n if (handler && (!isExecutable || isWindows)) {\n return handler(commandLine[0]);\n }\n }\n return commandLine;\n}\n\nfunction contextOverflowCleanup(location: string | undefined, assembly: cxapi.CloudAssembly) {\n if (location) {\n fs.removeSync(path.dirname(location));\n\n const tree = loadTree(assembly);\n const frameworkDoesNotSupportContextOverflow = some(tree, node => {\n const fqn = node.constructInfo?.fqn;\n const version = node.constructInfo?.version;\n return (fqn === 'aws-cdk-lib.App' && version != null && semver.lte(version, '2.38.0'))\n || fqn === '@aws-cdk/core.App'; // v1\n });\n\n // We're dealing with an old version of the framework here. It is unaware of the temporary\n // file, which means that it will ignore the context overflow.\n if (frameworkDoesNotSupportContextOverflow) {\n warning('Part of the context could not be sent to the application. Please update the AWS CDK library to the latest version.');\n }\n }\n}\n\nexport function spaceAvailableForContext(env: { [key: string]: string }, limit: number) {\n const size = (value: string) => value != null ? Buffer.byteLength(value) : 0;\n\n const usedSpace = Object.entries(env)\n .map(([k, v]) => k === cxapi.CONTEXT_ENV ? size(k) : size(k) + size(v))\n .reduce((a, b) => a + b, 0);\n\n return Math.max(0, limit - usedSpace);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,uBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAoBO;AACP,iCAQO;AACP,mCAmFO;AACP,oCAQO;AACP,8BAKO;AACP,wBA6BO;AACP,wBA6BO;AACP,wBAaO;AACP,8CAeO;AACP,wBAWO;AACP,wBAQO;AACP,2BAkBO;AACP,6BAWO;AACP,uBA4BO;AACP,oCAKO;AACP,wBAKO;AACP,wBAKO;AACP,wBAAoD;AACpD,yBAAuB;AACvB,iCAA4C;AAG5C,wBAAwC;;;ACnUxC,IAAAC,QAAsB;AACtB,IAAAC,MAAoB;;;ACDpB,IAAAC,QAAsB;AACtB,IAAAC,SAAuB;;;ACDvB,WAAsB;AACtB,YAAuB;AACvB,eAA0B;;;ACF1B,IAAM,uBAAuB,OAAO,IAAI,+BAA+B;AACvE,IAAM,8BAA8B,OAAO,IAAI,sCAAsC;AACrF,IAAM,wBAAwB,OAAO,IAAI,gCAAgC;AACzE,IAAM,gCAAgC,OAAO,IAAI,uCAAuC;AAKjF,IAAM,eAAN,MAAM,sBAAqB,MAAM;AAAA;AAAA;AAAA;AAAA,EAItC,OAAc,eAAe,GAA2B;AACtD,WAAO,MAAM,QAAQ,OAAO,MAAO,YAAY,wBAAw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AA,IACT;AAGA,UAAM,gBAAgB,MAAM,OAAU,eAAU,UAAU;AAC1D,UAAM,YAAY,QAAQ,aAAa;AAEvC,UAAM,UAAU,cAAc,IAAS,eAAQ,YAAY,CAAC,CAAC,CAAC;AAC9D,QAAI,YAAY,CAAC,gBAAgB,YAAY;AAC3C,aAAO,QAAQ,YAAY,CAAC,CAAC;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AAsBO,SAAS,yBAAyB,KAAgC,OAAe;AACtF,QAAM,OAAO,CAAC,UAAkB,SAAS,OAAO,OAAO,WAAW,KAAK,IAAI;AAE3E,QAAM,YAAY,OAAO,QAAQ,GAAG,EACjC,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,MAAY,qBAAc,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,EACrE,OAAO,CAAC,GAAG,MAAM,IAAI,GAAG,CAAC;AAE5B,SAAO,KAAK,IAAI,GAAG,QAAQ,SAAS;AACtC;",
6
- "names": ["CloudAssembly", "path", "fs", "util", "chalk", "prompt", "dirname", "cached", "path", "fs", "error", "ECRDescribeImagesCommand", "os", "import_credential_providers", "promptly", "path", "import_util", "import_util", "chalk", "import_util", "fs", "os", "fs", "path", "path", "import_util", "import_cx_api", "import_client_cloudformation", "import_cdk_assets", "error", "info", "debug", "trace", "util", "chalk", "StackActivityProgress", "path", "trace", "import_client_cloudformation", "_StackStatus", "path", "import_cx_api", "import_client_s3", "import_middleware_endpoint", "chalk", "fs", "debug", "debug", "chalk", "import_cx_api", "import_cdk_assets", "debug", "import_util", "chalk", "path", "cxschema", "cxapi", "chalk", "debug", "import_util", "chalk", "path", "fs", "HotswapMode", "error", "error", "archiver", "resolve", "info", "error", "debug", "info", "path", "fs", "semver", "path", "chalk", "fs", "semver", "import_util", "semver", "_exec", "path", "fs", "resolve", "cached", "import_util", "chalk", "debug", "bootstrapStack", "debug", "import_cx_api", "debug", "suffixWithErrors", "import_util", "chalk", "fs", "promptly", "info", "error", "prompt", "chalk", "fs", "info", "util", "chalk", "sleep", "error", "debug", "trace", "path", "cxapi", "import_cdk_assets", "cxschema", "cxapi", "path", "propertyMatchesFilter", "import_cx_api", "import_cx_api", "flatMap", "flatMap", "path", "fs", "import_cx_api", "chalk", "semver", "ExtendedStackSelection", "CloudAssembly", "path", "cxschema", "cxapi", "fs", "semver"]
3
+ "sources": ["aws-cdk.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk.ts", "../../../../aws-cdk/lib/api/aws-auth/account-cache.ts", "../../../../aws-cdk/lib/logging.ts", "../../../../aws-cdk/lib/toolkit/cli-io-host.ts", "../../../tmp-toolkit-helpers/src/api/toolkit-error.ts", "../../../../aws-cdk/lib/util/archive.ts", "../../../../aws-cdk/lib/util/format-error.ts", "../../../../aws-cdk/lib/util/arrays.ts", "../../../../aws-cdk/lib/util/bytes.ts", "../../../../aws-cdk/lib/util/cloudformation.ts", "../../../../aws-cdk/lib/util/content-hash.ts", "../../../../aws-cdk/lib/util/types.ts", "../../../../aws-cdk/lib/util/objects.ts", "../../../../aws-cdk/lib/util/parallel.ts", "../../../../aws-cdk/lib/util/serialize.ts", "../../../../aws-cdk/lib/util/yaml-cfn.ts", "../../../../aws-cdk/lib/util/string-manipulation.ts", "../../../../aws-cdk/lib/util/version-range.ts", "../../../../aws-cdk/lib/cli/activity-printer/base.ts", "../../../../aws-cdk/lib/cli/activity-printer/history.ts", "../../../../aws-cdk/lib/cli/activity-printer/current.ts", "../../../../aws-cdk/lib/cli/activity-printer/display.ts", "../../../../aws-cdk/lib/util/directories.ts", "../../../../aws-cdk/lib/api/aws-auth/cached.ts", "../../../../aws-cdk/lib/api/aws-auth/tracing.ts", "../../../../aws-cdk/lib/api/aws-auth/user-agent.ts", "../../../../aws-cdk/lib/api/aws-auth/util.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk-provider.ts", "../../../../aws-cdk/lib/api/aws-auth/awscli-compatible.ts", "../../../../aws-cdk/lib/api/aws-auth/provider-caching.ts", "../../../../aws-cdk/lib/api/aws-auth/credential-plugins.ts", "../../../../aws-cdk/lib/api/plugin/plugin.ts", "../../../../aws-cdk/lib/api/plugin/context-provider-plugin.ts", "../../../../aws-cdk/lib/api/aws-auth/sdk-logger.ts", "../../../../aws-cdk/lib/api/settings.ts", "../../../../aws-cdk/lib/api/context.ts", "../../../../aws-cdk/lib/api/deployments/cloudformation.ts", "../../../../aws-cdk/lib/api/deployments/asset-manifest-builder.ts", "../../../../aws-cdk/lib/cli/messages.ts", "../../../../aws-cdk/lib/api/stack-events/stack-activity-monitor.ts", "../../../../aws-cdk/lib/api/stack-events/stack-event-poller.ts", "../../../../aws-cdk/lib/api/stack-events/stack-progress-monitor.ts", "../../../../aws-cdk/lib/api/stack-events/stack-status.ts", "../../../../aws-cdk/lib/api/util/template-body-parameter.ts", "../../../../aws-cdk/lib/api/deployments/deployments.ts", "../../../../aws-cdk/lib/api/deployments/asset-publishing.ts", "../../../../aws-cdk/lib/api/deployments/checks.ts", "../../../../aws-cdk/lib/api/deployments/deploy-stack.ts", "../../../../aws-cdk/lib/api/deployments/assets.ts", "../../../../aws-cdk/lib/api/deployments/hotswap-deployments.ts", "../../../../aws-cdk/lib/api/deployments/nested-stack-helpers.ts", "../../../../aws-cdk/lib/api/evaluate-cloudformation-template.ts", "../../../../aws-cdk/lib/api/hotswap/common.ts", "../../../../aws-cdk/lib/api/hotswap/appsync-mapping-templates.ts", "../../../../aws-cdk/lib/api/hotswap/code-build-projects.ts", "../../../../aws-cdk/lib/api/hotswap/ecs-services.ts", "../../../../aws-cdk/lib/api/hotswap/lambda-functions.ts", "../../../../aws-cdk/lib/api/hotswap/s3-bucket-deployments.ts", "../../../../aws-cdk/lib/api/hotswap/stepfunctions-state-machines.ts", "../../../../aws-cdk/lib/notices.ts", "../../../../aws-cdk/lib/cli/version.ts", "../../../../aws-cdk/lib/cli/util/console-formatters.ts", "../../../../aws-cdk/lib/cli/util/npm.ts", "../../../../aws-cdk/lib/tree.ts", "../../../../aws-cdk/lib/api/toolkit-info.ts", "../../../../aws-cdk/lib/api/bootstrap/bootstrap-props.ts", "../../../../aws-cdk/lib/api/environment/environment-resources.ts", "../../../../aws-cdk/lib/api/util/placeholders.ts", "../../../../aws-cdk/lib/api/environment/environment-access.ts", "../../../../aws-cdk/lib/api/deployments/deployment-result.ts", "../../../../aws-cdk/lib/api/tags.ts", "../../../../aws-cdk/lib/api/resource-import/importer.ts", "../../../../aws-cdk/lib/api/resource-import/migrator.ts", "../../../../aws-cdk/lib/api/logs/logs-monitor.ts", "../../../../aws-cdk/lib/api/logs/find-cloudwatch-logs.ts", "../../../../aws-cdk/lib/api/work-graph/work-graph.ts", "../../../../aws-cdk/lib/api/work-graph/work-graph-builder.ts", "../../../../aws-cdk/lib/context-providers/index.ts", "../../../../aws-cdk/lib/context-providers/ami.ts", "../../../../aws-cdk/lib/context-providers/availability-zones.ts", "../../../../aws-cdk/lib/util/json.ts", "../../../../aws-cdk/lib/context-providers/cc-api-provider.ts", "../../../../aws-cdk/lib/context-providers/endpoint-service-availability-zones.ts", "../../../../aws-cdk/lib/context-providers/hosted-zones.ts", "../../../../aws-cdk/lib/context-providers/keys.ts", "../../../../aws-cdk/lib/context-providers/load-balancers.ts", "../../../../aws-cdk/lib/context-providers/security-groups.ts", "../../../../aws-cdk/lib/context-providers/ssm-parameters.ts", "../../../../aws-cdk/lib/context-providers/vpcs.ts", "../../../../aws-cdk/lib/api/util/rwlock.ts", "../../../../aws-cdk/lib/api/cxapp/cloud-assembly.ts", "../../../../aws-cdk/lib/api/cxapp/exec.ts"],
4
+ "sourcesContent": ["/* eslint-disable import/no-restricted-paths */\n\n// APIs\nexport { formatSdkLoggerContent, SdkProvider } from '../../../../aws-cdk/lib/api/aws-auth';\nexport { Context, PROJECT_CONTEXT } from '../../../../aws-cdk/lib/api/context';\nexport { Deployments, type SuccessfulDeployStackResult } from '../../../../aws-cdk/lib/api/deployments';\nexport { Settings } from '../../../../aws-cdk/lib/api/settings';\nexport { tagsForStack, Tag } from '../../../../aws-cdk/lib/api/tags';\nexport { DEFAULT_TOOLKIT_STACK_NAME } from '../../../../aws-cdk/lib/api/toolkit-info';\nexport { ResourceMigrator } from '../../../../aws-cdk/lib/api/resource-import';\nexport { CloudWatchLogEventMonitor, findCloudWatchLogGroups } from '../../../../aws-cdk/lib/api/logs';\nexport { type WorkGraph, WorkGraphBuilder, AssetBuildNode, AssetPublishNode, StackNode, Concurrency } from '../../../../aws-cdk/lib/api/work-graph';\n\n// Context Providers\nexport * as contextproviders from '../../../../aws-cdk/lib/context-providers';\n\n// utils\nexport { formatTime } from '../../../../aws-cdk/lib/util/string-manipulation';\nexport { formatErrorMessage } from '../../../../aws-cdk/lib/util/format-error';\nexport { obscureTemplate, serializeStructure } from '../../../../aws-cdk/lib/util/serialize';\nexport { validateSnsTopicArn } from '../../../../aws-cdk/lib/util/cloudformation';\nexport { splitBySize } from '../../../../aws-cdk/lib/util/objects';\n\n// @todo APIs not clean import\nexport { HotswapMode } from '../../../../aws-cdk/lib/api/hotswap/common';\nexport { HotswapPropertyOverrides, EcsHotswapProperties } from '../../../../aws-cdk/lib/api/hotswap/common';\nexport { RWLock, type ILock } from '../../../../aws-cdk/lib/api/util/rwlock';\n\n// @todo Not yet API probably should be\nexport { loadTree, some } from '../../../../aws-cdk/lib/tree';\n\n// @todo Cloud Assembly and Executable - this is a messy API right now\nexport { CloudAssembly, sanitizePatterns, type StackDetails, StackCollection, ExtendedStackSelection } from '../../../../aws-cdk/lib/api/cxapp/cloud-assembly';\nexport { prepareDefaultEnvironment, prepareContext, spaceAvailableForContext } from '../../../../aws-cdk/lib/api/cxapp/exec';\nexport { guessExecutable } from '../../../../aws-cdk/lib/api/cxapp/exec';\n\n// @todo Should not use! investigate how to replace\nexport { versionNumber } from '../../../../aws-cdk/lib/cli/version';\nexport { CliIoHost } from '../../../../aws-cdk/lib/toolkit/cli-io-host';\n", "import {\n AppSyncClient,\n FunctionConfiguration,\n GetSchemaCreationStatusCommand,\n type GetSchemaCreationStatusCommandInput,\n type GetSchemaCreationStatusCommandOutput,\n type ListFunctionsCommandInput,\n paginateListFunctions,\n StartSchemaCreationCommand,\n type StartSchemaCreationCommandInput,\n type StartSchemaCreationCommandOutput,\n UpdateApiKeyCommand,\n type UpdateApiKeyCommandInput,\n type UpdateApiKeyCommandOutput,\n UpdateFunctionCommand,\n type UpdateFunctionCommandInput,\n type UpdateFunctionCommandOutput,\n UpdateResolverCommand,\n type UpdateResolverCommandInput,\n type UpdateResolverCommandOutput,\n} from '@aws-sdk/client-appsync';\nimport {\n CloudControlClient,\n GetResourceCommand,\n GetResourceCommandInput,\n GetResourceCommandOutput,\n ListResourcesCommand,\n ListResourcesCommandInput,\n ListResourcesCommandOutput,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudFormationClient,\n ContinueUpdateRollbackCommand,\n ContinueUpdateRollbackCommandInput,\n ContinueUpdateRollbackCommandOutput,\n CreateChangeSetCommand,\n type CreateChangeSetCommandInput,\n type CreateChangeSetCommandOutput,\n CreateGeneratedTemplateCommand,\n type CreateGeneratedTemplateCommandInput,\n type CreateGeneratedTemplateCommandOutput,\n CreateStackCommand,\n type CreateStackCommandInput,\n type CreateStackCommandOutput,\n DeleteChangeSetCommand,\n type DeleteChangeSetCommandInput,\n type DeleteChangeSetCommandOutput,\n DeleteGeneratedTemplateCommand,\n type DeleteGeneratedTemplateCommandInput,\n type DeleteGeneratedTemplateCommandOutput,\n DeleteStackCommand,\n type DeleteStackCommandInput,\n type DeleteStackCommandOutput,\n DescribeChangeSetCommand,\n type DescribeChangeSetCommandInput,\n type DescribeChangeSetCommandOutput,\n DescribeGeneratedTemplateCommand,\n type DescribeGeneratedTemplateCommandInput,\n type DescribeGeneratedTemplateCommandOutput,\n DescribeResourceScanCommand,\n type DescribeResourceScanCommandInput,\n type DescribeResourceScanCommandOutput,\n DescribeStackEventsCommand,\n type DescribeStackEventsCommandInput,\n DescribeStackEventsCommandOutput,\n DescribeStackResourcesCommand,\n DescribeStackResourcesCommandInput,\n DescribeStackResourcesCommandOutput,\n DescribeStacksCommand,\n type DescribeStacksCommandInput,\n type DescribeStacksCommandOutput,\n ExecuteChangeSetCommand,\n type ExecuteChangeSetCommandInput,\n type ExecuteChangeSetCommandOutput,\n GetGeneratedTemplateCommand,\n type GetGeneratedTemplateCommandInput,\n type GetGeneratedTemplateCommandOutput,\n GetTemplateCommand,\n type GetTemplateCommandInput,\n type GetTemplateCommandOutput,\n GetTemplateSummaryCommand,\n type GetTemplateSummaryCommandInput,\n type GetTemplateSummaryCommandOutput,\n ListExportsCommand,\n type ListExportsCommandInput,\n type ListExportsCommandOutput,\n ListResourceScanRelatedResourcesCommand,\n type ListResourceScanRelatedResourcesCommandInput,\n type ListResourceScanRelatedResourcesCommandOutput,\n ListResourceScanResourcesCommand,\n type ListResourceScanResourcesCommandInput,\n type ListResourceScanResourcesCommandOutput,\n ListResourceScansCommand,\n type ListResourceScansCommandInput,\n type ListResourceScansCommandOutput,\n type ListStackResourcesCommandInput,\n ListStacksCommand,\n ListStacksCommandInput,\n ListStacksCommandOutput,\n paginateListStackResources,\n RollbackStackCommand,\n RollbackStackCommandInput,\n RollbackStackCommandOutput,\n StackResourceSummary,\n StartResourceScanCommand,\n type StartResourceScanCommandInput,\n type StartResourceScanCommandOutput,\n UpdateStackCommand,\n type UpdateStackCommandInput,\n type UpdateStackCommandOutput,\n UpdateTerminationProtectionCommand,\n type UpdateTerminationProtectionCommandInput,\n type UpdateTerminationProtectionCommandOutput,\n} from '@aws-sdk/client-cloudformation';\nimport {\n CloudWatchLogsClient,\n DescribeLogGroupsCommand,\n type DescribeLogGroupsCommandInput,\n type DescribeLogGroupsCommandOutput,\n FilterLogEventsCommand,\n FilterLogEventsCommandInput,\n FilterLogEventsCommandOutput,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CodeBuildClient,\n UpdateProjectCommand,\n type UpdateProjectCommandInput,\n type UpdateProjectCommandOutput,\n} from '@aws-sdk/client-codebuild';\nimport {\n DescribeAvailabilityZonesCommand,\n type DescribeAvailabilityZonesCommandInput,\n type DescribeAvailabilityZonesCommandOutput,\n DescribeImagesCommand,\n type DescribeImagesCommandInput,\n type DescribeImagesCommandOutput,\n DescribeInstancesCommand,\n type DescribeInstancesCommandInput,\n type DescribeInstancesCommandOutput,\n DescribeRouteTablesCommand,\n type DescribeRouteTablesCommandInput,\n type DescribeRouteTablesCommandOutput,\n DescribeSecurityGroupsCommand,\n type DescribeSecurityGroupsCommandInput,\n type DescribeSecurityGroupsCommandOutput,\n DescribeSubnetsCommand,\n type DescribeSubnetsCommandInput,\n type DescribeSubnetsCommandOutput,\n DescribeVpcEndpointServicesCommand,\n type DescribeVpcEndpointServicesCommandInput,\n type DescribeVpcEndpointServicesCommandOutput,\n DescribeVpcsCommand,\n type DescribeVpcsCommandInput,\n type DescribeVpcsCommandOutput,\n DescribeVpnGatewaysCommand,\n type DescribeVpnGatewaysCommandInput,\n type DescribeVpnGatewaysCommandOutput,\n EC2Client,\n} from '@aws-sdk/client-ec2';\nimport {\n BatchDeleteImageCommand,\n BatchDeleteImageCommandInput,\n BatchDeleteImageCommandOutput,\n CreateRepositoryCommand,\n type CreateRepositoryCommandInput,\n type CreateRepositoryCommandOutput,\n DescribeImagesCommand as ECRDescribeImagesCommand,\n type DescribeImagesCommandInput as ECRDescribeImagesCommandInput,\n type DescribeImagesCommandOutput as ECRDescribeImagesCommandOutput,\n DescribeRepositoriesCommand,\n type DescribeRepositoriesCommandInput,\n type DescribeRepositoriesCommandOutput,\n ECRClient,\n GetAuthorizationTokenCommand,\n type GetAuthorizationTokenCommandInput,\n type GetAuthorizationTokenCommandOutput,\n ListImagesCommand,\n ListImagesCommandInput,\n ListImagesCommandOutput,\n PutImageCommand,\n PutImageCommandInput,\n PutImageCommandOutput,\n PutImageScanningConfigurationCommand,\n type PutImageScanningConfigurationCommandInput,\n type PutImageScanningConfigurationCommandOutput,\n BatchGetImageCommandInput,\n BatchGetImageCommand,\n BatchGetImageCommandOutput,\n} from '@aws-sdk/client-ecr';\nimport {\n DescribeServicesCommandInput,\n ECSClient,\n ListClustersCommand,\n type ListClustersCommandInput,\n type ListClustersCommandOutput,\n RegisterTaskDefinitionCommand,\n RegisterTaskDefinitionCommandInput,\n type RegisterTaskDefinitionCommandOutput,\n UpdateServiceCommand,\n type UpdateServiceCommandInput,\n type UpdateServiceCommandOutput,\n waitUntilServicesStable,\n} from '@aws-sdk/client-ecs';\nimport {\n DescribeListenersCommand,\n type DescribeListenersCommandInput,\n type DescribeListenersCommandOutput,\n DescribeLoadBalancersCommand,\n type DescribeLoadBalancersCommandInput,\n type DescribeLoadBalancersCommandOutput,\n DescribeTagsCommand,\n type DescribeTagsCommandInput,\n type DescribeTagsCommandOutput,\n ElasticLoadBalancingV2Client,\n Listener,\n LoadBalancer,\n paginateDescribeListeners,\n paginateDescribeLoadBalancers,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n CreatePolicyCommand,\n type CreatePolicyCommandInput,\n type CreatePolicyCommandOutput,\n GetPolicyCommand,\n type GetPolicyCommandInput,\n type GetPolicyCommandOutput,\n GetRoleCommand,\n type GetRoleCommandInput,\n type GetRoleCommandOutput,\n IAMClient,\n} from '@aws-sdk/client-iam';\nimport {\n DescribeKeyCommand,\n type DescribeKeyCommandInput,\n type DescribeKeyCommandOutput,\n KMSClient,\n ListAliasesCommand,\n type ListAliasesCommandInput,\n type ListAliasesCommandOutput,\n} from '@aws-sdk/client-kms';\nimport {\n InvokeCommand,\n type InvokeCommandInput,\n type InvokeCommandOutput,\n LambdaClient,\n PublishVersionCommand,\n type PublishVersionCommandInput,\n type PublishVersionCommandOutput,\n UpdateAliasCommand,\n type UpdateAliasCommandInput,\n type UpdateAliasCommandOutput,\n UpdateFunctionCodeCommand,\n type UpdateFunctionCodeCommandInput,\n type UpdateFunctionCodeCommandOutput,\n UpdateFunctionConfigurationCommand,\n type UpdateFunctionConfigurationCommandInput,\n type UpdateFunctionConfigurationCommandOutput,\n waitUntilFunctionUpdatedV2,\n} from '@aws-sdk/client-lambda';\nimport {\n GetHostedZoneCommand,\n type GetHostedZoneCommandInput,\n type GetHostedZoneCommandOutput,\n ListHostedZonesByNameCommand,\n type ListHostedZonesByNameCommandInput,\n type ListHostedZonesByNameCommandOutput,\n ListHostedZonesCommand,\n type ListHostedZonesCommandInput,\n type ListHostedZonesCommandOutput,\n Route53Client,\n} from '@aws-sdk/client-route-53';\nimport {\n type CompleteMultipartUploadCommandOutput,\n DeleteObjectsCommand,\n DeleteObjectsCommandInput,\n DeleteObjectsCommandOutput,\n DeleteObjectTaggingCommand,\n DeleteObjectTaggingCommandInput,\n DeleteObjectTaggingCommandOutput,\n GetBucketEncryptionCommand,\n type GetBucketEncryptionCommandInput,\n type GetBucketEncryptionCommandOutput,\n GetBucketLocationCommand,\n type GetBucketLocationCommandInput,\n type GetBucketLocationCommandOutput,\n GetObjectCommand,\n type GetObjectCommandInput,\n type GetObjectCommandOutput,\n GetObjectTaggingCommand,\n GetObjectTaggingCommandInput,\n GetObjectTaggingCommandOutput,\n ListObjectsV2Command,\n type ListObjectsV2CommandInput,\n type ListObjectsV2CommandOutput,\n type PutObjectCommandInput,\n PutObjectTaggingCommand,\n PutObjectTaggingCommandInput,\n PutObjectTaggingCommandOutput,\n S3Client,\n} from '@aws-sdk/client-s3';\nimport {\n GetSecretValueCommand,\n type GetSecretValueCommandInput,\n type GetSecretValueCommandOutput,\n SecretsManagerClient,\n} from '@aws-sdk/client-secrets-manager';\nimport {\n SFNClient,\n UpdateStateMachineCommand,\n UpdateStateMachineCommandInput,\n UpdateStateMachineCommandOutput,\n} from '@aws-sdk/client-sfn';\nimport {\n GetParameterCommand,\n type GetParameterCommandInput,\n type GetParameterCommandOutput,\n SSMClient,\n} from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { ConfiguredRetryStrategy } from '@smithy/util-retry';\nimport { WaiterResult } from '@smithy/util-waiter';\nimport { AccountAccessKeyCache } from './account-cache';\nimport { cachedAsync } from './cached';\nimport { Account } from './sdk-provider';\nimport { traceMemberMethods } from './tracing';\nimport { defaultCliUserAgent } from './user-agent';\nimport { debug } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\n\nexport interface S3ClientOptions {\n /**\n * If APIs are used that require MD5 checksums.\n *\n * Some S3 APIs in SDKv2 have a bug that always requires them to use a MD5 checksum.\n * These APIs are not going to be supported in a FIPS environment.\n */\n needsMd5Checksums?: boolean;\n}\n\n/**\n * Additional SDK configuration options\n */\nexport interface SdkOptions {\n /**\n * Additional descriptive strings that indicate where the \"AssumeRole\" credentials are coming from\n *\n * Will be printed in an error message to help users diagnose auth problems.\n */\n readonly assumeRoleCredentialsSourceDescription?: string;\n}\n\n// TODO: still some cleanup here. Make the pagination functions do all the work here instead of in individual packages.\n// Also add async/await. Does that actually matter in this context? Find out and update accordingly.\n\n// Also add notes to the PR about why you imported everything individually and used 'type' so reviewers don't have to ask.\n\nexport interface ConfigurationOptions {\n region: string;\n credentials: AwsCredentialIdentityProvider;\n requestHandler: NodeHttpHandlerOptions;\n retryStrategy: ConfiguredRetryStrategy;\n customUserAgent: string;\n logger?: Logger;\n s3DisableBodySigning?: boolean;\n computeChecksums?: boolean;\n}\n\nexport interface IAppSyncClient {\n getSchemaCreationStatus(input: GetSchemaCreationStatusCommandInput): Promise<GetSchemaCreationStatusCommandOutput>;\n startSchemaCreation(input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput>;\n updateApiKey(input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput>;\n updateFunction(input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput>;\n updateResolver(input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput>;\n // Pagination functions\n listFunctions(input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]>;\n}\n\nexport interface ICloudControlClient{\n listResources(input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput>;\n getResource(input: GetResourceCommandInput): Promise<GetResourceCommandOutput>;\n}\n\nexport interface ICloudFormationClient {\n continueUpdateRollback(input: ContinueUpdateRollbackCommandInput): Promise<ContinueUpdateRollbackCommandOutput>;\n createChangeSet(input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput>;\n createGeneratedTemplate(input: CreateGeneratedTemplateCommandInput): Promise<CreateGeneratedTemplateCommandOutput>;\n createStack(input: CreateStackCommandInput): Promise<CreateStackCommandOutput>;\n deleteChangeSet(input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput>;\n deleteGeneratedTemplate(input: DeleteGeneratedTemplateCommandInput): Promise<DeleteGeneratedTemplateCommandOutput>;\n deleteStack(input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput>;\n describeChangeSet(input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput>;\n describeGeneratedTemplate(\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput>;\n describeResourceScan(input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput>;\n describeStacks(input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput>;\n describeStackResources(input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput>;\n executeChangeSet(input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput>;\n getGeneratedTemplate(input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput>;\n getTemplate(input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput>;\n getTemplateSummary(input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput>;\n listExports(input: ListExportsCommandInput): Promise<ListExportsCommandOutput>;\n listResourceScanRelatedResources(\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput>;\n listResourceScanResources(\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput>;\n listResourceScans(input?: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput>;\n listStacks(input: ListStacksCommandInput): Promise<ListStacksCommandOutput>;\n rollbackStack(input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput>;\n startResourceScan(input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput>;\n updateStack(input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput>;\n updateTerminationProtection(\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput>;\n // Pagination functions\n describeStackEvents(input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput>;\n listStackResources(input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]>;\n}\n\nexport interface ICloudWatchLogsClient {\n describeLogGroups(input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput>;\n filterLogEvents(input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput>;\n}\n\nexport interface ICodeBuildClient {\n updateProject(input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput>;\n}\nexport interface IEC2Client {\n describeAvailabilityZones(\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput>;\n describeImages(input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput>;\n describeInstances(input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput>;\n describeRouteTables(input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput>;\n describeSecurityGroups(input: DescribeSecurityGroupsCommandInput): Promise<DescribeSecurityGroupsCommandOutput>;\n describeSubnets(input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput>;\n describeVpcEndpointServices(\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput>;\n describeVpcs(input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput>;\n describeVpnGateways(input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput>;\n}\n\nexport interface IECRClient {\n batchDeleteImage(input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput>;\n batchGetImage(input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput>;\n createRepository(input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput>;\n describeImages(input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput>;\n describeRepositories(input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput>;\n getAuthorizationToken(input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput>;\n listImages(input: ListImagesCommandInput): Promise<ListImagesCommandOutput>;\n putImage(input: PutImageCommandInput): Promise<PutImageCommandOutput>;\n putImageScanningConfiguration(\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput>;\n}\n\nexport interface IECSClient {\n listClusters(input: ListClustersCommandInput): Promise<ListClustersCommandOutput>;\n registerTaskDefinition(input: RegisterTaskDefinitionCommandInput): Promise<RegisterTaskDefinitionCommandOutput>;\n updateService(input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput>;\n // Waiters\n waitUntilServicesStable(input: DescribeServicesCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IElasticLoadBalancingV2Client {\n describeListeners(input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput>;\n describeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput>;\n describeTags(input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput>;\n // Pagination\n paginateDescribeListeners(input: DescribeListenersCommandInput): Promise<Listener[]>;\n paginateDescribeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]>;\n}\n\nexport interface IIAMClient {\n createPolicy(input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput>;\n getPolicy(input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput>;\n getRole(input: GetRoleCommandInput): Promise<GetRoleCommandOutput>;\n}\n\nexport interface IKMSClient {\n describeKey(input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput>;\n listAliases(input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput>;\n}\n\nexport interface ILambdaClient {\n invokeCommand(input: InvokeCommandInput): Promise<InvokeCommandOutput>;\n publishVersion(input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput>;\n updateAlias(input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput>;\n updateFunctionCode(input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput>;\n updateFunctionConfiguration(\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput>;\n // Waiters\n waitUntilFunctionUpdated(delaySeconds: number, input: UpdateFunctionConfigurationCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IRoute53Client {\n getHostedZone(input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput>;\n listHostedZones(input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput>;\n listHostedZonesByName(input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput>;\n}\n\nexport interface IS3Client {\n deleteObjects(input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput>;\n deleteObjectTagging(input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput>;\n getBucketEncryption(input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput>;\n getBucketLocation(input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput>;\n getObject(input: GetObjectCommandInput): Promise<GetObjectCommandOutput>;\n getObjectTagging(input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput>;\n listObjectsV2(input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput>;\n putObjectTagging(input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput>;\n upload(input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput>;\n}\n\nexport interface ISecretsManagerClient {\n getSecretValue(input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput>;\n}\n\nexport interface ISSMClient {\n getParameter(input: GetParameterCommandInput): Promise<GetParameterCommandOutput>;\n}\n\nexport interface IStepFunctionsClient {\n updateStateMachine(input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput>;\n}\n\n/**\n * Base functionality of SDK without credential fetching\n */\n@traceMemberMethods\nexport class SDK {\n private static readonly accountCache = new AccountAccessKeyCache();\n\n public readonly currentRegion: string;\n\n public readonly config: ConfigurationOptions;\n\n protected readonly logger?: Logger;\n\n /**\n * STS is used to check credential validity, don't do too many retries.\n */\n private readonly stsRetryStrategy = new ConfiguredRetryStrategy(3, (attempt) => 100 * (2 ** attempt));\n\n /**\n * Whether we have proof that the credentials have not expired\n *\n * We need to do some manual plumbing around this because the JS SDKv2 treats `ExpiredToken`\n * as retriable and we have hefty retries on CFN calls making the CLI hang for a good 15 minutes\n * if the credentials have expired.\n */\n private _credentialsValidated = false;\n\n constructor(\n private readonly credProvider: AwsCredentialIdentityProvider,\n region: string,\n requestHandler: NodeHttpHandlerOptions,\n logger?: Logger,\n ) {\n this.config = {\n region,\n credentials: credProvider,\n requestHandler,\n retryStrategy: new ConfiguredRetryStrategy(7, (attempt) => 300 * (2 ** attempt)),\n customUserAgent: defaultCliUserAgent(),\n logger,\n };\n this.logger = logger;\n this.currentRegion = region;\n }\n\n public appendCustomUserAgent(userAgentData?: string): void {\n if (!userAgentData) {\n return;\n }\n\n const currentCustomUserAgent = this.config.customUserAgent;\n this.config.customUserAgent = currentCustomUserAgent ? `${currentCustomUserAgent} ${userAgentData}` : userAgentData;\n }\n\n public removeCustomUserAgent(userAgentData: string): void {\n this.config.customUserAgent = this.config.customUserAgent?.replace(userAgentData, '');\n }\n\n public appsync(): IAppSyncClient {\n const client = new AppSyncClient(this.config);\n return {\n getSchemaCreationStatus: (\n input: GetSchemaCreationStatusCommandInput,\n ): Promise<GetSchemaCreationStatusCommandOutput> => client.send(new GetSchemaCreationStatusCommand(input)),\n startSchemaCreation: (input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput> =>\n client.send(new StartSchemaCreationCommand(input)),\n updateApiKey: (input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput> =>\n client.send(new UpdateApiKeyCommand(input)),\n updateFunction: (input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput> =>\n client.send(new UpdateFunctionCommand(input)),\n updateResolver: (input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput> =>\n client.send(new UpdateResolverCommand(input)),\n\n // Pagination Functions\n listFunctions: async (input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]> => {\n const functions = Array<FunctionConfiguration>();\n const paginator = paginateListFunctions({ client }, input);\n for await (const page of paginator) {\n functions.push(...(page.functions || []));\n }\n return functions;\n },\n };\n }\n\n public cloudControl(): ICloudControlClient {\n const client = new CloudControlClient(this.config);\n return {\n listResources: (input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput> =>\n client.send(new ListResourcesCommand(input)),\n getResource: (input: GetResourceCommandInput): Promise<GetResourceCommandOutput> =>\n client.send(new GetResourceCommand(input)),\n };\n }\n\n public cloudFormation(): ICloudFormationClient {\n const client = new CloudFormationClient({\n ...this.config,\n retryStrategy: new ConfiguredRetryStrategy(11, (attempt: number) => 1000 * (2 ** attempt)),\n });\n return {\n continueUpdateRollback: async (\n input: ContinueUpdateRollbackCommandInput,\n ): Promise<ContinueUpdateRollbackCommandOutput> => client.send(new ContinueUpdateRollbackCommand(input)),\n createChangeSet: (input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput> =>\n client.send(new CreateChangeSetCommand(input)),\n createGeneratedTemplate: (\n input: CreateGeneratedTemplateCommandInput,\n ): Promise<CreateGeneratedTemplateCommandOutput> => client.send(new CreateGeneratedTemplateCommand(input)),\n createStack: (input: CreateStackCommandInput): Promise<CreateStackCommandOutput> =>\n client.send(new CreateStackCommand(input)),\n deleteChangeSet: (input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput> =>\n client.send(new DeleteChangeSetCommand(input)),\n deleteGeneratedTemplate: (\n input: DeleteGeneratedTemplateCommandInput,\n ): Promise<DeleteGeneratedTemplateCommandOutput> => client.send(new DeleteGeneratedTemplateCommand(input)),\n deleteStack: (input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput> =>\n client.send(new DeleteStackCommand(input)),\n describeChangeSet: (input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput> =>\n client.send(new DescribeChangeSetCommand(input)),\n describeGeneratedTemplate: (\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput> => client.send(new DescribeGeneratedTemplateCommand(input)),\n describeResourceScan: (input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput> =>\n client.send(new DescribeResourceScanCommand(input)),\n describeStacks: (input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput> =>\n client.send(new DescribeStacksCommand(input)),\n describeStackResources: (input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput> =>\n client.send(new DescribeStackResourcesCommand(input)),\n executeChangeSet: (input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput> =>\n client.send(new ExecuteChangeSetCommand(input)),\n getGeneratedTemplate: (input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput> =>\n client.send(new GetGeneratedTemplateCommand(input)),\n getTemplate: (input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput> =>\n client.send(new GetTemplateCommand(input)),\n getTemplateSummary: (input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput> =>\n client.send(new GetTemplateSummaryCommand(input)),\n listExports: (input: ListExportsCommandInput): Promise<ListExportsCommandOutput> =>\n client.send(new ListExportsCommand(input)),\n listResourceScanRelatedResources: (\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput> =>\n client.send(new ListResourceScanRelatedResourcesCommand(input)),\n listResourceScanResources: (\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput> => client.send(new ListResourceScanResourcesCommand(input)),\n listResourceScans: (input: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput> =>\n client.send(new ListResourceScansCommand(input)),\n listStacks: (input: ListStacksCommandInput): Promise<ListStacksCommandOutput> =>\n client.send(new ListStacksCommand(input)),\n rollbackStack: (input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput> =>\n client.send(new RollbackStackCommand(input)),\n startResourceScan: (input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput> =>\n client.send(new StartResourceScanCommand(input)),\n updateStack: (input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput> =>\n client.send(new UpdateStackCommand(input)),\n updateTerminationProtection: (\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput> =>\n client.send(new UpdateTerminationProtectionCommand(input)),\n describeStackEvents: (input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput> => {\n return client.send(new DescribeStackEventsCommand(input));\n },\n listStackResources: async (input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]> => {\n const stackResources = Array<StackResourceSummary>();\n const paginator = paginateListStackResources({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackResourceSummaries || []));\n }\n return stackResources;\n },\n };\n }\n\n public cloudWatchLogs(): ICloudWatchLogsClient {\n const client = new CloudWatchLogsClient(this.config);\n return {\n describeLogGroups: (input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput> =>\n client.send(new DescribeLogGroupsCommand(input)),\n filterLogEvents: (input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput> =>\n client.send(new FilterLogEventsCommand(input)),\n };\n }\n\n public codeBuild(): ICodeBuildClient {\n const client = new CodeBuildClient(this.config);\n return {\n updateProject: (input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput> =>\n client.send(new UpdateProjectCommand(input)),\n };\n }\n\n public ec2(): IEC2Client {\n const client = new EC2Client(this.config);\n return {\n describeAvailabilityZones: (\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput> => client.send(new DescribeAvailabilityZonesCommand(input)),\n describeImages: (input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput> =>\n client.send(new DescribeImagesCommand(input)),\n describeInstances: (input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput> =>\n client.send(new DescribeInstancesCommand(input)),\n describeRouteTables: (input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput> =>\n client.send(new DescribeRouteTablesCommand(input)),\n describeSecurityGroups: (\n input: DescribeSecurityGroupsCommandInput,\n ): Promise<DescribeSecurityGroupsCommandOutput> => client.send(new DescribeSecurityGroupsCommand(input)),\n describeSubnets: (input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput> =>\n client.send(new DescribeSubnetsCommand(input)),\n describeVpcEndpointServices: (\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput> =>\n client.send(new DescribeVpcEndpointServicesCommand(input)),\n describeVpcs: (input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput> =>\n client.send(new DescribeVpcsCommand(input)),\n describeVpnGateways: (input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput> =>\n client.send(new DescribeVpnGatewaysCommand(input)),\n };\n }\n\n public ecr(): IECRClient {\n const client = new ECRClient(this.config);\n return {\n batchDeleteImage: (input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput> =>\n client.send(new BatchDeleteImageCommand(input)),\n batchGetImage: (input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput> =>\n client.send(new BatchGetImageCommand(input)),\n createRepository: (input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput> =>\n client.send(new CreateRepositoryCommand(input)),\n describeImages: (input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput> =>\n client.send(new ECRDescribeImagesCommand(input)),\n describeRepositories: (input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput> =>\n client.send(new DescribeRepositoriesCommand(input)),\n getAuthorizationToken: (input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput> =>\n client.send(new GetAuthorizationTokenCommand(input)),\n listImages: (input: ListImagesCommandInput): Promise<ListImagesCommandOutput> =>\n client.send(new ListImagesCommand(input)),\n putImage: (input: PutImageCommandInput): Promise<PutImageCommandOutput> =>\n client.send(new PutImageCommand(input)),\n putImageScanningConfiguration: (\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput> =>\n client.send(new PutImageScanningConfigurationCommand(input)),\n };\n }\n\n public ecs(): IECSClient {\n const client = new ECSClient(this.config);\n return {\n listClusters: (input: ListClustersCommandInput): Promise<ListClustersCommandOutput> =>\n client.send(new ListClustersCommand(input)),\n registerTaskDefinition: (\n input: RegisterTaskDefinitionCommandInput,\n ): Promise<RegisterTaskDefinitionCommandOutput> => client.send(new RegisterTaskDefinitionCommand(input)),\n updateService: (input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput> =>\n client.send(new UpdateServiceCommand(input)),\n // Waiters\n waitUntilServicesStable: (input: DescribeServicesCommandInput): Promise<WaiterResult> => {\n return waitUntilServicesStable(\n {\n client,\n maxWaitTime: 600,\n minDelay: 6,\n maxDelay: 6,\n },\n input,\n );\n },\n };\n }\n\n public elbv2(): IElasticLoadBalancingV2Client {\n const client = new ElasticLoadBalancingV2Client(this.config);\n return {\n describeListeners: (input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput> =>\n client.send(new DescribeListenersCommand(input)),\n describeLoadBalancers: (input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput> =>\n client.send(new DescribeLoadBalancersCommand(input)),\n describeTags: (input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput> =>\n client.send(new DescribeTagsCommand(input)),\n // Pagination Functions\n paginateDescribeListeners: async (input: DescribeListenersCommandInput): Promise<Listener[]> => {\n const listeners = Array<Listener>();\n const paginator = paginateDescribeListeners({ client }, input);\n for await (const page of paginator) {\n listeners.push(...(page?.Listeners || []));\n }\n return listeners;\n },\n paginateDescribeLoadBalancers: async (input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]> => {\n const loadBalancers = Array<LoadBalancer>();\n const paginator = paginateDescribeLoadBalancers({ client }, input);\n for await (const page of paginator) {\n loadBalancers.push(...(page?.LoadBalancers || []));\n }\n return loadBalancers;\n },\n };\n }\n\n public iam(): IIAMClient {\n const client = new IAMClient(this.config);\n return {\n createPolicy: (input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput> =>\n client.send(new CreatePolicyCommand(input)),\n getPolicy: (input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput> =>\n client.send(new GetPolicyCommand(input)),\n getRole: (input: GetRoleCommandInput): Promise<GetRoleCommandOutput> => client.send(new GetRoleCommand(input)),\n };\n }\n\n public kms(): IKMSClient {\n const client = new KMSClient(this.config);\n return {\n describeKey: (input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput> =>\n client.send(new DescribeKeyCommand(input)),\n listAliases: (input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput> =>\n client.send(new ListAliasesCommand(input)),\n };\n }\n\n public lambda(): ILambdaClient {\n const client = new LambdaClient(this.config);\n return {\n invokeCommand: (input: InvokeCommandInput): Promise<InvokeCommandOutput> => client.send(new InvokeCommand(input)),\n publishVersion: (input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput> =>\n client.send(new PublishVersionCommand(input)),\n updateAlias: (input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput> =>\n client.send(new UpdateAliasCommand(input)),\n updateFunctionCode: (input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput> =>\n client.send(new UpdateFunctionCodeCommand(input)),\n updateFunctionConfiguration: (\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput> =>\n client.send(new UpdateFunctionConfigurationCommand(input)),\n // Waiters\n waitUntilFunctionUpdated: (\n delaySeconds: number,\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<WaiterResult> => {\n return waitUntilFunctionUpdatedV2(\n {\n client,\n maxDelay: delaySeconds,\n minDelay: delaySeconds,\n maxWaitTime: delaySeconds * 60,\n },\n input,\n );\n },\n };\n }\n\n public route53(): IRoute53Client {\n const client = new Route53Client(this.config);\n return {\n getHostedZone: (input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput> =>\n client.send(new GetHostedZoneCommand(input)),\n listHostedZones: (input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput> =>\n client.send(new ListHostedZonesCommand(input)),\n listHostedZonesByName: (input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput> =>\n client.send(new ListHostedZonesByNameCommand(input)),\n };\n }\n\n public s3(): IS3Client {\n const client = new S3Client(this.config);\n return {\n deleteObjects: (input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput> =>\n client.send(new DeleteObjectsCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n deleteObjectTagging: (input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput> =>\n client.send(new DeleteObjectTaggingCommand(input)),\n getBucketEncryption: (input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput> =>\n client.send(new GetBucketEncryptionCommand(input)),\n getBucketLocation: (input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput> =>\n client.send(new GetBucketLocationCommand(input)),\n getObject: (input: GetObjectCommandInput): Promise<GetObjectCommandOutput> =>\n client.send(new GetObjectCommand(input)),\n getObjectTagging: (input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput> =>\n client.send(new GetObjectTaggingCommand(input)),\n listObjectsV2: (input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput> =>\n client.send(new ListObjectsV2Command(input)),\n putObjectTagging: (input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput> =>\n client.send(new PutObjectTaggingCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n upload: (input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput> => {\n try {\n const upload = new Upload({\n client,\n params: { ...input, ChecksumAlgorithm: 'SHA256' },\n });\n\n return upload.done();\n } catch (e: any) {\n throw new AuthenticationError(`Upload failed: ${formatErrorMessage(e)}`);\n }\n },\n };\n }\n\n public secretsManager(): ISecretsManagerClient {\n const client = new SecretsManagerClient(this.config);\n return {\n getSecretValue: (input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput> =>\n client.send(new GetSecretValueCommand(input)),\n };\n }\n\n public ssm(): ISSMClient {\n const client = new SSMClient(this.config);\n return {\n getParameter: (input: GetParameterCommandInput): Promise<GetParameterCommandOutput> =>\n client.send(new GetParameterCommand(input)),\n };\n }\n\n public stepFunctions(): IStepFunctionsClient {\n const client = new SFNClient(this.config);\n return {\n updateStateMachine: (input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput> =>\n client.send(new UpdateStateMachineCommand(input)),\n };\n }\n\n /**\n * The AWS SDK v3 requires a client config and a command in order to get an endpoint for\n * any given service.\n */\n public async getUrlSuffix(region: string): Promise<string> {\n const cfn = new CloudFormationClient({ region });\n const endpoint = await getEndpointFromInstructions({}, DescribeStackResourcesCommand, { ...cfn.config });\n return endpoint.url.hostname.split(`${region}.`).pop()!;\n }\n\n public async currentAccount(): Promise<Account> {\n return cachedAsync(this, CURRENT_ACCOUNT_KEY, async () => {\n const creds = await this.credProvider();\n return SDK.accountCache.fetch(creds.accessKeyId, async () => {\n // if we don't have one, resolve from STS and store in cache.\n debug('Looking up default account ID from STS');\n const client = new STSClient({\n ...this.config,\n retryStrategy: this.stsRetryStrategy,\n });\n const command = new GetCallerIdentityCommand({});\n const result = await client.send(command);\n const accountId = result.Account;\n const partition = result.Arn!.split(':')[1];\n if (!accountId) {\n throw new AuthenticationError(\"STS didn't return an account ID\");\n }\n debug('Default account ID:', accountId);\n\n // Save another STS call later if this one already succeeded\n this._credentialsValidated = true;\n return { accountId, partition };\n });\n });\n }\n\n /**\n * Make sure the the current credentials are not expired\n */\n public async validateCredentials() {\n if (this._credentialsValidated) {\n return;\n }\n\n const client = new STSClient({ ...this.config, retryStrategy: this.stsRetryStrategy });\n await client.send(new GetCallerIdentityCommand({}));\n this._credentialsValidated = true;\n }\n}\n\nconst CURRENT_ACCOUNT_KEY = Symbol('current_account_key');\n", "import * as path from 'path';\nimport * as fs from 'fs-extra';\nimport { Account } from './sdk-provider';\nimport { debug } from '../../logging';\nimport { cdkCacheDir } from '../../util/directories';\n\n/**\n * Disk cache which maps access key IDs to account IDs.\n * Usage:\n * cache.get(accessKey) => accountId | undefined\n * cache.put(accessKey, accountId)\n */\nexport class AccountAccessKeyCache {\n /**\n * Max number of entries in the cache, after which the cache will be reset.\n */\n public static readonly MAX_ENTRIES = 1000;\n\n private readonly cacheFile: string;\n\n /**\n * @param filePath Path to the cache file\n */\n constructor(filePath?: string) {\n this.cacheFile = filePath || path.join(cdkCacheDir(), 'accounts_partitions.json');\n }\n\n /**\n * Tries to fetch the account ID from cache. If it's not in the cache, invokes\n * the resolver function which should retrieve the account ID and return it.\n * Then, it will be stored into disk cache returned.\n *\n * Example:\n *\n * const accountId = cache.fetch(accessKey, async () => {\n * return await fetchAccountIdFromSomewhere(accessKey);\n * });\n */\n public async fetch<A extends Account>(accessKeyId: string, resolver: () => Promise<A>) {\n // try to get account ID based on this access key ID from disk.\n const cached = await this.get(accessKeyId);\n if (cached) {\n debug(`Retrieved account ID ${cached.accountId} from disk cache`);\n return cached;\n }\n\n // if it's not in the cache, resolve and put in cache.\n const account = await resolver();\n if (account) {\n await this.put(accessKeyId, account);\n }\n\n return account;\n }\n\n /** Get the account ID from an access key or undefined if not in cache */\n public async get(accessKeyId: string): Promise<Account | undefined> {\n const map = await this.loadMap();\n return map[accessKeyId];\n }\n\n /** Put a mapping between access key and account ID */\n public async put(accessKeyId: string, account: Account) {\n let map = await this.loadMap();\n\n // nuke cache if it's too big.\n if (Object.keys(map).length >= AccountAccessKeyCache.MAX_ENTRIES) {\n map = {};\n }\n\n map[accessKeyId] = account;\n await this.saveMap(map);\n }\n\n private async loadMap(): Promise<{ [accessKeyId: string]: Account }> {\n try {\n return await fs.readJson(this.cacheFile);\n } catch (e: any) {\n // File doesn't exist or is not readable. This is a cache,\n // pretend we successfully loaded an empty map.\n if (e.code === 'ENOENT' || e.code === 'EACCES') {\n return {};\n }\n // File is not JSON, could be corrupted because of concurrent writes.\n // Again, an empty cache is fine.\n if (e instanceof SyntaxError) {\n return {};\n }\n throw e;\n }\n }\n\n private async saveMap(map: { [accessKeyId: string]: Account }) {\n try {\n await fs.ensureFile(this.cacheFile);\n await fs.writeJson(this.cacheFile, map, { spaces: 2 });\n } catch (e: any) {\n // File doesn't exist or file/dir isn't writable. This is a cache,\n // if we can't write it then too bad.\n if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'EROFS') {\n return;\n }\n throw e;\n }\n }\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport { IoMessageLevel, IoMessage, CliIoHost, IoMessageSpecificCode, IoMessageCode, IoMessageCodeCategory, IoCodeLevel } from './toolkit/cli-io-host';\n\n/**\n * Internal helper that processes log inputs into a consistent format.\n * Handles string interpolation, format strings, and object parameter styles.\n * Applies optional styling and sends the message to the IoHost.\n */\nfunction formatMessageAndLog(\n level: IoMessageLevel,\n input: LogInput<IoCodeLevel>,\n style?: (str: string) => string,\n ...args: unknown[]\n): void {\n // Extract message and code from input, using new default code format\n const { message, code = getDefaultCode(level) } = typeof input === 'object' ? input : { message: input };\n\n // Format message if args are provided\n const formattedMessage = args.length > 0\n ? util.format(message, ...args)\n : message;\n\n // Apply style if provided\n const finalMessage = style ? style(formattedMessage) : formattedMessage;\n\n const ioHost = CliIoHost.instance();\n const ioMessage: IoMessage<undefined> = {\n time: new Date(),\n action: ioHost.currentAction,\n level,\n message: finalMessage,\n code,\n };\n\n void ioHost.notify(ioMessage);\n}\n\nfunction getDefaultCode(level: IoMessageLevel, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessageCode {\n const levelIndicator = level === 'error' ? 'E' :\n level === 'warn' ? 'W' :\n 'I';\n return `CDK_${category}_${levelIndicator}0000`;\n}\n\n// Type for the object parameter style\ninterface LogParams<L extends IoCodeLevel> {\n /**\n * @see {@link IoMessage.code}\n */\n readonly code?: IoMessageSpecificCode<L>;\n /**\n * @see {@link IoMessage.message}\n */\n readonly message: string;\n}\n\n// Type for the exported log function arguments\ntype LogInput<L extends IoCodeLevel> = string | LogParams<L>;\n\n// Exported logging functions. If any additional logging functionality is required, it should be added as\n// a new logging function here.\n\n/**\n * Logs an error level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * error(`operation failed: ${e}`) // infers default error code `CDK_TOOLKIT_E000`\n * error('operation failed: %s', e) // infers default error code `CDK_TOOLKIT_E000`\n * error({ message: 'operation failed', code: 'CDK_SDK_E001' }) // specifies error code `CDK_SDK_E001`\n * error({ message: 'operation failed: %s', code: 'CDK_SDK_E001' }, e) // specifies error code `CDK_SDK_E001`\n * ```\n */\nexport const error = (input: LogInput<'E'>, ...args: unknown[]) => {\n return formatMessageAndLog('error', input, undefined, ...args);\n};\n\n/**\n * Logs an warning level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * warning(`deprected feature: ${message}`) // infers default warning code `CDK_TOOLKIT_W000`\n * warning('deprected feature: %s', message) // infers default warning code `CDK_TOOLKIT_W000`\n * warning({ message: 'deprected feature', code: 'CDK_SDK_W001' }) // specifies warning code `CDK_SDK_W001`\n * warning({ message: 'deprected feature: %s', code: 'CDK_SDK_W001' }, message) // specifies warning code `CDK_SDK_W001`\n * ```\n */\nexport const warning = (input: LogInput<'W'>, ...args: unknown[]) => {\n return formatMessageAndLog('warn', input, undefined, ...args);\n};\n\n/**\n * Logs an info level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * info(`processing: ${message}`) // infers default info code `CDK_TOOLKIT_I000`\n * info('processing: %s', message) // infers default info code `CDK_TOOLKIT_I000`\n * info({ message: 'processing', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * info({ message: 'processing: %s', code: 'CDK_TOOLKIT_I001' }, message) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const info = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, undefined, ...args);\n};\n\n/**\n * Logs an result. In the CLI, this always goes to stdout.\n *\n * Can be used in multiple ways:\n * ```ts\n * result(`${JSON.stringify(stats)}`) // infers default info code `CDK_TOOLKIT_I000`\n * result('{\"count\": %d}', count) // infers default info code `CDK_TOOLKIT_I000`\n * result({ message: 'stats: %j', code: 'CDK_DATA_I001' }) // specifies info code `CDK_DATA_I001`\n * result({ message: 'stats: %j', code: 'CDK_DATA_I001' }, stats) // specifies info code `CDK_DATA_I001`\n * ```\n */\nexport const result = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('result', input, undefined, ...args);\n};\n\n/**\n * Logs a debug level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * debug(`state: ${JSON.stringify(state)}`) // infers default info code `CDK_TOOLKIT_I000`\n * debug('cache hit ratio: %d%%', ratio) // infers default info code `CDK_TOOLKIT_I000`\n * debug({ message: 'state update', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * debug({ message: 'ratio: %d%%', code: 'CDK_TOOLKIT_I001' }, ratio) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const debug = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('debug', input, undefined, ...args);\n};\n\n/**\n * Logs a trace level message.\n *\n * Can be used in multiple ways:\n * ```ts\n * trace(`entered ${name} with ${args}`) // infers default info code `CDK_TOOLKIT_I000`\n * trace('method: %s, args: %j', name, args) // infers default info code `CDK_TOOLKIT_I000`\n * trace({ message: 'entered', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * trace({ message: 'method: %s', code: 'CDK_TOOLKIT_I001' }, name) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const trace = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('trace', input, undefined, ...args);\n};\n\n/**\n * Logs an info level success message in green text.\n *\n * Can be used in multiple ways:\n * ```ts\n * success(`deployment completed: ${name}`) // infers default info code `CDK_TOOLKIT_I000`\n * success('processed %d items', count) // infers default info code `CDK_TOOLKIT_I000`\n * success({ message: 'completed', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * success({ message: 'items: %d', code: 'CDK_TOOLKIT_I001' }, count) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const success = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, chalk.green, ...args);\n};\n\n/**\n * Logs an info level message in bold text.\n *\n * Can be used in multiple ways:\n * ```ts\n * highlight(`important: ${msg}`) // infers default info code `CDK_TOOLKIT_I000`\n * highlight('attention required: %s', reason) // infers default info code `CDK_TOOLKIT_I000`\n * highlight({ message: 'notice', code: 'CDK_TOOLKIT_I001' }) // specifies info code `CDK_TOOLKIT_I001`\n * highlight({ message: 'notice: %s', code: 'CDK_TOOLKIT_I001' }, msg) // specifies info code `CDK_TOOLKIT_I001`\n * ```\n */\nexport const highlight = (input: LogInput<'I'>, ...args: unknown[]) => {\n return formatMessageAndLog('info', input, chalk.bold, ...args);\n};\n", "import * as util from 'node:util';\nimport * as chalk from 'chalk';\nimport * as promptly from 'promptly';\nimport { ToolkitError } from './error';\nimport { ActivityPrinterProps, CurrentActivityPrinter, HistoryActivityPrinter, IActivityPrinter } from '../cli/activity-printer';\nimport { StackActivityProgress } from '../commands/deploy';\n\nexport type IoMessageCodeCategory = 'TOOLKIT' | 'SDK' | 'ASSETS';\nexport type IoCodeLevel = 'E' | 'W' | 'I';\nexport type IoMessageSpecificCode<L extends IoCodeLevel> = `CDK_${IoMessageCodeCategory}_${L}${number}${number}${number}${number}`;\nexport type IoMessageCode = IoMessageSpecificCode<IoCodeLevel>;\n\n/**\n * Basic message structure for toolkit notifications.\n * Messages are emitted by the toolkit and handled by the IoHost.\n */\nexport interface IoMessage<T> {\n /**\n * The time the message was emitted.\n */\n readonly time: Date;\n\n /**\n * The log level of the message.\n */\n readonly level: IoMessageLevel;\n\n /**\n * The action that triggered the message.\n */\n readonly action: ToolkitAction;\n\n /**\n * A short message code uniquely identifying a message type using the format CDK_[CATEGORY]_[E/W/I][000-999].\n *\n * The level indicator follows these rules:\n * - 'E' for error level messages\n * - 'W' for warning level messages\n * - 'I' for info/debug/trace level messages\n *\n * Codes ending in 000 are generic messages, while codes ending in 001-999 are specific to a particular message.\n * The following are examples of valid and invalid message codes:\n * ```ts\n * 'CDK_ASSETS_I000' // valid: generic assets info message\n * 'CDK_TOOLKIT_E002' // valid: specific toolkit error message\n * 'CDK_SDK_W023' // valid: specific sdk warning message\n * ```\n */\n readonly code: IoMessageCode;\n\n /**\n * The message text.\n */\n readonly message: string;\n\n /**\n * The data attached to the message.\n */\n readonly data?: T;\n}\n\nexport interface IoRequest<T, U> extends IoMessage<T> {\n /**\n * The default response that will be used if no data is returned.\n */\n readonly defaultResponse: U;\n}\n\nexport type IoMessageLevel = 'error' | 'result' | 'warn' | 'info' | 'debug' | 'trace';\n\nexport const levelPriority: Record<IoMessageLevel, number> = {\n error: 0,\n result: 1,\n warn: 2,\n info: 3,\n debug: 4,\n trace: 5,\n};\n\n/**\n * Temporary helper to group required props for IoMessages\n */\nexport interface IoMessaging {\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\n/**\n * The current action being performed by the CLI. 'none' represents the absence of an action.\n */\nexport type ToolkitAction =\n| 'assembly'\n| 'bootstrap'\n| 'synth'\n| 'list'\n| 'diff'\n| 'deploy'\n| 'rollback'\n| 'watch'\n| 'destroy'\n| 'context'\n| 'docs'\n| 'doctor'\n| 'gc'\n| 'import'\n| 'metadata'\n| 'notices'\n| 'init'\n| 'migrate'\n| 'version';\n\nexport interface IIoHost {\n /**\n * Notifies the host of a message.\n * The caller waits until the notification completes.\n */\n notify<T>(msg: IoMessage<T>): Promise<void>;\n\n /**\n * Notifies the host of a message that requires a response.\n *\n * If the host does not return a response the suggested\n * default response from the input message will be used.\n */\n requestResponse<T, U>(msg: IoRequest<T, U>): Promise<U>;\n}\n\nexport interface CliIoHostProps {\n /**\n * The initial Toolkit action the hosts starts with.\n *\n * @default 'none'\n */\n readonly currentAction?: ToolkitAction;\n\n /**\n * Determines the verbosity of the output.\n *\n * The CliIoHost will still receive all messages and requests,\n * but only the messages included in this level will be printed.\n *\n * @default 'info'\n */\n readonly logLevel?: IoMessageLevel;\n\n /**\n * Overrides the automatic TTY detection.\n *\n * When TTY is disabled, the CLI will have no interactions or color.\n *\n * @default - determined from the current process\n */\n readonly isTTY?: boolean;\n\n /**\n * Whether the CliIoHost is running in CI mode.\n *\n * In CI mode, all non-error output goes to stdout instead of stderr.\n * Set to false in the CliIoHost constructor it will be overwritten if the CLI CI argument is passed\n *\n * @default - determined from the environment, specifically based on `process.env.CI`\n */\n readonly isCI?: boolean;\n\n /**\n * The initial Toolkit action the hosts starts with.\n *\n * @default StackActivityProgress.BAR\n */\n readonly stackProgress?: StackActivityProgress;\n}\n\n/**\n * A simple IO host for the CLI that writes messages to the console.\n */\nexport class CliIoHost implements IIoHost {\n /**\n * Returns the singleton instance\n */\n static instance(props: CliIoHostProps = {}, forceNew = false): CliIoHost {\n if (forceNew || !CliIoHost._instance) {\n CliIoHost._instance = new CliIoHost(props);\n }\n return CliIoHost._instance;\n }\n\n /**\n * Singleton instance of the CliIoHost\n */\n private static _instance: CliIoHost | undefined;\n\n // internal state for getters/setter\n private _currentAction: ToolkitAction;\n private _isCI: boolean;\n private _isTTY: boolean;\n private _logLevel: IoMessageLevel;\n private _internalIoHost?: IIoHost;\n private _progress: StackActivityProgress = StackActivityProgress.BAR;\n\n // Stack Activity Printer\n private activityPrinter?: IActivityPrinter;\n\n // Corked Logging\n private corkedCounter = 0;\n private readonly corkedLoggingBuffer: IoMessage<any>[] = [];\n\n private constructor(props: CliIoHostProps = {}) {\n this._currentAction = props.currentAction ?? 'none' as ToolkitAction;\n this._isTTY = props.isTTY ?? process.stdout.isTTY ?? false;\n this._logLevel = props.logLevel ?? 'info';\n this._isCI = props.isCI ?? isCI();\n\n this.stackProgress = props.stackProgress ?? StackActivityProgress.BAR;\n }\n\n /**\n * Returns the singleton instance\n */\n public registerIoHost(ioHost: IIoHost) {\n if (ioHost !== this) {\n this._internalIoHost = ioHost;\n }\n }\n\n /**\n * Update the stackProgress preference.\n */\n public set stackProgress(type: StackActivityProgress) {\n this._progress = type;\n }\n\n /**\n * Gets the stackProgress value.\n *\n * This takes into account other state of the ioHost,\n * like if isTTY and isCI.\n */\n public get stackProgress(): StackActivityProgress {\n // We can always use EVENTS\n if (this._progress === StackActivityProgress.EVENTS) {\n return this._progress;\n }\n\n // if log level is tracing or debug, we default to the full history printer\n const verboseLogging = levelPriority[this.logLevel] > levelPriority.info;\n if (verboseLogging) {\n return StackActivityProgress.EVENTS;\n }\n\n // On Windows we cannot use fancy output\n const isWindows = process.platform === 'win32';\n if (isWindows) {\n return StackActivityProgress.EVENTS;\n }\n\n // On some CI systems (such as CircleCI) output still reports as a TTY so we also\n // need an individual check for whether we're running on CI.\n // see: https://discuss.circleci.com/t/circleci-terminal-is-a-tty-but-term-is-not-set/9965\n const fancyOutputAvailable = this.isTTY && !this.isCI;\n if (!fancyOutputAvailable) {\n return StackActivityProgress.EVENTS;\n }\n\n // Use the user preference\n return this._progress;\n }\n\n /**\n * The current action being performed by the CLI.\n */\n public get currentAction(): ToolkitAction {\n return this._currentAction;\n }\n\n /**\n * Sets the current action being performed by the CLI.\n *\n * @param action The action being performed by the CLI.\n */\n public set currentAction(action: ToolkitAction) {\n this._currentAction = action;\n }\n\n /**\n * Whether the host can use interactions and message styling.\n */\n public get isTTY(): boolean {\n return this._isTTY;\n }\n\n /**\n * Set TTY mode, i.e can the host use interactions and message styling.\n *\n * @param value set TTY mode\n */\n public set isTTY(value: boolean) {\n this._isTTY = value;\n }\n\n /**\n * Whether the CliIoHost is running in CI mode. In CI mode, all non-error output goes to stdout instead of stderr.\n */\n public get isCI(): boolean {\n return this._isCI;\n }\n\n /**\n * Set the CI mode. In CI mode, all non-error output goes to stdout instead of stderr.\n * @param value set the CI mode\n */\n public set isCI(value: boolean) {\n this._isCI = value;\n }\n\n /**\n * The current threshold. Messages with a lower priority level will be ignored.\n */\n public get logLevel(): IoMessageLevel {\n return this._logLevel;\n }\n\n /**\n * Sets the current threshold. Messages with a lower priority level will be ignored.\n * @param level The new log level threshold\n */\n public set logLevel(level: IoMessageLevel) {\n this._logLevel = level;\n }\n\n /**\n * Executes a block of code with corked logging. All log messages during execution\n * are buffered and only written when all nested cork blocks complete (when CORK_COUNTER reaches 0).\n * The corking is bound to the specific instance of the CliIoHost.\n *\n * @param block - Async function to execute with corked logging\n * @returns Promise that resolves with the block's return value\n */\n public async withCorkedLogging<T>(block: () => Promise<T>): Promise<T> {\n this.corkedCounter++;\n try {\n return await block();\n } finally {\n this.corkedCounter--;\n if (this.corkedCounter === 0) {\n // Process each buffered message through notify\n for (const ioMessage of this.corkedLoggingBuffer) {\n await this.notify(ioMessage);\n }\n // remove all buffered messages in-place\n this.corkedLoggingBuffer.splice(0);\n }\n }\n }\n\n /**\n * Notifies the host of a message.\n * The caller waits until the notification completes.\n */\n public async notify<T>(msg: IoMessage<T>): Promise<void> {\n if (this._internalIoHost) {\n return this._internalIoHost.notify(msg);\n }\n\n if (this.isStackActivity(msg)) {\n if (!this.activityPrinter) {\n this.activityPrinter = this.makeActivityPrinter();\n }\n await this.activityPrinter.notify(msg);\n return;\n }\n\n if (levelPriority[msg.level] > levelPriority[this.logLevel]) {\n return;\n }\n\n if (this.corkedCounter > 0) {\n this.corkedLoggingBuffer.push(msg);\n return;\n }\n\n const output = this.formatMessage(msg);\n const stream = this.selectStream(msg.level);\n stream.write(output);\n }\n\n /**\n * Detect stack activity messages so they can be send to the printer.\n */\n private isStackActivity(msg: IoMessage<any>) {\n return [\n 'CDK_TOOLKIT_I5501',\n 'CDK_TOOLKIT_I5502',\n 'CDK_TOOLKIT_I5503',\n ].includes(msg.code);\n }\n\n /**\n * Determines the output stream, based on message level and configuration.\n */\n private selectStream(level: IoMessageLevel) {\n // The stream selection policy for the CLI is the following:\n //\n // (1) Messages of level `result` always go to `stdout`\n // (2) Messages of level `error` always go to `stderr`.\n // (3a) All remaining messages go to `stderr`.\n // (3b) If we are in CI mode, all remaining messages go to `stdout`.\n //\n switch (level) {\n case 'error':\n return process.stderr;\n case 'result':\n return process.stdout;\n default:\n return this.isCI ? process.stdout : process.stderr;\n }\n }\n\n /**\n * Notifies the host of a message that requires a response.\n *\n * If the host does not return a response the suggested\n * default response from the input message will be used.\n */\n public async requestResponse<DataType, ResponseType>(msg: IoRequest<DataType, ResponseType>): Promise<ResponseType> {\n // First call out to a registered instance if we have one\n if (this._internalIoHost) {\n return this._internalIoHost.requestResponse(msg);\n }\n\n // If the request cannot be prompted for by the CliIoHost, we just accept the default\n if (!isPromptableRequest(msg)) {\n await this.notify(msg);\n return msg.defaultResponse;\n }\n\n const response = await this.withCorkedLogging(async (): Promise<string | number | true> => {\n // prepare prompt data\n // @todo this format is not defined anywhere, probably should be\n const data: {\n motivation?: string;\n concurrency?: number;\n } = msg.data ?? {};\n\n const motivation = data.motivation ?? 'User input is needed';\n const concurrency = data.concurrency ?? 0;\n\n // only talk to user if STDIN is a terminal (otherwise, fail)\n if (!this.isTTY) {\n throw new ToolkitError(`${motivation}, but terminal (TTY) is not attached so we are unable to get a confirmation from the user`);\n }\n\n // only talk to user if concurrency is 1 (otherwise, fail)\n if (concurrency > 1) {\n throw new ToolkitError(`${motivation}, but concurrency is greater than 1 so we are unable to get a confirmation from the user`);\n }\n\n // Basic confirmation prompt\n // We treat all requests with a boolean response as confirmation prompts\n if (isConfirmationPrompt(msg)) {\n const confirmed = await promptly.confirm(`${chalk.cyan(msg.message)} (y/n)`);\n if (!confirmed) {\n throw new ToolkitError('Aborted by user');\n }\n return confirmed;\n }\n\n // Asking for a specific value\n const prompt = extractPromptInfo(msg);\n const answer = await promptly.prompt(`${chalk.cyan(msg.message)} (${prompt.default})`, {\n default: prompt.default,\n });\n return prompt.convertAnswer(answer);\n });\n\n // We need to cast this because it is impossible to narrow the generic type\n // isPromptableRequest ensures that the response type is one we can prompt for\n // the remaining code ensure we are indeed returning the correct type\n return response as ResponseType;\n }\n\n /**\n * Formats a message for console output with optional color support\n */\n private formatMessage(msg: IoMessage<any>): string {\n // apply provided style or a default style if we're in TTY mode\n let message_text = this._isTTY\n ? styleMap[msg.level](msg.message)\n : msg.message;\n\n // prepend timestamp if IoMessageLevel is DEBUG or TRACE. Postpend a newline.\n return ((msg.level === 'debug' || msg.level === 'trace')\n ? `[${this.formatTime(msg.time)}] ${message_text}`\n : message_text) + '\\n';\n }\n\n /**\n * Formats date to HH:MM:SS\n */\n private formatTime(d: Date): string {\n const pad = (n: number): string => n.toString().padStart(2, '0');\n return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;\n }\n\n /**\n * Get an instance of the ActivityPrinter\n */\n private makeActivityPrinter() {\n const props: ActivityPrinterProps = {\n stream: this.selectStream('info'),\n };\n\n switch (this.stackProgress) {\n case StackActivityProgress.EVENTS:\n return new HistoryActivityPrinter(props);\n case StackActivityProgress.BAR:\n return new CurrentActivityPrinter(props);\n }\n }\n}\n\n/**\n * This IoHost implementation considers a request promptable, if:\n * - it's a yes/no confirmation\n * - asking for a string or number value\n */\nfunction isPromptableRequest(msg: IoRequest<any, any>): msg is IoRequest<any, string | number | boolean> {\n return isConfirmationPrompt(msg)\n || typeof msg.defaultResponse === 'string'\n || typeof msg.defaultResponse === 'number';\n}\n\n/**\n * Check if the request is a confirmation prompt\n * We treat all requests with a boolean response as confirmation prompts\n */\nfunction isConfirmationPrompt(msg: IoRequest<any, any>): msg is IoRequest<any, boolean> {\n return typeof msg.defaultResponse === 'boolean';\n}\n\n/**\n * Helper to extract information for promptly from the request\n */\nfunction extractPromptInfo(msg: IoRequest<any, any>): {\n default: string;\n convertAnswer: (input: string) => string | number;\n} {\n const isNumber = (typeof msg.defaultResponse === 'number');\n return {\n default: util.format(msg.defaultResponse),\n convertAnswer: isNumber ? (v) => Number(v) : (v) => String(v),\n };\n}\n\nconst styleMap: Record<IoMessageLevel, (str: string) => string> = {\n error: chalk.red,\n warn: chalk.yellow,\n result: chalk.white,\n info: chalk.white,\n debug: chalk.gray,\n trace: chalk.gray,\n};\n\n/**\n * Returns true if the current process is running in a CI environment\n * @returns true if the current process is running in a CI environment\n */\nexport function isCI(): boolean {\n return process.env.CI !== undefined && process.env.CI !== 'false' && process.env.CI !== '0';\n}\n\n", "const TOOLKIT_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.ToolkitError');\nconst AUTHENTICATION_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.AuthenticationError');\nconst ASSEMBLY_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.AssemblyError');\nconst CONTEXT_PROVIDER_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit.ContextProviderError');\n\n/**\n * Represents a general toolkit error in the AWS CDK Toolkit.\n */\nexport class ToolkitError extends Error {\n /**\n * Determines if a given error is an instance of ToolkitError.\n */\n public static isToolkitError(x: any): x is ToolkitError {\n return x !== null && typeof(x) === 'object' && TOOLKIT_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AuthenticationError.\n */\n public static isAuthenticationError(x: any): x is AuthenticationError {\n return this.isToolkitError(x) && AUTHENTICATION_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isAssemblyError(x: any): x is AssemblyError {\n return this.isToolkitError(x) && ASSEMBLY_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isContextProviderError(x: any): x is ContextProviderError {\n return this.isToolkitError(x) && CONTEXT_PROVIDER_ERROR_SYMBOL in x;\n }\n\n /**\n * The type of the error, defaults to \"toolkit\".\n */\n public readonly type: string;\n\n constructor(message: string, type: string = 'toolkit') {\n super(message);\n Object.setPrototypeOf(this, ToolkitError.prototype);\n Object.defineProperty(this, TOOLKIT_ERROR_SYMBOL, { value: true });\n this.name = new.target.name;\n this.type = type;\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AuthenticationError extends ToolkitError {\n constructor(message: string) {\n super(message, 'authentication');\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n Object.defineProperty(this, AUTHENTICATION_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AssemblyError extends ToolkitError {\n constructor(message: string) {\n super(message, 'assembly');\n Object.setPrototypeOf(this, AssemblyError.prototype);\n Object.defineProperty(this, ASSEMBLY_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an error originating from a Context Provider\n */\nexport class ContextProviderError extends ToolkitError {\n constructor(message: string) {\n super(message, 'context-provider');\n Object.setPrototypeOf(this, ContextProviderError.prototype);\n Object.defineProperty(this, CONTEXT_PROVIDER_ERROR_SYMBOL, { value: true });\n }\n}\n", "import { error } from 'console';\nimport { createWriteStream, promises as fs } from 'fs';\nimport * as path from 'path';\nimport * as glob from 'glob';\nimport { formatErrorMessage } from './format-error';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\n// Adapted from cdk-assets\nexport async function zipDirectory(directory: string, outputFile: string): Promise<void> {\n // We write to a temporary file and rename at the last moment. This is so that if we are\n // interrupted during this process, we don't leave a half-finished file in the target location.\n const temporaryOutputFile = `${outputFile}.${randomString()}._tmp`;\n await writeZipFile(directory, temporaryOutputFile);\n await moveIntoPlace(temporaryOutputFile, outputFile);\n}\n\nfunction writeZipFile(directory: string, outputFile: string): Promise<void> {\n return new Promise(async (ok, fail) => {\n // The below options are needed to support following symlinks when building zip files:\n // - nodir: This will prevent symlinks themselves from being copied into the zip.\n // - follow: This will follow symlinks and copy the files within.\n const globOptions = {\n dot: true,\n nodir: true,\n follow: true,\n cwd: directory,\n };\n const files = glob.sync('**', globOptions); // The output here is already sorted\n\n const output = createWriteStream(outputFile);\n\n const archive = archiver('zip');\n archive.on('warning', fail);\n archive.on('error', fail);\n\n // archive has been finalized and the output file descriptor has closed, resolve promise\n // this has to be done before calling `finalize` since the events may fire immediately after.\n // see https://www.npmjs.com/package/archiver\n output.once('close', ok);\n\n archive.pipe(output);\n\n // Append files serially to ensure file order\n for (const file of files) {\n const fullPath = path.resolve(directory, file);\n // Exactly 2 promises\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const [data, stat] = await Promise.all([fs.readFile(fullPath), fs.stat(fullPath)]);\n archive.append(data, {\n name: file,\n mode: stat.mode,\n });\n }\n\n await archive.finalize();\n });\n}\n\n/**\n * Rename the file to the target location, taking into account:\n *\n * - That we may see EPERM on Windows while an Antivirus scanner still has the\n * file open, so retry a couple of times.\n * - This same function may be called in parallel and be interrupted at any point.\n */\nasync function moveIntoPlace(source: string, target: string) {\n let delay = 100;\n let attempts = 5;\n while (true) {\n try {\n // 'rename' is guaranteed to overwrite an existing target, as long as it is a file (not a directory)\n await fs.rename(source, target);\n return;\n } catch (e: any) {\n if (e.code !== 'EPERM' || attempts-- <= 0) {\n throw e;\n }\n error(formatErrorMessage(e));\n await sleep(Math.floor(Math.random() * delay));\n delay *= 2;\n }\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise(ok => setTimeout(ok, ms));\n}\n\nfunction randomString() {\n return Math.random().toString(36).replace(/[^a-z0-9]+/g, '');\n}\n", "/**\n * Takes in an error and returns a correctly formatted string of its error message.\n * If it is an AggregateError, it will return a string with all the inner errors\n * formatted and separated by a newline.\n *\n * @param error The error to format\n * @returns A string with the error message(s) of the error\n */\nexport function formatErrorMessage(error: any): string {\n if (error && Array.isArray(error.errors)) {\n const innerMessages = error.errors\n .map((innerError: { message: any; toString: () => any }) => (innerError?.message || innerError?.toString()))\n .join('\\n');\n return `AggregateError: ${innerMessages}`;\n }\n\n // Fallback for regular Error or other types\n return error?.message || error?.toString() || 'Unknown error';\n}\n", "/**\n * Map a function over an array and concatenate the results\n */\nexport function flatMap<T, U>(xs: T[], fn: ((x: T, i: number) => U[])): U[] {\n return flatten(xs.map(fn));\n}\n\n/**\n * Flatten a list of lists into a list of elements\n */\nexport function flatten<T>(xs: T[][]): T[] {\n return Array.prototype.concat.apply([], xs);\n}\n\n/**\n * Partition a collection by removing and returning all elements that match a predicate\n *\n * Note: the input collection is modified in-place!\n */\nexport function partition<T>(collection: T[], pred: (x: T) => boolean): T[] {\n const ret: T[] = [];\n let i = 0;\n while (i < collection.length) {\n if (pred(collection[i])) {\n ret.push(collection.splice(i, 1)[0]);\n } else {\n i++;\n }\n }\n return ret;\n}\n", "/**\n * Format bytes as a human readable string\n *\n * @param bytes Number of bytes to format\n * @param decimals Number of decimal places to show (default 2)\n * @returns Formatted string with appropriate unit suffix\n */\nexport function formatBytes(bytes: number, decimals: number = 2): string {\n decimals = decimals < 0 ? 0 : decimals;\n\n if (bytes === 0) {\n return '0 Bytes';\n }\n\n const k = 1024;\n const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;\n}\n", "/**\n * Validate SNS topic arn\n */\nexport function validateSnsTopicArn(arn: string): boolean {\n return /^arn:aws:sns:[a-z0-9\\-]+:[0-9]+:[a-z0-9\\-\\_]+$/i.test(arn);\n}\n\n/**\n * Does a Stack Event have an error message based on the status.\n */\nexport function stackEventHasErrorMessage(status: string): boolean {\n return status.endsWith('_FAILED') || status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS';\n}\n\n/**\n * Calculate the maximal length of all resource types for a given template.\n *\n * @param template the stack template to analyze\n * @param startWidth the initial width to start with. Defaults to the length of 'AWS::CloudFormation::Stack'.\n * @returns the determined width\n */\nexport function maxResourceTypeLength(template: any, startWidth = 'AWS::CloudFormation::Stack'.length): number {\n const resources = (template && template.Resources) || {};\n let maxWidth = startWidth;\n for (const id of Object.keys(resources)) {\n const type = resources[id].Type || '';\n if (type.length > maxWidth) {\n maxWidth = type.length;\n }\n }\n return maxWidth;\n}\n", "import * as crypto from 'crypto';\n\nexport function contentHash(data: string | Buffer | DataView) {\n return crypto.createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * A stably sorted hash of an arbitrary JS object\n */\nexport function contentHashAny(value: unknown) {\n const ret = crypto.createHash('sha256');\n recurse(value);\n return ret.digest('hex');\n\n function recurse(x: unknown) {\n if (typeof x === 'string') {\n ret.update(x);\n return;\n }\n\n if (Array.isArray(x)) {\n ret.update('[');\n for (const e of x) {\n recurse(e);\n ret.update('||');\n }\n ret.update(']');\n return;\n }\n\n if (x && typeof x === 'object') {\n ret.update('{');\n for (const key of Object.keys(x).sort()) {\n ret.update(key);\n ret.update(':');\n recurse((x as any)[key]);\n }\n ret.update('}');\n return;\n }\n\n ret.update(`${x}${typeof x}`); // typeof to make sure hash('123') !== hash(123)\n }\n}\n", "/**\n * Type of a map mapping strings to some arbitrary type\n *\n * Name is not ideal, but:\n *\n * - Cannot call it Object, that already means something.\n * - Cannot call it Dict or Dictionary, since in other languages\n * those also allow specifying the key type.\n */\nexport type Obj<T> = {[key: string]: T};\n\n/**\n * Return whether the given value is an object\n *\n * Even though arrays technically are objects, we usually want to treat them differently,\n * so we return false in those cases.\n */\nexport function isObject(x: any): x is Obj<any> {\n return x !== null && typeof x === 'object' && !isArray(x);\n}\n\n/**\n * Return whether the given value is an array\n */\nexport const isArray = Array.isArray;\n\n/**\n * Return the value of the first argument if it's not undefined, otherwise the default\n */\nexport function ifDefined<T>(x: T | undefined, def: T): T {\n return typeof x !== 'undefined' ? x : def;\n}\n", "import { isArray, isObject, Obj } from './types';\nimport { ToolkitError } from '../toolkit/error';\n\n/**\n * Return a new object by adding missing keys into another object\n */\nexport function applyDefaults(hash: any, defaults: any) {\n const result: any = { };\n\n Object.keys(hash).forEach(k => result[k] = hash[k]);\n\n Object.keys(defaults)\n .filter(k => !(k in result))\n .forEach(k => result[k] = defaults[k]);\n\n return result;\n}\n\n/**\n * Return whether the given parameter is an empty object or empty list.\n */\nexport function isEmpty(x: any) {\n if (x == null) {\n return false;\n }\n if (isArray(x)) {\n return x.length === 0;\n }\n return Object.keys(x).length === 0;\n}\n\n/**\n * Deep clone a tree of objects, lists or scalars\n *\n * Does not support cycles.\n */\nexport function deepClone(x: any): any {\n if (typeof x === 'undefined') {\n return undefined;\n }\n if (x === null) {\n return null;\n }\n if (isArray(x)) {\n return x.map(deepClone);\n }\n if (isObject(x)) {\n return makeObject(mapObject(x, (k, v) => [k, deepClone(v)] as [string, any]));\n }\n return x;\n}\n\n/**\n * Map over an object, treating it as a dictionary\n */\nexport function mapObject<T, U>(x: Obj<T>, fn: (key: string, value: T) => U): U[] {\n const ret: U[] = [];\n Object.keys(x).forEach(key => {\n ret.push(fn(key, x[key]));\n });\n return ret;\n}\n\n/**\n * Construct an object from a list of (k, v) pairs\n */\nexport function makeObject<T>(pairs: Array<[string, T]>): Obj<T> {\n const ret: Obj<T> = {};\n for (const pair of pairs) {\n ret[pair[0]] = pair[1];\n }\n return ret;\n}\n\n/**\n * Deep get a value from a tree of nested objects\n *\n * Returns undefined if any part of the path was unset or\n * not an object.\n */\nexport function deepGet(x: any, path: string[]): any {\n path = path.slice();\n\n while (path.length > 0 && isObject(x)) {\n const key = path.shift()!;\n x = x[key];\n }\n return path.length === 0 ? x : undefined;\n}\n\n/**\n * Deep set a value in a tree of nested objects\n *\n * Throws an error if any part of the path is not an object.\n */\nexport function deepSet(x: any, path: string[], value: any) {\n path = path.slice();\n\n if (path.length === 0) {\n throw new ToolkitError('Path may not be empty');\n }\n\n while (path.length > 1 && isObject(x)) {\n const key = path.shift()!;\n if (!(key in x)) {\n x[key] = {};\n }\n x = x[key];\n }\n\n if (!isObject(x)) {\n throw new ToolkitError(`Expected an object, got '${x}'`);\n }\n\n if (value !== undefined) {\n x[path[0]] = value;\n } else {\n delete x[path[0]];\n }\n}\n\n/**\n * Recursively merge objects together\n *\n * The leftmost object is mutated and returned. Arrays are not merged\n * but overwritten just like scalars.\n *\n * If an object is merged into a non-object, the non-object is lost.\n */\nexport function deepMerge(...objects: Array<Obj<any> | undefined>) {\n function mergeOne(target: Obj<any>, source: Obj<any>) {\n for (const key of Object.keys(source)) {\n if (key === '__proto__' || key === 'constructor') {\n continue;\n }\n\n const value = source[key];\n\n if (isObject(value)) {\n if (!isObject(target[key])) {\n target[key] = {};\n } // Overwrite on purpose\n mergeOne(target[key], value);\n } else if (typeof value !== 'undefined') {\n target[key] = value;\n }\n }\n }\n\n const others = objects.filter(x => x != null) as Array<Obj<any>>;\n\n if (others.length === 0) {\n return {};\n }\n const into = others.splice(0, 1)[0];\n\n others.forEach(other => mergeOne(into, other));\n return into;\n}\n\n/**\n * Splits the given object into two, such that:\n *\n * 1. The size of the first object (after stringified in UTF-8) is less than or equal to the provided size limit.\n * 2. Merging the two objects results in the original one.\n */\nexport function splitBySize(data: any, maxSizeBytes: number): [any, any] {\n if (maxSizeBytes < 2) {\n // It's impossible to fit anything in the first object\n return [undefined, data];\n }\n const entries = Object.entries(data);\n return recurse(0, 0);\n\n function recurse(index: number, runningTotalSize: number): [any, any] {\n if (index >= entries.length) {\n // Everything fits in the first object\n return [data, undefined];\n }\n\n const size = runningTotalSize + entrySize(entries[index]);\n return (size > maxSizeBytes) ? cutAt(index) : recurse(index + 1, size);\n }\n\n function entrySize(entry: [string, unknown]) {\n return Buffer.byteLength(JSON.stringify(Object.fromEntries([entry])));\n }\n\n function cutAt(index: number): [any, any] {\n return [\n Object.fromEntries(entries.slice(0, index)),\n Object.fromEntries(entries.slice(index)),\n ];\n }\n}\n", "/**\n * Run a number of promise generators with max parallelism\n *\n * Order is not maintained between the input and output.\n */\nexport async function parallelPromises<A>(n: number, promises: Array<() => Promise<A>>): Promise<Array<A>> {\n const ret = new Array<A>();\n let count = 0;\n let error: Error | undefined;\n const queue = [...promises];\n\n return new Promise((ok, ko) => {\n tick();\n\n function tick() {\n if (count === 0 && error) {\n ko(error);\n return;\n }\n if (count === 0 && queue.length === 0) {\n ok(ret);\n return;\n }\n\n while (count < n && queue.length > 0 && !error) {\n const next = queue.shift();\n if (next !== undefined) {\n start(next);\n }\n }\n }\n\n function start(fn: () => Promise<A>) {\n count += 1;\n fn()\n .then((result) => {\n ret.push(result);\n })\n .catch((e) => {\n error = e;\n })\n .finally(() => {\n count -= 1;\n tick();\n });\n }\n });\n}\n", "import * as fs from 'fs-extra';\nimport { formatBytes } from './bytes';\nimport * as yaml_cfn from './yaml-cfn';\n\n/**\n * Stringify to YAML\n */\nexport function toYAML(obj: any): string {\n return yaml_cfn.serialize(obj);\n}\n\n/**\n * Parse either YAML or JSON\n */\nexport function deserializeStructure(str: string): any {\n return yaml_cfn.deserialize(str);\n}\n\n/**\n * Serialize to either YAML or JSON\n */\nexport function serializeStructure(object: any, json: boolean) {\n if (json) {\n return JSON.stringify(object, undefined, 2);\n } else {\n return toYAML(object);\n }\n}\n\n/**\n * Load a YAML or JSON file from disk\n */\nexport async function loadStructuredFile(fileName: string) {\n const contents = await fs.readFile(fileName, { encoding: 'utf-8' });\n return deserializeStructure(contents);\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n */\nexport function obscureTemplate(template: any = {}) {\n if (template.Rules) {\n // see https://github.com/aws/aws-cdk/issues/17942\n if (template.Rules.CheckBootstrapVersion) {\n if (Object.keys(template.Rules).length > 1) {\n delete template.Rules.CheckBootstrapVersion;\n } else {\n delete template.Rules;\n }\n }\n }\n\n return template;\n}\n\n/**\n * Detects a buffer that has been converted to a JSON-like object\n * In Node, `Buffer`s have `toJSON()` method that converts the buffer\n * into a JS object that can be JSON stringified.\n * Unfortunately this conversion happens before the replacer is called,\n * so normal means of detecting a `Buffer` objet don't work anymore.\n * @see https://github.com/nodejs/node-v0.x-archive/issues/5110\n */\nfunction isJsonBuffer(value: any): value is {\n type: 'Buffer';\n data: number[];\n} {\n return typeof value === 'object'\n && 'type' in value\n && value.type === 'Buffer'\n && 'data' in value\n && Array.isArray(value.data);\n}\n\n/**\n * A JSON.stringify() replacer that converts Buffers into a string with information\n * Use this if you plan to print out JSON stringified objects that may contain a Buffer.\n * Without this, large buffers (think: Megabytes) will completely fill up the output\n * and even crash the system.\n */\nexport function replacerBufferWithInfo(_key: any, value: any): any {\n if (isJsonBuffer(value)) {\n return `<Buffer: ${formatBytes(value.data.length)}>`;\n }\n return value;\n}\n", "import * as yaml from 'yaml';\nimport * as yaml_cst from 'yaml/parse-cst';\nimport * as yaml_types from 'yaml/types';\n\n/**\n * Serializes the given data structure into valid YAML.\n *\n * @param obj the data structure to serialize\n * @returns a string containing the YAML representation of {@param obj}\n */\nexport function serialize(obj: any): string {\n const oldFold = yaml_types.strOptions.fold.lineWidth;\n try {\n yaml_types.strOptions.fold.lineWidth = 0;\n return yaml.stringify(obj, { schema: 'yaml-1.1' });\n } finally {\n yaml_types.strOptions.fold.lineWidth = oldFold;\n }\n}\n\n/**\n * Deserialize the YAML into the appropriate data structure.\n *\n * @param str the string containing YAML\n * @returns the data structure the YAML represents\n * (most often in case of CloudFormation, an object)\n */\nexport function deserialize(str: string): any {\n return parseYamlStrWithCfnTags(str);\n}\n\nfunction makeTagForCfnIntrinsic(intrinsicName: string, addFnPrefix: boolean): yaml_types.Schema.CustomTag {\n return {\n identify(value: any) {\n return typeof value === 'string';\n },\n tag: `!${intrinsicName}`,\n resolve: (_doc: yaml.Document, cstNode: yaml_cst.CST.Node) => {\n const ret: any = {};\n ret[addFnPrefix ? `Fn::${intrinsicName}` : intrinsicName] =\n // the +1 is to account for the ! the short form begins with\n parseYamlStrWithCfnTags(cstNode.toString().substring(intrinsicName.length + 1));\n return ret;\n },\n };\n}\n\nconst shortForms: yaml_types.Schema.CustomTag[] = [\n 'Base64', 'Cidr', 'FindInMap', 'GetAZs', 'ImportValue', 'Join', 'Sub',\n 'Select', 'Split', 'Transform', 'And', 'Equals', 'If', 'Not', 'Or', 'GetAtt',\n].map(name => makeTagForCfnIntrinsic(name, true)).concat(\n makeTagForCfnIntrinsic('Ref', false),\n makeTagForCfnIntrinsic('Condition', false),\n);\n\nfunction parseYamlStrWithCfnTags(text: string): any {\n return yaml.parse(text, {\n customTags: shortForms,\n schema: 'core',\n });\n}\n", "/**\n * Pad 's' on the left with 'char' until it is n characters wide\n */\nexport function padLeft(n: number, x: string, char: string = ' '): string {\n return char.repeat(Math.max(0, n - x.length)) + x;\n}\n\n/**\n * Pad 's' on the right with 'char' until it is n characters wide\n */\nexport function padRight(n: number, x: string, char: string = ' '): string {\n return x + char.repeat(Math.max(0, n - x.length));\n}\n\n/**\n * Formats time in milliseconds (which we get from 'Date.getTime()')\n * to a human-readable time; returns time in seconds rounded to 2\n * decimal places.\n */\nexport function formatTime(num: number): number {\n return roundPercentage(millisecondsToSeconds(num));\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(100 * num) / 100;\n}\n\n/**\n * Given a time in milliseconds, return an equivalent amount in seconds.\n */\nfunction millisecondsToSeconds(num: number): number {\n return num / 1000;\n}\n", "import * as semver from 'semver';\nimport { ToolkitError } from '../toolkit/error';\n\n// bracket - https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN401\n// pep - https://www.python.org/dev/peps/pep-0440/#version-specifiers\nexport type RangeType = 'bracket' | 'pep'\n\nexport function rangeFromSemver(ver: string, targetType: RangeType) {\n const re = ver.match(/^([^\\d]*)([\\d.]*)$/);\n if (!re || !semver.valid(re[2])) {\n throw new ToolkitError('not a semver or unsupported range syntax');\n }\n const prefixPart = re[1];\n const verPart = re[2];\n\n switch (targetType) {\n case 'bracket':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return ver;\n case '^':\n return `[${verPart},${semver.major(verPart)+1}.0.0)`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n case 'pep':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return `==${ver}`;\n case '^':\n return `>=${verPart},<${semver.major(verPart)+1}.0.0`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n }\n}\n", "import { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { StackActivity } from '../../api/stack-events';\nimport { StackProgress } from '../../api/stack-events/stack-progress-monitor';\nimport { IoMessage } from '../../toolkit/cli-io-host';\nimport { maxResourceTypeLength, stackEventHasErrorMessage } from '../../util';\n\nexport interface IActivityPrinter {\n notify<T>(msg: IoMessage<T>): void;\n}\n\nexport interface ActivityPrinterProps {\n /**\n * Stream to write to\n */\n readonly stream: NodeJS.WriteStream;\n}\n\nexport abstract class ActivityPrinterBase implements IActivityPrinter {\n protected static readonly TIMESTAMP_WIDTH = 12;\n protected static readonly STATUS_WIDTH = 20;\n\n /**\n * Stream to write to\n */\n protected readonly stream: NodeJS.WriteStream;\n\n /**\n * The with of the \"resource type\" column.\n */\n protected resourceTypeColumnWidth: number = maxResourceTypeLength({});\n\n /**\n * A list of resource IDs which are currently being processed\n */\n protected resourcesInProgress: Record<string, StackActivity> = {};\n\n protected stackProgress?: StackProgress;\n\n protected rollingBack = false;\n\n protected readonly failures = new Array<StackActivity>();\n\n protected hookFailureMap = new Map<string, Map<string, string>>();\n\n constructor(protected readonly props: ActivityPrinterProps) {\n this.stream = props.stream;\n }\n\n protected abstract print(): void;\n\n /**\n * Receive a stack activity message\n */\n public notify(msg: IoMessage<any>): void {\n switch (msg.code) {\n case 'CDK_TOOLKIT_I5501':\n this.start(msg.data);\n break;\n case 'CDK_TOOLKIT_I5502':\n this.activity(msg.data as StackActivity);\n break;\n case 'CDK_TOOLKIT_I5503':\n this.stop();\n break;\n default:\n // ignore all other messages\n break;\n }\n }\n\n public start({ stack }: { stack: CloudFormationStackArtifact}) {\n this.resourceTypeColumnWidth = maxResourceTypeLength(stack.template);\n }\n\n public activity(activity: StackActivity) {\n // process the activity and then call print\n this.addActivity(activity);\n this.print();\n }\n\n public stop() {\n // final print after the stack is done\n this.print();\n }\n\n protected addActivity(activity: StackActivity) {\n const status = activity.event.ResourceStatus;\n const hookStatus = activity.event.HookStatus;\n const hookType = activity.event.HookType;\n if (!status || !activity.event.LogicalResourceId) {\n return;\n }\n\n this.stackProgress = activity.progress;\n\n if (status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS') {\n // Only triggered on the stack once we've started doing a rollback\n this.rollingBack = true;\n }\n\n if (status.endsWith('_IN_PROGRESS')) {\n this.resourcesInProgress[activity.event.LogicalResourceId] = activity;\n }\n\n if (stackEventHasErrorMessage(status)) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason\n if (!isCancelled) {\n this.failures.push(activity);\n }\n }\n\n if (status.endsWith('_COMPLETE') || status.endsWith('_FAILED')) {\n delete this.resourcesInProgress[activity.event.LogicalResourceId];\n }\n\n if (\n hookStatus !== undefined &&\n hookStatus.endsWith('_COMPLETE_FAILED') &&\n activity.event.LogicalResourceId !== undefined &&\n hookType !== undefined\n ) {\n if (this.hookFailureMap.has(activity.event.LogicalResourceId)) {\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n } else {\n this.hookFailureMap.set(activity.event.LogicalResourceId, new Map<string, string>());\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n }\n }\n }\n\n protected failureReason(activity: StackActivity) {\n const resourceStatusReason = activity.event.ResourceStatusReason ?? '';\n const logicalResourceId = activity.event.LogicalResourceId ?? '';\n const hookFailureReasonMap = this.hookFailureMap.get(logicalResourceId);\n\n if (hookFailureReasonMap !== undefined) {\n for (const hookType of hookFailureReasonMap.keys()) {\n if (resourceStatusReason.includes(hookType)) {\n return resourceStatusReason + ' : ' + hookFailureReasonMap.get(hookType);\n }\n }\n }\n return resourceStatusReason;\n }\n\n /**\n * Is the activity a meta activity for the stack itself.\n */\n protected isActivityForTheStack(activity: StackActivity) {\n return activity.event.PhysicalResourceId === activity.event.StackId;\n }\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport { ActivityPrinterBase, ActivityPrinterProps } from './base';\nimport type { StackActivity } from '../../api/stack-events';\nimport { padRight } from '../../util';\n\n/**\n * Activity Printer which shows a full log of all CloudFormation events\n *\n * When there hasn't been activity for a while, it will print the resources\n * that are currently in progress, to show what's holding up the deployment.\n */\nexport class HistoryActivityPrinter extends ActivityPrinterBase {\n /**\n * Last time we printed something to the console.\n *\n * Used to measure timeout for progress reporting.\n */\n private lastPrintTime = Date.now();\n\n private lastPrinted?: StackActivity;\n\n /**\n * Number of ms of change absence before we tell the user about the resources that are currently in progress.\n */\n private readonly inProgressDelay = 30_000;\n\n private readonly printable = new Array<StackActivity>();\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n }\n\n public activity(activity: StackActivity) {\n this.printable.push(activity);\n super.activity(activity);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n if (this.failures.length > 0) {\n this.stream.write('\\nFailed resources:\\n');\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n this.printOne(failure, false);\n }\n }\n }\n\n protected print() {\n for (const activity of this.printable) {\n this.printOne(activity);\n this.lastPrinted = activity;\n }\n this.printable.splice(0, this.printable.length);\n this.printInProgress(this.lastPrinted?.progress.formatted);\n }\n\n private printOne(activity: StackActivity, progress?: boolean) {\n const event = activity.event;\n const color = colorFromStatusResult(event.ResourceStatus);\n let reasonColor = chalk.cyan;\n\n let stackTrace = '';\n const metadata = activity.metadata;\n\n if (event.ResourceStatus && event.ResourceStatus.indexOf('FAILED') !== -1) {\n if (progress == undefined || progress) {\n event.ResourceStatusReason = event.ResourceStatusReason ? this.failureReason(activity) : '';\n }\n if (metadata) {\n stackTrace = metadata.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '';\n }\n reasonColor = chalk.red;\n }\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n this.stream.write(\n util.format(\n '%s | %s%s | %s | %s | %s %s%s%s\\n',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n color(padRight(HistoryActivityPrinter.STATUS_WIDTH, (event.ResourceStatus || '').slice(0, HistoryActivityPrinter.STATUS_WIDTH))), // pad left and trim\n padRight(this.resourceTypeColumnWidth, event.ResourceType || ''),\n color(chalk.bold(resourceName)),\n logicalId,\n reasonColor(chalk.bold(event.ResourceStatusReason ? event.ResourceStatusReason : '')),\n reasonColor(stackTrace),\n ),\n );\n\n this.lastPrintTime = Date.now();\n }\n\n /**\n * If some resources are taking a while to create, notify the user about what's currently in progress\n */\n private printInProgress(progress?: string) {\n if (!progress || Date.now() < this.lastPrintTime + this.inProgressDelay) {\n return;\n }\n\n if (Object.keys(this.resourcesInProgress).length > 0) {\n this.stream.write(\n util.format(\n '%s Currently in progress: %s\\n',\n progress,\n chalk.bold(Object.keys(this.resourcesInProgress).join(', ')),\n ),\n );\n }\n\n // We cheat a bit here. To prevent printInProgress() from repeatedly triggering,\n // we set the timestamp into the future. It will be reset whenever a regular print\n // occurs, after which we can be triggered again.\n this.lastPrintTime = +Infinity;\n }\n}\n\nfunction colorFromStatusResult(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.indexOf('FAILED') !== -1) {\n return chalk.red;\n }\n if (status.indexOf('ROLLBACK') !== -1) {\n return chalk.yellow;\n }\n if (status.indexOf('COMPLETE') !== -1) {\n return chalk.green;\n }\n\n return chalk.reset;\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport { ActivityPrinterBase, ActivityPrinterProps } from './base';\nimport { RewritableBlock } from './display';\nimport type { StackActivity } from '../../api/stack-events';\nimport { padLeft, padRight, stackEventHasErrorMessage } from '../../util';\n\n/**\n * Activity Printer which shows the resources currently being updated\n *\n * It will continuously re-update the terminal and show only the resources\n * that are currently being updated, in addition to a progress bar which\n * shows how far along the deployment is.\n *\n * Resources that have failed will always be shown, and will be recapitulated\n * along with their stack trace when the monitoring ends.\n *\n * Resources that failed deployment because they have been cancelled are\n * not included.\n */\nexport class CurrentActivityPrinter extends ActivityPrinterBase {\n /**\n * Continuously write to the same output block.\n */\n private block: RewritableBlock;\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n this.block = new RewritableBlock(this.stream);\n }\n\n protected print(): void {\n const lines = [];\n\n // Add a progress bar at the top\n const progressWidth = Math.max(\n Math.min((this.block.width ?? 80) - PROGRESSBAR_EXTRA_SPACE - 1, MAX_PROGRESSBAR_WIDTH),\n MIN_PROGRESSBAR_WIDTH,\n );\n const prog = this.progressBar(progressWidth);\n if (prog) {\n lines.push(' ' + prog, '');\n }\n\n // Normally we'd only print \"resources in progress\", but it's also useful\n // to keep an eye on the failures and know about the specific errors asquickly\n // as possible (while the stack is still rolling back), so add those in.\n const toPrint: StackActivity[] = [...this.failures, ...Object.values(this.resourcesInProgress)];\n toPrint.sort((a, b) => a.event.Timestamp!.getTime() - b.event.Timestamp!.getTime());\n\n lines.push(\n ...toPrint.map((res) => {\n const color = colorFromStatusActivity(res.event.ResourceStatus);\n const resourceName = res.metadata?.constructPath ?? res.event.LogicalResourceId ?? '';\n\n return util.format(\n '%s | %s | %s | %s%s',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(res.event.Timestamp!).toLocaleTimeString()),\n color(padRight(CurrentActivityPrinter.STATUS_WIDTH, (res.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH))),\n padRight(this.resourceTypeColumnWidth, res.event.ResourceType || ''),\n color(chalk.bold(shorten(40, resourceName))),\n this.failureReasonOnNextLine(res),\n );\n }),\n );\n\n this.block.displayLines(lines);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n const lines = new Array<string>();\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n lines.push(\n util.format(\n chalk.red('%s | %s | %s | %s%s') + '\\n',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(failure.event.Timestamp!).toLocaleTimeString()),\n padRight(CurrentActivityPrinter.STATUS_WIDTH, (failure.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH)),\n padRight(this.resourceTypeColumnWidth, failure.event.ResourceType || ''),\n shorten(40, failure.event.LogicalResourceId ?? ''),\n this.failureReasonOnNextLine(failure),\n ),\n );\n\n const trace = failure.metadata?.entry?.trace;\n if (trace) {\n lines.push(chalk.red(`\\t${trace.join('\\n\\t\\\\_ ')}\\n`));\n }\n }\n\n // Display in the same block space, otherwise we're going to have silly empty lines.\n this.block.displayLines(lines);\n this.block.removeEmptyLines();\n }\n\n private progressBar(width: number) {\n if (!this.stackProgress || !this.stackProgress.total) {\n return '';\n }\n const fraction = Math.min(this.stackProgress.completed / this.stackProgress.total, 1);\n const innerWidth = Math.max(1, width - 2);\n const chars = innerWidth * fraction;\n const remainder = chars - Math.floor(chars);\n\n const fullChars = FULL_BLOCK.repeat(Math.floor(chars));\n const partialChar = PARTIAL_BLOCK[Math.floor(remainder * PARTIAL_BLOCK.length)];\n const filler = '\u00B7'.repeat(innerWidth - Math.floor(chars) - (partialChar ? 1 : 0));\n\n const color = this.rollingBack ? chalk.yellow : chalk.green;\n\n return '[' + color(fullChars + partialChar) + filler + `] (${this.stackProgress.completed}/${this.stackProgress.total})`;\n }\n\n private failureReasonOnNextLine(activity: StackActivity) {\n return stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')\n ? `\\n${' '.repeat(CurrentActivityPrinter.TIMESTAMP_WIDTH + CurrentActivityPrinter.STATUS_WIDTH + 6)}${chalk.red(this.failureReason(activity) ?? '')}`\n : '';\n }\n}\n\nconst FULL_BLOCK = '\u2588';\nconst PARTIAL_BLOCK = ['', '\u258F', '\u258E', '\u258D', '\u258C', '\u258B', '\u258A', '\u2589'];\nconst MAX_PROGRESSBAR_WIDTH = 60;\nconst MIN_PROGRESSBAR_WIDTH = 10;\nconst PROGRESSBAR_EXTRA_SPACE =\n 2 /* leading spaces */ + 2 /* brackets */ + 4 /* progress number decoration */ + 6; /* 2 progress numbers up to 999 */\n\nfunction colorFromStatusActivity(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.endsWith('_FAILED')) {\n return chalk.red;\n }\n\n if (status.startsWith('CREATE_') || status.startsWith('UPDATE_') || status.startsWith('IMPORT_')) {\n return chalk.green;\n }\n // For stacks, it may also be 'UPDDATE_ROLLBACK_IN_PROGRESS'\n if (status.indexOf('ROLLBACK_') !== -1) {\n return chalk.yellow;\n }\n if (status.startsWith('DELETE_')) {\n return chalk.yellow;\n }\n\n return chalk.reset;\n}\n\nfunction shorten(maxWidth: number, p: string) {\n if (p.length <= maxWidth) {\n return p;\n }\n const half = Math.floor((maxWidth - 3) / 2);\n return p.slice(0, half) + '...' + p.slice(-half);\n}\n\n", "// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst wrapAnsi = require('wrap-ansi');\n\n/**\n * A class representing rewritable display lines\n */\nexport class RewritableBlock {\n private lastHeight = 0;\n private trailingEmptyLines = 0;\n\n constructor(private readonly stream: NodeJS.WriteStream) {\n }\n\n public get width() {\n // Might get changed if the user resizes the terminal\n return this.stream.columns;\n }\n\n public get height() {\n // Might get changed if the user resizes the terminal\n return this.stream.rows;\n }\n\n public displayLines(lines: string[]) {\n lines = terminalWrap(this.width, expandNewlines(lines));\n lines = lines.slice(0, getMaxBlockHeight(this.height, this.lastHeight, lines));\n\n this.stream.write(cursorUp(this.lastHeight));\n for (const line of lines) {\n this.stream.write(cll() + line + '\\n');\n }\n\n this.trailingEmptyLines = Math.max(0, this.lastHeight - lines.length);\n\n // Clear remainder of unwritten lines\n for (let i = 0; i < this.trailingEmptyLines; i++) {\n this.stream.write(cll() + '\\n');\n }\n\n // The block can only ever get bigger\n this.lastHeight = Math.max(this.lastHeight, lines.length);\n }\n\n public removeEmptyLines() {\n this.stream.write(cursorUp(this.trailingEmptyLines));\n }\n}\n\nconst ESC = '\\u001b';\n\n/*\n * Move cursor up `n` lines. Default is 1\n */\nfunction cursorUp(n: number) {\n n = typeof n === 'number' ? n : 1;\n return n > 0 ? ESC + '[' + n + 'A' : '';\n}\n\n/**\n * Clear to end of line\n */\nfunction cll() {\n return ESC + '[K';\n}\n\nfunction terminalWrap(width: number | undefined, lines: string[]) {\n if (width === undefined) {\n return lines;\n }\n\n return lines.flatMap(line => wrapAnsi(line, width - 1, {\n hard: true,\n trim: true,\n wordWrap: false,\n }).split('\\n'));\n}\n\n/**\n * Make sure there are no hidden newlines in the gin strings\n */\nfunction expandNewlines(lines: string[]): string[] {\n return lines.flatMap(line => line.split('\\n'));\n}\n\nfunction getMaxBlockHeight(windowHeight: number | undefined, lastHeight: number, lines: string[]): number {\n if (windowHeight === undefined) {\n return Math.max(lines.length, lastHeight);\n }\n return lines.length < windowHeight ? lines.length : windowHeight - 1;\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { ToolkitError } from '../toolkit/error';\n\n/**\n * Return a location that will be used as the CDK home directory.\n * Currently the only thing that is placed here is the cache.\n *\n * First try to use the users home directory (i.e. /home/someuser/),\n * but if that directory does not exist for some reason create a tmp directory.\n *\n * Typically it wouldn't make sense to create a one time use tmp directory for\n * the purpose of creating a cache, but since this only applies to users that do\n * not have a home directory (some CI systems?) this should be fine.\n */\nexport function cdkHomeDir() {\n const tmpDir = fs.realpathSync(os.tmpdir());\n let home;\n try {\n let userInfoHome: string | undefined = os.userInfo().homedir;\n // Node returns this if the user doesn't have a home directory\n /* istanbul ignore if: will not happen in normal setups */\n if (userInfoHome == '/var/empty') {\n userInfoHome = undefined;\n }\n home = path.join((userInfoHome ?? os.homedir()).trim(), '.cdk');\n } catch {\n }\n return process.env.CDK_HOME\n ? path.resolve(process.env.CDK_HOME)\n : home || fs.mkdtempSync(path.join(tmpDir, '.cdk')).trim();\n}\n\nexport function cdkCacheDir() {\n return path.join(cdkHomeDir(), 'cache');\n}\n\n/**\n * From the current file, find the directory that contains the CLI's package.json\n *\n * Can't use `__dirname` in production code, as the CLI will get bundled as it's\n * released and `__dirname` will refer to a different location in the `.ts` form\n * as it will in the final executing form.\n */\nexport function rootDir(): string;\nexport function rootDir(fail: true): string;\nexport function rootDir(fail: false): string | undefined;\nexport function rootDir(fail?: boolean) {\n function _rootDir(dirname: string): string | undefined {\n const manifestPath = path.join(dirname, 'package.json');\n if (fs.existsSync(manifestPath)) {\n return dirname;\n }\n if (path.dirname(dirname) === dirname) {\n if (fail ?? true) {\n throw new ToolkitError('Unable to find package manifest');\n }\n return undefined;\n }\n return _rootDir(path.dirname(dirname));\n }\n\n return _rootDir(__dirname);\n}\n", "/**\n * Cache the result of a function on an object\n *\n * We could have used @decorators to make this nicer but we don't use them anywhere yet,\n * so let's keep it simple and readable.\n */\nexport function cached<A extends object, B>(obj: A, sym: symbol, fn: () => B): B {\n if (!(sym in obj)) {\n (obj as any)[sym] = fn();\n }\n return (obj as any)[sym];\n}\n\n/**\n * Like 'cached', but async\n */\nexport async function cachedAsync<A extends object, B>(obj: A, sym: symbol, fn: () => Promise<B>): Promise<B> {\n if (!(sym in obj)) {\n (obj as any)[sym] = await fn();\n }\n return (obj as any)[sym];\n}\n", "import type { Logger } from '@smithy/types';\n\nlet ENABLED = false;\nlet INDENT = 0;\n\nexport function setSdkTracing(enabled: boolean) {\n ENABLED = enabled;\n}\n\n/**\n * Method decorator to trace a single static or member method, any time it's called\n */\nexport function callTrace(fn: string, className?: string, logger?: Logger) {\n if (!ENABLED || !logger) {\n return;\n }\n\n logger.info(`[trace] ${' '.repeat(INDENT)}${className || '(anonymous)'}#${fn}()`);\n}\n\n/**\n * Method decorator to trace a single member method any time it's called\n */\nfunction traceCall(receiver: object, _propertyKey: string, descriptor: PropertyDescriptor, parentClassName?: string) {\n const fn = descriptor.value;\n const className = typeof receiver === 'function' ? receiver.name : parentClassName;\n\n descriptor.value = function (...args: any[]) {\n const logger = (this as any).logger;\n if (!ENABLED || typeof logger?.info !== 'function') {\n return fn.apply(this, args);\n }\n\n logger.info.apply(logger, [`[trace] ${' '.repeat(INDENT)}${className || this.constructor.name || '(anonymous)'}#${fn.name}()`]);\n INDENT += 2;\n\n const ret = fn.apply(this, args);\n if (ret instanceof Promise) {\n return ret.finally(() => {\n INDENT -= 2;\n });\n } else {\n INDENT -= 2;\n return ret;\n }\n };\n return descriptor;\n}\n\n/**\n * Class decorator, enable tracing for all member methods on this class\n * @deprecated this doesn't work well with localized logging instances, don't use\n */\nexport function traceMemberMethods(constructor: Function) {\n // Instance members\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(constructor.prototype))) {\n if (typeof descriptor.value !== 'function') {\n continue;\n }\n const newDescriptor = traceCall(constructor.prototype, name, descriptor, constructor.name) ?? descriptor;\n Object.defineProperty(constructor.prototype, name, newDescriptor);\n }\n}\n", "import * as path from 'path';\nimport { readIfPossible } from './util';\nimport { rootDir } from '../../util/directories';\n\n/**\n * Find the package.json from the main toolkit.\n *\n * If we can't read it for some reason, try to do something reasonable anyway.\n * Fall back to argv[1], or a standard string if that is undefined for some reason.\n */\nexport function defaultCliUserAgent() {\n const root = rootDir(false);\n const pkg = JSON.parse((root ? readIfPossible(path.join(root, 'package.json')) : undefined) ?? '{}');\n const name = pkg.name ?? path.basename(process.argv[1] ?? 'cdk-cli');\n const version = pkg.version ?? '<unknown>';\n return `${name}/${version}`;\n}\n", "import * as fs from 'fs-extra';\nimport { debug } from '../../logging';\n\n/**\n * Read a file if it exists, or return undefined\n *\n * Not async because it is used in the constructor\n */\nexport function readIfPossible(filename: string): string | undefined {\n try {\n if (!fs.pathExistsSync(filename)) {\n return undefined;\n }\n return fs.readFileSync(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n debug(e);\n return undefined;\n }\n}\n", "import * as os from 'os';\nimport { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema';\nimport { Environment, EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport { AssumeRoleCommandInput } from '@aws-sdk/client-sts';\nimport { fromTemporaryCredentials } from '@aws-sdk/credential-providers';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { AwsCliCompatible } from './awscli-compatible';\nimport { cached } from './cached';\nimport { CredentialPlugins } from './credential-plugins';\nimport { makeCachingProvider } from './provider-caching';\nimport { SDK } from './sdk';\nimport { callTrace, traceMemberMethods } from './tracing';\nimport { debug, warning } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { Mode } from '../plugin/mode';\n\nexport type AssumeRoleAdditionalOptions = Partial<Omit<AssumeRoleCommandInput, 'ExternalId' | 'RoleArn'>>;\n\n/**\n * Options for the default SDK provider\n */\nexport interface SdkProviderOptions {\n /**\n * Profile to read from ~/.aws\n *\n * @default - No profile\n */\n readonly profile?: string;\n\n /**\n * HTTP options for SDK\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * The logger for sdk calls.\n */\n readonly logger?: Logger;\n}\n\n/**\n * Options for individual SDKs\n */\nexport interface SdkHttpOptions {\n /**\n * Proxy address to use\n *\n * @default No proxy\n */\n readonly proxyAddress?: string;\n\n /**\n * A path to a certificate bundle that contains a cert to be trusted.\n *\n * @default No certificate bundle\n */\n readonly caBundlePath?: string;\n}\n\nconst CACHED_ACCOUNT = Symbol('cached_account');\n\n/**\n * SDK configuration for a given environment\n * 'forEnvironment' will attempt to assume a role and if it\n * is not successful, then it will either:\n * 1. Check to see if the default credentials (local credentials the CLI was executed with)\n * are for the given environment. If they are then return those.\n * 2. If the default credentials are not for the given environment then\n * throw an error\n *\n * 'didAssumeRole' allows callers to whether they are receiving the assume role\n * credentials or the default credentials.\n */\nexport interface SdkForEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * Whether or not the assume role was successful.\n * If the assume role was not successful (false)\n * then that means that the 'sdk' returned contains\n * the default credentials (not the assume role credentials)\n */\n readonly didAssumeRole: boolean;\n}\n\n/**\n * Creates instances of the AWS SDK appropriate for a given account/region.\n *\n * Behavior is as follows:\n *\n * - First, a set of \"base\" credentials are established\n * - If a target environment is given and the default (\"current\") SDK credentials are for\n * that account, return those; otherwise\n * - If a target environment is given, scan all credential provider plugins\n * for credentials, and return those if found; otherwise\n * - Return default (\"current\") SDK credentials, noting that they might be wrong.\n *\n * - Second, a role may optionally need to be assumed. Use the base credentials\n * established in the previous process to assume that role.\n * - If assuming the role fails and the base credentials are for the correct\n * account, return those. This is a fallback for people who are trying to interact\n * with a Default Synthesized stack and already have right credentials setup.\n *\n * Typical cases we see in the wild:\n * - Credential plugin setup that, although not recommended, works for them\n * - Seeded terminal with `ReadOnly` credentials in order to do `cdk diff`--the `ReadOnly`\n * role doesn't have `sts:AssumeRole` and will fail for no real good reason.\n */\n@traceMemberMethods\nexport class SdkProvider {\n /**\n * Create a new SdkProvider which gets its defaults in a way that behaves like the AWS CLI does\n *\n * The AWS SDK for JS behaves slightly differently from the AWS CLI in a number of ways; see the\n * class `AwsCliCompatible` for the details.\n */\n public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions = {}) {\n callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger);\n const credentialProvider = await AwsCliCompatible.credentialChainBuilder({\n profile: options.profile,\n httpOptions: options.httpOptions,\n logger: options.logger,\n });\n\n const region = await AwsCliCompatible.region(options.profile);\n const requestHandler = AwsCliCompatible.requestHandlerBuilder(options.httpOptions);\n return new SdkProvider(credentialProvider, region, requestHandler, options.logger);\n }\n\n private readonly plugins = new CredentialPlugins();\n\n public constructor(\n private readonly defaultCredentialProvider: AwsCredentialIdentityProvider,\n /**\n * Default region\n */\n public readonly defaultRegion: string,\n private readonly requestHandler: NodeHttpHandlerOptions = {},\n private readonly logger?: Logger,\n ) {\n }\n\n /**\n * Return an SDK which can do operations in the given environment\n *\n * The `environment` parameter is resolved first (see `resolveEnvironment()`).\n */\n public async forEnvironment(\n environment: Environment,\n mode: Mode,\n options?: CredentialsOptions,\n quiet = false,\n ): Promise<SdkForEnvironment> {\n const env = await this.resolveEnvironment(environment);\n\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n\n // At this point, we need at least SOME credentials\n if (baseCreds.source === 'none') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Simple case is if we don't need to \"assumeRole\" here. If so, we must now have credentials for the right\n // account.\n if (options?.assumeRoleArn === undefined) {\n if (baseCreds.source === 'incorrectDefault') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Our current credentials must be valid and not expired. Confirm that before we get into doing\n // actual CloudFormation calls, which might take a long time to hang.\n const sdk = new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger);\n await sdk.validateCredentials();\n return { sdk, didAssumeRole: false };\n }\n\n try {\n // We will proceed to AssumeRole using whatever we've been given.\n const sdk = await this.withAssumedRole(\n baseCreds,\n options.assumeRoleArn,\n options.assumeRoleExternalId,\n options.assumeRoleAdditionalOptions,\n env.region,\n );\n\n return { sdk, didAssumeRole: true };\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n // AssumeRole failed. Proceed and warn *if and only if* the baseCredentials were already for the right account\n // or returned from a plugin. This is to cover some current setups for people using plugins or preferring to\n // feed the CLI credentials which are sufficient by themselves. Prefer to assume the correct role if we can,\n // but if we can't then let's just try with available credentials anyway.\n if (baseCreds.source === 'correctDefault' || baseCreds.source === 'plugin') {\n debug(err.message);\n const logger = quiet ? debug : warning;\n logger(\n `${fmtObtainedCredentials(baseCreds)} could not be used to assume '${options.assumeRoleArn}', but are for the right account. Proceeding anyway.`,\n );\n return {\n sdk: new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger),\n didAssumeRole: false,\n };\n }\n\n throw err;\n }\n }\n\n /**\n * Return the partition that base credentials are for\n *\n * Returns `undefined` if there are no base credentials.\n */\n public async baseCredentialsPartition(environment: Environment, mode: Mode): Promise<string | undefined> {\n const env = await this.resolveEnvironment(environment);\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n if (baseCreds.source === 'none') {\n return undefined;\n }\n return (await new SDK(baseCreds.credentials, env.region, this.requestHandler, this.logger).currentAccount()).partition;\n }\n\n /**\n * Resolve the environment for a stack\n *\n * Replaces the magic values `UNKNOWN_REGION` and `UNKNOWN_ACCOUNT`\n * with the defaults for the current SDK configuration (`~/.aws/config` or\n * otherwise).\n *\n * It is an error if `UNKNOWN_ACCOUNT` is used but the user hasn't configured\n * any SDK credentials.\n */\n public async resolveEnvironment(env: Environment): Promise<Environment> {\n const region = env.region !== UNKNOWN_REGION ? env.region : this.defaultRegion;\n const account = env.account !== UNKNOWN_ACCOUNT ? env.account : (await this.defaultAccount())?.accountId;\n\n if (!account) {\n throw new AuthenticationError(\n 'Unable to resolve AWS account to use. It must be either configured when you define your CDK Stack, or through the environment',\n );\n }\n\n return {\n region,\n account,\n name: EnvironmentUtils.format(account, region),\n };\n }\n\n /**\n * The account we'd auth into if we used default credentials.\n *\n * Default credentials are the set of ambiently configured credentials using\n * one of the environment variables, or ~/.aws/credentials, or the *one*\n * profile that was passed into the CLI.\n *\n * Might return undefined if there are no default/ambient credentials\n * available (in which case the user should better hope they have\n * credential plugins configured).\n *\n * Uses a cache to avoid STS calls if we don't need 'em.\n */\n public async defaultAccount(): Promise<Account | undefined> {\n return cached(this, CACHED_ACCOUNT, async () => {\n try {\n return await new SDK(this.defaultCredentialProvider, this.defaultRegion, this.requestHandler, this.logger).currentAccount();\n } catch (e: any) {\n // Treat 'ExpiredToken' specially. This is a common situation that people may find themselves in, and\n // they are complaining about if we fail 'cdk synth' on them. We loudly complain in order to show that\n // the current situation is probably undesirable, but we don't fail.\n if (e.name === 'ExpiredToken') {\n warning(\n 'There are expired AWS credentials in your environment. The CDK app will synth without current account information.',\n );\n return undefined;\n }\n\n debug(`Unable to determine the default AWS account (${e.name}): ${formatErrorMessage(e)}`);\n return undefined;\n }\n });\n }\n\n /**\n * Get credentials for the given account ID in the given mode\n *\n * 1. Use the default credentials if the destination account matches the\n * current credentials' account.\n * 2. Otherwise try all credential plugins.\n * 3. Fail if neither of these yield any credentials.\n * 4. Return a failure if any of them returned credentials\n */\n private async obtainBaseCredentials(accountId: string, mode: Mode): Promise<ObtainBaseCredentialsResult> {\n // First try 'current' credentials\n const defaultAccountId = (await this.defaultAccount())?.accountId;\n if (defaultAccountId === accountId) {\n return {\n source: 'correctDefault',\n credentials: await this.defaultCredentialProvider,\n };\n }\n\n // Then try the plugins\n const pluginCreds = await this.plugins.fetchCredentialsFor(accountId, mode);\n if (pluginCreds) {\n return { source: 'plugin', ...pluginCreds };\n }\n\n // Fall back to default credentials with a note that they're not the right ones yet\n if (defaultAccountId !== undefined) {\n return {\n source: 'incorrectDefault',\n accountId: defaultAccountId,\n credentials: await this.defaultCredentialProvider,\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n // Apparently we didn't find any at all\n return {\n source: 'none',\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n /**\n * Return an SDK which uses assumed role credentials\n *\n * The base credentials used to retrieve the assumed role credentials will be the\n * same credentials returned by obtainCredentials if an environment and mode is passed,\n * otherwise it will be the current credentials.\n */\n private async withAssumedRole(\n mainCredentials: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>,\n roleArn: string,\n externalId?: string,\n additionalOptions?: AssumeRoleAdditionalOptions,\n region?: string,\n ): Promise<SDK> {\n debug(`Assuming role '${roleArn}'.`);\n\n region = region ?? this.defaultRegion;\n\n const sourceDescription = fmtObtainedCredentials(mainCredentials);\n\n try {\n const credentials = await makeCachingProvider(fromTemporaryCredentials({\n masterCredentials: mainCredentials.credentials,\n params: {\n RoleArn: roleArn,\n ExternalId: externalId,\n RoleSessionName: `aws-cdk-${safeUsername()}`,\n ...additionalOptions,\n TransitiveTagKeys: additionalOptions?.Tags ? additionalOptions.Tags.map((t) => t.Key!) : undefined,\n },\n clientConfig: {\n region,\n requestHandler: this.requestHandler,\n customUserAgent: 'aws-cdk',\n logger: this.logger,\n },\n logger: this.logger,\n }));\n\n // Call the provider at least once here, to catch an error if it occurs\n await credentials();\n\n return new SDK(credentials, region, this.requestHandler, this.logger);\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n debug(`Assuming role failed: ${err.message}`);\n throw new AuthenticationError(\n [\n 'Could not assume role in target account',\n ...(sourceDescription ? [`using ${sourceDescription}`] : []),\n err.message,\n \". Please make sure that this role exists in the account. If it doesn't exist, (re)-bootstrap the environment \" +\n \"with the right '--trust', using the latest version of the CDK CLI.\",\n ].join(' '),\n );\n }\n }\n}\n\n/**\n * An AWS account\n *\n * An AWS account always exists in only one partition. Usually we don't care about\n * the partition, but when we need to form ARNs we do.\n */\nexport interface Account {\n /**\n * The account number\n */\n readonly accountId: string;\n\n /**\n * The partition ('aws' or 'aws-cn' or otherwise)\n */\n readonly partition: string;\n}\n\n/**\n * Return the username with characters invalid for a RoleSessionName removed\n *\n * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters\n */\nfunction safeUsername() {\n try {\n return os.userInfo().username.replace(/[^\\w+=,.@-]/g, '@');\n } catch {\n return 'noname';\n }\n}\n\n/**\n * Options for obtaining credentials for an environment\n */\nexport interface CredentialsOptions {\n /**\n * The ARN of the role that needs to be assumed, if any\n */\n readonly assumeRoleArn?: string;\n\n /**\n * External ID required to assume the given role.\n */\n readonly assumeRoleExternalId?: string;\n\n /**\n * Session tags required to assume the given role.\n */\n readonly assumeRoleAdditionalOptions?: AssumeRoleAdditionalOptions;\n}\n\n/**\n * Result of obtaining base credentials\n */\ntype ObtainBaseCredentialsResult =\n | { source: 'correctDefault'; credentials: AwsCredentialIdentityProvider }\n | { source: 'plugin'; pluginName: string; credentials: AwsCredentialIdentityProvider }\n | {\n source: 'incorrectDefault';\n credentials: AwsCredentialIdentityProvider;\n accountId: string;\n unusedPlugins: string[];\n }\n | { source: 'none'; unusedPlugins: string[] };\n\n/**\n * Isolating the code that translates calculation errors into human error messages\n *\n * We cover the following cases:\n *\n * - No credentials are available at all\n * - Default credentials are for the wrong account\n */\nfunction fmtObtainCredentialsError(\n targetAccountId: string,\n obtainResult: ObtainBaseCredentialsResult & {\n source: 'none' | 'incorrectDefault';\n },\n): string {\n const msg = [`Need to perform AWS calls for account ${targetAccountId}`];\n switch (obtainResult.source) {\n case 'incorrectDefault':\n msg.push(`but the current credentials are for ${obtainResult.accountId}`);\n break;\n case 'none':\n msg.push('but no credentials have been configured');\n }\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`and none of these plugins found any: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n return msg.join(', ');\n}\n\n/**\n * Format a message indicating where we got base credentials for the assume role\n *\n * We cover the following cases:\n *\n * - Default credentials for the right account\n * - Default credentials for the wrong account\n * - Credentials returned from a plugin\n */\nfunction fmtObtainedCredentials(obtainResult: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>): string {\n switch (obtainResult.source) {\n case 'correctDefault':\n return 'current credentials';\n case 'plugin':\n return `credentials returned by plugin '${obtainResult.pluginName}'`;\n case 'incorrectDefault':\n const msg = [];\n msg.push(`current credentials (which are for account ${obtainResult.accountId}`);\n\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`, and none of the following plugins provided credentials: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n msg.push(')');\n\n return msg.join('');\n }\n}\n\n/**\n * Instantiate an SDK for context providers. This function ensures that all\n * lookup assume role options are used when context providers perform lookups.\n */\nexport async function initContextProviderSdk(aws: SdkProvider, options: ContextLookupRoleOptions): Promise<SDK> {\n const account = options.account;\n const region = options.region;\n\n const creds: CredentialsOptions = {\n assumeRoleArn: options.lookupRoleArn,\n assumeRoleExternalId: options.lookupRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n };\n\n return (await aws.forEnvironment(EnvironmentUtils.make(account, region), Mode.ForReading, creds)).sdk;\n}\n", "import { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers';\nimport { MetadataService } from '@aws-sdk/ec2-metadata-service';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader';\nimport { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport * as promptly from 'promptly';\nimport { ProxyAgent } from 'proxy-agent';\nimport { makeCachingProvider } from './provider-caching';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { readIfPossible } from './util';\nimport { debug } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\nconst DEFAULT_TIMEOUT = 300000;\n\n/**\n * Behaviors to match AWS CLI\n *\n * See these links:\n *\n * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html\n * https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html\n */\nexport class AwsCliCompatible {\n /**\n * Build an AWS CLI-compatible credential chain provider\n *\n * The credential chain returned by this function is always caching.\n */\n public static async credentialChainBuilder(\n options: CredentialChainOptions = {},\n ): Promise<AwsCredentialIdentityProvider> {\n const clientConfig = {\n requestHandler: AwsCliCompatible.requestHandlerBuilder(options.httpOptions),\n customUserAgent: 'aws-cdk',\n logger: options.logger,\n };\n\n // Super hacky solution to https://github.com/aws/aws-cdk/issues/32510, proposed by the SDK team.\n //\n // Summary of the problem: we were reading the region from the config file and passing it to\n // the credential providers. However, in the case of SSO, this makes the credential provider\n // use that region to do the SSO flow, which is incorrect. The region that should be used for\n // that is the one set in the sso_session section of the config file.\n //\n // The idea here: the \"clientConfig\" is for configuring the inner auth client directly,\n // and has the highest priority, whereas \"parentClientConfig\" is the upper data client\n // and has lower priority than the sso_region but still higher priority than STS global region.\n const parentClientConfig = {\n region: await this.region(options.profile),\n };\n /**\n * The previous implementation matched AWS CLI behavior:\n *\n * If a profile is explicitly set using `--profile`,\n * we use that to the exclusion of everything else.\n *\n * Note: this does not apply to AWS_PROFILE,\n * environment credentials still take precedence over AWS_PROFILE\n */\n if (options.profile) {\n return makeCachingProvider(fromIni({\n profile: options.profile,\n ignoreCache: true,\n mfaCodeProvider: tokenCodeFn,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n }));\n }\n\n const envProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE;\n\n /**\n * Env AWS - EnvironmentCredentials with string AWS\n * Env Amazon - EnvironmentCredentials with string AMAZON\n * Profile Credentials - PatchedSharedIniFileCredentials with implicit profile, credentials file, http options, and token fn\n * SSO with implicit profile only\n * SharedIniFileCredentials with implicit profile and preferStaticCredentials true (profile with source_profile)\n * Shared Credential file that points to Environment Credentials with AWS prefix\n * Shared Credential file that points to EC2 Metadata\n * Shared Credential file that points to ECS Credentials\n * SSO Credentials - SsoCredentials with implicit profile and http options\n * ProcessCredentials with implicit profile\n * ECS Credentials - ECSCredentials with no input OR Web Identity - TokenFileWebIdentityCredentials with no input OR EC2 Metadata - EC2MetadataCredentials with no input\n *\n * These translate to:\n * fromEnv()\n * fromSSO()/fromIni()\n * fromProcess()\n * fromContainerMetadata()\n * fromTokenFile()\n * fromInstanceMetadata()\n *\n * The NodeProviderChain is already cached.\n */\n const nodeProviderChain = fromNodeProviderChain({\n profile: envProfile,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n mfaCodeProvider: tokenCodeFn,\n ignoreCache: true,\n });\n\n return shouldPrioritizeEnv()\n ? createCredentialChain(fromEnv(), nodeProviderChain).expireAfter(60 * 60_000)\n : nodeProviderChain;\n }\n\n public static requestHandlerBuilder(options: SdkHttpOptions = {}): NodeHttpHandlerOptions {\n const agent = this.proxyAgent(options);\n\n return {\n connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,\n requestTimeout: DEFAULT_TIMEOUT,\n httpsAgent: agent,\n httpAgent: agent,\n };\n }\n\n public static proxyAgent(options: SdkHttpOptions) {\n // Force it to use the proxy provided through the command line.\n // Otherwise, let the ProxyAgent auto-detect the proxy using environment variables.\n const getProxyForUrl = options.proxyAddress != null\n ? () => Promise.resolve(options.proxyAddress!)\n : undefined;\n\n return new ProxyAgent({\n ca: tryGetCACert(options.caBundlePath),\n getProxyForUrl,\n });\n }\n\n /**\n * Attempts to get the region from a number of sources and falls back to us-east-1 if no region can be found,\n * as is done in the AWS CLI.\n *\n * The order of priority is the following:\n *\n * 1. Environment variables specifying region, with both an AWS prefix and AMAZON prefix\n * to maintain backwards compatibility, and without `DEFAULT` in the name because\n * Lambda and CodeBuild set the $AWS_REGION variable.\n * 2. Regions listed in the Shared Ini Files - First checking for the profile provided\n * and then checking for the default profile.\n * 3. IMDS instance identity region from the Metadata Service.\n * 4. us-east-1\n */\n public static async region(maybeProfile?: string): Promise<string> {\n const defaultRegion = 'us-east-1';\n const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';\n\n const region =\n process.env.AWS_REGION ||\n process.env.AMAZON_REGION ||\n process.env.AWS_DEFAULT_REGION ||\n process.env.AMAZON_DEFAULT_REGION ||\n (await getRegionFromIni(profile)) ||\n (await regionFromMetadataService());\n\n if (!region) {\n const usedProfile = !profile ? '' : ` (profile: \"${profile}\")`;\n debug(\n `Unable to determine AWS region from environment or AWS configuration${usedProfile}, defaulting to '${defaultRegion}'`,\n );\n return defaultRegion;\n }\n\n return region;\n }\n}\n\n/**\n * Looks up the region of the provided profile. If no region is present,\n * it will attempt to lookup the default region.\n * @param profile The profile to use to lookup the region\n * @returns The region for the profile or default profile, if present. Otherwise returns undefined.\n */\nasync function getRegionFromIni(profile: string): Promise<string | undefined> {\n const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true });\n\n // Priority:\n //\n // credentials come before config because aws-cli v1 behaves like that.\n //\n // 1. profile-region-in-credentials\n // 2. profile-region-in-config\n // 3. default-region-in-credentials\n // 4. default-region-in-config\n\n return getRegionFromIniFile(profile, sharedFiles.credentialsFile)\n ?? getRegionFromIniFile(profile, sharedFiles.configFile)\n ?? getRegionFromIniFile('default', sharedFiles.credentialsFile)\n ?? getRegionFromIniFile('default', sharedFiles.configFile);\n}\n\nfunction getRegionFromIniFile(profile: string, data?: any) {\n return data?.[profile]?.region;\n}\n\nfunction tryGetCACert(bundlePath?: string) {\n const path = bundlePath || caBundlePathFromEnvironment();\n if (path) {\n debug('Using CA bundle path: %s', path);\n return readIfPossible(path);\n }\n return undefined;\n}\n\n/**\n * Find and return a CA certificate bundle path to be passed into the SDK.\n */\nfunction caBundlePathFromEnvironment(): string | undefined {\n if (process.env.aws_ca_bundle) {\n return process.env.aws_ca_bundle;\n }\n if (process.env.AWS_CA_BUNDLE) {\n return process.env.AWS_CA_BUNDLE;\n }\n return undefined;\n}\n\n/**\n * We used to support both AWS and AMAZON prefixes for these environment variables.\n *\n * Adding this for backward compatibility.\n */\nfunction shouldPrioritizeEnv() {\n const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;\n const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;\n\n if (!!id && !!key) {\n process.env.AWS_ACCESS_KEY_ID = id;\n process.env.AWS_SECRET_ACCESS_KEY = key;\n\n const sessionToken = process.env.AWS_SESSION_TOKEN ?? process.env.AMAZON_SESSION_TOKEN;\n if (sessionToken) {\n process.env.AWS_SESSION_TOKEN = sessionToken;\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * The MetadataService class will attempt to fetch the instance identity document from\n * IMDSv2 first, and then will attempt v1 as a fallback.\n *\n * If this fails, we will use us-east-1 as the region so no error should be thrown.\n * @returns The region for the instance identity\n */\nasync function regionFromMetadataService() {\n debug('Looking up AWS region in the EC2 Instance Metadata Service (IMDS).');\n try {\n const metadataService = new MetadataService({\n httpOptions: {\n timeout: 1000,\n },\n });\n\n await metadataService.fetchMetadataToken();\n const document = await metadataService.request('/latest/dynamic/instance-identity/document', {});\n return JSON.parse(document).region;\n } catch (e) {\n debug(`Unable to retrieve AWS region from IMDS: ${e}`);\n }\n}\n\nexport interface CredentialChainOptions {\n readonly profile?: string;\n readonly httpOptions?: SdkHttpOptions;\n readonly logger?: Logger;\n}\n\n/**\n * Ask user for MFA token for given serial\n *\n * Result is send to callback function for SDK to authorize the request\n */\nasync function tokenCodeFn(serialArn: string): Promise<string> {\n debug('Require MFA token for serial ARN', serialArn);\n try {\n const token: string = await promptly.prompt(`MFA token for ${serialArn}: `, {\n trim: true,\n default: '',\n });\n debug('Successfully got MFA token from user');\n return token;\n } catch (err: any) {\n debug('Failed to get MFA token', err);\n const e = new AuthenticationError(`Error fetching MFA token: ${err.message ?? err}`);\n e.name = 'SharedIniFileCredentialsProviderFailure';\n throw e;\n }\n}\n", "import { memoize } from '@smithy/property-provider';\nimport { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\n\n/**\n * Wrap a credential provider in a cache\n *\n * Some credential providers in the SDKv3 are cached (the default Node\n * chain, specifically) but most others are not.\n *\n * Since we want to avoid duplicate calls to `AssumeRole`, or duplicate\n * MFA prompts or what have you, we are going to liberally wrap providers\n * in caches which will return the cached value until it expires.\n */\nexport function makeCachingProvider(provider: AwsCredentialIdentityProvider): AwsCredentialIdentityProvider {\n return memoize(\n provider,\n credentialsAboutToExpire,\n (token) => !!token.expiration,\n );\n}\n\nexport function credentialsAboutToExpire(token: AwsCredentialIdentity) {\n const expiryMarginSecs = 5;\n // token.expiration is sometimes null\n return !!token.expiration && token.expiration.getTime() - Date.now() < expiryMarginSecs * 1000;\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, ForReading, ForWriting, PluginProviderResult, SDKv2CompatibleCredentials, SDKv3CompatibleCredentialProvider, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\nimport { credentialsAboutToExpire, makeCachingProvider } from './provider-caching';\nimport { debug, warning } from '../../logging';\nimport { AuthenticationError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { Mode } from '../plugin/mode';\nimport { PluginHost } from '../plugin/plugin';\n\n/**\n * Cache for credential providers.\n *\n * Given an account and an operating mode (read or write) will return an\n * appropriate credential provider for credentials for the given account. The\n * credential provider will be cached so that multiple AWS clients for the same\n * environment will not make multiple network calls to obtain credentials.\n *\n * Will use default credentials if they are for the right account; otherwise,\n * all loaded credential provider plugins will be tried to obtain credentials\n * for the given account.\n */\nexport class CredentialPlugins {\n private readonly cache: { [key: string]: PluginCredentialsFetchResult | undefined } = {};\n private readonly host: PluginHost;\n\n constructor(host?: PluginHost) {\n this.host = host ?? PluginHost.instance;\n }\n\n public async fetchCredentialsFor(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const key = `${awsAccountId}-${mode}`;\n if (!(key in this.cache)) {\n this.cache[key] = await this.lookupCredentials(awsAccountId, mode);\n }\n return this.cache[key];\n }\n\n public get availablePluginNames(): string[] {\n return this.host.credentialProviderSources.map((s) => s.name);\n }\n\n private async lookupCredentials(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const triedSources: CredentialProviderSource[] = [];\n // Otherwise, inspect the various credential sources we have\n for (const source of this.host.credentialProviderSources) {\n let available: boolean;\n try {\n available = await source.isAvailable();\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n warning(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`);\n available = false;\n }\n\n if (!available) {\n debug('Credentials source %s is not available, ignoring it.', source.name);\n continue;\n }\n triedSources.push(source);\n let canProvide: boolean;\n try {\n canProvide = await source.canProvideCredentials(awsAccountId);\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n warning(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`);\n canProvide = false;\n }\n if (!canProvide) {\n continue;\n }\n debug(`Using ${source.name} credentials for account ${awsAccountId}`);\n\n return {\n credentials: await v3ProviderFromPlugin(() => source.getProvider(awsAccountId, mode as ForReading | ForWriting, {\n supportsV3Providers: true,\n })),\n pluginName: source.name,\n };\n }\n return undefined;\n }\n}\n\n/**\n * Result from trying to fetch credentials from the Plugin host\n */\nexport interface PluginCredentialsFetchResult {\n /**\n * SDK-v3 compatible credential provider\n */\n readonly credentials: AwsCredentialIdentityProvider;\n\n /**\n * Name of plugin that successfully provided credentials\n */\n readonly pluginName: string;\n}\n\n/**\n * Take a function that calls the plugin, and turn it into an SDKv3-compatible credential provider.\n *\n * What we will do is the following:\n *\n * - Query the plugin and see what kind of result it gives us.\n * - If the result is self-refreshing or doesn't need refreshing, we turn it into an SDKv3 provider\n * and return it directly.\n * * If the underlying return value is a provider, we will make it a caching provider\n * (because we can't know if it will cache by itself or not).\n * * If the underlying return value is a static credential, caching isn't relevant.\n * * If the underlying return value is V2 credentials, those have caching built-in.\n * - If the result is a static credential that expires, we will wrap it in an SDKv3 provider\n * that will query the plugin again when the credential expires.\n */\nasync function v3ProviderFromPlugin(producer: () => Promise<PluginProviderResult>): Promise<AwsCredentialIdentityProvider> {\n const initial = await producer();\n\n if (isV3Provider(initial)) {\n // Already a provider, make caching\n return makeCachingProvider(initial);\n } else if (isV3Credentials(initial) && initial.expiration === undefined) {\n // Static credentials that don't need refreshing nor caching\n return () => Promise.resolve(initial);\n } else if (isV3Credentials(initial) && initial.expiration !== undefined) {\n // Static credentials that do need refreshing and caching\n return refreshFromPluginProvider(initial, producer);\n } else if (isV2Credentials(initial)) {\n // V2 credentials that refresh and cache themselves\n return v3ProviderFromV2Credentials(initial);\n } else {\n throw new AuthenticationError(`Plugin returned a value that doesn't resemble AWS credentials: ${inspect(initial)}`);\n }\n}\n\n/**\n * Converts a V2 credential into a V3-compatible provider\n */\nfunction v3ProviderFromV2Credentials(x: SDKv2CompatibleCredentials): AwsCredentialIdentityProvider {\n return async () => {\n // Get will fetch or refresh as necessary\n await x.getPromise();\n\n return {\n accessKeyId: x.accessKeyId,\n secretAccessKey: x.secretAccessKey,\n sessionToken: x.sessionToken,\n expiration: x.expireTime ?? undefined,\n };\n };\n}\n\nfunction refreshFromPluginProvider(current: AwsCredentialIdentity, producer: () => Promise<PluginProviderResult>): AwsCredentialIdentityProvider {\n return async () => {\n if (credentialsAboutToExpire(current)) {\n const newCreds = await producer();\n if (!isV3Credentials(newCreds)) {\n throw new AuthenticationError(`Plugin initially returned static V3 credentials but now returned something else: ${inspect(newCreds)}`);\n }\n current = newCreds;\n }\n return current;\n };\n}\n\nfunction isV3Provider(x: PluginProviderResult): x is SDKv3CompatibleCredentialProvider {\n return typeof x === 'function';\n}\n\nfunction isV2Credentials(x: PluginProviderResult): x is SDKv2CompatibleCredentials {\n return !!(x && typeof x === 'object' && (x as SDKv2CompatibleCredentials).getPromise);\n}\n\nfunction isV3Credentials(x: PluginProviderResult): x is SDKv3CompatibleCredentials {\n return !!(x && typeof x === 'object' && x.accessKeyId && !isV2Credentials(x));\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';\n\nimport * as chalk from 'chalk';\nimport { type ContextProviderPlugin, isContextProviderPlugin } from './context-provider-plugin';\nimport { error } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\n\nexport let TESTING = false;\n\nexport function markTesting() {\n TESTING = true;\n}\n\n/**\n * A utility to manage plug-ins.\n *\n */\nexport class PluginHost implements IPluginHost {\n public static instance = new PluginHost();\n\n /**\n * Access the currently registered CredentialProviderSources. New sources can\n * be registered using the +registerCredentialProviderSource+ method.\n */\n public readonly credentialProviderSources = new Array<CredentialProviderSource>();\n\n public readonly contextProviderPlugins: Record<string, ContextProviderPlugin> = {};\n\n constructor() {\n if (!TESTING && PluginHost.instance && PluginHost.instance !== this) {\n throw new ToolkitError('New instances of PluginHost must not be built. Use PluginHost.instance instead!');\n }\n }\n\n /**\n * Loads a plug-in into this PluginHost.\n *\n * @param moduleSpec the specification (path or name) of the plug-in module to be loaded.\n */\n public load(moduleSpec: string) {\n try {\n /* eslint-disable @typescript-eslint/no-require-imports */\n const plugin = require(moduleSpec);\n /* eslint-enable */\n if (!isPlugin(plugin)) {\n error(`Module ${chalk.green(moduleSpec)} is not a valid plug-in, or has an unsupported version.`);\n throw new ToolkitError(`Module ${moduleSpec} does not define a valid plug-in.`);\n }\n if (plugin.init) {\n plugin.init(this);\n }\n } catch (e: any) {\n error(`Unable to load ${chalk.green(moduleSpec)}: ${e.stack}`);\n throw new ToolkitError(`Unable to load plug-in: ${moduleSpec}: ${e}`);\n }\n\n function isPlugin(x: any): x is Plugin {\n return x != null && x.version === '1';\n }\n }\n\n /**\n * Allows plug-ins to register new CredentialProviderSources.\n *\n * @param source a new CredentialProviderSource to register.\n */\n public registerCredentialProviderSource(source: CredentialProviderSource) {\n // Forward to the right credentials-related plugin host\n this.credentialProviderSources.push(source);\n }\n\n /**\n * (EXPERIMENTAL) Allow plugins to register context providers\n *\n * Context providers are objects with the following method:\n *\n * ```ts\n * getValue(args: {[key: string]: any}): Promise<any>;\n * ```\n *\n * Currently, they cannot reuse the CDK's authentication mechanisms, so they\n * must be prepared to either not make AWS calls or use their own source of\n * AWS credentials.\n *\n * This feature is experimental, and only intended to be used internally at Amazon\n * as a trial.\n *\n * After registering with 'my-plugin-name', the provider must be addressed as follows:\n *\n * ```ts\n * const value = ContextProvider.getValue(this, {\n * providerName: 'plugin',\n * props: {\n * pluginName: 'my-plugin-name',\n * myParameter1: 'xyz',\n * },\n * includeEnvironment: true | false,\n * dummyValue: 'what-to-return-on-the-first-pass',\n * })\n * ```\n *\n * @experimental\n */\n public registerContextProviderAlpha(pluginProviderName: string, provider: ContextProviderPlugin) {\n if (!isContextProviderPlugin(provider)) {\n throw new ToolkitError(`Object you gave me does not look like a ContextProviderPlugin: ${inspect(provider)}`);\n }\n this.contextProviderPlugins[pluginProviderName] = provider;\n }\n}\n", "export interface ContextProviderPlugin {\n getValue(args: {[key: string]: any}): Promise<any>;\n}\n\nexport function isContextProviderPlugin(x: unknown): x is ContextProviderPlugin {\n return typeof x === 'object' && !!x && !!(x as any).getValue;\n}\n", "import { inspect, format } from 'util';\nimport { Logger } from '@smithy/types';\nimport type { IIoHost } from '../../toolkit/cli-io-host';\nimport { replacerBufferWithInfo } from '../../util/serialize';\n\nexport class SdkToCliLogger implements Logger {\n private readonly ioHost: IIoHost;\n\n public constructor(ioHost: IIoHost) {\n this.ioHost = ioHost;\n }\n\n private notify(level: 'debug' | 'info' | 'warn' | 'error', ...content: any[]) {\n void this.ioHost.notify({\n time: new Date(),\n level: 'trace', // always log all SDK logs at trace level, no matter what level they are coming from the SDK\n action: 'none' as any,\n code: 'CDK_SDK_I0000',\n message: format('[SDK %s] %s', level, formatSdkLoggerContent(content)),\n });\n }\n\n public trace(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('trace', ...content);\n }\n\n public debug(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('debug', ...content);\n }\n\n /**\n * Info is called mostly (exclusively?) for successful API calls\n *\n * Payload:\n *\n * (Note the input contains entire CFN templates, for example)\n *\n * ```\n * {\n * clientName: 'S3Client',\n * commandName: 'GetBucketLocationCommand',\n * input: {\n * Bucket: '.....',\n * ExpectedBucketOwner: undefined\n * },\n * output: { LocationConstraint: 'eu-central-1' },\n * metadata: {\n * httpStatusCode: 200,\n * requestId: '....',\n * extendedRequestId: '...',\n * cfId: undefined,\n * attempts: 1,\n * totalRetryDelay: 0\n * }\n * }\n * ```\n */\n public info(...content: any[]) {\n this.notify('info', ...content);\n }\n\n public warn(...content: any[]) {\n this.notify('warn', ...content);\n }\n\n /**\n * Error is called mostly (exclusively?) for failing API calls\n *\n * Payload (input would be the entire API call arguments).\n *\n * ```\n * {\n * clientName: 'STSClient',\n * commandName: 'GetCallerIdentityCommand',\n * input: {},\n * error: AggregateError [ECONNREFUSED]:\n * at internalConnectMultiple (node:net:1121:18)\n * at afterConnectMultiple (node:net:1688:7) {\n * code: 'ECONNREFUSED',\n * '$metadata': { attempts: 3, totalRetryDelay: 600 },\n * [errors]: [ [Error], [Error] ]\n * },\n * metadata: { attempts: 3, totalRetryDelay: 600 }\n * }\n * ```\n */\n public error(...content: any[]) {\n this.notify('error', ...content);\n }\n}\n\n/**\n * This can be anything.\n *\n * For debug, it seems to be mostly strings.\n * For info, it seems to be objects.\n *\n * Stringify and join without separator.\n */\nexport function formatSdkLoggerContent(content: any[]) {\n if (content.length === 1) {\n const apiFmt = formatApiCall(content[0]);\n if (apiFmt) {\n return apiFmt;\n }\n }\n return content.map((x) => typeof x === 'string' ? x : inspect(x)).join('');\n}\n\nfunction formatApiCall(content: any): string | undefined {\n if (!isSdkApiCallSuccess(content) && !isSdkApiCallError(content)) {\n return undefined;\n }\n\n const service = content.clientName.replace(/Client$/, '');\n const api = content.commandName.replace(/Command$/, '');\n\n const parts = [];\n if ((content.metadata?.attempts ?? 0) > 1) {\n parts.push(`[${content.metadata?.attempts} attempts, ${content.metadata?.totalRetryDelay}ms retry]`);\n }\n\n parts.push(`${service}.${api}(${JSON.stringify(content.input, replacerBufferWithInfo)})`);\n\n if (isSdkApiCallSuccess(content)) {\n parts.push('-> OK');\n } else {\n parts.push(`-> ${content.error}`);\n }\n\n return parts.join(' ');\n}\n\ninterface SdkApiCallBase {\n clientName: string;\n commandName: string;\n input: Record<string, unknown>;\n metadata?: {\n httpStatusCode?: number;\n requestId?: string;\n extendedRequestId?: string;\n cfId?: string;\n attempts?: number;\n totalRetryDelay?: number;\n };\n}\n\ntype SdkApiCallSuccess = SdkApiCallBase & { output: Record<string, unknown> };\ntype SdkApiCallError = SdkApiCallBase & { error: Error };\n\nfunction isSdkApiCallSuccess(x: any): x is SdkApiCallSuccess {\n return x && typeof x === 'object' && x.commandName && x.output;\n}\n\nfunction isSdkApiCallError(x: any): x is SdkApiCallError {\n return x && typeof x === 'object' && x.commandName && x.error;\n}\n", "import * as os from 'os';\nimport * as fs_path from 'path';\nimport * as fs from 'fs-extra';\nimport { warning } from '../logging';\nimport { ToolkitError } from '../toolkit/error';\nimport * as util from '../util/objects';\n\nexport type SettingsMap = { [key: string]: any };\n\n/**\n * If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json\n */\nexport const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';\n\n/**\n * A single bag of settings\n */\nexport class Settings {\n public static mergeAll(...settings: Settings[]): Settings {\n let ret = new Settings();\n for (const setting of settings) {\n ret = ret.merge(setting);\n }\n return ret;\n }\n\n constructor(\n private settings: SettingsMap = {},\n public readonly readOnly = false,\n ) {\n }\n\n public async load(fileName: string): Promise<this> {\n if (this.readOnly) {\n throw new ToolkitError(\n `Can't load ${fileName}: settings object is readonly`,\n );\n }\n this.settings = {};\n\n const expanded = expandHomeDir(fileName);\n if (await fs.pathExists(expanded)) {\n this.settings = await fs.readJson(expanded);\n }\n\n // See https://github.com/aws/aws-cdk/issues/59\n this.prohibitContextKey('default-account', fileName);\n this.prohibitContextKey('default-region', fileName);\n this.warnAboutContextKey('aws:', fileName);\n\n return this;\n }\n\n public async save(fileName: string): Promise<this> {\n const expanded = expandHomeDir(fileName);\n await fs.writeJson(expanded, stripTransientValues(this.settings), {\n spaces: 2,\n });\n return this;\n }\n\n public get all(): any {\n return this.get([]);\n }\n\n public merge(other: Settings): Settings {\n return new Settings(util.deepMerge(this.settings, other.settings));\n }\n\n public subSettings(keyPrefix: string[]) {\n return new Settings(this.get(keyPrefix) || {}, false);\n }\n\n public makeReadOnly(): Settings {\n return new Settings(this.settings, true);\n }\n\n public clear() {\n if (this.readOnly) {\n throw new ToolkitError('Cannot clear(): settings are readonly');\n }\n this.settings = {};\n }\n\n public get empty(): boolean {\n return Object.keys(this.settings).length === 0;\n }\n\n public get(path: string[]): any {\n return util.deepClone(util.deepGet(this.settings, path));\n }\n\n public set(path: string[], value: any): Settings {\n if (this.readOnly) {\n throw new ToolkitError(`Can't set ${path}: settings object is readonly`);\n }\n if (path.length === 0) {\n // deepSet can't handle this case\n this.settings = value;\n } else {\n util.deepSet(this.settings, path, value);\n }\n return this;\n }\n\n public unset(path: string[]) {\n this.set(path, undefined);\n }\n\n private prohibitContextKey(key: string, fileName: string) {\n if (!this.settings.context) {\n return;\n }\n if (key in this.settings.context) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `The 'context.${key}' key was found in ${fs_path.resolve(\n fileName,\n )}, but it is no longer supported. Please remove it.`,\n );\n }\n }\n\n private warnAboutContextKey(prefix: string, fileName: string) {\n if (!this.settings.context) {\n return;\n }\n for (const contextKey of Object.keys(this.settings.context)) {\n if (contextKey.startsWith(prefix)) {\n // eslint-disable-next-line max-len\n warning(\n `A reserved context key ('context.${prefix}') key was found in ${fs_path.resolve(\n fileName,\n )}, it might cause surprising behavior and should be removed.`,\n );\n }\n }\n }\n}\n\nfunction expandHomeDir(x: string) {\n if (x.startsWith('~')) {\n return fs_path.join(os.homedir(), x.slice(1));\n }\n return x;\n}\n\n/**\n * Return all context value that are not transient context values\n */\nfunction stripTransientValues(obj: { [key: string]: any }) {\n const ret: any = {};\n for (const [key, value] of Object.entries(obj)) {\n if (!isTransientValue(value)) {\n ret[key] = value;\n }\n }\n return ret;\n}\n\n/**\n * Return whether the given value is a transient context value\n *\n * Values that are objects with a magic key set to a truthy value are considered transient.\n */\nfunction isTransientValue(value: any) {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as any)[TRANSIENT_CONTEXT_KEY]\n );\n}\n", "import { Settings } from './settings';\nimport { ToolkitError } from '../toolkit/error';\n\nexport { TRANSIENT_CONTEXT_KEY } from './settings';\nexport const PROJECT_CONTEXT = 'cdk.context.json';\n\ninterface ContextBag {\n /**\n * The file name of the context. Will be used to potentially\n * save new context back to the original file.\n */\n fileName?: string;\n\n /**\n * The context values.\n */\n bag: Settings;\n}\n\n/**\n * Class that supports overlaying property bags\n *\n * Reads come from the first property bag that can has the given key,\n * writes go to the first property bag that is not readonly. A write\n * will remove the value from all property bags after the first\n * writable one.\n */\nexport class Context {\n private readonly bags: Settings[];\n private readonly fileNames: (string | undefined)[];\n\n constructor(...bags: ContextBag[]) {\n this.bags = bags.length > 0 ? bags.map((b) => b.bag) : [new Settings()];\n this.fileNames =\n bags.length > 0 ? bags.map((b) => b.fileName) : ['default'];\n }\n\n public get keys(): string[] {\n return Object.keys(this.all);\n }\n\n public has(key: string) {\n return this.keys.indexOf(key) > -1;\n }\n\n public get all(): { [key: string]: any } {\n let ret = new Settings();\n\n // In reverse order so keys to the left overwrite keys to the right of them\n for (const bag of [...this.bags].reverse()) {\n ret = ret.merge(bag);\n }\n\n return ret.all;\n }\n\n public get(key: string): any {\n for (const bag of this.bags) {\n const v = bag.get([key]);\n if (v !== undefined) {\n return v;\n }\n }\n return undefined;\n }\n\n public set(key: string, value: any) {\n for (const bag of this.bags) {\n if (bag.readOnly) {\n continue;\n }\n\n // All bags past the first one have the value erased\n bag.set([key], value);\n value = undefined;\n }\n }\n\n public unset(key: string) {\n this.set(key, undefined);\n }\n\n public clear() {\n for (const key of this.keys) {\n this.unset(key);\n }\n }\n\n /**\n * Save a specific context file\n */\n public async save(fileName: string): Promise<this> {\n const index = this.fileNames.indexOf(fileName);\n\n // File not found, don't do anything in this scenario\n if (index === -1) {\n return this;\n }\n\n const bag = this.bags[index];\n if (bag.readOnly) {\n throw new ToolkitError(`Context file ${fileName} is read only!`);\n }\n\n await bag.save(fileName);\n return this;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { SSMPARAM_NO_INVALIDATE } from '@aws-cdk/cx-api';\nimport {\n ChangeSetStatus,\n type DescribeChangeSetCommandOutput,\n type Parameter,\n type ResourceIdentifierSummary,\n type ResourceToImport,\n type Stack,\n type Tag,\n} from '@aws-sdk/client-cloudformation';\nimport { AssetManifest, FileManifestEntry } from 'cdk-assets';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { Deployments } from './deployments';\nimport { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { deserializeStructure } from '../../util/serialize';\nimport type { ICloudFormationClient, SdkProvider } from '../aws-auth';\nimport { StackStatus } from '../stack-events';\nimport { makeBodyParameter, TemplateBodyParameter } from '../util/template-body-parameter';\n\nexport type ResourcesToImport = ResourceToImport[];\nexport type ResourceIdentifierSummaries = ResourceIdentifierSummary[];\nexport type ResourceIdentifierProperties = Record<string, string>;\n\nexport type Template = {\n Parameters?: Record<string, TemplateParameter>;\n [key: string]: any;\n};\n\ninterface TemplateParameter {\n Type: string;\n Default?: any;\n Description?: string;\n [key: string]: any;\n}\n\n/**\n * Represents an (existing) Stack in CloudFormation\n *\n * Bundle and cache some information that we need during deployment (so we don't have to make\n * repeated calls to CloudFormation).\n */\nexport class CloudFormationStack {\n public static async lookup(\n cfn: ICloudFormationClient,\n stackName: string,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<CloudFormationStack> {\n try {\n const response = await cfn.describeStacks({ StackName: stackName });\n return new CloudFormationStack(cfn, stackName, response.Stacks && response.Stacks[0], retrieveProcessedTemplate);\n } catch (e: any) {\n if (e.name === 'ValidationError' && formatErrorMessage(e) === `Stack with id ${stackName} does not exist`) {\n return new CloudFormationStack(cfn, stackName, undefined);\n }\n throw e;\n }\n }\n\n /**\n * Return a copy of the given stack that does not exist\n *\n * It's a little silly that it needs arguments to do that, but there we go.\n */\n public static doesNotExist(cfn: ICloudFormationClient, stackName: string) {\n return new CloudFormationStack(cfn, stackName);\n }\n\n /**\n * From static information (for testing)\n */\n public static fromStaticInformation(cfn: ICloudFormationClient, stackName: string, stack: Stack) {\n return new CloudFormationStack(cfn, stackName, stack);\n }\n\n private _template: any;\n\n protected constructor(\n private readonly cfn: ICloudFormationClient,\n public readonly stackName: string,\n private readonly stack?: Stack,\n private readonly retrieveProcessedTemplate: boolean = false,\n ) {\n }\n\n /**\n * Retrieve the stack's deployed template\n *\n * Cached, so will only be retrieved once. Will return an empty\n * structure if the stack does not exist.\n */\n public async template(): Promise<Template> {\n if (!this.exists) {\n return {};\n }\n\n if (this._template === undefined) {\n const response = await this.cfn.getTemplate({\n StackName: this.stackName,\n TemplateStage: this.retrieveProcessedTemplate ? 'Processed' : 'Original',\n });\n this._template = (response.TemplateBody && deserializeStructure(response.TemplateBody)) || {};\n }\n return this._template;\n }\n\n /**\n * Whether the stack exists\n */\n public get exists() {\n return this.stack !== undefined;\n }\n\n /**\n * The stack's ID\n *\n * Throws if the stack doesn't exist.\n */\n public get stackId() {\n this.assertExists();\n return this.stack!.StackId!;\n }\n\n /**\n * The stack's current outputs\n *\n * Empty object if the stack doesn't exist\n */\n public get outputs(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const result: { [name: string]: string } = {};\n (this.stack!.Outputs || []).forEach((output) => {\n result[output.OutputKey!] = output.OutputValue!;\n });\n return result;\n }\n\n /**\n * The stack's status\n *\n * Special status NOT_FOUND if the stack does not exist.\n */\n public get stackStatus(): StackStatus {\n if (!this.exists) {\n return new StackStatus('NOT_FOUND', 'Stack not found during lookup');\n }\n return StackStatus.fromStackDescription(this.stack!);\n }\n\n /**\n * The stack's current tags\n *\n * Empty list if the stack does not exist\n */\n public get tags(): Tag[] {\n return this.stack?.Tags || [];\n }\n\n /**\n * SNS Topic ARNs that will receive stack events.\n *\n * Empty list if the stack does not exist\n */\n public get notificationArns(): string[] {\n return this.stack?.NotificationARNs ?? [];\n }\n\n /**\n * Return the names of all current parameters to the stack\n *\n * Empty list if the stack does not exist.\n */\n public get parameterNames(): string[] {\n return Object.keys(this.parameters);\n }\n\n /**\n * Return the names and values of all current parameters to the stack\n *\n * Empty object if the stack does not exist.\n */\n public get parameters(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const ret: Record<string, string> = {};\n for (const param of this.stack!.Parameters ?? []) {\n ret[param.ParameterKey!] = param.ResolvedValue ?? param.ParameterValue!;\n }\n return ret;\n }\n\n /**\n * Return the termination protection of the stack\n */\n public get terminationProtection(): boolean | undefined {\n return this.stack?.EnableTerminationProtection;\n }\n\n private assertExists() {\n if (!this.exists) {\n throw new ToolkitError(`No stack named '${this.stackName}'`);\n }\n }\n}\n\n/**\n * Describe a changeset in CloudFormation, regardless of its current state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the change set description.\n *\n * @returns CloudFormation information about the ChangeSet\n */\nasync function describeChangeSet(\n cfn: ICloudFormationClient,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n const response = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n\n // If fetchAll is true, traverse all pages from the change set description.\n while (fetchAll && response.NextToken != null) {\n const nextPage = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: response.ChangeSetId ?? changeSetName,\n NextToken: response.NextToken,\n });\n\n // Consolidate the changes\n if (nextPage.Changes != null) {\n response.Changes = response.Changes != null ? response.Changes.concat(nextPage.Changes) : nextPage.Changes;\n }\n\n // Forward the new NextToken\n response.NextToken = nextPage.NextToken;\n }\n\n return response;\n}\n\n/**\n * Waits for a function to return non-+undefined+ before returning.\n *\n * @param valueProvider a function that will return a value that is not +undefined+ once the wait should be over\n * @param timeout the time to wait between two calls to +valueProvider+\n *\n * @returns the value that was returned by +valueProvider+\n */\nasync function waitFor<T>(\n valueProvider: () => Promise<T | null | undefined>,\n timeout: number = 5000,\n): Promise<T | undefined> {\n while (true) {\n const result = await valueProvider();\n if (result === null) {\n return undefined;\n } else if (result !== undefined) {\n return result;\n }\n await new Promise((cb) => setTimeout(cb, timeout));\n }\n}\n\n/**\n * Waits for a ChangeSet to be available for triggering a StackUpdate.\n *\n * Will return a changeset that is either ready to be executed or has no changes.\n * Will throw in other cases.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack that the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the ChangeSet before returning.\n *\n * @returns the CloudFormation description of the ChangeSet\n */\nexport async function waitForChangeSet(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n await ioHost.notify(debug(action, format('Waiting for changeset %s on stack %s to finish creating...', changeSetName, stackName)));\n const ret = await waitFor(async () => {\n const description = await describeChangeSet(cfn, stackName, changeSetName, {\n fetchAll,\n });\n // The following doesn't use a switch because tsc will not allow fall-through, UNLESS it is allows\n // EVERYWHERE that uses this library directly or indirectly, which is undesirable.\n if (description.Status === 'CREATE_PENDING' || description.Status === 'CREATE_IN_PROGRESS') {\n await ioHost.notify(debug(action, format('Changeset %s on stack %s is still creating', changeSetName, stackName)));\n return undefined;\n }\n\n if (description.Status === ChangeSetStatus.CREATE_COMPLETE || changeSetHasNoChanges(description)) {\n return description;\n }\n\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `Failed to create ChangeSet ${changeSetName} on ${stackName}: ${description.Status || 'NO_STATUS'}, ${description.StatusReason || 'no reason provided'}`,\n );\n });\n\n if (!ret) {\n throw new ToolkitError('Change set took too long to be created; aborting');\n }\n\n return ret;\n}\n\nexport type PrepareChangeSetOptions = {\n stack: cxapi.CloudFormationStackArtifact;\n deployments: Deployments;\n uuid: string;\n willExecute: boolean;\n sdkProvider: SdkProvider;\n stream: NodeJS.WritableStream;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourcesToImport;\n}\n\nexport type CreateChangeSetOptions = {\n cfn: ICloudFormationClient;\n changeSetName: string;\n willExecute: boolean;\n exists: boolean;\n uuid: string;\n stack: cxapi.CloudFormationStackArtifact;\n bodyParameter: TemplateBodyParameter;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourceToImport[];\n role?: string;\n};\n\n/**\n * Create a changeset for a diff operation\n */\nexport async function createDiffChangeSet(\n { ioHost, action }: IoMessaging,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n // `options.stack` has been modified to include any nested stack templates directly inline with its own template, under a special `NestedTemplate` property.\n // Thus the parent template's Resources section contains the nested template's CDK metadata check, which uses Fn::Equals.\n // This causes CreateChangeSet to fail with `Template Error: Fn::Equals cannot be partially collapsed`.\n for (const resource of Object.values(options.stack.template.Resources ?? {})) {\n if ((resource as any).Type === 'AWS::CloudFormation::Stack') {\n await ioHost.notify(debug(action, 'This stack contains one or more nested stacks, falling back to template-only diff...'));\n\n return undefined;\n }\n }\n\n return uploadBodyParameterAndCreateChangeSet({ ioHost, action }, options);\n}\n\n/**\n * Returns all file entries from an AssetManifestArtifact that look like templates.\n *\n * This is used in the `uploadBodyParameterAndCreateChangeSet` function to find\n * all template asset files to build and publish.\n *\n * Returns a tuple of [AssetManifest, FileManifestEntry[]]\n */\nfunction templatesFromAssetManifestArtifact(\n artifact: cxapi.AssetManifestArtifact,\n): [AssetManifest, FileManifestEntry[]] {\n const assets: FileManifestEntry[] = [];\n const fileName = artifact.file;\n const assetManifest = AssetManifest.fromFile(fileName);\n\n assetManifest.entries.forEach((entry) => {\n if (entry.type === 'file') {\n const source = (entry as FileManifestEntry).source;\n if (source.path && source.path.endsWith('.template.json')) {\n assets.push(entry as FileManifestEntry);\n }\n }\n });\n return [assetManifest, assets];\n}\n\nasync function uploadBodyParameterAndCreateChangeSet(\n { ioHost, action }: IoMessaging,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n try {\n await uploadStackTemplateAssets(options.stack, options.deployments);\n const env = await options.deployments.envs.accessStackForMutableStackOperations(options.stack);\n\n const bodyParameter = await makeBodyParameter(\n options.stack,\n env.resolvedEnvironment,\n new AssetManifestBuilder(),\n env.resources,\n );\n const cfn = env.sdk.cloudFormation();\n const exists = (await CloudFormationStack.lookup(cfn, options.stack.stackName, false)).exists;\n\n const executionRoleArn = await env.replacePlaceholders(options.stack.cloudFormationExecutionRoleArn);\n options.stream.write(\n 'Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)\\n',\n );\n\n return await createChangeSet({ ioHost, action }, {\n cfn,\n changeSetName: 'cdk-diff-change-set',\n stack: options.stack,\n exists,\n uuid: options.uuid,\n willExecute: options.willExecute,\n bodyParameter,\n parameters: options.parameters,\n resourcesToImport: options.resourcesToImport,\n role: executionRoleArn,\n });\n } catch (e: any) {\n await ioHost.notify(debug(action, e));\n options.stream.write(\n 'Could not create a change set, will base the diff on template differences (run again with -v to see the reason)\\n',\n );\n\n return undefined;\n }\n}\n\n/**\n * Uploads the assets that look like templates for this CloudFormation stack\n *\n * This is necessary for any CloudFormation call that needs the template, it may need\n * to be uploaded to an S3 bucket first. We have to follow the instructions in the\n * asset manifest, because technically that is the only place that knows about\n * bucket and assumed roles and such.\n */\nexport async function uploadStackTemplateAssets(stack: cxapi.CloudFormationStackArtifact, deployments: Deployments) {\n for (const artifact of stack.dependencies) {\n // Skip artifact if it is not an Asset Manifest Artifact\n if (!cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n continue;\n }\n\n const [assetManifest, file_entries] = templatesFromAssetManifestArtifact(artifact);\n for (const entry of file_entries) {\n await deployments.buildSingleAsset(artifact, assetManifest, entry, {\n stack,\n });\n await deployments.publishSingleAsset(assetManifest, entry, {\n stack,\n });\n }\n }\n}\n\nexport async function createChangeSet(\n { ioHost, action }: IoMessaging,\n options: CreateChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput> {\n await cleanupOldChangeset(options.cfn, { ioHost, action }, options.changeSetName, options.stack.stackName);\n\n await ioHost.notify(debug(action, `Attempting to create ChangeSet with name ${options.changeSetName} for stack ${options.stack.stackName}`));\n\n const templateParams = TemplateParameters.fromTemplate(options.stack.template);\n const stackParams = templateParams.supplyAll(options.parameters);\n\n const changeSet = await options.cfn.createChangeSet({\n StackName: options.stack.stackName,\n ChangeSetName: options.changeSetName,\n ChangeSetType: options.resourcesToImport ? 'IMPORT' : options.exists ? 'UPDATE' : 'CREATE',\n Description: `CDK Changeset for diff ${options.uuid}`,\n ClientToken: `diff${options.uuid}`,\n TemplateURL: options.bodyParameter.TemplateURL,\n TemplateBody: options.bodyParameter.TemplateBody,\n Parameters: stackParams.apiParameters,\n ResourcesToImport: options.resourcesToImport,\n RoleARN: options.role,\n Tags: toCfnTags(options.stack.tags),\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n });\n\n await ioHost.notify(debug(action, format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n const createdChangeSet = await waitForChangeSet(options.cfn, { ioHost, action }, options.stack.stackName, options.changeSetName, {\n fetchAll: options.willExecute,\n });\n await cleanupOldChangeset(options.cfn, { ioHost, action }, options.changeSetName, options.stack.stackName);\n\n return createdChangeSet;\n}\n\nfunction toCfnTags(tags: { [id: string]: string }): Tag[] {\n return Object.entries(tags).map(([k, v]) => ({\n Key: k,\n Value: v,\n }));\n}\n\nasync function cleanupOldChangeset(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n changeSetName: string,\n stackName: string,\n) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await ioHost.notify(debug(action, `Removing existing change set with name ${changeSetName} if it exists`));\n await cfn.deleteChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n}\n\n/**\n * Return true if the given change set has no changes\n *\n * This must be determined from the status, not the 'Changes' array on the\n * object; the latter can be empty because no resources were changed, but if\n * there are changes to Outputs, the change set can still be executed.\n */\nexport function changeSetHasNoChanges(description: DescribeChangeSetCommandOutput) {\n const noChangeErrorPrefixes = [\n // Error message for a regular template\n \"The submitted information didn't contain changes.\",\n // Error message when a Transform is involved (see #10650)\n 'No updates are to be performed.',\n ];\n\n return (\n description.Status === 'FAILED' && noChangeErrorPrefixes.some((p) => (description.StatusReason ?? '').startsWith(p))\n );\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after a delete operation is issued.\n *\n * Fails if the stack is in a FAILED state. Will not fail if the stack was\n * already deleted.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after a delete\n *\n * @returns the CloudFormation description of the stabilized stack after the delete attempt\n */\nexport async function waitForStackDelete(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n if (status.isFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} is in a failed state. You may need to delete it from the AWS console : ${status}`,\n );\n } else if (status.isDeleted) {\n return undefined;\n }\n return stack;\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after an update/create operation is issued.\n *\n * Fails if the stack is in a FAILED state, ROLLBACK state, or DELETED state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after an update\n *\n * @returns the CloudFormation description of the stabilized stack after the update attempt\n */\nexport async function waitForStackDeploy(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n\n if (status.isCreationFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} failed creation, it may need to be manually deleted from the AWS console: ${status}`,\n );\n } else if (!status.isDeploySuccess) {\n throw new ToolkitError(`The stack named ${stackName} failed to deploy: ${status}`);\n }\n\n return stack;\n}\n\n/**\n * Wait for a stack to become stable (no longer _IN_PROGRESS), returning it\n */\nexport async function stabilizeStack(\n cfn: ICloudFormationClient,\n { ioHost, action }: IoMessaging, stackName: string,\n) {\n await ioHost.notify(debug(action, format('Waiting for stack %s to finish creating or updating...', stackName)));\n return waitFor(async () => {\n const stack = await CloudFormationStack.lookup(cfn, stackName);\n if (!stack.exists) {\n await ioHost.notify(debug(action, format('Stack %s does not exist', stackName)));\n return null;\n }\n const status = stack.stackStatus;\n if (status.isInProgress) {\n await ioHost.notify(debug(action, format('Stack %s has an ongoing operation in progress and is not stable (%s)', stackName, status)));\n return undefined;\n } else if (status.isReviewInProgress) {\n // This may happen if a stack creation operation is interrupted before the ChangeSet execution starts. Recovering\n // from this would requiring manual intervention (deleting or executing the pending ChangeSet), and failing to do\n // so will result in an endless wait here (the ChangeSet wont delete or execute itself). Instead of blocking\n // \"forever\" we proceed as if the stack was existing and stable. If there is a concurrent operation that just\n // hasn't finished proceeding just yet, either this operation or the concurrent one may fail due to the other one\n // having made progress. Which is fine. I guess.\n await ioHost.notify(debug(action, format('Stack %s is in REVIEW_IN_PROGRESS state. Considering this is a stable status (%s)', stackName, status)));\n }\n\n return stack;\n });\n}\n\n/**\n * The set of (formal) parameters that have been declared in a template\n */\nexport class TemplateParameters {\n public static fromTemplate(template: Template) {\n return new TemplateParameters(template.Parameters || {});\n }\n\n constructor(private readonly params: Record<string, TemplateParameter>) {\n }\n\n /**\n * Calculate stack parameters to pass from the given desired parameter values\n *\n * Will throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public supplyAll(updates: Record<string, string | undefined>): ParameterValues {\n return new ParameterValues(this.params, updates);\n }\n\n /**\n * From the template, the given desired values and the current values, calculate the changes to the stack parameters\n *\n * Will take into account parameters already set on the template (will emit\n * 'UsePreviousValue: true' for those unless the value is changed), and will\n * throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public updateExisting(\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string>,\n ): ParameterValues {\n return new ParameterValues(this.params, updates, previousValues);\n }\n}\n\n/**\n * The set of parameters we're going to pass to a Stack\n */\nexport class ParameterValues {\n public readonly values: Record<string, string> = {};\n public readonly apiParameters: Parameter[] = [];\n\n constructor(\n private readonly formalParams: Record<string, TemplateParameter>,\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string> = {},\n ) {\n const missingRequired = new Array<string>();\n\n for (const [key, formalParam] of Object.entries(this.formalParams)) {\n // Check updates first, then use the previous value (if available), then use\n // the default (if available).\n //\n // If we don't find a parameter value using any of these methods, then that's an error.\n const updatedValue = updates[key];\n if (updatedValue !== undefined) {\n this.values[key] = updatedValue;\n this.apiParameters.push({\n ParameterKey: key,\n ParameterValue: updates[key],\n });\n continue;\n }\n\n if (key in previousValues) {\n this.values[key] = previousValues[key];\n this.apiParameters.push({ ParameterKey: key, UsePreviousValue: true });\n continue;\n }\n\n if (formalParam.Default !== undefined) {\n this.values[key] = formalParam.Default;\n continue;\n }\n\n // Oh no\n missingRequired.push(key);\n }\n\n if (missingRequired.length > 0) {\n throw new ToolkitError(`The following CloudFormation Parameters are missing a value: ${missingRequired.join(', ')}`);\n }\n\n // Just append all supplied overrides that aren't really expected (this\n // will fail CFN but maybe people made typos that they want to be notified\n // of)\n const unknownParam = ([key, _]: [string, any]) => this.formalParams[key] === undefined;\n const hasValue = ([_, value]: [string, any]) => !!value;\n for (const [key, value] of Object.entries(updates).filter(unknownParam).filter(hasValue)) {\n this.values[key] = value!;\n this.apiParameters.push({ ParameterKey: key, ParameterValue: value });\n }\n }\n\n /**\n * Whether this set of parameter updates will change the actual stack values\n */\n public hasChanges(currentValues: Record<string, string>): ParameterChanges {\n // If any of the parameters are SSM parameters, deploying must always happen\n // because we can't predict what the values will be. We will allow some\n // parameters to opt out of this check by having a magic string in their description.\n if (\n Object.values(this.formalParams).some(\n (p) => p.Type.startsWith('AWS::SSM::Parameter::') && !p.Description?.includes(SSMPARAM_NO_INVALIDATE),\n )\n ) {\n return 'ssm';\n }\n\n // Otherwise we're dirty if:\n // - any of the existing values are removed, or changed\n if (Object.entries(currentValues).some(([key, value]) => !(key in this.values) || value !== this.values[key])) {\n return true;\n }\n\n // - any of the values we're setting are new\n if (Object.keys(this.values).some((key) => !(key in currentValues))) {\n return true;\n }\n\n return false;\n }\n}\n\nexport type ParameterChanges = boolean | 'ssm';\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport { AssetManifest } from 'cdk-assets';\n\nexport class AssetManifestBuilder {\n private readonly manifest: cxschema.AssetManifest = {\n version: cxschema.Manifest.version(),\n files: {},\n dockerImages: {},\n };\n\n public addFileAsset(id: string, source: cxschema.FileSource, destination: cxschema.FileDestination) {\n this.manifest.files![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public addDockerImageAsset(id: string, source: cxschema.DockerImageSource, destination: cxschema.DockerImageDestination) {\n this.manifest.dockerImages![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public toManifest(directory: string): AssetManifest {\n return new AssetManifest(directory, this.manifest);\n }\n}\n", "// This file is a backport from @aws-cdk/toolkit.\n// The CLI cannot depend on the toolkit yet, because the toolkit currently depends on the CLI.\n// Once we have complete the repo split, we will create a temporary, private library package\n// for all code that is shared between CLI and toolkit. This is where this file will then live.\nimport { IoMessage, IoMessageCode, IoMessageCodeCategory, IoMessageLevel, ToolkitAction } from '../toolkit/cli-io-host';\n\ntype Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;\ntype SimplifiedMessage<T> = Omit<IoMessage<T>, 'time'>;\n\n/**\n * Internal helper that processes log inputs into a consistent format.\n * Handles string interpolation, format strings, and object parameter styles.\n * Applies optional styling and prepares the final message for logging.\n */\nexport function formatMessage<T>(msg: Optional<SimplifiedMessage<T>, 'code'>, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessage<T> {\n return {\n time: new Date(),\n level: msg.level,\n action: msg.action,\n code: msg.code ?? defaultMessageCode(msg.level, category),\n message: msg.message,\n data: msg.data,\n };\n}\n\n/**\n * Build a message code from level and category. The code must be valid for this function to pass.\n * Otherwise it returns a ToolkitError.\n */\nfunction defaultMessageCode(level: IoMessageLevel, category: IoMessageCodeCategory = 'TOOLKIT'): IoMessageCode {\n const levelIndicator = level === 'error' ? 'E' :\n level === 'warn' ? 'W' :\n 'I';\n return `CDK_${category}_${levelIndicator}0000`;\n}\n\n/**\n * Creates an error level message.\n * Errors must always have a unique code.\n */\nexport const error = <T>(action: ToolkitAction, message: string, code: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'error',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a result level message and represents the most important message for a given action.\n *\n * They should be used sparsely, with an action usually having no or exactly one result.\n * However actions that operate on Cloud Assemblies might include a result per Stack.\n * Unlike other messages, results must always have a code and a payload.\n */\nexport const result = <T>(action: ToolkitAction, message: string, code: IoMessageCode, payload: T) => {\n return formatMessage({\n level: 'result',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a warning level message.\n */\nexport const warn = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'warn',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates an info level message.\n */\nexport const info = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'info',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a debug level message.\n */\nexport const debug = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'debug',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n/**\n * Creates a trace level message.\n */\nexport const trace = <T>(action: ToolkitAction, message: string, code?: IoMessageCode, payload?: T) => {\n return formatMessage({\n level: 'trace',\n action,\n code,\n message,\n data: payload,\n });\n};\n\n", "\nimport * as util from 'util';\nimport { ArtifactMetadataEntryType, type MetadataEntry } from '@aws-cdk/cloud-assembly-schema';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport { StackEvent } from '@aws-sdk/client-cloudformation';\nimport * as uuid from 'uuid';\nimport { StackEventPoller } from './stack-event-poller';\nimport { debug, error, info } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { stackEventHasErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { StackProgress, StackProgressMonitor } from './stack-progress-monitor';\n\n/**\n * Payload when stack monitoring is starting or stopping for a given stack deployment.\n */\nexport interface StackMonitoringControlEvent {\n /**\n * A unique identifier for a specific stack deployment.\n *\n * Use this value to attribute stack activities received for concurrent deployments.\n */\n readonly deployment: string;\n\n /**\n * The stack artifact that is getting deployed\n */\n readonly stack: CloudFormationStackArtifact;\n\n /**\n * The name of the Stack that is getting deployed\n */\n readonly stackName: string;\n\n /**\n * Total number of resources taking part in this deployment\n *\n * The number might not always be known or accurate.\n * Only use for informational purposes and handle the case when it's unavailable.\n */\n readonly resourcesTotal?: number;\n}\n\nexport interface StackActivity {\n /**\n * A unique identifier for a specific stack deployment.\n *\n * Use this value to attribute stack activities received for concurrent deployments.\n */\n readonly deployment: string;\n\n /**\n * The Stack Event as received from CloudFormation\n */\n readonly event: StackEvent;\n\n /**\n * Additional resource metadata\n */\n readonly metadata?: ResourceMetadata;\n\n /**\n * The stack progress\n */\n readonly progress: StackProgress;\n}\n\nexport interface ResourceMetadata {\n entry: MetadataEntry;\n constructPath: string;\n}\n\nexport interface StackActivityMonitorProps {\n /**\n * The CloudFormation client\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * The IoHost used for messaging\n */\n readonly ioHost: IoMessaging['ioHost'];\n\n /**\n * The current ToolkitAction\n */\n readonly action: IoMessaging['action'];\n\n /**\n * The stack artifact that is getting deployed\n */\n readonly stack: CloudFormationStackArtifact;\n\n /**\n * The name of the Stack that is getting deployed\n */\n readonly stackName: string;\n\n /**\n * Total number of resources to update\n *\n * Used to calculate a progress bar.\n *\n * @default - No progress reporting.\n */\n readonly resourcesTotal?: number;\n\n /**\n * Creation time of the change set\n *\n * This will be used to filter events, only showing those from after the change\n * set creation time.\n *\n * It is recommended to use this, otherwise the filtering will be subject\n * to clock drift between local and cloud machines.\n *\n * @default - local machine's current time\n */\n readonly changeSetCreationTime?: Date;\n\n /**\n * Time to wait between fetching new activities.\n *\n * Must wait a reasonable amount of time between polls, since we need to consider CloudFormation API limits\n *\n * @default 2_000\n */\n readonly pollingInterval?: number;\n}\n\nexport class StackActivityMonitor {\n /**\n * The poller used to read stack events\n */\n private readonly poller: StackEventPoller;\n\n /**\n * Fetch new activity every 1 second\n * Printers can decide to update a view less frequently if desired\n */\n private readonly pollingInterval: number;\n\n public readonly errors: string[] = [];\n\n private monitorId?: string;\n\n private readonly progressMonitor: StackProgressMonitor;\n\n /**\n * Current tick timer\n */\n private tickTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * Set to the activity of reading the current events\n */\n private readPromise?: Promise<any>;\n\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n private readonly stackName: string;\n private readonly stack: CloudFormationStackArtifact;\n\n constructor({\n cfn,\n ioHost,\n action,\n stack,\n stackName,\n resourcesTotal,\n changeSetCreationTime,\n pollingInterval = 2_000,\n }: StackActivityMonitorProps) {\n this.ioHost = ioHost;\n this.action = action;\n this.stack = stack;\n this.stackName = stackName;\n\n this.progressMonitor = new StackProgressMonitor(resourcesTotal);\n this.pollingInterval = pollingInterval;\n this.poller = new StackEventPoller(cfn, {\n stackName,\n startTime: changeSetCreationTime?.getTime() ?? Date.now(),\n });\n }\n\n public async start() {\n this.monitorId = uuid.v4();\n await this.ioHost.notify(debug(this.action, `Deploying ${this.stackName}`, 'CDK_TOOLKIT_I5501', {\n deployment: this.monitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n } as StackMonitoringControlEvent));\n this.scheduleNextTick();\n return this;\n }\n\n public async stop() {\n const oldMonitorId = this.monitorId!;\n this.monitorId = undefined;\n if (this.tickTimer) {\n clearTimeout(this.tickTimer);\n }\n\n // Do a final poll for all events. This is to handle the situation where DescribeStackStatus\n // already returned an error, but the monitor hasn't seen all the events yet and we'd end\n // up not printing the failure reason to users.\n await this.finalPollToEnd(oldMonitorId);\n\n await this.ioHost.notify(debug(this.action, `Completed ${this.stackName}`, 'CDK_TOOLKIT_I5503', {\n deployment: oldMonitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n } as StackMonitoringControlEvent));\n }\n\n private scheduleNextTick() {\n if (!this.monitorId) {\n return;\n }\n\n this.tickTimer = setTimeout(() => void this.tick(), this.pollingInterval);\n }\n\n private async tick() {\n if (!this.monitorId) {\n return;\n }\n\n try {\n this.readPromise = this.readNewEvents(this.monitorId);\n await this.readPromise;\n this.readPromise = undefined;\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.monitorId) {\n return;\n }\n } catch (e) {\n await this.ioHost.notify(error(\n this.action,\n util.format('Error occurred while monitoring stack: %s', e),\n 'CDK_TOOLKIT_E5500',\n { error: e },\n ));\n }\n this.scheduleNextTick();\n }\n\n private findMetadataFor(logicalId: string | undefined): ResourceMetadata | undefined {\n const metadata = this.stack.manifest?.metadata;\n if (!logicalId || !metadata) {\n return undefined;\n }\n for (const path of Object.keys(metadata)) {\n const entry = metadata[path]\n .filter((e) => e.type === ArtifactMetadataEntryType.LOGICAL_ID)\n .find((e) => e.data === logicalId);\n if (entry) {\n return {\n entry,\n constructPath: this.simplifyConstructPath(path),\n };\n }\n }\n return undefined;\n }\n\n /**\n * Reads all new events from the stack history\n *\n * The events are returned in reverse chronological order; we continue to the next page if we\n * see a next page and the last event in the page is new to us (and within the time window).\n * haven't seen the final event\n */\n private async readNewEvents(monitorId: string): Promise<void> {\n const pollEvents = await this.poller.poll();\n\n for (const resourceEvent of pollEvents) {\n this.progressMonitor.process(resourceEvent.event);\n\n const activity: StackActivity = {\n deployment: monitorId,\n event: resourceEvent.event,\n metadata: this.findMetadataFor(resourceEvent.event.LogicalResourceId),\n progress: this.progressMonitor.progress,\n };\n\n this.checkForErrors(activity);\n await this.ioHost.notify(info(this.action, this.formatActivity(activity, true), 'CDK_TOOLKIT_I5502', activity));\n }\n }\n\n /**\n * Perform a final poll to the end and flush out all events to the printer\n *\n * Finish any poll currently in progress, then do a final one until we've\n * reached the last page.\n */\n private async finalPollToEnd(monitorId: string) {\n // If we were doing a poll, finish that first. It was started before\n // the moment we were sure we weren't going to get any new events anymore\n // so we need to do a new one anyway. Need to wait for this one though\n // because our state is single-threaded.\n if (this.readPromise) {\n await this.readPromise;\n }\n\n await this.readNewEvents(monitorId);\n }\n\n /**\n * Formats a stack activity into a basic string\n */\n private formatActivity(activity: StackActivity, progress: boolean): string {\n const event = activity.event;\n const metadata = activity.metadata;\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n return util.format(\n '%s | %s%s | %s | %s | %s %s%s%s',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n event.ResourceStatus || '',\n event.ResourceType,\n resourceName,\n logicalId,\n event.ResourceStatusReason ? event.ResourceStatusReason : '',\n metadata?.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '',\n );\n }\n\n private checkForErrors(activity: StackActivity) {\n if (stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason, nor is the stack message (stack\n // message will just say something like \"stack failed to update\")\n if (!isCancelled && activity.event.StackName !== activity.event.LogicalResourceId) {\n this.errors.push(activity.event.ResourceStatusReason ?? '');\n }\n }\n }\n\n private simplifyConstructPath(path: string) {\n path = path.replace(/\\/Resource$/, '');\n path = path.replace(/^\\//, ''); // remove \"/\" prefix\n\n // remove \"<stack-name>/\" prefix\n if (path.startsWith(this.stackName + '/')) {\n path = path.slice(this.stackName.length + 1);\n }\n return path;\n }\n}\n", "import type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { ICloudFormationClient } from '../aws-auth';\n\nexport interface StackEventPollerProps {\n /**\n * The stack to poll\n */\n readonly stackName: string;\n\n /**\n * IDs of parent stacks of this resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds?: string[];\n\n /**\n * Timestamp for the oldest event we're interested in\n *\n * @default - Read all events\n */\n readonly startTime?: number;\n\n /**\n * Stop reading when we see the stack entering this status\n *\n * Should be something like `CREATE_IN_PROGRESS`, `UPDATE_IN_PROGRESS`,\n * `DELETE_IN_PROGRESS, `ROLLBACK_IN_PROGRESS`.\n *\n * @default - Read all events\n */\n readonly stackStatuses?: string[];\n}\n\nexport interface ResourceEvent {\n /**\n * The Stack Event as received from CloudFormation\n */\n readonly event: StackEvent;\n\n /**\n * IDs of parent stacks of the resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds: string[];\n\n /**\n * Whether this event regards the root stack\n *\n * @default false\n */\n readonly isStackEvent?: boolean;\n}\n\nexport class StackEventPoller {\n public readonly events: ResourceEvent[] = [];\n public complete: boolean = false;\n\n private readonly eventIds = new Set<string>();\n private readonly nestedStackPollers: Record<string, StackEventPoller> = {};\n\n constructor(\n private readonly cfn: ICloudFormationClient,\n private readonly props: StackEventPollerProps,\n ) {\n }\n\n /**\n * From all accumulated events, return only the errors\n */\n public get resourceErrors(): ResourceEvent[] {\n return this.events.filter((e) => e.event.ResourceStatus?.endsWith('_FAILED') && !e.isStackEvent);\n }\n\n /**\n * Poll for new stack events\n *\n * Will not return events older than events indicated by the constructor filters.\n *\n * Recurses into nested stacks, and returns events old-to-new.\n */\n public async poll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = await this.doPoll();\n\n // Also poll all nested stacks we're currently tracking\n for (const [logicalId, poller] of Object.entries(this.nestedStackPollers)) {\n events.push(...(await poller.poll()));\n if (poller.complete) {\n delete this.nestedStackPollers[logicalId];\n }\n }\n\n // Return what we have so far\n events.sort((a, b) => a.event.Timestamp!.valueOf() - b.event.Timestamp!.valueOf());\n this.events.push(...events);\n return events;\n }\n\n private async doPoll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = [];\n try {\n let nextToken: string | undefined;\n let finished = false;\n\n while (!finished) {\n const page = await this.cfn.describeStackEvents({ StackName: this.props.stackName, NextToken: nextToken });\n for (const event of page?.StackEvents ?? []) {\n // Event from before we were interested in 'em\n if (this.props.startTime !== undefined && event.Timestamp!.valueOf() < this.props.startTime) {\n return events;\n }\n\n // Already seen this one\n if (this.eventIds.has(event.EventId!)) {\n return events;\n }\n this.eventIds.add(event.EventId!);\n\n // The events for the stack itself are also included next to events about resources; we can test for them in this way.\n const isParentStackEvent = event.PhysicalResourceId === event.StackId;\n\n if (isParentStackEvent && this.props.stackStatuses?.includes(event.ResourceStatus ?? '')) {\n return events;\n }\n\n // Fresh event\n const resEvent: ResourceEvent = {\n event: event,\n parentStackLogicalIds: this.props.parentStackLogicalIds ?? [],\n isStackEvent: isParentStackEvent,\n };\n events.push(resEvent);\n\n if (\n !isParentStackEvent &&\n event.ResourceType === 'AWS::CloudFormation::Stack' &&\n isStackBeginOperationState(event.ResourceStatus)\n ) {\n // If the event is not for `this` stack and has a physical resource Id, recursively call for events in the nested stack\n this.trackNestedStack(event, [...(this.props.parentStackLogicalIds ?? []), event.LogicalResourceId ?? '']);\n }\n\n if (isParentStackEvent && isStackTerminalState(event.ResourceStatus)) {\n this.complete = true;\n }\n }\n\n nextToken = page?.NextToken;\n if (nextToken === undefined) {\n finished = true;\n }\n }\n } catch (e: any) {\n if (!(e.name === 'ValidationError' && formatErrorMessage(e) === `Stack [${this.props.stackName}] does not exist`)) {\n throw e;\n }\n }\n\n return events;\n }\n\n /**\n * On the CREATE_IN_PROGRESS, UPDATE_IN_PROGRESS, DELETE_IN_PROGRESS event of a nested stack, poll the nested stack updates\n */\n private trackNestedStack(event: StackEvent, parentStackLogicalIds: string[]) {\n const logicalId = event.LogicalResourceId;\n const physicalResourceId = event.PhysicalResourceId;\n\n // The CREATE_IN_PROGRESS event for a Nested Stack is emitted twice; first without a PhysicalResourceId\n // and then with. Ignore this event if we don't have that property yet.\n //\n // (At this point, I also don't trust that logicalId is always going to be there so validate that as well)\n if (!logicalId || !physicalResourceId) {\n return;\n }\n\n if (!this.nestedStackPollers[logicalId]) {\n this.nestedStackPollers[logicalId] = new StackEventPoller(this.cfn, {\n stackName: physicalResourceId,\n parentStackLogicalIds: parentStackLogicalIds,\n startTime: event.Timestamp!.valueOf(),\n });\n }\n }\n}\n\nfunction isStackBeginOperationState(state: string | undefined) {\n return [\n 'CREATE_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'DELETE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_IN_PROGRESS',\n ].includes(state ?? '');\n}\n\nfunction isStackTerminalState(state: string | undefined) {\n return !(state ?? '').endsWith('_IN_PROGRESS');\n}\n", "\nimport * as util from 'util';\nimport { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { padLeft } from '../../util/string-manipulation';\n\nexport interface StackProgress {\n /**\n * The total number of progress monitored resources.\n */\n readonly total?: number;\n\n /**\n * The number of completed resources.\n */\n readonly completed: number;\n\n /**\n * The current progress as a [34/42] string, or just [34] if the total is unknown.\n */\n readonly formatted: string;\n}\n\n/**\n * Monitors stack progress.s\n */\nexport class StackProgressMonitor {\n /**\n * Previous completion state observed by logical ID\n *\n * We use this to detect that if we see a DELETE_COMPLETE after a\n * CREATE_COMPLETE, it's actually a rollback and we should DECREASE\n * resourcesDone instead of increase it\n */\n private resourcesPrevCompleteState: Record<string, string> = {};\n\n /**\n * Count of resources that have reported a _COMPLETE status\n */\n private resourcesDone: number = 0;\n\n /**\n * How many digits we need to represent the total count (for lining up the status reporting)\n */\n private readonly resourceDigits: number = 0;\n\n /**\n * Number of expected resources in the monitor.\n */\n private readonly resourcesTotal?: number;\n\n constructor(resourcesTotal?: number) {\n // +1 because the stack also emits a \"COMPLETE\" event at the end, and that wasn't\n // counted yet. This makes it line up with the amount of events we expect.\n this.resourcesTotal = resourcesTotal ? resourcesTotal + 1 : undefined;\n\n // How many digits does this number take to represent?\n this.resourceDigits = this.resourcesTotal ? Math.ceil(Math.log10(this.resourcesTotal)) : 0;\n }\n\n /**\n * Report the stack progress\n */\n public get progress(): StackProgress {\n return {\n total: this.total,\n completed: this.completed,\n formatted: this.formatted,\n };\n }\n\n /**\n * The total number of progress monitored resources.\n */\n public get total(): number | undefined {\n return this.resourcesTotal;\n }\n\n /**\n * The number of completed resources.\n */\n public get completed(): number {\n return this.resourcesDone;\n }\n\n /**\n * Report the current progress as a [34/42] string, or just [34] if the total is unknown\n */\n public get formatted(): string {\n if (this.resourcesTotal == null) {\n // Don't have total, show simple count and hope the human knows\n return padLeft(3, util.format('%s', this.resourcesDone)); // max 500 resources\n }\n\n return util.format(\n '%s/%s',\n padLeft(this.resourceDigits, this.resourcesDone.toString()),\n padLeft(this.resourceDigits, this.resourcesTotal.toString()),\n );\n }\n\n /**\n * Process as stack event and update the progress state.\n */\n public process(event: StackEvent): void {\n const status = event.ResourceStatus;\n if (!status || !event.LogicalResourceId) {\n return;\n }\n\n if (status.endsWith('_COMPLETE_CLEANUP_IN_PROGRESS')) {\n this.resourcesDone++;\n }\n\n if (status.endsWith('_COMPLETE')) {\n const prevState = this.resourcesPrevCompleteState[event.LogicalResourceId];\n if (!prevState) {\n this.resourcesDone++;\n } else {\n // If we completed this before and we're completing it AGAIN, means we're rolling back.\n // Protect against silly underflow.\n this.resourcesDone--;\n if (this.resourcesDone < 0) {\n this.resourcesDone = 0;\n }\n }\n this.resourcesPrevCompleteState[event.LogicalResourceId] = status;\n }\n }\n}\n", "import { type Stack, StackStatus as _StackStatus } from '@aws-sdk/client-cloudformation';\n\n/**\n * A utility class to inspect CloudFormation stack statuses.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html\n */\nexport class StackStatus {\n public static fromStackDescription(description: Stack) {\n return new StackStatus(description.StackStatus!, description.StackStatusReason);\n }\n\n constructor(\n public readonly name: string,\n public readonly reason?: string,\n ) {\n }\n\n get isCreationFailure(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.ROLLBACK_FAILED;\n }\n\n get isDeleted(): boolean {\n return this.name.startsWith('DELETE_');\n }\n\n get isFailure(): boolean {\n return this.name.endsWith('FAILED');\n }\n\n get isInProgress(): boolean {\n return this.name.endsWith('_IN_PROGRESS') && !this.isReviewInProgress;\n }\n\n get isReviewInProgress(): boolean {\n return this.name === _StackStatus.REVIEW_IN_PROGRESS;\n }\n\n get isNotFound(): boolean {\n return this.name === 'NOT_FOUND';\n }\n\n get isDeploySuccess(): boolean {\n return (\n !this.isNotFound &&\n (this.name === _StackStatus.CREATE_COMPLETE ||\n this.name === _StackStatus.UPDATE_COMPLETE ||\n this.name === _StackStatus.IMPORT_COMPLETE)\n );\n }\n\n get isRollbackSuccess(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.UPDATE_ROLLBACK_COMPLETE;\n }\n\n /**\n * Whether the stack is in a paused state due to `--no-rollback`.\n *\n * The possible actions here are retrying a new `--no-rollback` deployment, or initiating a rollback.\n */\n get rollbackChoice(): RollbackChoice {\n switch (this.name) {\n case _StackStatus.CREATE_FAILED:\n case _StackStatus.UPDATE_FAILED:\n return RollbackChoice.START_ROLLBACK;\n case _StackStatus.UPDATE_ROLLBACK_FAILED:\n return RollbackChoice.CONTINUE_UPDATE_ROLLBACK;\n case _StackStatus.ROLLBACK_FAILED:\n // Unfortunately there is no option to continue a failed rollback without\n // a stable target state.\n return RollbackChoice.ROLLBACK_FAILED;\n default:\n return RollbackChoice.NONE;\n }\n }\n\n get isRollbackable(): boolean {\n return [RollbackChoice.START_ROLLBACK, RollbackChoice.CONTINUE_UPDATE_ROLLBACK].includes(this.rollbackChoice);\n }\n\n public toString(): string {\n return this.name + (this.reason ? ` (${this.reason})` : '');\n }\n}\n\n/**\n * Describe the current rollback options for this state\n */\nexport enum RollbackChoice {\n START_ROLLBACK,\n CONTINUE_UPDATE_ROLLBACK,\n /**\n * A sign that stack creation AND its rollback have failed.\n *\n * There is no way to recover from this, other than recreating the stack.\n */\n ROLLBACK_FAILED,\n NONE,\n}\n", "import * as path from 'path';\nimport { type CloudFormationStackArtifact, type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { HeadObjectCommand, S3Client } from '@aws-sdk/client-s3';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport { debug, error } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\nimport { contentHash } from '../../util/content-hash';\nimport { toYAML } from '../../util/serialize';\nimport { type AssetManifestBuilder } from '../deployments';\nimport { EnvironmentResources } from '../environment';\n\nexport type TemplateBodyParameter = {\n TemplateBody?: string;\n TemplateURL?: string;\n};\n\nconst LARGE_TEMPLATE_SIZE_KB = 50;\n\n/**\n * Prepares the body parameter for +CreateChangeSet+.\n *\n * If the template is small enough to be inlined into the API call, just return\n * it immediately.\n *\n * Otherwise, add it to the asset manifest to get uploaded to the staging\n * bucket and return its coordinates. If there is no staging bucket, an error\n * is thrown.\n *\n * @param stack the synthesized stack that provides the CloudFormation template\n * @param toolkitInfo information about the toolkit stack\n */\nexport async function makeBodyParameter(\n stack: CloudFormationStackArtifact,\n resolvedEnvironment: Environment,\n assetManifest: AssetManifestBuilder,\n resources: EnvironmentResources,\n overrideTemplate?: any,\n): Promise<TemplateBodyParameter> {\n // If the template has already been uploaded to S3, just use it from there.\n if (stack.stackTemplateAssetObjectUrl && !overrideTemplate) {\n return {\n TemplateURL: await restUrlFromManifest(stack.stackTemplateAssetObjectUrl, resolvedEnvironment),\n };\n }\n\n // Otherwise, pass via API call (if small) or upload here (if large)\n const templateJson = toYAML(overrideTemplate ?? stack.template);\n\n if (templateJson.length <= LARGE_TEMPLATE_SIZE_KB * 1024) {\n return { TemplateBody: templateJson };\n }\n\n const toolkitInfo = await resources.lookupToolkit();\n if (!toolkitInfo.found) {\n error(\n `The template for stack \"${stack.displayName}\" is ${Math.round(templateJson.length / 1024)}KiB. ` +\n `Templates larger than ${LARGE_TEMPLATE_SIZE_KB}KiB must be uploaded to S3.\\n` +\n 'Run the following command in order to setup an S3 bucket in this environment, and then re-deploy:\\n\\n',\n chalk.blue(`\\t$ cdk bootstrap ${resolvedEnvironment.name}\\n`),\n );\n\n throw new ToolkitError('Template too large to deploy (\"cdk bootstrap\" is required)');\n }\n\n const templateHash = contentHash(templateJson);\n const key = `cdk/${stack.id}/${templateHash}.yml`;\n\n let templateFile = stack.templateFile;\n if (overrideTemplate) {\n // Add a variant of this template\n templateFile = `${stack.templateFile}-${templateHash}.yaml`;\n const templateFilePath = path.join(stack.assembly.directory, templateFile);\n await fs.writeFile(templateFilePath, templateJson, { encoding: 'utf-8' });\n }\n\n assetManifest.addFileAsset(\n templateHash,\n {\n path: templateFile,\n },\n {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n },\n );\n\n const templateURL = `${toolkitInfo.bucketUrl}/${key}`;\n debug('Storing template in S3 at:', templateURL);\n return { TemplateURL: templateURL };\n}\n\n/**\n * Format an S3 URL in the manifest for use with CloudFormation\n *\n * Replaces environment placeholders (which this field may contain),\n * and reformats s3://.../... urls into S3 REST URLs (which CloudFormation\n * expects)\n */\nasync function restUrlFromManifest(url: string, environment: Environment): Promise<string> {\n const doNotUseMarker = '**DONOTUSE**';\n const region = environment.region;\n // This URL may contain placeholders, so still substitute those.\n url = EnvironmentPlaceholders.replace(url, {\n accountId: environment.account,\n region,\n partition: doNotUseMarker,\n });\n\n // Yes, this is extremely crude, but we don't actually need this so I'm not inclined to spend\n // a lot of effort trying to thread the right value to this location.\n if (url.indexOf(doNotUseMarker) > -1) {\n throw new ToolkitError(\"Cannot use '${AWS::Partition}' in the 'stackTemplateAssetObjectUrl' field\");\n }\n\n const s3Url = url.match(/s3:\\/\\/([^/]+)\\/(.*)$/);\n if (!s3Url) {\n return url;\n }\n\n // We need to pass an 'https://s3.REGION.amazonaws.com[.cn]/bucket/object' URL to CloudFormation, but we\n // got an 's3://bucket/object' URL instead. Construct the rest API URL here.\n const bucketName = s3Url[1];\n const objectKey = s3Url[2];\n\n // SDK v3 no longer allows for getting endpoints from only region.\n // A command and client config must now be provided.\n const s3 = new S3Client({ region });\n const endpoint = await getEndpointFromInstructions({}, HeadObjectCommand, {\n ...s3.config,\n });\n endpoint.url.hostname;\n\n return `${endpoint.url.origin}/${bucketName}/${objectKey}`;\n}\n", "import { randomUUID } from 'crypto';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as cdk_assets from 'cdk-assets';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport {\n BasePublishProgressListener,\n PublishingAws,\n} from './asset-publishing';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport {\n CloudFormationStack,\n type ResourceIdentifierSummaries,\n ResourcesToImport,\n stabilizeStack,\n Template,\n uploadStackTemplateAssets,\n} from './cloudformation';\nimport { deployStack, destroyStack } from './deploy-stack';\nimport { DeploymentMethod } from './deployment-method';\nimport { DeployStackResult } from './deployment-result';\nimport {\n loadCurrentTemplate,\n loadCurrentTemplateWithNestedStacks,\n type RootTemplateWithNestedStacks,\n} from './nested-stack-helpers';\nimport { debug, warn } from '../../cli/messages';\nimport { IIoHost, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SdkProvider } from '../aws-auth/sdk-provider';\nimport { type EnvironmentResources, EnvironmentAccess } from '../environment';\nimport { HotswapMode, HotswapPropertyOverrides } from '../hotswap/common';\nimport { StackActivityMonitor, StackEventPoller, RollbackChoice } from '../stack-events';\nimport type { Tag } from '../tags';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\nimport { makeBodyParameter } from '../util/template-body-parameter';\n\nconst BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK = 23;\n\nexport interface DeployStackOptions {\n /**\n * Stack to deploy\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Topic ARNs to send a message when deployment finishes (pass through to CloudFormation)\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Override name under which stack will be deployed\n *\n * @default - Use artifact default\n */\n readonly deployName?: string;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * List of asset IDs which should NOT be built or uploaded\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Stack tags (pass through to CloudFormation)\n */\n readonly tags?: Tag[];\n\n /**\n * Stage the change set but don't execute it\n *\n * @default - true\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly execute?: boolean;\n\n /**\n * Optional name to use for the CloudFormation change set.\n * If not provided, a name will be generated automatically.\n *\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly changeSetName?: string;\n\n /**\n * Select the deployment method (direct or using a change set)\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Force deployment, even if the deployed template is identical to the one we are about to deploy.\n * @default false deployment will be skipped if the template is identical\n */\n readonly force?: boolean;\n\n /**\n * Extra parameters for CloudFormation\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * List of existing resources to be IMPORTED into the stack, instead of being CREATED\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @default false\n */\n ignoreNoStacks?: boolean;\n}\n\nexport interface RollbackStackOptions {\n /**\n * Stack to roll back\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Don't show stack deployment events, just wait\n *\n * @default false\n */\n readonly quiet?: boolean;\n\n /**\n * Whether we are on a CI system\n *\n * @default false\n */\n readonly ci?: boolean;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * Whether to force a rollback or not\n *\n * Forcing a rollback will orphan all undeletable resources.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Orphan the resources with the given logical IDs\n *\n * @default - No orphaning\n */\n readonly orphanLogicalIds?: string[];\n\n /**\n * Whether to validate the version of the bootstrap stack permissions\n *\n * @default true\n */\n readonly validateBootstrapStackVersion?: boolean;\n}\n\nexport interface RollbackStackResult {\n readonly notInRollbackableState?: boolean;\n readonly success?: boolean;\n}\n\ninterface AssetOptions {\n /**\n * Stack with assets to build.\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the building.\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n}\n\nexport interface BuildStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\ninterface PublishStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\nexport interface DestroyStackOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n roleArn?: string;\n quiet?: boolean;\n force?: boolean;\n ci?: boolean;\n}\n\nexport interface StackExistsOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n tryLookupRole?: boolean;\n}\n\nexport interface DeploymentsProps {\n readonly sdkProvider: SdkProvider;\n readonly toolkitStackName?: string;\n readonly ioHost: IIoHost;\n readonly action: ToolkitAction;\n}\n\n/**\n * Scope for a single set of deployments from a set of Cloud Assembly Artifacts\n *\n * Manages lookup of SDKs, Bootstrap stacks, etc.\n */\nexport class Deployments {\n public readonly envs: EnvironmentAccess;\n\n /**\n * SDK provider for asset publishing (do not use for anything else).\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to asset handling routines.\n */\n private readonly assetSdkProvider: SdkProvider;\n\n /**\n * SDK provider for passing to deployStack\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to `deployStack`.\n */\n private readonly deployStackSdkProvider: SdkProvider;\n\n private readonly publisherCache = new Map<cdk_assets.AssetManifest, cdk_assets.AssetPublishing>();\n\n private _allowCrossAccountAssetPublishing: boolean | undefined;\n\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n constructor(private readonly props: DeploymentsProps) {\n this.assetSdkProvider = props.sdkProvider;\n this.deployStackSdkProvider = props.sdkProvider;\n this.ioHost = props.ioHost;\n this.action = props.action;\n this.envs = new EnvironmentAccess(\n props.sdkProvider,\n props.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME,\n { ioHost: this.ioHost, action: this.action },\n );\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.envs.resolveStackEnvironment(stack);\n }\n\n public async readCurrentTemplateWithNestedStacks(\n rootStackArtifact: cxapi.CloudFormationStackArtifact,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<RootTemplateWithNestedStacks> {\n const env = await this.envs.accessStackForLookupBestEffort(rootStackArtifact);\n return loadCurrentTemplateWithNestedStacks(rootStackArtifact, env.sdk, retrieveProcessedTemplate);\n }\n\n public async readCurrentTemplate(stackArtifact: cxapi.CloudFormationStackArtifact): Promise<Template> {\n await this.ioHost.notify(debug(this.action, `Reading existing template for stack ${stackArtifact.displayName}.`));\n const env = await this.envs.accessStackForLookupBestEffort(stackArtifact);\n return loadCurrentTemplate(stackArtifact, env.sdk);\n }\n\n public async resourceIdentifierSummaries(\n stackArtifact: cxapi.CloudFormationStackArtifact,\n ): Promise<ResourceIdentifierSummaries> {\n await this.ioHost.notify(debug(this.action, `Retrieving template summary for stack ${stackArtifact.displayName}.`));\n // Currently, needs to use `deploy-role` since it may need to read templates in the staging\n // bucket which have been encrypted with a KMS key (and lookup-role may not read encrypted things)\n const env = await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);\n const cfn = env.sdk.cloudFormation();\n\n await uploadStackTemplateAssets(stackArtifact, this);\n\n // Upload the template, if necessary, before passing it to CFN\n const builder = new AssetManifestBuilder();\n const cfnParam = await makeBodyParameter(\n stackArtifact,\n env.resolvedEnvironment,\n builder,\n env.resources);\n\n // If the `makeBodyParameter` before this added assets, make sure to publish them before\n // calling the API.\n const addedAssets = builder.toManifest(stackArtifact.assembly.directory);\n for (const entry of addedAssets.entries) {\n await this.buildSingleAsset('no-version-validation', addedAssets, entry, {\n stack: stackArtifact,\n });\n await this.publishSingleAsset(addedAssets, entry, {\n stack: stackArtifact,\n });\n }\n\n const response = await cfn.getTemplateSummary(cfnParam);\n if (!response.ResourceIdentifierSummaries) {\n await this.ioHost.notify(debug(this.action, 'GetTemplateSummary API call did not return \"ResourceIdentifierSummaries\"'));\n }\n return response.ResourceIdentifierSummaries ?? [];\n }\n\n public async deployStack(options: DeployStackOptions): Promise<DeployStackResult> {\n let deploymentMethod = options.deploymentMethod;\n if (options.changeSetName || options.execute !== undefined) {\n if (deploymentMethod) {\n throw new ToolkitError(\n \"You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.\",\n );\n }\n deploymentMethod = {\n method: 'change-set',\n changeSetName: options.changeSetName,\n execute: options.execute,\n };\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n options.stack.requiresBootstrapStackVersion,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return deployStack({\n stack: options.stack,\n resolvedEnvironment: env.resolvedEnvironment,\n deployName: options.deployName,\n notificationArns: options.notificationArns,\n sdk: env.sdk,\n sdkProvider: this.deployStackSdkProvider,\n roleArn: executionRoleArn,\n reuseAssets: options.reuseAssets,\n envResources: env.resources,\n tags: options.tags,\n deploymentMethod,\n force: options.force,\n parameters: options.parameters,\n usePreviousParameters: options.usePreviousParameters,\n rollback: options.rollback,\n hotswap: options.hotswap,\n hotswapPropertyOverrides: options.hotswapPropertyOverrides,\n extraUserAgent: options.extraUserAgent,\n resourcesToImport: options.resourcesToImport,\n overrideTemplate: options.overrideTemplate,\n assetParallelism: options.assetParallelism,\n }, { ioHost: this.ioHost, action: this.action });\n }\n\n public async rollbackStack(options: RollbackStackOptions): Promise<RollbackStackResult> {\n let resourcesToSkip: string[] = options.orphanLogicalIds ?? [];\n if (options.force && resourcesToSkip.length > 0) {\n throw new ToolkitError('Cannot combine --force with --orphan');\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n if (options.validateBootstrapStackVersion ?? true) {\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const cfn = env.sdk.cloudFormation();\n const deployName = options.stack.stackName;\n\n // We loop in case of `--force` and the stack ends up in `CONTINUE_UPDATE_ROLLBACK`.\n let maxLoops = 10;\n while (maxLoops--) {\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n switch (cloudFormationStack.stackStatus.rollbackChoice) {\n case RollbackChoice.NONE:\n await this.ioHost.notify(warn(this.action, `Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`));\n return { notInRollbackableState: true };\n\n case RollbackChoice.START_ROLLBACK:\n await this.ioHost.notify(debug(this.action, `Initiating rollback of stack ${deployName}`));\n await cfn.rollbackStack({\n StackName: deployName,\n RoleARN: executionRoleArn,\n ClientRequestToken: randomUUID(),\n // Enabling this is just the better overall default, the only reason it isn't the upstream default is backwards compatibility\n RetainExceptOnCreate: true,\n });\n break;\n\n case RollbackChoice.CONTINUE_UPDATE_ROLLBACK:\n if (options.force) {\n // Find the failed resources from the deployment and automatically skip them\n // (Using deployment log because we definitely have `DescribeStackEvents` permissions, and we might not have\n // `DescribeStackResources` permissions).\n const poller = new StackEventPoller(cfn, {\n stackName: deployName,\n stackStatuses: ['ROLLBACK_IN_PROGRESS', 'UPDATE_ROLLBACK_IN_PROGRESS'],\n });\n await poller.poll();\n resourcesToSkip = poller.resourceErrors\n .filter((r) => !r.isStackEvent && r.parentStackLogicalIds.length === 0)\n .map((r) => r.event.LogicalResourceId ?? '');\n }\n\n const skipDescription = resourcesToSkip.length > 0 ? ` (orphaning: ${resourcesToSkip.join(', ')})` : '';\n await this.ioHost.notify(warn(this.action, `Continuing rollback of stack ${deployName}${skipDescription}`));\n await cfn.continueUpdateRollback({\n StackName: deployName,\n ClientRequestToken: randomUUID(),\n RoleARN: executionRoleArn,\n ResourcesToSkip: resourcesToSkip,\n });\n break;\n\n case RollbackChoice.ROLLBACK_FAILED:\n await this.ioHost.notify(warn(\n this.action,\n `Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`,\n ));\n return { notInRollbackableState: true };\n\n default:\n throw new ToolkitError(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`);\n }\n\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHost: this.ioHost,\n action: this.action,\n });\n await monitor.start();\n\n let stackErrorMessage: string | undefined = undefined;\n let finalStackState = cloudFormationStack;\n try {\n const successStack = await stabilizeStack(cfn, { ioHost: this.ioHost, action: this.action }, deployName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were rolling it back)');\n }\n finalStackState = successStack;\n\n const errors = monitor.errors.join(', ');\n if (errors) {\n stackErrorMessage = errors;\n }\n } catch (e: any) {\n stackErrorMessage = suffixWithErrors(formatErrorMessage(e), monitor.errors);\n } finally {\n await monitor.stop();\n }\n\n if (finalStackState.stackStatus.isRollbackSuccess || !stackErrorMessage) {\n return { success: true };\n }\n\n // Either we need to ignore some resources to continue the rollback, or something went wrong\n if (finalStackState.stackStatus.rollbackChoice === RollbackChoice.CONTINUE_UPDATE_ROLLBACK && options.force) {\n // Do another loop-de-loop\n continue;\n }\n\n throw new ToolkitError(\n `${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`,\n );\n }\n throw new ToolkitError(\n \"Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.\",\n );\n }\n\n public async destroyStack(options: DestroyStackOptions): Promise<void> {\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return destroyStack({\n sdk: env.sdk,\n roleArn: executionRoleArn,\n stack: options.stack,\n deployName: options.deployName,\n quiet: options.quiet,\n ci: options.ci,\n }, { ioHost: this.ioHost, action: this.action });\n }\n\n public async stackExists(options: StackExistsOptions): Promise<boolean> {\n let env;\n if (options.tryLookupRole) {\n env = await this.envs.accessStackForLookupBestEffort(options.stack);\n } else {\n env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n }\n const stack = await CloudFormationStack.lookup(env.sdk.cloudFormation(), options.deployName ?? options.stack.stackName);\n return stack.exists;\n }\n\n /**\n * Build a single asset from an asset manifest\n *\n * If an assert manifest artifact is given, the bootstrap stack version\n * will be validated according to the constraints in that manifest artifact.\n * If that is not necessary, `'no-version-validation'` can be passed.\n */\n // eslint-disable-next-line max-len\n public async buildSingleAsset(\n assetArtifact: cxapi.AssetManifestArtifact | 'no-version-validation',\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: BuildStackAssetsOptions,\n ) {\n if (assetArtifact !== 'no-version-validation') {\n const env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n assetArtifact.requiresBootstrapStackVersion,\n assetArtifact.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const resolvedEnvironment = await this.envs.resolveStackEnvironment(options.stack);\n\n const publisher = this.cachedPublisher(assetManifest, resolvedEnvironment, options.stackName);\n await publisher.buildEntry(asset);\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to build asset ${asset.id}`);\n }\n }\n\n /**\n * Publish a single asset from an asset manifest\n */\n public async publishSingleAsset(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n\n // No need to validate anymore, we already did that during build\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n await publisher.publishEntry(asset, { allowCrossAccount: await this.allowCrossAccountAssetPublishingForEnv(options.stack) });\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to publish asset ${asset.id}`);\n }\n }\n\n private async allowCrossAccountAssetPublishingForEnv(stack: cxapi.CloudFormationStackArtifact): Promise<boolean> {\n if (this._allowCrossAccountAssetPublishing === undefined) {\n const env = await this.envs.accessStackForReadOnlyStackOperations(stack);\n this._allowCrossAccountAssetPublishing = await determineAllowCrossAccountAssetPublishing(env.sdk, {\n ioHost: this.ioHost,\n action: this.action,\n }, this.props.toolkitStackName);\n }\n return this._allowCrossAccountAssetPublishing;\n }\n\n /**\n * Return whether a single asset has been published already\n */\n public async isSingleAssetPublished(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n return publisher.isEntryPublished(asset);\n }\n\n /**\n * Validate that the bootstrap stack has the right version for this stack\n *\n * Call into envResources.validateVersion, but prepend the stack name in case of failure.\n */\n private async validateBootstrapStackVersion(\n stackName: string,\n requiresBootstrapStackVersion: number | undefined,\n bootstrapStackVersionSsmParameter: string | undefined,\n envResources: EnvironmentResources,\n ) {\n try {\n await envResources.validateVersion(requiresBootstrapStackVersion, bootstrapStackVersionSsmParameter);\n } catch (e: any) {\n throw new ToolkitError(`${stackName}: ${formatErrorMessage(e)}`);\n }\n }\n\n private cachedPublisher(assetManifest: cdk_assets.AssetManifest, env: cxapi.Environment, stackName?: string) {\n const existing = this.publisherCache.get(assetManifest);\n if (existing) {\n return existing;\n }\n const prefix = stackName ? `${chalk.bold(stackName)}: ` : '';\n const publisher = new cdk_assets.AssetPublishing(assetManifest, {\n // The AssetPublishing class takes care of role assuming etc, so it's okay to\n // give it a direct `SdkProvider`.\n aws: new PublishingAws(this.assetSdkProvider, env),\n progressListener: new ParallelSafeAssetProgress(prefix, { ioHost: this.ioHost, action: this.action }),\n });\n this.publisherCache.set(assetManifest, publisher);\n return publisher;\n }\n}\n\n/**\n * Asset progress that doesn't do anything with percentages (currently)\n */\nclass ParallelSafeAssetProgress extends BasePublishProgressListener {\n private readonly prefix: string;\n\n constructor(prefix: string, { ioHost, action }: IoMessaging) {\n super({ ioHost, action });\n this.prefix = prefix;\n }\n\n protected getMessage(type: cdk_assets.EventType, event: cdk_assets.IPublishProgress): string {\n return `${this.prefix}${type}: ${event.message}`;\n }\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n", "import { type Environment, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport {\n type Account,\n type AssetManifest,\n AssetPublishing,\n ClientOptions,\n EventType,\n type IAws,\n type IECRClient,\n type IPublishProgress,\n type IPublishProgressListener,\n type IS3Client,\n type ISecretsManagerClient,\n} from 'cdk-assets';\nimport type { SDK } from '..';\nimport { formatMessage } from '../../cli/messages';\nimport { IIoHost, IoMessageLevel, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SdkProvider } from '../aws-auth';\nimport { Mode } from '../plugin';\n\ninterface PublishAssetsOptions {\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly parallel?: boolean;\n\n /**\n * Whether cdk-assets is allowed to do cross account publishing.\n */\n readonly allowCrossAccount: boolean;\n}\n\n/**\n * Use cdk-assets to publish all assets in the given manifest.\n *\n * @deprecated used in legacy deployments only, should be migrated at some point\n */\nexport async function publishAssets(\n manifest: AssetManifest,\n sdk: SdkProvider,\n targetEnv: Environment,\n options: PublishAssetsOptions,\n { ioHost, action }: IoMessaging,\n) {\n // This shouldn't really happen (it's a programming error), but we don't have\n // the types here to guide us. Do an runtime validation to be super super sure.\n if (\n targetEnv.account === undefined ||\n targetEnv.account === UNKNOWN_ACCOUNT ||\n targetEnv.region === undefined ||\n targetEnv.account === UNKNOWN_REGION\n ) {\n throw new ToolkitError(`Asset publishing requires resolved account and region, got ${JSON.stringify(targetEnv)}`);\n }\n\n const publisher = new AssetPublishing(manifest, {\n aws: new PublishingAws(sdk, targetEnv),\n progressListener: new PublishingProgressListener({ ioHost, action }),\n throwOnError: false,\n publishInParallel: options.parallel ?? true,\n buildAssets: true,\n publishAssets: true,\n quiet: false,\n });\n await publisher.publish({ allowCrossAccount: options.allowCrossAccount });\n if (publisher.hasFailures) {\n throw new ToolkitError('Failed to publish one or more assets. See the error messages above for more information.');\n }\n}\n\nexport class PublishingAws implements IAws {\n private sdkCache: Map<String, SDK> = new Map();\n\n constructor(\n /**\n * The base SDK to work with\n */\n private readonly aws: SdkProvider,\n\n /**\n * Environment where the stack we're deploying is going\n */\n private readonly targetEnv: Environment,\n ) {\n }\n\n public async discoverPartition(): Promise<string> {\n return (await this.aws.baseCredentialsPartition(this.targetEnv, Mode.ForWriting)) ?? 'aws';\n }\n\n public async discoverDefaultRegion(): Promise<string> {\n return this.targetEnv.region;\n }\n\n public async discoverCurrentAccount(): Promise<Account> {\n const account = await this.aws.defaultAccount();\n return (\n account ?? {\n accountId: '<unknown account>',\n partition: 'aws',\n }\n );\n }\n\n public async discoverTargetAccount(options: ClientOptions): Promise<Account> {\n return (await this.sdk(options)).currentAccount();\n }\n\n public async s3Client(options: ClientOptions): Promise<IS3Client> {\n return (await this.sdk(options)).s3();\n }\n\n public async ecrClient(options: ClientOptions): Promise<IECRClient> {\n return (await this.sdk(options)).ecr();\n }\n\n public async secretsManagerClient(options: ClientOptions): Promise<ISecretsManagerClient> {\n return (await this.sdk(options)).secretsManager();\n }\n\n /**\n * Get an SDK appropriate for the given client options\n */\n private async sdk(options: ClientOptions): Promise<SDK> {\n const env = {\n ...this.targetEnv,\n region: options.region ?? this.targetEnv.region, // Default: same region as the stack\n };\n\n const cacheKeyMap: any = {\n env, // region, name, account\n assumeRuleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n quiet: options.quiet,\n };\n\n if (options.assumeRoleAdditionalOptions) {\n cacheKeyMap.assumeRoleAdditionalOptions = options.assumeRoleAdditionalOptions;\n }\n\n const cacheKey = JSON.stringify(cacheKeyMap);\n\n const maybeSdk = this.sdkCache.get(cacheKey);\n if (maybeSdk) {\n return maybeSdk;\n }\n\n const sdk = (\n await this.aws.forEnvironment(\n env,\n Mode.ForWriting,\n {\n assumeRoleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n },\n options.quiet,\n )\n ).sdk;\n this.sdkCache.set(cacheKey, sdk);\n\n return sdk;\n }\n}\n\nexport const EVENT_TO_LEVEL: Record<EventType, IoMessageLevel | false> = {\n build: 'debug',\n cached: 'debug',\n check: 'debug',\n debug: 'debug',\n fail: 'error',\n found: 'debug',\n start: 'info',\n success: 'info',\n upload: 'debug',\n shell_open: 'debug',\n shell_stderr: false,\n shell_stdout: false,\n shell_close: false,\n};\n\nexport abstract class BasePublishProgressListener implements IPublishProgressListener {\n protected readonly ioHost: IIoHost;\n protected readonly action: ToolkitAction;\n\n constructor({ ioHost, action }: IoMessaging) {\n this.ioHost = ioHost;\n this.action = action;\n }\n\n protected abstract getMessage(type: EventType, event: IPublishProgress): string;\n\n public onPublishEvent(type: EventType, event: IPublishProgress): void {\n const level = EVENT_TO_LEVEL[type];\n if (level) {\n void this.ioHost.notify(\n formatMessage({\n level,\n action: this.action,\n message: this.getMessage(type, event),\n }),\n );\n }\n }\n}\n\nclass PublishingProgressListener extends BasePublishProgressListener {\n protected getMessage(type: EventType, event: IPublishProgress): string {\n return `[${event.percentComplete}%] ${type}: ${event.message}`;\n }\n}\n", "import { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { SDK } from '../aws-auth';\n\nexport async function determineAllowCrossAccountAssetPublishing(\n sdk: SDK,\n { ioHost, action }: IoMessaging,\n customStackName?: string,\n): Promise<boolean> {\n try {\n const stackName = customStackName || 'CDKToolkit';\n const stackInfo = await getBootstrapStackInfo(sdk, stackName);\n\n if (!stackInfo.hasStagingBucket) {\n // indicates an intentional cross account setup\n return true;\n }\n\n if (stackInfo.bootstrapVersion >= 21) {\n // bootstrap stack version 21 contains a fix that will prevent cross\n // account publishing on the IAM level\n // https://github.com/aws/aws-cdk/pull/30823\n return true;\n }\n\n // If there is a staging bucket AND the bootstrap version is old, then we want to protect\n // against accidental cross-account publishing.\n return false;\n } catch (e) {\n // You would think we would need to fail closed here, but the reality is\n // that we get here if we couldn't find the bootstrap stack: that is\n // completely valid, and many large organizations may have their own method\n // of creating bootstrap resources. If they do, there's nothing for us to validate,\n // but we can't use that as a reason to disallow cross-account publishing. We'll just\n // have to trust they did their due diligence. So we fail open.\n await ioHost.notify(debug(action, `Error determining cross account asset publishing: ${e}`));\n await ioHost.notify(debug(action, 'Defaulting to allowing cross account asset publishing'));\n return true;\n }\n}\n\ninterface BootstrapStackInfo {\n hasStagingBucket: boolean;\n bootstrapVersion: number;\n}\n\nexport async function getBootstrapStackInfo(sdk: SDK, stackName: string): Promise<BootstrapStackInfo> {\n try {\n const cfn = sdk.cloudFormation();\n const stackResponse = await cfn.describeStacks({ StackName: stackName });\n\n if (!stackResponse.Stacks || stackResponse.Stacks.length === 0) {\n throw new ToolkitError(`Toolkit stack ${stackName} not found`);\n }\n\n const stack = stackResponse.Stacks[0];\n const versionOutput = stack.Outputs?.find(output => output.OutputKey === 'BootstrapVersion');\n\n if (!versionOutput?.OutputValue) {\n throw new ToolkitError(`Unable to find BootstrapVersion output in the toolkit stack ${stackName}`);\n }\n\n const bootstrapVersion = parseInt(versionOutput.OutputValue);\n if (isNaN(bootstrapVersion)) {\n throw new ToolkitError(`Invalid BootstrapVersion value: ${versionOutput.OutputValue}`);\n }\n\n // try to get bucketname from the logical resource id. If there is no\n // bucketname, or the value doesn't look like an S3 bucket name, we assume\n // the bucket doesn't exist (this is for the case where a template customizer did\n // not dare to remove the Output, but put a dummy value there like '' or '-' or '***').\n //\n // We would have preferred to look at the stack resources here, but\n // unfortunately the deploy role doesn't have permissions call DescribeStackResources.\n const bucketName = stack.Outputs?.find(output => output.OutputKey === 'BucketName')?.OutputValue;\n // Must begin and end with letter or number.\n const hasStagingBucket = !!(bucketName && bucketName.match(/^[a-z0-9]/) && bucketName.match(/[a-z0-9]$/));\n\n return {\n hasStagingBucket,\n bootstrapVersion,\n };\n } catch (e) {\n throw new ToolkitError(`Error retrieving toolkit stack info: ${e}`);\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport type {\n CreateChangeSetCommandInput,\n CreateStackCommandInput,\n DescribeChangeSetCommandOutput,\n ExecuteChangeSetCommandInput,\n UpdateStackCommandInput,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { publishAssets } from './asset-publishing';\nimport { addMetadataAssetsToManifest } from './assets';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport {\n changeSetHasNoChanges,\n CloudFormationStack,\n TemplateParameters,\n waitForChangeSet,\n waitForStackDeploy,\n waitForStackDelete,\n ParameterValues,\n ParameterChanges,\n ResourcesToImport,\n} from './cloudformation';\nimport { ChangeSetDeploymentMethod, DeploymentMethod } from './deployment-method';\nimport { DeployStackResult, SuccessfulDeployStackResult } from './deployment-result';\nimport { tryHotswapDeployment } from './hotswap-deployments';\nimport { debug, info, warn } from '../../cli/messages';\nimport { IIoHost, IoMessaging, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK, SdkProvider, ICloudFormationClient } from '../aws-auth';\nimport type { EnvironmentResources } from '../environment';\nimport { CfnEvaluationException } from '../evaluate-cloudformation-template';\nimport { HotswapMode, HotswapPropertyOverrides, ICON } from '../hotswap/common';\nimport { StackActivityMonitor } from '../stack-events';\nimport { StringWithoutPlaceholders } from '../util/placeholders';\nimport { type TemplateBodyParameter, makeBodyParameter } from '../util/template-body-parameter';\n\nexport interface DeployStackOptions {\n /**\n * The stack to be deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * The SDK to use for deploying the stack\n *\n * Should have been initialized with the correct role with which\n * stack operations should be performed.\n */\n readonly sdk: SDK;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to:\n *\n * - Publish assets, either legacy assets or large CFN templates\n * that aren't themselves assets from a manifest. (Needs an SDK\n * Provider because the file publishing role is declared as part\n * of the asset).\n * - Hotswap\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Information about the bootstrap stack found in the target environment\n */\n readonly envResources: EnvironmentResources;\n\n /**\n * Role to pass to CloudFormation to execute the change set\n *\n * To obtain a `StringWithoutPlaceholders`, run a regular\n * string though `TargetEnvironment.replacePlaceholders`.\n *\n * @default - No execution role; CloudFormation either uses the role currently associated with\n * the stack, or otherwise uses current AWS credentials.\n */\n readonly roleArn?: StringWithoutPlaceholders;\n\n /**\n * Notification ARNs to pass to CloudFormation to notify when the change set has completed\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Name to deploy the stack under\n *\n * @default - Name from assembly\n */\n readonly deployName?: string;\n\n /**\n * List of asset IDs which shouldn't be built\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Tags to pass to CloudFormation to add to stack\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * What deployment method to use\n *\n * @default - Change set with defaults\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * The collection of extra parameters\n * (in addition to those used for assets)\n * to pass to the deployed template.\n * Note that parameters with `undefined` or empty values will be ignored,\n * and not passed to the template.\n *\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default false\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Deploy even if the deployed template is identical to the one we are about to deploy.\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Extra properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * If set, change set of type IMPORT will be created, and resourcesToImport\n * passed to it.\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n}\n\nexport async function deployStack(options: DeployStackOptions, { ioHost, action }: IoMessaging): Promise<DeployStackResult> {\n const stackArtifact = options.stack;\n\n const stackEnv = options.resolvedEnvironment;\n\n options.sdk.appendCustomUserAgent(options.extraUserAgent);\n const cfn = options.sdk.cloudFormation();\n const deployName = options.deployName || stackArtifact.stackName;\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n if (cloudFormationStack.stackStatus.isCreationFailure) {\n await ioHost.notify(debug(action,\n `Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`,\n ));\n await cfn.deleteStack({ StackName: deployName });\n const deletedStack = await waitForStackDelete(cfn, { ioHost, action }, deployName);\n if (deletedStack && deletedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(\n `Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`,\n );\n }\n // Update variable to mark that the stack does not exist anymore, but avoid\n // doing an actual lookup in CloudFormation (which would be silly to do if\n // we just deleted it).\n cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);\n }\n\n // Detect \"legacy\" assets (which remain in the metadata) and publish them via\n // an ad-hoc asset manifest, while passing their locations via template\n // parameters.\n const legacyAssets = new AssetManifestBuilder();\n const assetParams = await addMetadataAssetsToManifest(\n { ioHost, action },\n stackArtifact,\n legacyAssets,\n options.envResources,\n options.reuseAssets,\n );\n\n const finalParameterValues = { ...options.parameters, ...assetParams };\n\n const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);\n const stackParams = options.usePreviousParameters\n ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)\n : templateParams.supplyAll(finalParameterValues);\n\n const hotswapMode = options.hotswap ?? HotswapMode.FULL_DEPLOYMENT;\n const hotswapPropertyOverrides = options.hotswapPropertyOverrides ?? new HotswapPropertyOverrides();\n\n if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters), { ioHost, action })) {\n await ioHost.notify(debug(action, `${deployName}: skipping deployment (use --force to override)`));\n // if we can skip deployment and we are performing a hotswap, let the user know\n // that no hotswap deployment happened\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n await ioHost.notify(info(action,\n format(\n `\\n ${ICON} %s\\n`,\n chalk.bold('hotswap deployment skipped - no changes were detected (use --force to override)'),\n ),\n ));\n }\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: cloudFormationStack.outputs,\n stackArn: cloudFormationStack.stackId,\n };\n } else {\n await ioHost.notify(debug(action, `${deployName}: deploying...`));\n }\n\n const bodyParameter = await makeBodyParameter(\n stackArtifact,\n options.resolvedEnvironment,\n legacyAssets,\n options.envResources,\n options.overrideTemplate,\n );\n let bootstrapStackName: string | undefined;\n try {\n bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;\n } catch (e) {\n await ioHost.notify(debug(action, `Could not determine the bootstrap stack name: ${e}`));\n }\n await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {\n parallel: options.assetParallelism,\n allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, { ioHost, action }, bootstrapStackName),\n }, { ioHost, action });\n\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n // attempt to short-circuit the deployment if possible\n try {\n const hotswapDeploymentResult = await tryHotswapDeployment(\n options.sdkProvider,\n { ioHost, action },\n stackParams.values,\n cloudFormationStack,\n stackArtifact,\n hotswapMode, hotswapPropertyOverrides,\n );\n if (hotswapDeploymentResult) {\n return hotswapDeploymentResult;\n }\n await ioHost.notify(info(action, format(\n 'Could not perform a hotswap deployment, as the stack %s contains non-Asset changes',\n stackArtifact.displayName,\n )));\n } catch (e) {\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n await ioHost.notify(info(action, format(\n 'Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s',\n formatErrorMessage(e),\n )));\n }\n\n if (hotswapMode === HotswapMode.FALL_BACK) {\n await ioHost.notify(info(action, 'Falling back to doing a full deployment'));\n options.sdk.appendCustomUserAgent('cdk-hotswap/fallback');\n } else {\n return {\n type: 'did-deploy-stack',\n noOp: true,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n }\n\n // could not short-circuit the deployment, perform a full CFN deploy instead\n const fullDeployment = new FullCloudFormationDeployment(\n options,\n cloudFormationStack,\n stackArtifact,\n stackParams,\n bodyParameter,\n ioHost,\n action,\n );\n return fullDeployment.performDeployment();\n}\n\ntype CommonPrepareOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof CreateChangeSetCommandInput;\ntype CommonExecuteOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof ExecuteChangeSetCommandInput;\n\n/**\n * This class shares state and functionality between the different full deployment modes\n */\nclass FullCloudFormationDeployment {\n private readonly cfn: ICloudFormationClient;\n private readonly stackName: string;\n private readonly update: boolean;\n private readonly verb: string;\n private readonly uuid: string;\n\n constructor(\n private readonly options: DeployStackOptions,\n private readonly cloudFormationStack: CloudFormationStack,\n private readonly stackArtifact: cxapi.CloudFormationStackArtifact,\n private readonly stackParams: ParameterValues,\n private readonly bodyParameter: TemplateBodyParameter,\n private readonly ioHost: IIoHost,\n private readonly action: ToolkitAction,\n ) {\n this.cfn = options.sdk.cloudFormation();\n this.stackName = options.deployName ?? stackArtifact.stackName;\n\n this.update = cloudFormationStack.exists && cloudFormationStack.stackStatus.name !== 'REVIEW_IN_PROGRESS';\n this.verb = this.update ? 'update' : 'create';\n this.uuid = uuid.v4();\n }\n\n public async performDeployment(): Promise<DeployStackResult> {\n const deploymentMethod = this.options.deploymentMethod ?? {\n method: 'change-set',\n };\n\n if (deploymentMethod.method === 'direct' && this.options.resourcesToImport) {\n throw new ToolkitError('Importing resources requires a changeset deployment');\n }\n\n switch (deploymentMethod.method) {\n case 'change-set':\n return this.changeSetDeployment(deploymentMethod);\n\n case 'direct':\n return this.directDeployment();\n }\n }\n\n private async changeSetDeployment(deploymentMethod: ChangeSetDeploymentMethod): Promise<DeployStackResult> {\n const changeSetName = deploymentMethod.changeSetName ?? 'cdk-deploy-change-set';\n const execute = deploymentMethod.execute ?? true;\n const importExistingResources = deploymentMethod.importExistingResources ?? false;\n const changeSetDescription = await this.createChangeSet(changeSetName, execute, importExistingResources);\n await this.updateTerminationProtection();\n\n if (changeSetHasNoChanges(changeSetDescription)) {\n await this.ioHost.notify(debug(this.action, format('No changes are to be performed on %s.', this.stackName)));\n if (execute) {\n await this.ioHost.notify(debug(this.action, format('Deleting empty change set %s', changeSetDescription.ChangeSetId)));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n\n if (this.options.force) {\n await this.ioHost.notify(warn(\n this.action,\n [\n 'You used the --force flag, but CloudFormation reported that the deployment would not make any changes.',\n 'According to CloudFormation, all resources are already up-to-date with the state in your CDK app.',\n '',\n 'You cannot use the --force flag to get rid of changes you made in the console. Try using',\n 'CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html',\n ].join('\\n'),\n ));\n }\n\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n if (!execute) {\n await this.ioHost.notify(info(this.action, format(\n 'Changeset %s created and waiting in review for manual execution (--no-execute)',\n changeSetDescription.ChangeSetId,\n )));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n // If there are replacements in the changeset, check the rollback flag and stack status\n const replacement = hasReplacement(changeSetDescription);\n const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;\n const rollback = this.options.rollback ?? true;\n if (isPausedFailState && replacement) {\n return { type: 'failpaused-need-rollback-first', reason: 'replacement', status: this.cloudFormationStack.stackStatus.name };\n }\n if (isPausedFailState && rollback) {\n return { type: 'failpaused-need-rollback-first', reason: 'not-norollback', status: this.cloudFormationStack.stackStatus.name };\n }\n if (!rollback && replacement) {\n return { type: 'replacement-requires-rollback' };\n }\n\n return this.executeChangeSet(changeSetDescription);\n }\n\n private async createChangeSet(changeSetName: string, willExecute: boolean, importExistingResources: boolean) {\n await this.cleanupOldChangeset(changeSetName);\n\n await this.ioHost.notify(debug(this.action, `Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`));\n await this.ioHost.notify(info(this.action, format('%s: creating CloudFormation changeset...', chalk.bold(this.stackName))));\n const changeSet = await this.cfn.createChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n ChangeSetType: this.options.resourcesToImport ? 'IMPORT' : this.update ? 'UPDATE' : 'CREATE',\n ResourcesToImport: this.options.resourcesToImport,\n Description: `CDK Changeset for execution ${this.uuid}`,\n ClientToken: `create${this.uuid}`,\n ImportExistingResources: importExistingResources,\n ...this.commonPrepareOptions(),\n });\n\n await this.ioHost.notify(debug(this.action, format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n return waitForChangeSet(this.cfn, { ioHost: this.ioHost, action: this.action }, this.stackName, changeSetName, {\n fetchAll: willExecute,\n });\n }\n\n private async executeChangeSet(changeSet: DescribeChangeSetCommandOutput): Promise<SuccessfulDeployStackResult> {\n await this.ioHost.notify(debug(this.action, format('Initiating execution of changeset %s on stack %s', changeSet.ChangeSetId, this.stackName)));\n\n await this.cfn.executeChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSet.ChangeSetName!,\n ClientRequestToken: `exec${this.uuid}`,\n ...this.commonExecuteOptions(),\n });\n\n await this.ioHost.notify(debug(\n this.action,\n format(\n 'Execution of changeset %s on stack %s has started; waiting for the update to complete...',\n changeSet.ChangeSetId,\n this.stackName,\n ),\n ));\n\n // +1 for the extra event emitted from updates.\n const changeSetLength: number = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);\n return this.monitorDeployment(changeSet.CreationTime!, changeSetLength);\n }\n\n private async cleanupOldChangeset(changeSetName: string) {\n if (this.cloudFormationStack.exists) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await this.ioHost.notify(debug(this.action, `Removing existing change set with name ${changeSetName} if it exists`));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n }\n\n private async updateTerminationProtection() {\n // Update termination protection only if it has changed.\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {\n await this.ioHost.notify(debug(\n this.action,\n format (\n 'Updating termination protection from %s to %s for stack %s',\n this.cloudFormationStack.terminationProtection,\n terminationProtection,\n this.stackName,\n ),\n ));\n await this.cfn.updateTerminationProtection({\n StackName: this.stackName,\n EnableTerminationProtection: terminationProtection,\n });\n await this.ioHost.notify(debug(this.action, format('Termination protection updated to %s for stack %s', terminationProtection, this.stackName)));\n }\n }\n\n private async directDeployment(): Promise<SuccessfulDeployStackResult> {\n await this.ioHost.notify(info(this.action, format('%s: %s stack...', chalk.bold(this.stackName), this.update ? 'updating' : 'creating')));\n\n const startTime = new Date();\n\n if (this.update) {\n await this.updateTerminationProtection();\n\n try {\n await this.cfn.updateStack({\n StackName: this.stackName,\n ClientRequestToken: `update${this.uuid}`,\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n } catch (err: any) {\n if (err.message === 'No updates are to be performed.') {\n await this.ioHost.notify(debug(this.action, format('No updates are to be performed for stack %s', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: this.cloudFormationStack.stackId,\n };\n }\n throw err;\n }\n\n return this.monitorDeployment(startTime, undefined);\n } else {\n // Take advantage of the fact that we can set termination protection during create\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n\n await this.cfn.createStack({\n StackName: this.stackName,\n ClientRequestToken: `create${this.uuid}`,\n ...(terminationProtection ? { EnableTerminationProtection: true } : undefined),\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n\n return this.monitorDeployment(startTime, undefined);\n }\n }\n\n private async monitorDeployment(startTime: Date, expectedChanges: number | undefined): Promise<SuccessfulDeployStackResult> {\n const monitor = new StackActivityMonitor({\n cfn: this.cfn,\n stack: this.stackArtifact,\n stackName: this.stackName,\n resourcesTotal: expectedChanges,\n ioHost: this.ioHost,\n action: this.action,\n changeSetCreationTime: startTime,\n });\n await monitor.start();\n\n let finalState = this.cloudFormationStack;\n try {\n const successStack = await waitForStackDeploy(this.cfn, { ioHost: this.ioHost, action: this.action }, this.stackName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were deploying it)');\n }\n finalState = successStack;\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n await monitor.stop();\n }\n debug(this.action, format('Stack %s has completed updating', this.stackName));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: finalState.outputs,\n stackArn: finalState.stackId,\n };\n }\n\n /**\n * Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet\n */\n private commonPrepareOptions(): Partial<Pick<UpdateStackCommandInput, CommonPrepareOptions>> {\n return {\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n NotificationARNs: this.options.notificationArns,\n Parameters: this.stackParams.apiParameters,\n RoleARN: this.options.roleArn,\n TemplateBody: this.bodyParameter.TemplateBody,\n TemplateURL: this.bodyParameter.TemplateURL,\n Tags: this.options.tags,\n };\n }\n\n /**\n * Return the options that are shared between UpdateStack and CreateChangeSet\n *\n * Be careful not to add in keys for options that aren't used, as the features may not have been\n * deployed everywhere yet.\n */\n private commonExecuteOptions(): Partial<Pick<UpdateStackCommandInput, CommonExecuteOptions>> {\n const shouldDisableRollback = this.options.rollback === false;\n\n return {\n StackName: this.stackName,\n ...(shouldDisableRollback ? { DisableRollback: true } : undefined),\n };\n }\n}\n\nexport interface DestroyStackOptions {\n /**\n * The stack to be destroyed\n */\n stack: cxapi.CloudFormationStackArtifact;\n\n sdk: SDK;\n roleArn?: string;\n deployName?: string;\n quiet?: boolean;\n ci?: boolean;\n}\n\nexport async function destroyStack(options: DestroyStackOptions, { ioHost, action }: IoMessaging) {\n const deployName = options.deployName || options.stack.stackName;\n const cfn = options.sdk.cloudFormation();\n\n const currentStack = await CloudFormationStack.lookup(cfn, deployName);\n if (!currentStack.exists) {\n return;\n }\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHost,\n action,\n });\n await monitor.start();\n\n try {\n await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });\n const destroyedStack = await waitForStackDelete(cfn, { ioHost, action }, deployName);\n if (destroyedStack && destroyedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`);\n }\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n if (monitor) {\n await monitor.stop();\n }\n }\n}\n\n/**\n * Checks whether we can skip deployment\n *\n * We do this in a complicated way by preprocessing (instead of just\n * looking at the changeset), because if there are nested stacks involved\n * the changeset will always show the nested stacks as needing to be\n * updated, and the deployment will take a long time to in effect not\n * do anything.\n */\nasync function canSkipDeploy(\n deployStackOptions: DeployStackOptions,\n cloudFormationStack: CloudFormationStack,\n parameterChanges: ParameterChanges,\n { ioHost, action }: IoMessaging,\n): Promise<boolean> {\n const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;\n await ioHost.notify(debug(action, `${deployName}: checking if we can skip deploy`));\n\n // Forced deploy\n if (deployStackOptions.force) {\n await ioHost.notify(debug(action, `${deployName}: forced deployment`));\n return false;\n }\n\n // Creating changeset only (default true), never skip\n if (\n deployStackOptions.deploymentMethod?.method === 'change-set' &&\n deployStackOptions.deploymentMethod.execute === false\n ) {\n await ioHost.notify(debug(action, `${deployName}: --no-execute, always creating change set`));\n return false;\n }\n\n // No existing stack\n if (!cloudFormationStack.exists) {\n await ioHost.notify(debug(action, `${deployName}: no existing stack`));\n return false;\n }\n\n // Template has changed (assets taken into account here)\n if (JSON.stringify(deployStackOptions.stack.template) !== JSON.stringify(await cloudFormationStack.template())) {\n await ioHost.notify(debug(action, `${deployName}: template has changed`));\n return false;\n }\n\n // Tags have changed\n if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {\n await ioHost.notify(debug(action, `${deployName}: tags have changed`));\n return false;\n }\n\n // Notification arns have changed\n if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {\n await ioHost.notify(debug(action, `${deployName}: notification arns have changed`));\n return false;\n }\n\n // Termination protection has been updated\n if (!!deployStackOptions.stack.terminationProtection !== !!cloudFormationStack.terminationProtection) {\n await ioHost.notify(debug(action, `${deployName}: termination protection has been updated`));\n return false;\n }\n\n // Parameters have changed\n if (parameterChanges) {\n if (parameterChanges === 'ssm') {\n await ioHost.notify(debug(action, `${deployName}: some parameters come from SSM so we have to assume they may have changed`));\n } else {\n await ioHost.notify(debug(action, `${deployName}: parameters have changed`));\n }\n return false;\n }\n\n // Existing stack is in a failed state\n if (cloudFormationStack.stackStatus.isFailure) {\n await ioHost.notify(debug(action, `${deployName}: stack is in a failure state`));\n return false;\n }\n\n // We can skip deploy\n return true;\n}\n\n/**\n * Compares two list of tags, returns true if identical.\n */\nfunction compareTags(a: Tag[], b: Tag[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (const aTag of a) {\n const bTag = b.find((tag) => tag.Key === aTag.Key);\n\n if (!bTag || bTag.Value !== aTag.Value) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n\nfunction arrayEquals(a: any[], b: any[]): boolean {\n return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));\n}\n\nfunction hasReplacement(cs: DescribeChangeSetCommandOutput) {\n return (cs.Changes ?? []).some(c => {\n const a = c.ResourceChange?.PolicyAction;\n return a === 'ReplaceAndDelete' || a === 'ReplaceAndRetain' || a === 'ReplaceAndSnapshot';\n });\n}\n", "// eslint-disable-next-line max-len\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { debug } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { EnvironmentResources } from '../environment';\nimport { ToolkitInfo } from '../toolkit-info';\n\n/**\n * Take the metadata assets from the given stack and add them to the given asset manifest\n *\n * Returns the CloudFormation parameters that need to be sent to the template to\n * pass Asset coordinates.\n */\nexport async function addMetadataAssetsToManifest(\n { ioHost, action }: IoMessaging,\n stack: cxapi.CloudFormationStackArtifact,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n reuse?: string[],\n): Promise<Record<string, string>> {\n reuse = reuse || [];\n const assets = stack.assets;\n\n if (assets.length === 0) {\n return {};\n }\n\n const toolkitInfo = await envResources.lookupToolkit();\n if (!toolkitInfo.found) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(`This stack uses assets, so the toolkit stack must be deployed to the environment (Run \"${chalk.blue('cdk bootstrap ' + stack.environment!.name)}\")`);\n }\n\n const params: Record<string, string> = {};\n\n for (const asset of assets) {\n // FIXME: Should have excluded by construct path here instead of by unique ID, preferably using\n // minimatch so we can support globs. Maybe take up during artifact refactoring.\n const reuseAsset = reuse.indexOf(asset.id) > -1;\n\n if (reuseAsset) {\n await ioHost.notify(debug(action, `Reusing asset ${asset.id}: ${JSON.stringify(asset)}`));\n continue;\n }\n\n await ioHost.notify(debug(action, `Preparing asset ${asset.id}: ${JSON.stringify(asset)}`));\n if (!stack.assembly) {\n throw new ToolkitError('Unexpected: stack assembly is required in order to find assets in assembly directory');\n }\n\n Object.assign(params, await prepareAsset({ ioHost, action }, asset, assetManifest, envResources, toolkitInfo));\n }\n\n return params;\n}\n\n// eslint-disable-next-line max-len\nasync function prepareAsset(\n { ioHost, action }: IoMessaging,\n asset: cxschema.AssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n toolkitInfo: ToolkitInfo,\n): Promise<Record<string, string>> {\n switch (asset.packaging) {\n case 'zip':\n case 'file':\n return prepareFileAsset(\n { ioHost, action },\n asset,\n assetManifest,\n toolkitInfo,\n asset.packaging === 'zip' ? cxschema.FileAssetPackaging.ZIP_DIRECTORY : cxschema.FileAssetPackaging.FILE);\n case 'container-image':\n return prepareDockerImageAsset(asset, assetManifest, envResources);\n default:\n // eslint-disable-next-line max-len\n throw new ToolkitError(`Unsupported packaging type: ${(asset as any).packaging}. You might need to upgrade your aws-cdk toolkit to support this asset type.`);\n }\n}\n\nasync function prepareFileAsset(\n { ioHost, action }: IoMessaging,\n asset: cxschema.FileAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n toolkitInfo: ToolkitInfo,\n packaging: cxschema.FileAssetPackaging,\n): Promise<Record<string, string>> {\n const extension = packaging === cxschema.FileAssetPackaging.ZIP_DIRECTORY ? '.zip' : path.extname(asset.path);\n const baseName = `${asset.sourceHash}${extension}`;\n // Simplify key: assets/abcdef/abcdef.zip is kinda silly and unnecessary, so if they're the same just pick one component.\n const s3Prefix = asset.id === asset.sourceHash ? 'assets/' : `assets/${asset.id}/`;\n const key = `${s3Prefix}${baseName}`;\n const s3url = `s3://${toolkitInfo.bucketName}/${key}`;\n\n await ioHost.notify(debug(action, `Storing asset ${asset.path} at ${s3url}`));\n\n assetManifest.addFileAsset(asset.sourceHash, {\n path: asset.path,\n packaging,\n }, {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n });\n\n return {\n [asset.s3BucketParameter]: toolkitInfo.bucketName,\n [asset.s3KeyParameter]: `${s3Prefix}${cxapi.ASSET_PREFIX_SEPARATOR}${baseName}`,\n [asset.artifactHashParameter]: asset.sourceHash,\n };\n}\n\nasync function prepareDockerImageAsset(\n asset: cxschema.ContainerImageAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources): Promise<Record<string, string>> {\n // Pre-1.21.0, repositoryName can be specified by the user or can be left out, in which case we make\n // a per-asset repository which will get adopted and cleaned up along with the stack.\n // Post-1.21.0, repositoryName will always be specified and it will be a shared repository between\n // all assets, and asset will have imageTag specified as well. Validate the combination.\n if (!asset.imageNameParameter && (!asset.repositoryName || !asset.imageTag)) {\n throw new ToolkitError('Invalid Docker image asset configuration: \"repositoryName\" and \"imageTag\" are required when \"imageNameParameter\" is left out');\n }\n\n const repositoryName = asset.repositoryName ?? 'cdk/' + asset.id.replace(/[:/]/g, '-').toLowerCase();\n\n // Make sure the repository exists, since the 'cdk-assets' tool will not create it for us.\n const { repositoryUri } = await envResources.prepareEcrRepository(repositoryName);\n const imageTag = asset.imageTag ?? asset.sourceHash;\n\n assetManifest.addDockerImageAsset(asset.sourceHash, {\n directory: asset.path,\n dockerBuildArgs: asset.buildArgs,\n dockerBuildSsh: asset.buildSsh,\n dockerBuildTarget: asset.target,\n dockerFile: asset.file,\n networkMode: asset.networkMode,\n platform: asset.platform,\n dockerOutputs: asset.outputs,\n }, {\n repositoryName,\n imageTag,\n });\n\n if (!asset.imageNameParameter) {\n return {};\n }\n return { [asset.imageNameParameter]: `${repositoryUri}:${imageTag}` };\n}\n", "import { format } from 'util';\nimport * as cfn_diff from '@aws-cdk/cloudformation-diff';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { WaiterResult } from '@smithy/util-waiter';\nimport * as chalk from 'chalk';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { CloudFormationStack } from './cloudformation';\nimport { NestedStackTemplates, loadCurrentTemplateWithNestedStacks } from './nested-stack-helpers';\nimport { info } from '../../cli/messages';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\nimport { isHotswappableAppSyncChange } from '../hotswap/appsync-mapping-templates';\nimport { isHotswappableCodeBuildProjectChange } from '../hotswap/code-build-projects';\nimport {\n ICON,\n ChangeHotswapResult,\n HotswapMode,\n HotswappableChange,\n NonHotswappableChange,\n HotswappableChangeCandidate,\n HotswapPropertyOverrides, ClassifiedResourceChanges,\n reportNonHotswappableChange,\n reportNonHotswappableResource,\n} from '../hotswap/common';\nimport { isHotswappableEcsServiceChange } from '../hotswap/ecs-services';\nimport { isHotswappableLambdaFunctionChange } from '../hotswap/lambda-functions';\nimport {\n skipChangeForS3DeployCustomResourcePolicy,\n isHotswappableS3BucketDeploymentChange,\n} from '../hotswap/s3-bucket-deployments';\nimport { isHotswappableStateMachineChange } from '../hotswap/stepfunctions-state-machines';\nimport { Mode } from '../plugin';\nimport { SuccessfulDeployStackResult } from './deployment-result';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\n\n// Must use a require() otherwise esbuild complains about calling a namespace\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\ntype HotswapDetector = (\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n) => Promise<ChangeHotswapResult>;\n\nconst RESOURCE_DETECTORS: { [key: string]: HotswapDetector } = {\n // Lambda\n 'AWS::Lambda::Function': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Version': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Alias': isHotswappableLambdaFunctionChange,\n\n // AppSync\n 'AWS::AppSync::Resolver': isHotswappableAppSyncChange,\n 'AWS::AppSync::FunctionConfiguration': isHotswappableAppSyncChange,\n 'AWS::AppSync::GraphQLSchema': isHotswappableAppSyncChange,\n 'AWS::AppSync::ApiKey': isHotswappableAppSyncChange,\n\n 'AWS::ECS::TaskDefinition': isHotswappableEcsServiceChange,\n 'AWS::CodeBuild::Project': isHotswappableCodeBuildProjectChange,\n 'AWS::StepFunctions::StateMachine': isHotswappableStateMachineChange,\n 'Custom::CDKBucketDeployment': isHotswappableS3BucketDeploymentChange,\n 'AWS::IAM::Policy': async (\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n ): Promise<ChangeHotswapResult> => {\n // If the policy is for a S3BucketDeploymentChange, we can ignore the change\n if (await skipChangeForS3DeployCustomResourcePolicy(logicalId, change, evaluateCfnTemplate)) {\n return [];\n }\n\n return reportNonHotswappableResource(change, 'This resource type is not supported for hotswap deployments');\n },\n\n 'AWS::CDK::Metadata': async () => [],\n};\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * If it's not possible to short-circuit the deployment\n * (because the CDK Stack contains changes that cannot be deployed without CloudFormation),\n * returns `undefined`.\n */\nexport async function tryHotswapDeployment(\n sdkProvider: SdkProvider,\n { ioHost, action }: IoMessaging,\n assetParams: { [key: string]: string },\n cloudFormationStack: CloudFormationStack,\n stackArtifact: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode, hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<SuccessfulDeployStackResult | undefined> {\n // resolve the environment, so we can substitute things like AWS::Region in CFN expressions\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // create a new SDK using the CLI credentials, because the default one will not work for new-style synthesis -\n // it assumes the bootstrap deploy Role, which doesn't have permissions to update Lambda functions\n const sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForWriting)).sdk;\n\n const currentTemplate = await loadCurrentTemplateWithNestedStacks(stackArtifact, sdk);\n\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackName: stackArtifact.stackName,\n template: stackArtifact.template,\n parameters: assetParams,\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n nestedStacks: currentTemplate.nestedStacks,\n });\n\n const stackChanges = cfn_diff.fullDiff(currentTemplate.deployedRootTemplate, stackArtifact.template);\n const { hotswappableChanges, nonHotswappableChanges } = await classifyResourceChanges(\n stackChanges,\n evaluateCfnTemplate,\n sdk,\n currentTemplate.nestedStacks, hotswapPropertyOverrides,\n );\n\n await logNonHotswappableChanges({ ioHost, action }, nonHotswappableChanges, hotswapMode);\n\n // preserve classic hotswap behavior\n if (hotswapMode === HotswapMode.FALL_BACK) {\n if (nonHotswappableChanges.length > 0) {\n return undefined;\n }\n }\n\n // apply the short-circuitable changes\n await applyAllHotswappableChanges(sdk, { ioHost, action }, hotswappableChanges);\n\n return {\n type: 'did-deploy-stack',\n noOp: hotswappableChanges.length === 0,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n}\n\n/**\n * Classifies all changes to all resources as either hotswappable or not.\n * Metadata changes are excluded from the list of (non)hotswappable resources.\n */\nasync function classifyResourceChanges(\n stackChanges: cfn_diff.TemplateDiff,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n nestedStackNames: { [nestedStackName: string]: NestedStackTemplates },\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedResourceChanges> {\n const resourceDifferences = getStackResourceDifferences(stackChanges);\n\n const promises: Array<() => Promise<ChangeHotswapResult>> = [];\n const hotswappableResources = new Array<HotswappableChange>();\n const nonHotswappableResources = new Array<NonHotswappableChange>();\n for (const logicalId of Object.keys(stackChanges.outputs.changes)) {\n nonHotswappableResources.push({\n hotswappable: false,\n reason: 'output was changed',\n logicalId,\n rejectedChanges: [],\n resourceType: 'Stack Output',\n });\n }\n // gather the results of the detector functions\n for (const [logicalId, change] of Object.entries(resourceDifferences)) {\n if (change.newValue?.Type === 'AWS::CloudFormation::Stack' && change.oldValue?.Type === 'AWS::CloudFormation::Stack') {\n const nestedHotswappableResources = await findNestedHotswappableChanges(\n logicalId,\n change,\n nestedStackNames,\n evaluateCfnTemplate,\n sdk,\n hotswapPropertyOverrides,\n );\n hotswappableResources.push(...nestedHotswappableResources.hotswappableChanges);\n nonHotswappableResources.push(...nestedHotswappableResources.nonHotswappableChanges);\n\n continue;\n }\n\n const hotswappableChangeCandidate = isCandidateForHotswapping(change, logicalId);\n // we don't need to run this through the detector functions, we can already judge this\n if ('hotswappable' in hotswappableChangeCandidate) {\n if (!hotswappableChangeCandidate.hotswappable) {\n nonHotswappableResources.push(hotswappableChangeCandidate);\n }\n\n continue;\n }\n\n const resourceType: string = hotswappableChangeCandidate.newValue.Type;\n if (resourceType in RESOURCE_DETECTORS) {\n // run detector functions lazily to prevent unhandled promise rejections\n promises.push(() =>\n RESOURCE_DETECTORS[resourceType](logicalId, hotswappableChangeCandidate, evaluateCfnTemplate, hotswapPropertyOverrides),\n );\n } else {\n reportNonHotswappableChange(\n nonHotswappableResources,\n hotswappableChangeCandidate,\n undefined,\n 'This resource type is not supported for hotswap deployments',\n );\n }\n }\n\n // resolve all detector results\n const changesDetectionResults: Array<ChangeHotswapResult> = [];\n for (const detectorResultPromises of promises) {\n // Constant set of promises per resource\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const hotswapDetectionResults = await Promise.all(await detectorResultPromises());\n changesDetectionResults.push(hotswapDetectionResults);\n }\n\n for (const resourceDetectionResults of changesDetectionResults) {\n for (const propertyResult of resourceDetectionResults) {\n propertyResult.hotswappable\n ? hotswappableResources.push(propertyResult)\n : nonHotswappableResources.push(propertyResult);\n }\n }\n\n return {\n hotswappableChanges: hotswappableResources,\n nonHotswappableChanges: nonHotswappableResources,\n };\n}\n\n/**\n * Returns all changes to resources in the given Stack.\n *\n * @param stackChanges the collection of all changes to a given Stack\n */\nfunction getStackResourceDifferences(stackChanges: cfn_diff.TemplateDiff): {\n [logicalId: string]: cfn_diff.ResourceDifference;\n} {\n // we need to collapse logical ID rename changes into one change,\n // as they are represented in stackChanges as a pair of two changes: one addition and one removal\n const allResourceChanges: { [logId: string]: cfn_diff.ResourceDifference } = stackChanges.resources.changes;\n const allRemovalChanges = filterDict(allResourceChanges, (resChange) => resChange.isRemoval);\n const allNonRemovalChanges = filterDict(allResourceChanges, (resChange) => !resChange.isRemoval);\n for (const [logId, nonRemovalChange] of Object.entries(allNonRemovalChanges)) {\n if (nonRemovalChange.isAddition) {\n const addChange = nonRemovalChange;\n // search for an identical removal change\n const identicalRemovalChange = Object.entries(allRemovalChanges).find(([_, remChange]) => {\n return changesAreForSameResource(remChange, addChange);\n });\n // if we found one, then this means this is a rename change\n if (identicalRemovalChange) {\n const [removedLogId, removedResourceChange] = identicalRemovalChange;\n allNonRemovalChanges[logId] = makeRenameDifference(removedResourceChange, addChange);\n // delete the removal change that forms the rename pair\n delete allRemovalChanges[removedLogId];\n }\n }\n }\n // the final result are all of the remaining removal changes,\n // plus all of the non-removal changes\n // (we saved the rename changes in that object already)\n return {\n ...allRemovalChanges,\n ...allNonRemovalChanges,\n };\n}\n\n/** Filters an object with string keys based on whether the callback returns 'true' for the given value in the object. */\nfunction filterDict<T>(dict: { [key: string]: T }, func: (t: T) => boolean): { [key: string]: T } {\n return Object.entries(dict).reduce(\n (acc, [key, t]) => {\n if (func(t)) {\n acc[key] = t;\n }\n return acc;\n },\n {} as { [key: string]: T },\n );\n}\n\n/** Finds any hotswappable changes in all nested stacks. */\nasync function findNestedHotswappableChanges(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n nestedStackTemplates: { [nestedStackName: string]: NestedStackTemplates },\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedResourceChanges> {\n const nestedStack = nestedStackTemplates[logicalId];\n if (!nestedStack.physicalName) {\n return {\n hotswappableChanges: [],\n nonHotswappableChanges: [\n {\n hotswappable: false,\n logicalId,\n reason: `physical name for AWS::CloudFormation::Stack '${logicalId}' could not be found in CloudFormation, so this is a newly created nested stack and cannot be hotswapped`,\n rejectedChanges: [],\n resourceType: 'AWS::CloudFormation::Stack',\n },\n ],\n };\n }\n\n const evaluateNestedCfnTemplate = await evaluateCfnTemplate.createNestedEvaluateCloudFormationTemplate(\n nestedStack.physicalName,\n nestedStack.generatedTemplate,\n change.newValue?.Properties?.Parameters,\n );\n\n const nestedDiff = cfn_diff.fullDiff(\n nestedStackTemplates[logicalId].deployedTemplate,\n nestedStackTemplates[logicalId].generatedTemplate,\n );\n\n return classifyResourceChanges(\n nestedDiff,\n evaluateNestedCfnTemplate,\n sdk,\n nestedStackTemplates[logicalId].nestedStackTemplates,\n hotswapPropertyOverrides);\n}\n\n/** Returns 'true' if a pair of changes is for the same resource. */\nfunction changesAreForSameResource(\n oldChange: cfn_diff.ResourceDifference,\n newChange: cfn_diff.ResourceDifference,\n): boolean {\n return (\n oldChange.oldResourceType === newChange.newResourceType &&\n // this isn't great, but I don't want to bring in something like underscore just for this comparison\n JSON.stringify(oldChange.oldProperties) === JSON.stringify(newChange.newProperties)\n );\n}\n\nfunction makeRenameDifference(\n remChange: cfn_diff.ResourceDifference,\n addChange: cfn_diff.ResourceDifference,\n): cfn_diff.ResourceDifference {\n return new cfn_diff.ResourceDifference(\n // we have to fill in the old value, because otherwise this will be classified as a non-hotswappable change\n remChange.oldValue,\n addChange.newValue,\n {\n resourceType: {\n oldType: remChange.oldResourceType,\n newType: addChange.newResourceType,\n },\n propertyDiffs: (addChange as any).propertyDiffs,\n otherDiffs: (addChange as any).otherDiffs,\n },\n );\n}\n\n/**\n * Returns a `HotswappableChangeCandidate` if the change is hotswappable\n * Returns an empty `HotswappableChange` if the change is to CDK::Metadata\n * Returns a `NonHotswappableChange` if the change is not hotswappable\n */\nfunction isCandidateForHotswapping(\n change: cfn_diff.ResourceDifference,\n logicalId: string,\n): HotswappableChange | NonHotswappableChange | HotswappableChangeCandidate {\n // a resource has been removed OR a resource has been added; we can't short-circuit that change\n if (!change.oldValue) {\n return {\n hotswappable: false,\n resourceType: change.newValue!.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' was created by this deployment`,\n };\n } else if (!change.newValue) {\n return {\n hotswappable: false,\n resourceType: change.oldValue!.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' was destroyed by this deployment`,\n };\n }\n\n // a resource has had its type changed\n if (change.newValue?.Type !== change.oldValue?.Type) {\n return {\n hotswappable: false,\n resourceType: change.newValue?.Type,\n logicalId,\n rejectedChanges: [],\n reason: `resource '${logicalId}' had its type changed from '${change.oldValue?.Type}' to '${change.newValue?.Type}'`,\n };\n }\n\n return {\n logicalId,\n oldValue: change.oldValue,\n newValue: change.newValue,\n propertyUpdates: change.propertyUpdates,\n };\n}\n\nasync function applyAllHotswappableChanges(sdk: SDK, { ioHost, action }: IoMessaging, hotswappableChanges: HotswappableChange[]): Promise<void[]> {\n if (hotswappableChanges.length > 0) {\n await ioHost.notify(info(action, `\\n${ICON} hotswapping resources:`));\n }\n const limit = pLimit(10);\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(hotswappableChanges.map(hotswapOperation => limit(() => {\n return applyHotswappableChange(sdk, { ioHost, action }, hotswapOperation);\n })));\n}\n\nasync function applyHotswappableChange(sdk: SDK, { ioHost, action }: IoMessaging, hotswapOperation: HotswappableChange): Promise<void> {\n // note the type of service that was successfully hotswapped in the User-Agent\n const customUserAgent = `cdk-hotswap/success-${hotswapOperation.service}`;\n sdk.appendCustomUserAgent(customUserAgent);\n\n for (const name of hotswapOperation.resourceNames) {\n await ioHost.notify(info(action, format(` ${ICON} %s`, chalk.bold(name))));\n }\n\n // if the SDK call fails, an error will be thrown by the SDK\n // and will prevent the green 'hotswapped!' text from being displayed\n try {\n await hotswapOperation.apply(sdk);\n } catch (e: any) {\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n const result: WaiterResult = JSON.parse(formatErrorMessage(e));\n const error = new ToolkitError(formatWaiterErrorResult(result));\n error.name = e.name;\n throw error;\n }\n throw e;\n }\n\n for (const name of hotswapOperation.resourceNames) {\n await ioHost.notify(info(action, format(`${ICON} %s %s`, chalk.bold(name), chalk.green('hotswapped!'))));\n }\n\n sdk.removeCustomUserAgent(customUserAgent);\n}\n\nfunction formatWaiterErrorResult(result: WaiterResult) {\n const main = [\n `Resource is not in the expected state due to waiter status: ${result.state}`,\n result.reason ? `${result.reason}.` : '',\n ].join('. ');\n\n if (result.observedResponses != null) {\n const observedResponses = Object\n .entries(result.observedResponses)\n .map(([msg, count]) => ` - ${msg} (${count})`)\n .join('\\n');\n\n return `${main} Observed responses:\\n${observedResponses}`;\n }\n\n return main;\n}\n\nasync function logNonHotswappableChanges(\n { ioHost, action }: IoMessaging,\n nonHotswappableChanges: NonHotswappableChange[],\n hotswapMode: HotswapMode,\n): Promise<void> {\n if (nonHotswappableChanges.length === 0) {\n return;\n }\n /**\n * EKS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n if (hotswapMode === HotswapMode.HOTSWAP_ONLY) {\n nonHotswappableChanges = nonHotswappableChanges.filter((change) => change.hotswapOnlyVisible === true);\n\n if (nonHotswappableChanges.length === 0) {\n return;\n }\n }\n\n const messages = ['']; // start with empty line\n\n if (hotswapMode === HotswapMode.HOTSWAP_ONLY) {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found. To reconcile these using CloudFormation, specify --hotswap-fallback')));\n } else {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found:')));\n }\n\n for (const change of nonHotswappableChanges) {\n if (change.rejectedChanges.length > 0) {\n messages.push(format(\n ' logicalID: %s, type: %s, rejected changes: %s, reason: %s',\n chalk.bold(change.logicalId),\n chalk.bold(change.resourceType),\n chalk.bold(change.rejectedChanges),\n chalk.red(change.reason),\n ));\n } else {\n messages.push(format(\n ' logicalID: %s, type: %s, reason: %s',\n chalk.bold(change.logicalId),\n chalk.bold(change.resourceType),\n chalk.red(change.reason),\n ));\n }\n }\n messages.push(''); // newline\n\n await ioHost.notify(info(action, messages.join('\\n')));\n}\n", "import * as path from 'path';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { SDK } from '../aws-auth';\nimport { CloudFormationStack, type Template } from './cloudformation';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { LazyListStackResources, type ListStackResources } from '../evaluate-cloudformation-template';\n\nexport interface NestedStackTemplates {\n readonly physicalName: string | undefined;\n readonly deployedTemplate: Template;\n readonly generatedTemplate: Template;\n readonly nestedStackTemplates: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport interface RootTemplateWithNestedStacks {\n readonly deployedRootTemplate: Template;\n readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Reads the currently deployed template and all of its nested stack templates from CloudFormation.\n */\nexport async function loadCurrentTemplateWithNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<RootTemplateWithNestedStacks> {\n const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate);\n const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, {\n generatedTemplate: rootStackArtifact.template,\n deployedTemplate: deployedRootTemplate,\n deployedStackName: rootStackArtifact.stackName,\n });\n\n return {\n deployedRootTemplate,\n nestedStacks,\n };\n}\n\n/**\n * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`.\n */\nexport async function loadCurrentTemplate(\n stackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n return loadCurrentStackTemplate(stackArtifact.stackName, sdk, retrieveProcessedTemplate);\n}\n\nasync function loadCurrentStackTemplate(\n stackName: string,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n const cfn = sdk.cloudFormation();\n const stack = await CloudFormationStack.lookup(cfn, stackName, retrieveProcessedTemplate);\n return stack.template();\n}\n\nasync function loadNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n parentTemplates: StackTemplates,\n): Promise<{ [nestedStackLogicalId: string]: NestedStackTemplates }> {\n const listStackResources = parentTemplates.deployedStackName\n ? new LazyListStackResources(sdk, parentTemplates.deployedStackName)\n : undefined;\n const nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } = {};\n for (const [nestedStackLogicalId, generatedNestedStackResource] of Object.entries(\n parentTemplates.generatedTemplate.Resources ?? {},\n )) {\n if (!isCdkManagedNestedStack(generatedNestedStackResource)) {\n continue;\n }\n\n const assetPath = generatedNestedStackResource.Metadata['aws:asset:path'];\n const nestedStackTemplates = await getNestedStackTemplates(\n rootStackArtifact,\n assetPath,\n nestedStackLogicalId,\n listStackResources,\n sdk,\n );\n\n nestedStacks[nestedStackLogicalId] = {\n deployedTemplate: nestedStackTemplates.deployedTemplate,\n generatedTemplate: nestedStackTemplates.generatedTemplate,\n physicalName: nestedStackTemplates.deployedStackName,\n nestedStackTemplates: await loadNestedStacks(rootStackArtifact, sdk, nestedStackTemplates),\n };\n }\n\n return nestedStacks;\n}\n\nasync function getNestedStackTemplates(\n rootStackArtifact: CloudFormationStackArtifact,\n nestedTemplateAssetPath: string,\n nestedStackLogicalId: string,\n listStackResources: ListStackResources | undefined,\n sdk: SDK,\n): Promise<StackTemplates> {\n const nestedTemplatePath = path.join(rootStackArtifact.assembly.directory, nestedTemplateAssetPath);\n\n // CFN generates the nested stack name in the form `ParentStackName-NestedStackLogicalID-SomeHashWeCan'tCompute,\n // the arn is of the form: arn:aws:cloudformation:region:123456789012:stack/NestedStackName/AnotherHashWeDon'tNeed\n // so we get the ARN and manually extract the name.\n const nestedStackArn = await getNestedStackArn(nestedStackLogicalId, listStackResources);\n const deployedStackName = nestedStackArn?.slice(nestedStackArn.indexOf('/') + 1, nestedStackArn.lastIndexOf('/'));\n\n return {\n generatedTemplate: JSON.parse(fs.readFileSync(nestedTemplatePath, 'utf-8')),\n deployedTemplate: deployedStackName ? await loadCurrentStackTemplate(deployedStackName, sdk) : {},\n deployedStackName,\n };\n}\n\nasync function getNestedStackArn(\n nestedStackLogicalId: string,\n listStackResources?: ListStackResources,\n): Promise<string | undefined> {\n try {\n const stackResources = await listStackResources?.listStackResources();\n return stackResources?.find((sr) => sr.LogicalResourceId === nestedStackLogicalId)?.PhysicalResourceId;\n } catch (e: any) {\n if (formatErrorMessage(e).startsWith('Stack with id ') && formatErrorMessage(e).endsWith(' does not exist')) {\n return;\n }\n throw e;\n }\n}\n\nfunction isCdkManagedNestedStack(stackResource: any): stackResource is NestedStackResource {\n return (\n stackResource.Type === 'AWS::CloudFormation::Stack' &&\n stackResource.Metadata &&\n stackResource.Metadata['aws:asset:path']\n );\n}\n\ninterface StackTemplates {\n readonly generatedTemplate: any;\n readonly deployedTemplate: any;\n readonly deployedStackName: string | undefined;\n}\n\ninterface NestedStackResource {\n readonly Metadata: { 'aws:asset:path': string };\n readonly Properties: any;\n}\n", "import type { Export, ListExportsCommandOutput, StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport type { SDK } from './aws-auth';\nimport type { NestedStackTemplates } from './deployments';\nimport { ToolkitError } from '../toolkit/error';\n\nexport interface ListStackResources {\n listStackResources(): Promise<StackResourceSummary[]>;\n}\n\nexport class LazyListStackResources implements ListStackResources {\n private stackResources: Promise<StackResourceSummary[]> | undefined;\n\n constructor(\n private readonly sdk: SDK,\n private readonly stackName: string,\n ) {\n }\n\n public async listStackResources(): Promise<StackResourceSummary[]> {\n if (this.stackResources === undefined) {\n this.stackResources = this.sdk.cloudFormation().listStackResources({\n StackName: this.stackName,\n });\n }\n return this.stackResources;\n }\n}\n\nexport interface LookupExport {\n lookupExport(name: string): Promise<Export | undefined>;\n}\n\nexport class LookupExportError extends Error {\n}\n\nexport class LazyLookupExport implements LookupExport {\n private cachedExports: { [name: string]: Export } = {};\n\n constructor(private readonly sdk: SDK) {\n }\n\n async lookupExport(name: string): Promise<Export | undefined> {\n if (this.cachedExports[name]) {\n return this.cachedExports[name];\n }\n\n for await (const cfnExport of this.listExports()) {\n if (!cfnExport.Name) {\n continue; // ignore any result that omits a name\n }\n this.cachedExports[cfnExport.Name] = cfnExport;\n\n if (cfnExport.Name === name) {\n return cfnExport;\n }\n }\n\n return undefined; // export not found\n }\n\n // TODO: Paginate\n private async *listExports() {\n let nextToken: string | undefined = undefined;\n while (true) {\n const response: ListExportsCommandOutput = await this.sdk.cloudFormation().listExports({ NextToken: nextToken });\n for (const cfnExport of response.Exports ?? []) {\n yield cfnExport;\n }\n\n if (!response.NextToken) {\n return;\n }\n nextToken = response.NextToken;\n }\n }\n}\n\nexport class CfnEvaluationException extends Error {\n}\n\nexport interface ResourceDefinition {\n readonly LogicalId: string;\n readonly Type: string;\n readonly Properties: { [p: string]: any };\n}\n\nexport interface EvaluateCloudFormationTemplateProps {\n readonly stackName: string;\n readonly template: Template;\n readonly parameters: { [parameterName: string]: string };\n readonly account: string;\n readonly region: string;\n readonly partition: string;\n readonly sdk: SDK;\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport class EvaluateCloudFormationTemplate {\n private readonly stackName: string;\n private readonly template: Template;\n private readonly context: { [k: string]: any };\n private readonly account: string;\n private readonly region: string;\n private readonly partition: string;\n private readonly sdk: SDK;\n private readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n private readonly stackResources: ListStackResources;\n private readonly lookupExport: LookupExport;\n\n private cachedUrlSuffix: string | undefined;\n\n constructor(props: EvaluateCloudFormationTemplateProps) {\n this.stackName = props.stackName;\n this.template = props.template;\n this.context = {\n 'AWS::AccountId': props.account,\n 'AWS::Region': props.region,\n 'AWS::Partition': props.partition,\n ...props.parameters,\n };\n this.account = props.account;\n this.region = props.region;\n this.partition = props.partition;\n this.sdk = props.sdk;\n\n // We need names of nested stack so we can evaluate cross stack references\n this.nestedStacks = props.nestedStacks ?? {};\n\n // The current resources of the Stack.\n // We need them to figure out the physical name of a resource in case it wasn't specified by the user.\n // We fetch it lazily, to save a service call, in case all hotswapped resources have their physical names set.\n this.stackResources = new LazyListStackResources(this.sdk, this.stackName);\n\n // CloudFormation Exports lookup to be able to resolve Fn::ImportValue intrinsics in template\n this.lookupExport = new LazyLookupExport(this.sdk);\n }\n\n // clones current EvaluateCloudFormationTemplate object, but updates the stack name\n public async createNestedEvaluateCloudFormationTemplate(\n stackName: string,\n nestedTemplate: Template,\n nestedStackParameters: { [parameterName: string]: any },\n ) {\n const evaluatedParams = await this.evaluateCfnExpression(nestedStackParameters);\n return new EvaluateCloudFormationTemplate({\n stackName,\n template: nestedTemplate,\n parameters: evaluatedParams,\n account: this.account,\n region: this.region,\n partition: this.partition,\n sdk: this.sdk,\n nestedStacks: this.nestedStacks,\n });\n }\n\n public async establishResourcePhysicalName(\n logicalId: string,\n physicalNameInCfnTemplate: any,\n ): Promise<string | undefined> {\n if (physicalNameInCfnTemplate != null) {\n try {\n return await this.evaluateCfnExpression(physicalNameInCfnTemplate);\n } catch (e) {\n // If we can't evaluate the resource's name CloudFormation expression,\n // just look it up in the currently deployed Stack\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n }\n }\n return this.findPhysicalNameFor(logicalId);\n }\n\n public async findPhysicalNameFor(logicalId: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.LogicalResourceId === logicalId)?.PhysicalResourceId;\n }\n\n public async findLogicalIdForPhysicalName(physicalName: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.PhysicalResourceId === physicalName)?.LogicalResourceId;\n }\n\n public findReferencesTo(logicalId: string): Array<ResourceDefinition> {\n const ret = new Array<ResourceDefinition>();\n for (const [resourceLogicalId, resourceDef] of Object.entries(this.template?.Resources ?? {})) {\n if (logicalId !== resourceLogicalId && this.references(logicalId, resourceDef)) {\n ret.push({\n ...(resourceDef as any),\n LogicalId: resourceLogicalId,\n });\n }\n }\n return ret;\n }\n\n public async evaluateCfnExpression(cfnExpression: any): Promise<any> {\n const self = this;\n /**\n * Evaluates CloudFormation intrinsic functions\n *\n * Note that supported intrinsic functions are documented in README.md -- please update\n * list of supported functions when adding new evaluations\n *\n * See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html\n */\n class CfnIntrinsics {\n public evaluateIntrinsic(intrinsic: Intrinsic): any {\n const intrinsicFunc = (this as any)[intrinsic.name];\n if (!intrinsicFunc) {\n throw new CfnEvaluationException(`CloudFormation function ${intrinsic.name} is not supported`);\n }\n\n const argsAsArray = Array.isArray(intrinsic.args) ? intrinsic.args : [intrinsic.args];\n\n return intrinsicFunc.apply(this, argsAsArray);\n }\n\n async 'Fn::Join'(separator: string, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.join(separator);\n }\n\n async 'Fn::Split'(separator: string, args: any): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.split(separator);\n }\n\n async 'Fn::Select'(index: number, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs[index];\n }\n\n async Ref(logicalId: string): Promise<string> {\n const refTarget = await self.findRefTarget(logicalId);\n if (refTarget) {\n return refTarget;\n } else {\n throw new CfnEvaluationException(`Parameter or resource '${logicalId}' could not be found for evaluation`);\n }\n }\n\n async 'Fn::GetAtt'(logicalId: string, attributeName: string): Promise<string> {\n // ToDo handle the 'logicalId.attributeName' form of Fn::GetAtt\n const attrValue = await self.findGetAttTarget(logicalId, attributeName);\n if (attrValue) {\n return attrValue;\n } else {\n throw new CfnEvaluationException(\n `Attribute '${attributeName}' of resource '${logicalId}' could not be found for evaluation`,\n );\n }\n }\n\n async 'Fn::Sub'(template: string, explicitPlaceholders?: { [variable: string]: string }): Promise<string> {\n const placeholders = explicitPlaceholders ? await self.evaluateCfnExpression(explicitPlaceholders) : {};\n\n return asyncGlobalReplace(template, /\\${([^}]*)}/g, (key) => {\n if (key in placeholders) {\n return placeholders[key];\n } else {\n const splitKey = key.split('.');\n return splitKey.length === 1 ? this.Ref(key) : this['Fn::GetAtt'](splitKey[0], splitKey.slice(1).join('.'));\n }\n });\n }\n\n async 'Fn::ImportValue'(name: string): Promise<string> {\n const exported = await self.lookupExport.lookupExport(name);\n if (!exported) {\n throw new CfnEvaluationException(`Export '${name}' could not be found for evaluation`);\n }\n if (!exported.Value) {\n throw new CfnEvaluationException(`Export '${name}' exists without a value`);\n }\n return exported.Value;\n }\n }\n\n if (cfnExpression == null) {\n return cfnExpression;\n }\n\n if (Array.isArray(cfnExpression)) {\n // Small arrays in practice\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(cfnExpression.map((expr) => this.evaluateCfnExpression(expr)));\n }\n\n if (typeof cfnExpression === 'object') {\n const intrinsic = this.parseIntrinsic(cfnExpression);\n if (intrinsic) {\n return new CfnIntrinsics().evaluateIntrinsic(intrinsic);\n } else {\n const ret: { [key: string]: any } = {};\n for (const [key, val] of Object.entries(cfnExpression)) {\n ret[key] = await this.evaluateCfnExpression(val);\n }\n return ret;\n }\n }\n\n return cfnExpression;\n }\n\n public getResourceProperty(logicalId: string, propertyName: string): any {\n return this.template.Resources?.[logicalId]?.Properties?.[propertyName];\n }\n\n private references(logicalId: string, templateElement: any): boolean {\n if (typeof templateElement === 'string') {\n return logicalId === templateElement;\n }\n\n if (templateElement == null) {\n return false;\n }\n\n if (Array.isArray(templateElement)) {\n return templateElement.some((el) => this.references(logicalId, el));\n }\n\n if (typeof templateElement === 'object') {\n return Object.values(templateElement).some((el) => this.references(logicalId, el));\n }\n\n return false;\n }\n\n private parseIntrinsic(x: any): Intrinsic | undefined {\n const keys = Object.keys(x);\n if (keys.length === 1 && (keys[0].startsWith('Fn::') || keys[0] === 'Ref')) {\n return {\n name: keys[0],\n args: x[keys[0]],\n };\n }\n return undefined;\n }\n\n private async findRefTarget(logicalId: string): Promise<string | undefined> {\n // first, check to see if the Ref is a Parameter who's value we have\n if (logicalId === 'AWS::URLSuffix') {\n if (!this.cachedUrlSuffix) {\n this.cachedUrlSuffix = await this.sdk.getUrlSuffix(this.region);\n }\n\n return this.cachedUrlSuffix;\n }\n\n // Try finding the ref in the passed in parameters\n const parameterTarget = this.context[logicalId];\n if (parameterTarget) {\n return parameterTarget;\n }\n\n // If not in the passed in parameters, see if there is a default value in the template parameter that was not passed in\n const defaultParameterValue = this.template.Parameters?.[logicalId]?.Default;\n if (defaultParameterValue) {\n return defaultParameterValue;\n }\n\n // if it's not a Parameter, we need to search in the current Stack resources\n return this.findGetAttTarget(logicalId);\n }\n\n private async findGetAttTarget(logicalId: string, attribute?: string): Promise<string | undefined> {\n // Handle case where the attribute is referencing a stack output (used in nested stacks to share parameters)\n // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#w2ab1c17c23c19b5\n if (logicalId === 'Outputs' && attribute) {\n return this.evaluateCfnExpression(this.template.Outputs[attribute]?.Value);\n }\n\n const stackResources = await this.stackResources.listStackResources();\n const foundResource = stackResources.find((sr) => sr.LogicalResourceId === logicalId);\n if (!foundResource) {\n return undefined;\n }\n\n if (foundResource.ResourceType == 'AWS::CloudFormation::Stack' && attribute?.startsWith('Outputs.')) {\n const dependantStack = this.findNestedStack(logicalId, this.nestedStacks);\n if (!dependantStack || !dependantStack.physicalName) {\n // this is a newly created nested stack and cannot be hotswapped\n return undefined;\n }\n const evaluateCfnTemplate = await this.createNestedEvaluateCloudFormationTemplate(\n dependantStack.physicalName,\n dependantStack.generatedTemplate,\n dependantStack.generatedTemplate.Parameters!,\n );\n\n // Split Outputs.<refName> into 'Outputs' and '<refName>' and recursively call evaluate\n return evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::GetAtt': attribute.split(/\\.(.*)/s),\n });\n }\n // now, we need to format the appropriate identifier depending on the resource type,\n // and the requested attribute name\n return this.formatResourceAttribute(foundResource, attribute);\n }\n\n private findNestedStack(\n logicalId: string,\n nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n },\n ): NestedStackTemplates | undefined {\n for (const nestedStackLogicalId of Object.keys(nestedStacks)) {\n if (nestedStackLogicalId === logicalId) {\n return nestedStacks[nestedStackLogicalId];\n }\n const checkInNestedChildStacks = this.findNestedStack(\n logicalId,\n nestedStacks[nestedStackLogicalId].nestedStackTemplates,\n );\n if (checkInNestedChildStacks) return checkInNestedChildStacks;\n }\n return undefined;\n }\n\n private formatResourceAttribute(resource: StackResourceSummary, attribute: string | undefined): string | undefined {\n const physicalId = resource.PhysicalResourceId;\n\n // no attribute means Ref expression, for which we use the physical ID directly\n if (!attribute) {\n return physicalId;\n }\n\n const resourceTypeFormats = RESOURCE_TYPE_ATTRIBUTES_FORMATS[resource.ResourceType!];\n if (!resourceTypeFormats) {\n throw new CfnEvaluationException(\n `We don't support attributes of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const attributeFmtFunc = resourceTypeFormats[attribute];\n if (!attributeFmtFunc) {\n throw new CfnEvaluationException(\n `We don't support the '${attribute}' attribute of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const service = this.getServiceOfResource(resource);\n const resourceTypeArnPart = this.getResourceTypeArnPartOfResource(resource);\n return attributeFmtFunc({\n partition: this.partition,\n service,\n region: this.region,\n account: this.account,\n resourceType: resourceTypeArnPart,\n resourceName: physicalId!,\n });\n }\n\n private getServiceOfResource(resource: StackResourceSummary): string {\n return resource.ResourceType!.split('::')[1].toLowerCase();\n }\n\n private getResourceTypeArnPartOfResource(resource: StackResourceSummary): string {\n const resourceType = resource.ResourceType!;\n const specialCaseResourceType = RESOURCE_TYPE_SPECIAL_NAMES[resourceType]?.resourceType;\n return specialCaseResourceType\n ? specialCaseResourceType\n : // this is the default case\n resourceType.split('::')[2].toLowerCase();\n }\n}\n\nexport type Template = { [section: string]: { [headings: string]: any } };\n\ninterface ArnParts {\n readonly partition: string;\n readonly service: string;\n readonly region: string;\n readonly account: string;\n readonly resourceType: string;\n readonly resourceName: string;\n}\n\n/**\n * Usually, we deduce the names of the service and the resource type used to format the ARN from the CloudFormation resource type.\n * For a CFN type like AWS::Service::ResourceType, the second segment becomes the service name, and the third the resource type\n * (after converting both of them to lowercase).\n * However, some resource types break this simple convention, and we need to special-case them.\n * This map is for storing those cases.\n */\nconst RESOURCE_TYPE_SPECIAL_NAMES: {\n [type: string]: { resourceType: string };\n} = {\n 'AWS::Events::EventBus': {\n resourceType: 'event-bus',\n },\n};\n\nconst RESOURCE_TYPE_ATTRIBUTES_FORMATS: {\n [type: string]: { [attribute: string]: (parts: ArnParts) => string };\n} = {\n 'AWS::IAM::Role': { Arn: iamArnFmt },\n 'AWS::IAM::User': { Arn: iamArnFmt },\n 'AWS::IAM::Group': { Arn: iamArnFmt },\n 'AWS::S3::Bucket': { Arn: s3ArnFmt },\n 'AWS::Lambda::Function': { Arn: stdColonResourceArnFmt },\n 'AWS::Events::EventBus': {\n Arn: stdSlashResourceArnFmt,\n // the name attribute of the EventBus is the same as the Ref\n Name: (parts) => parts.resourceName,\n },\n 'AWS::DynamoDB::Table': { Arn: stdSlashResourceArnFmt },\n 'AWS::AppSync::GraphQLApi': { ApiId: appsyncGraphQlApiApiIdFmt },\n 'AWS::AppSync::FunctionConfiguration': {\n FunctionId: appsyncGraphQlFunctionIDFmt,\n },\n 'AWS::AppSync::DataSource': { Name: appsyncGraphQlDataSourceNameFmt },\n 'AWS::KMS::Key': { Arn: stdSlashResourceArnFmt },\n};\n\nfunction iamArnFmt(parts: ArnParts): string {\n // we skip region for IAM resources\n return `arn:${parts.partition}:${parts.service}::${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction s3ArnFmt(parts: ArnParts): string {\n // we skip account, region and resourceType for S3 resources\n return `arn:${parts.partition}:${parts.service}:::${parts.resourceName}`;\n}\n\nfunction stdColonResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType:resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}:${parts.resourceName}`;\n}\n\nfunction stdSlashResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType/resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction appsyncGraphQlApiApiIdFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>\n return parts.resourceName.split('/')[1];\n}\n\nfunction appsyncGraphQlFunctionIDFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/functions/<functionId>\n return parts.resourceName.split('/')[3];\n}\n\nfunction appsyncGraphQlDataSourceNameFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/datasources/<name>\n return parts.resourceName.split('/')[3];\n}\n\ninterface Intrinsic {\n readonly name: string;\n readonly args: any;\n}\n\nasync function asyncGlobalReplace(str: string, regex: RegExp, cb: (x: string) => Promise<string>): Promise<string> {\n if (!regex.global) {\n throw new ToolkitError('Regex must be created with /g flag');\n }\n\n const ret = new Array<string>();\n let start = 0;\n while (true) {\n const match = regex.exec(str);\n if (!match) {\n break;\n }\n\n ret.push(str.substring(start, match.index));\n ret.push(await cb(match[1]));\n\n start = regex.lastIndex;\n }\n ret.push(str.slice(start));\n\n return ret.join('');\n}\n", "import type { PropertyDifference, Resource } from '@aws-cdk/cloudformation-diff';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SDK } from '../aws-auth';\n\nexport const ICON = '\u2728';\n\nexport interface HotswappableChange {\n readonly hotswappable: true;\n readonly resourceType: string;\n readonly propsChanged: Array<string>;\n /**\n * The name of the service being hotswapped.\n * Used to set a custom User-Agent for SDK calls.\n */\n readonly service: string;\n\n /**\n * The names of the resources being hotswapped.\n */\n readonly resourceNames: string[];\n\n readonly apply: (sdk: SDK) => Promise<void>;\n}\n\nexport interface NonHotswappableChange {\n readonly hotswappable: false;\n readonly resourceType: string;\n readonly rejectedChanges: Array<string>;\n readonly logicalId: string;\n /**\n * Tells the user exactly why this change was deemed non-hotswappable and what its logical ID is.\n * If not specified, `reason` will be autofilled to state that the properties listed in `rejectedChanges` are not hotswappable.\n */\n readonly reason?: string;\n /**\n * Whether or not to show this change when listing non-hotswappable changes in HOTSWAP_ONLY mode. Does not affect\n * listing in FALL_BACK mode.\n *\n * @default true\n */\n readonly hotswapOnlyVisible?: boolean;\n}\n\nexport type ChangeHotswapResult = Array<HotswappableChange | NonHotswappableChange>;\n\nexport interface ClassifiedResourceChanges {\n hotswappableChanges: HotswappableChange[];\n nonHotswappableChanges: NonHotswappableChange[];\n}\n\nexport enum HotswapMode {\n /**\n * Will fall back to CloudFormation when a non-hotswappable change is detected\n */\n FALL_BACK = 'fall-back',\n\n /**\n * Will not fall back to CloudFormation when a non-hotswappable change is detected\n */\n HOTSWAP_ONLY = 'hotswap-only',\n\n /**\n * Will not attempt to hotswap anything and instead go straight to CloudFormation\n */\n FULL_DEPLOYMENT = 'full-deployment',\n}\n\n/**\n * Represents a change that can be hotswapped.\n */\nexport class HotswappableChangeCandidate {\n /**\n * The logical ID of the resource which is being changed\n */\n public readonly logicalId: string;\n\n /**\n * The value the resource is being updated from\n */\n public readonly oldValue: Resource;\n\n /**\n * The value the resource is being updated to\n */\n public readonly newValue: Resource;\n\n /**\n * The changes made to the resource properties\n */\n public readonly propertyUpdates: PropDiffs;\n\n public constructor(logicalId: string, oldValue: Resource, newValue: Resource, propertyUpdates: PropDiffs) {\n this.logicalId = logicalId;\n this.oldValue = oldValue;\n this.newValue = newValue;\n this.propertyUpdates = propertyUpdates;\n }\n}\n\ntype Exclude = { [key: string]: Exclude | true };\n\n/**\n * Represents configuration property overrides for hotswap deployments\n */\nexport class HotswapPropertyOverrides {\n // Each supported resource type will have its own properties. Currently this is ECS\n ecsHotswapProperties?: EcsHotswapProperties;\n\n public constructor (ecsHotswapProperties?: EcsHotswapProperties) {\n this.ecsHotswapProperties = ecsHotswapProperties;\n }\n}\n\n/**\n * Represents configuration properties for ECS hotswap deployments\n */\nexport class EcsHotswapProperties {\n // The lower limit on the number of your service's tasks that must remain in the RUNNING state during a deployment, as a percentage of the desiredCount\n readonly minimumHealthyPercent?: number;\n // The upper limit on the number of your service's tasks that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desiredCount\n readonly maximumHealthyPercent?: number;\n\n public constructor (minimumHealthyPercent?: number, maximumHealthyPercent?: number) {\n if (minimumHealthyPercent !== undefined && minimumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-minimum-healthy-percent can\\'t be a negative number');\n }\n if (maximumHealthyPercent !== undefined && maximumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-maximum-healthy-percent can\\'t be a negative number');\n }\n // In order to preserve the current behaviour, when minimumHealthyPercent is not defined, it will be set to the currently default value of 0\n if (minimumHealthyPercent == undefined) {\n this.minimumHealthyPercent = 0;\n } else {\n this.minimumHealthyPercent = minimumHealthyPercent;\n }\n this.maximumHealthyPercent = maximumHealthyPercent;\n }\n\n /**\n * Check if any hotswap properties are defined\n * @returns true if all properties are undefined, false otherwise\n */\n public isEmpty(): boolean {\n return this.minimumHealthyPercent === 0 && this.maximumHealthyPercent === undefined;\n }\n}\n\n/**\n * This function transforms all keys (recursively) in the provided `val` object.\n *\n * @param val The object whose keys need to be transformed.\n * @param transform The function that will be applied to each key.\n * @param exclude The keys that will not be transformed and copied to output directly\n * @returns A new object with the same values as `val`, but with all keys transformed according to `transform`.\n */\nexport function transformObjectKeys(val: any, transform: (str: string) => string, exclude: Exclude = {}): any {\n if (val == null || typeof val !== 'object') {\n return val;\n }\n if (Array.isArray(val)) {\n // For arrays we just pass parent's exclude object directly\n // since it makes no sense to specify different exclude options for each array element\n return val.map((input: any) => transformObjectKeys(input, transform, exclude));\n }\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(val)) {\n const childExclude = exclude[k];\n if (childExclude === true) {\n // we don't transform this object if the key is specified in exclude\n ret[transform(k)] = v;\n } else {\n ret[transform(k)] = transformObjectKeys(v, transform, childExclude);\n }\n }\n return ret;\n}\n\n/**\n * This function lower cases the first character of the string provided.\n */\nexport function lowerCaseFirstCharacter(str: string): string {\n return str.length > 0 ? `${str[0].toLowerCase()}${str.slice(1)}` : str;\n}\n\nexport type PropDiffs = Record<string, PropertyDifference<any>>;\n\nexport class ClassifiedChanges {\n public constructor(\n public readonly change: HotswappableChangeCandidate,\n public readonly hotswappableProps: PropDiffs,\n public readonly nonHotswappableProps: PropDiffs,\n ) {\n }\n\n public reportNonHotswappablePropertyChanges(ret: ChangeHotswapResult): void {\n const nonHotswappablePropNames = Object.keys(this.nonHotswappableProps);\n if (nonHotswappablePropNames.length > 0) {\n const tagOnlyChange = nonHotswappablePropNames.length === 1 && nonHotswappablePropNames[0] === 'Tags';\n reportNonHotswappableChange(\n ret,\n this.change,\n this.nonHotswappableProps,\n tagOnlyChange\n ? 'Tags are not hotswappable'\n : `resource properties '${nonHotswappablePropNames}' are not hotswappable on this resource type`,\n );\n }\n }\n\n public get namesOfHotswappableProps(): string[] {\n return Object.keys(this.hotswappableProps);\n }\n}\n\nexport function classifyChanges(xs: HotswappableChangeCandidate, hotswappablePropNames: string[]): ClassifiedChanges {\n const hotswappableProps: PropDiffs = {};\n const nonHotswappableProps: PropDiffs = {};\n\n for (const [name, propDiff] of Object.entries(xs.propertyUpdates)) {\n if (hotswappablePropNames.includes(name)) {\n hotswappableProps[name] = propDiff;\n } else {\n nonHotswappableProps[name] = propDiff;\n }\n }\n\n return new ClassifiedChanges(xs, hotswappableProps, nonHotswappableProps);\n}\n\nexport function reportNonHotswappableChange(\n ret: ChangeHotswapResult,\n change: HotswappableChangeCandidate,\n nonHotswappableProps?: PropDiffs,\n reason?: string,\n hotswapOnlyVisible?: boolean,\n): void {\n let hotswapOnlyVisibility = true;\n if (hotswapOnlyVisible === false) {\n hotswapOnlyVisibility = false;\n }\n ret.push({\n hotswappable: false,\n rejectedChanges: Object.keys(nonHotswappableProps ?? change.propertyUpdates),\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n reason,\n hotswapOnlyVisible: hotswapOnlyVisibility,\n });\n}\n\nexport function reportNonHotswappableResource(\n change: HotswappableChangeCandidate,\n reason?: string,\n): ChangeHotswapResult {\n return [\n {\n hotswappable: false,\n rejectedChanges: Object.keys(change.propertyUpdates),\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n reason,\n },\n ];\n}\n", "import type {\n GetSchemaCreationStatusCommandOutput,\n GetSchemaCreationStatusCommandInput,\n} from '@aws-sdk/client-appsync';\nimport {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n lowerCaseFirstCharacter,\n transformObjectKeys,\n} from './common';\nimport { ToolkitError } from '../../toolkit/error';\nimport type { SDK } from '../aws-auth';\n\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableAppSyncChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n const isResolver = change.newValue.Type === 'AWS::AppSync::Resolver';\n const isFunction = change.newValue.Type === 'AWS::AppSync::FunctionConfiguration';\n const isGraphQLSchema = change.newValue.Type === 'AWS::AppSync::GraphQLSchema';\n const isAPIKey = change.newValue.Type === 'AWS::AppSync::ApiKey';\n if (!isResolver && !isFunction && !isGraphQLSchema && !isAPIKey) {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n const classifiedChanges = classifyChanges(change, [\n 'RequestMappingTemplate',\n 'RequestMappingTemplateS3Location',\n 'ResponseMappingTemplate',\n 'ResponseMappingTemplateS3Location',\n 'Code',\n 'CodeS3Location',\n 'Definition',\n 'DefinitionS3Location',\n 'Expires',\n ]);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n let physicalName: string | undefined = undefined;\n const arn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n isFunction ? change.newValue.Properties?.Name : undefined,\n );\n if (isResolver) {\n const arnParts = arn?.split('/');\n physicalName = arnParts ? `${arnParts[3]}.${arnParts[5]}` : undefined;\n } else {\n physicalName = arn;\n }\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'appsync',\n resourceNames: [`${change.newValue.Type} '${physicalName}'`],\n apply: async (sdk: SDK) => {\n if (!physicalName) {\n return;\n }\n\n const sdkProperties: { [name: string]: any } = {\n ...change.oldValue.Properties,\n Definition: change.newValue.Properties?.Definition,\n DefinitionS3Location: change.newValue.Properties?.DefinitionS3Location,\n requestMappingTemplate: change.newValue.Properties?.RequestMappingTemplate,\n requestMappingTemplateS3Location: change.newValue.Properties?.RequestMappingTemplateS3Location,\n responseMappingTemplate: change.newValue.Properties?.ResponseMappingTemplate,\n responseMappingTemplateS3Location: change.newValue.Properties?.ResponseMappingTemplateS3Location,\n code: change.newValue.Properties?.Code,\n codeS3Location: change.newValue.Properties?.CodeS3Location,\n expires: change.newValue.Properties?.Expires,\n };\n const evaluatedResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression(sdkProperties);\n const sdkRequestObject = transformObjectKeys(evaluatedResourceProperties, lowerCaseFirstCharacter);\n\n // resolve s3 location files as SDK doesn't take in s3 location but inline code\n if (sdkRequestObject.requestMappingTemplateS3Location) {\n sdkRequestObject.requestMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.requestMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.requestMappingTemplateS3Location;\n }\n if (sdkRequestObject.responseMappingTemplateS3Location) {\n sdkRequestObject.responseMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.responseMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.responseMappingTemplateS3Location;\n }\n if (sdkRequestObject.definitionS3Location) {\n sdkRequestObject.definition = await fetchFileFromS3(sdkRequestObject.definitionS3Location, sdk);\n delete sdkRequestObject.definitionS3Location;\n }\n if (sdkRequestObject.codeS3Location) {\n sdkRequestObject.code = await fetchFileFromS3(sdkRequestObject.codeS3Location, sdk);\n delete sdkRequestObject.codeS3Location;\n }\n\n if (isResolver) {\n await sdk.appsync().updateResolver(sdkRequestObject);\n } else if (isFunction) {\n // Function version is only applicable when using VTL and mapping templates\n // Runtime only applicable when using code (JS mapping templates)\n if (sdkRequestObject.code) {\n delete sdkRequestObject.functionVersion;\n } else {\n delete sdkRequestObject.runtime;\n }\n\n const functions = await sdk.appsync().listFunctions({ apiId: sdkRequestObject.apiId });\n const { functionId } = functions.find((fn) => fn.name === physicalName) ?? {};\n // Updating multiple functions at the same time or along with graphql schema results in `ConcurrentModificationException`\n await exponentialBackOffRetry(\n () =>\n sdk.appsync().updateFunction({\n ...sdkRequestObject,\n functionId: functionId,\n }),\n 6,\n 1000,\n 'ConcurrentModificationException',\n );\n } else if (isGraphQLSchema) {\n let schemaCreationResponse: GetSchemaCreationStatusCommandOutput = await sdk\n .appsync()\n .startSchemaCreation(sdkRequestObject);\n while (\n schemaCreationResponse.status &&\n ['PROCESSING', 'DELETING'].some((status) => status === schemaCreationResponse.status)\n ) {\n await sleep(1000); // poll every second\n const getSchemaCreationStatusRequest: GetSchemaCreationStatusCommandInput = {\n apiId: sdkRequestObject.apiId,\n };\n schemaCreationResponse = await sdk.appsync().getSchemaCreationStatus(getSchemaCreationStatusRequest);\n }\n if (schemaCreationResponse.status === 'FAILED') {\n throw new ToolkitError(schemaCreationResponse.details ?? 'Schema creation has failed.');\n }\n } else {\n // isApiKey\n if (!sdkRequestObject.id) {\n // ApiKeyId is optional in CFN but required in SDK. Grab the KeyId from physicalArn if not available as part of CFN template\n const arnParts = physicalName?.split('/');\n if (arnParts && arnParts.length === 4) {\n sdkRequestObject.id = arnParts[3];\n }\n }\n await sdk.appsync().updateApiKey(sdkRequestObject);\n }\n },\n });\n }\n\n return ret;\n}\n\nasync function fetchFileFromS3(s3Url: string, sdk: SDK) {\n const s3PathParts = s3Url.split('/');\n const s3Bucket = s3PathParts[2]; // first two are \"s3:\" and \"\" due to s3://\n const s3Key = s3PathParts.splice(3).join('/'); // after removing first three we reconstruct the key\n return (await sdk.s3().getObject({ Bucket: s3Bucket, Key: s3Key })).Body?.transformToString();\n}\n\nasync function exponentialBackOffRetry(fn: () => Promise<any>, numOfRetries: number, backOff: number, errorCodeToRetry: string) {\n try {\n await fn();\n } catch (error: any) {\n if (error && error.name === errorCodeToRetry && numOfRetries > 0) {\n await sleep(backOff); // time to wait doubles everytime function fails, starts at 1 second\n await exponentialBackOffRetry(fn, numOfRetries - 1, backOff * 2, errorCodeToRetry);\n } else {\n throw error;\n }\n }\n}\n\nasync function sleep(ms: number) {\n return new Promise((ok) => setTimeout(ok, ms));\n}\n", "import type { UpdateProjectCommandInput } from '@aws-sdk/client-codebuild';\nimport {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n lowerCaseFirstCharacter,\n transformObjectKeys,\n} from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableCodeBuildProjectChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n if (change.newValue.Type !== 'AWS::CodeBuild::Project') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n const classifiedChanges = classifyChanges(change, ['Source', 'Environment', 'SourceVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n if (classifiedChanges.namesOfHotswappableProps.length > 0) {\n const updateProjectInput: UpdateProjectCommandInput = {\n name: '',\n };\n const projectName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.Name,\n );\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: classifiedChanges.namesOfHotswappableProps,\n service: 'codebuild',\n resourceNames: [`CodeBuild Project '${projectName}'`],\n apply: async (sdk: SDK) => {\n if (!projectName) {\n return;\n }\n updateProjectInput.name = projectName;\n\n for (const updatedPropName in change.propertyUpdates) {\n const updatedProp = change.propertyUpdates[updatedPropName];\n switch (updatedPropName) {\n case 'Source':\n updateProjectInput.source = transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n convertSourceCloudformationKeyToSdkKey,\n );\n break;\n case 'Environment':\n updateProjectInput.environment = await transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n lowerCaseFirstCharacter,\n );\n break;\n case 'SourceVersion':\n updateProjectInput.sourceVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n }\n }\n\n await sdk.codeBuild().updateProject(updateProjectInput);\n },\n });\n }\n\n return ret;\n}\n\nfunction convertSourceCloudformationKeyToSdkKey(key: string): string {\n if (key.toLowerCase() === 'buildspec') {\n return key.toLowerCase();\n }\n return lowerCaseFirstCharacter(key);\n}\n", "import {\n type ChangeHotswapResult,\n classifyChanges,\n type HotswappableChangeCandidate,\n HotswapPropertyOverrides, lowerCaseFirstCharacter,\n reportNonHotswappableChange,\n transformObjectKeys,\n} from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableEcsServiceChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ChangeHotswapResult> {\n // the only resource change we can evaluate here is an ECS TaskDefinition\n if (change.newValue.Type !== 'AWS::ECS::TaskDefinition') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n\n // We only allow a change in the ContainerDefinitions of the TaskDefinition for now -\n // it contains the image and environment variables, so seems like a safe bet for now.\n // We might revisit this decision in the future though!\n const classifiedChanges = classifyChanges(change, ['ContainerDefinitions']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // find all ECS Services that reference the TaskDefinition that changed\n const resourcesReferencingTaskDef = evaluateCfnTemplate.findReferencesTo(logicalId);\n const ecsServiceResourcesReferencingTaskDef = resourcesReferencingTaskDef.filter(\n (r) => r.Type === 'AWS::ECS::Service',\n );\n const ecsServicesReferencingTaskDef = new Array<EcsService>();\n for (const ecsServiceResource of ecsServiceResourcesReferencingTaskDef) {\n const serviceArn = await evaluateCfnTemplate.findPhysicalNameFor(ecsServiceResource.LogicalId);\n if (serviceArn) {\n ecsServicesReferencingTaskDef.push({ serviceArn });\n }\n }\n if (ecsServicesReferencingTaskDef.length === 0) {\n // if there are no resources referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n reportNonHotswappableChange(ret, change, undefined, 'No ECS services reference the changed task definition', false);\n }\n if (resourcesReferencingTaskDef.length > ecsServicesReferencingTaskDef.length) {\n // if something besides an ECS Service is referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n const nonEcsServiceTaskDefRefs = resourcesReferencingTaskDef.filter((r) => r.Type !== 'AWS::ECS::Service');\n for (const taskRef of nonEcsServiceTaskDefRefs) {\n reportNonHotswappableChange(\n ret,\n change,\n undefined,\n `A resource '${taskRef.LogicalId}' with Type '${taskRef.Type}' that is not an ECS Service was found referencing the changed TaskDefinition '${logicalId}'`,\n );\n }\n }\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const taskDefinitionResource = await prepareTaskDefinitionChange(evaluateCfnTemplate, logicalId, change);\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'ecs-service',\n resourceNames: [\n `ECS Task Definition '${await taskDefinitionResource.Family}'`,\n ...ecsServicesReferencingTaskDef.map((ecsService) => `ECS Service '${ecsService.serviceArn.split('/')[2]}'`),\n ],\n apply: async (sdk: SDK) => {\n // Step 1 - update the changed TaskDefinition, creating a new TaskDefinition Revision\n // we need to lowercase the evaluated TaskDef from CloudFormation,\n // as the AWS SDK uses lowercase property names for these\n\n // The SDK requires more properties here than its worth doing explicit typing for\n // instead, just use all the old values in the diff to fill them in implicitly\n const lowercasedTaskDef = transformObjectKeys(taskDefinitionResource, lowerCaseFirstCharacter, {\n // All the properties that take arbitrary string as keys i.e. { \"string\" : \"string\" }\n // https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html#API_RegisterTaskDefinition_RequestSyntax\n ContainerDefinitions: {\n DockerLabels: true,\n FirelensConfiguration: {\n Options: true,\n },\n LogConfiguration: {\n Options: true,\n },\n },\n Volumes: {\n DockerVolumeConfiguration: {\n DriverOpts: true,\n Labels: true,\n },\n },\n });\n const registerTaskDefResponse = await sdk.ecs().registerTaskDefinition(lowercasedTaskDef);\n const taskDefRevArn = registerTaskDefResponse.taskDefinition?.taskDefinitionArn;\n\n let ecsHotswapProperties = hotswapPropertyOverrides.ecsHotswapProperties;\n let minimumHealthyPercent = ecsHotswapProperties?.minimumHealthyPercent;\n let maximumHealthyPercent = ecsHotswapProperties?.maximumHealthyPercent;\n\n // Step 2 - update the services using that TaskDefinition to point to the new TaskDefinition Revision\n // Forcing New Deployment and setting Minimum Healthy Percent to 0.\n // As CDK HotSwap is development only, this seems the most efficient way to ensure all tasks are replaced immediately, regardless of original amount\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(\n ecsServicesReferencingTaskDef.map(async (service) => {\n const cluster = service.serviceArn.split('/')[1];\n const update = await sdk.ecs().updateService({\n service: service.serviceArn,\n taskDefinition: taskDefRevArn,\n cluster,\n forceNewDeployment: true,\n deploymentConfiguration: {\n minimumHealthyPercent: minimumHealthyPercent !== undefined ? minimumHealthyPercent : 0,\n maximumPercent: maximumHealthyPercent !== undefined ? maximumHealthyPercent : undefined,\n },\n });\n\n await sdk.ecs().waitUntilServicesStable({\n cluster: update.service?.clusterArn,\n services: [service.serviceArn],\n });\n }),\n );\n },\n });\n }\n\n return ret;\n}\n\ninterface EcsService {\n readonly serviceArn: string;\n}\n\nasync function prepareTaskDefinitionChange(\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n logicalId: string,\n change: HotswappableChangeCandidate,\n) {\n const taskDefinitionResource: { [name: string]: any } = {\n ...change.oldValue.Properties,\n ContainerDefinitions: change.newValue.Properties?.ContainerDefinitions,\n };\n // first, let's get the name of the family\n const familyNameOrArn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n taskDefinitionResource?.Family,\n );\n if (!familyNameOrArn) {\n // if the Family property has not been provided, and we can't find it in the current Stack,\n // this means hotswapping is not possible\n return;\n }\n // the physical name of the Task Definition in CloudFormation includes its current revision number at the end,\n // remove it if needed\n const familyNameOrArnParts = familyNameOrArn.split(':');\n const family =\n familyNameOrArnParts.length > 1\n ? // familyNameOrArn is actually an ARN, of the format 'arn:aws:ecs:region:account:task-definition/<family-name>:<revision-nr>'\n // so, take the 6th element, at index 5, and split it on '/'\n familyNameOrArnParts[5].split('/')[1]\n : // otherwise, familyNameOrArn is just the simple name evaluated from the CloudFormation template\n familyNameOrArn;\n // then, let's evaluate the body of the remainder of the TaskDef (without the Family property)\n return {\n ...(await evaluateCfnTemplate.evaluateCfnExpression({\n ...(taskDefinitionResource ?? {}),\n Family: undefined,\n })),\n Family: family,\n };\n}\n", "import { Writable } from 'stream';\nimport { type FunctionConfiguration, type UpdateFunctionConfigurationCommandInput } from '@aws-sdk/client-lambda';\nimport { type ChangeHotswapResult, classifyChanges, type HotswappableChangeCandidate, PropDiffs } from './common';\nimport { ToolkitError } from '../../toolkit/error';\nimport { flatMap } from '../../util';\nimport type { ILambdaClient, SDK } from '../aws-auth';\nimport { CfnEvaluationException, type EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\n// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\nexport async function isHotswappableLambdaFunctionChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n // if the change is for a Lambda Version,\n // ignore it by returning an empty hotswap operation -\n // we will publish a new version when we get to hotswapping the actual Function this Version points to, below\n // (Versions can't be changed in CloudFormation anyway, they're immutable)\n if (change.newValue.Type === 'AWS::Lambda::Version') {\n return [\n {\n hotswappable: true,\n resourceType: 'AWS::Lambda::Version',\n resourceNames: [],\n propsChanged: [],\n service: 'lambda',\n apply: async (_sdk: SDK) => {\n },\n },\n ];\n }\n\n // we handle Aliases specially too\n if (change.newValue.Type === 'AWS::Lambda::Alias') {\n return classifyAliasChanges(change);\n }\n\n if (change.newValue.Type !== 'AWS::Lambda::Function') {\n return [];\n }\n\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['Code', 'Environment', 'Description']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const functionName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.FunctionName,\n );\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'lambda',\n resourceNames: [\n `Lambda Function '${functionName}'`,\n // add Version here if we're publishing a new one\n ...(await renderVersions(logicalId, evaluateCfnTemplate, [`Lambda Version for Function '${functionName}'`])),\n // add any Aliases that we are hotswapping here\n ...(await renderAliases(\n logicalId,\n evaluateCfnTemplate,\n async (alias) => `Lambda Alias '${alias}' for Function '${functionName}'`,\n )),\n ],\n apply: async (sdk: SDK) => {\n const lambdaCodeChange = await evaluateLambdaFunctionProps(\n classifiedChanges.hotswappableProps,\n change.newValue.Properties?.Runtime,\n evaluateCfnTemplate,\n );\n if (lambdaCodeChange === undefined) {\n return;\n }\n\n if (!functionName) {\n return;\n }\n\n const { versionsReferencingFunction, aliasesNames } = await versionsAndAliases(logicalId, evaluateCfnTemplate);\n const lambda = sdk.lambda();\n const operations: Promise<any>[] = [];\n\n if (lambdaCodeChange.code !== undefined || lambdaCodeChange.configurations !== undefined) {\n if (lambdaCodeChange.code !== undefined) {\n const updateFunctionCodeResponse = await lambda.updateFunctionCode({\n FunctionName: functionName,\n S3Bucket: lambdaCodeChange.code.s3Bucket,\n S3Key: lambdaCodeChange.code.s3Key,\n ImageUri: lambdaCodeChange.code.imageUri,\n ZipFile: lambdaCodeChange.code.functionCodeZip,\n S3ObjectVersion: lambdaCodeChange.code.s3ObjectVersion,\n });\n\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n if (lambdaCodeChange.configurations !== undefined) {\n const updateRequest: UpdateFunctionConfigurationCommandInput = {\n FunctionName: functionName,\n };\n if (lambdaCodeChange.configurations.description !== undefined) {\n updateRequest.Description = lambdaCodeChange.configurations.description;\n }\n if (lambdaCodeChange.configurations.environment !== undefined) {\n updateRequest.Environment = lambdaCodeChange.configurations.environment;\n }\n const updateFunctionCodeResponse = await lambda.updateFunctionConfiguration(updateRequest);\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n // only if the code changed is there any point in publishing a new Version\n if (versionsReferencingFunction.length > 0) {\n const publishVersionPromise = lambda.publishVersion({\n FunctionName: functionName,\n });\n\n if (aliasesNames.length > 0) {\n // we need to wait for the Version to finish publishing\n const versionUpdate = await publishVersionPromise;\n for (const alias of aliasesNames) {\n operations.push(\n lambda.updateAlias({\n FunctionName: functionName,\n Name: alias,\n FunctionVersion: versionUpdate.Version,\n }),\n );\n }\n } else {\n operations.push(publishVersionPromise);\n }\n }\n }\n\n // run all of our updates in parallel\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(operations);\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Determines which changes to this Alias are hotswappable or not\n */\nfunction classifyAliasChanges(change: HotswappableChangeCandidate): ChangeHotswapResult {\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['FunctionVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: [],\n service: 'lambda',\n resourceNames: [],\n apply: async (_sdk: SDK) => {\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Evaluates the hotswappable properties of an AWS::Lambda::Function and\n * Returns a `LambdaFunctionChange` if the change is hotswappable.\n * Returns `undefined` if the change is not hotswappable.\n */\nasync function evaluateLambdaFunctionProps(\n hotswappablePropChanges: PropDiffs,\n runtime: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<LambdaFunctionChange | undefined> {\n /*\n * At first glance, we would want to initialize these using the \"previous\" values (change.oldValue),\n * in case only one of them changed, like the key, and the Bucket stayed the same.\n * However, that actually fails for old-style synthesis, which uses CFN Parameters!\n * Because the names of the Parameters depend on the hash of the Asset,\n * the Parameters used for the \"old\" values no longer exist in `assetParams` at this point,\n * which means we don't have the correct values available to evaluate the CFN expression with.\n * Fortunately, the diff will always include both the s3Bucket and s3Key parts of the Lambda's Code property,\n * even if only one of them was actually changed,\n * which means we don't need the \"old\" values at all, and we can safely initialize these with just `''`.\n */\n let code: LambdaFunctionCode | undefined = undefined;\n let description: string | undefined = undefined;\n let environment: { [key: string]: string } | undefined = undefined;\n\n for (const updatedPropName in hotswappablePropChanges) {\n const updatedProp = hotswappablePropChanges[updatedPropName];\n\n switch (updatedPropName) {\n case 'Code':\n let s3Bucket, s3Key, s3ObjectVersion, imageUri, functionCodeZip;\n\n for (const newPropName in updatedProp.newValue) {\n switch (newPropName) {\n case 'S3Bucket':\n s3Bucket = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3Key':\n s3Key = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3ObjectVersion':\n s3ObjectVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ImageUri':\n imageUri = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ZipFile':\n // We must create a zip package containing a file with the inline code\n const functionCode = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n const functionRuntime = await evaluateCfnTemplate.evaluateCfnExpression(runtime);\n if (!functionRuntime) {\n return undefined;\n }\n // file extension must be chosen depending on the runtime\n const codeFileExt = determineCodeFileExtFromRuntime(functionRuntime);\n functionCodeZip = await zipString(`index.${codeFileExt}`, functionCode);\n break;\n }\n }\n code = {\n s3Bucket,\n s3Key,\n s3ObjectVersion,\n imageUri,\n functionCodeZip,\n };\n break;\n case 'Description':\n description = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n case 'Environment':\n environment = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n default:\n // we will never get here, but just in case we do throw an error\n throw new ToolkitError(\n 'while apply()ing, found a property that cannot be hotswapped. Please report this at github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n }\n\n const configurations = description || environment ? { description, environment } : undefined;\n return code || configurations ? { code, configurations } : undefined;\n}\n\ninterface LambdaFunctionCode {\n readonly s3Bucket?: string;\n readonly s3Key?: string;\n readonly s3ObjectVersion?: string;\n readonly imageUri?: string;\n readonly functionCodeZip?: Buffer;\n}\n\ninterface LambdaFunctionConfigurations {\n readonly description?: string;\n readonly environment?: { [key: string]: string };\n}\n\ninterface LambdaFunctionChange {\n readonly code?: LambdaFunctionCode;\n readonly configurations?: LambdaFunctionConfigurations;\n}\n\n/**\n * Compress a string as a file, returning a promise for the zip buffer\n * https://github.com/archiverjs/node-archiver/issues/342\n */\nfunction zipString(fileName: string, rawString: string): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const buffers: Buffer[] = [];\n\n const converter = new Writable();\n\n converter._write = (chunk: Buffer, _: string, callback: () => void) => {\n buffers.push(chunk);\n process.nextTick(callback);\n };\n\n converter.on('finish', () => {\n resolve(Buffer.concat(buffers));\n });\n\n const archive = archiver('zip');\n\n archive.on('error', (err: any) => {\n reject(err);\n });\n\n archive.pipe(converter);\n\n archive.append(rawString, {\n name: fileName,\n date: new Date('1980-01-01T00:00:00.000Z'), // Add date to make resulting zip file deterministic\n });\n\n void archive.finalize();\n });\n}\n\n/**\n * After a Lambda Function is updated, it cannot be updated again until the\n * `State=Active` and the `LastUpdateStatus=Successful`.\n *\n * Depending on the configuration of the Lambda Function this could happen relatively quickly\n * or very slowly. For example, Zip based functions _not_ in a VPC can take ~1 second whereas VPC\n * or Container functions can take ~25 seconds (and 'idle' VPC functions can take minutes).\n */\nasync function waitForLambdasPropertiesUpdateToFinish(\n currentFunctionConfiguration: FunctionConfiguration,\n lambda: ILambdaClient,\n functionName: string,\n): Promise<void> {\n const functionIsInVpcOrUsesDockerForCode =\n currentFunctionConfiguration.VpcConfig?.VpcId || currentFunctionConfiguration.PackageType === 'Image';\n\n // if the function is deployed in a VPC or if it is a container image function\n // then the update will take much longer and we can wait longer between checks\n // otherwise, the update will be quick, so a 1-second delay is fine\n const delaySeconds = functionIsInVpcOrUsesDockerForCode ? 5 : 1;\n\n await lambda.waitUntilFunctionUpdated(delaySeconds, {\n FunctionName: functionName,\n });\n}\n\n/**\n * Get file extension from Lambda runtime string.\n * We use this extension to create a deployment package from Lambda inline code.\n */\nfunction determineCodeFileExtFromRuntime(runtime: string): string {\n if (runtime.startsWith('node')) {\n return 'js';\n }\n if (runtime.startsWith('python')) {\n return 'py';\n }\n // Currently inline code only supports Node.js and Python, ignoring other runtimes.\n // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#aws-properties-lambda-function-code-properties\n throw new CfnEvaluationException(\n `runtime ${runtime} is unsupported, only node.js and python runtimes are currently supported.`,\n );\n}\n\n/**\n * Finds all Versions that reference an AWS::Lambda::Function with logical ID `logicalId`\n * and Aliases that reference those Versions.\n */\nasync function versionsAndAliases(logicalId: string, evaluateCfnTemplate: EvaluateCloudFormationTemplate) {\n // find all Lambda Versions that reference this Function\n const versionsReferencingFunction = evaluateCfnTemplate\n .findReferencesTo(logicalId)\n .filter((r) => r.Type === 'AWS::Lambda::Version');\n // find all Lambda Aliases that reference the above Versions\n const aliasesReferencingVersions = flatMap(versionsReferencingFunction, v =>\n evaluateCfnTemplate.findReferencesTo(v.LogicalId));\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const aliasesNames = await Promise.all(aliasesReferencingVersions.map(a =>\n evaluateCfnTemplate.evaluateCfnExpression(a.Properties?.Name)));\n\n return { versionsReferencingFunction, aliasesNames };\n}\n\n/**\n * Renders the string used in displaying Alias resource names that reference the specified Lambda Function\n */\nasync function renderAliases(\n logicalId: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n callbackfn: (value: any, index: number, array: any[]) => Promise<string>,\n): Promise<string[]> {\n const aliasesNames = (await versionsAndAliases(logicalId, evaluateCfnTemplate)).aliasesNames;\n\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(aliasesNames.map(callbackfn));\n}\n\n/**\n * Renders the string used in displaying Version resource names that reference the specified Lambda Function\n */\nasync function renderVersions(\n logicalId: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n versionString: string[],\n): Promise<string[]> {\n const versions = (await versionsAndAliases(logicalId, evaluateCfnTemplate)).versionsReferencingFunction;\n\n return versions.length > 0 ? versionString : [];\n}\n", "import type { ChangeHotswapResult, HotswappableChangeCandidate } from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\n/**\n * This means that the value is required to exist by CloudFormation's Custom Resource API (or our S3 Bucket Deployment Lambda's API)\n * but the actual value specified is irrelevant\n */\nexport const REQUIRED_BY_CFN = 'required-to-be-present-by-cfn';\n\nexport async function isHotswappableS3BucketDeploymentChange(\n _logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n // In old-style synthesis, the policy used by the lambda to copy assets Ref's the assets directly,\n // meaning that the changes made to the Policy are artifacts that can be safely ignored\n const ret: ChangeHotswapResult = [];\n\n if (change.newValue.Type !== 'Custom::CDKBucketDeployment') {\n return [];\n }\n\n // no classification to be done here; all the properties of this custom resource thing are hotswappable\n const customResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression({\n ...change.newValue.Properties,\n ServiceToken: undefined,\n });\n\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: ['*'],\n service: 'custom-s3-deployment',\n resourceNames: [`Contents of S3 Bucket '${customResourceProperties.DestinationBucketName}'`],\n apply: async (sdk: SDK) => {\n // note that this gives the ARN of the lambda, not the name. This is fine though, the invoke() sdk call will take either\n const functionName = await evaluateCfnTemplate.evaluateCfnExpression(change.newValue.Properties?.ServiceToken);\n if (!functionName) {\n return;\n }\n\n await sdk.lambda().invokeCommand({\n FunctionName: functionName,\n // Lambda refuses to take a direct JSON object and requires it to be stringify()'d\n Payload: JSON.stringify({\n RequestType: 'Update',\n ResponseURL: REQUIRED_BY_CFN,\n PhysicalResourceId: REQUIRED_BY_CFN,\n StackId: REQUIRED_BY_CFN,\n RequestId: REQUIRED_BY_CFN,\n LogicalResourceId: REQUIRED_BY_CFN,\n ResourceProperties: stringifyObject(customResourceProperties), // JSON.stringify() doesn't turn the actual objects to strings, but the lambda expects strings\n }),\n });\n },\n });\n\n return ret;\n}\n\nexport async function skipChangeForS3DeployCustomResourcePolicy(\n iamPolicyLogicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<boolean> {\n if (change.newValue.Type !== 'AWS::IAM::Policy') {\n return false;\n }\n const roles: string[] = change.newValue.Properties?.Roles;\n\n // If no roles are referenced, the policy is definitely not used for a S3Deployment\n if (!roles || !roles.length) {\n return false;\n }\n\n // Check if every role this policy is referenced by is only used for a S3Deployment\n for (const role of roles) {\n const roleArn = await evaluateCfnTemplate.evaluateCfnExpression(role);\n const roleLogicalId = await evaluateCfnTemplate.findLogicalIdForPhysicalName(roleArn);\n\n // We must assume this role is used for something else, because we can't check it\n if (!roleLogicalId) {\n return false;\n }\n\n // Find all interesting reference to the role\n const roleRefs = evaluateCfnTemplate\n .findReferencesTo(roleLogicalId)\n // we are not interested in the reference from the original policy - it always exists\n .filter((roleRef) => !(roleRef.Type == 'AWS::IAM::Policy' && roleRef.LogicalId === iamPolicyLogicalId));\n\n // Check if the role is only used for S3Deployment\n // We know this is the case, if S3Deployment -> Lambda -> Role is satisfied for every reference\n // And we have at least one reference.\n const isRoleOnlyForS3Deployment =\n roleRefs.length >= 1 &&\n roleRefs.every((roleRef) => {\n if (roleRef.Type === 'AWS::Lambda::Function') {\n const lambdaRefs = evaluateCfnTemplate.findReferencesTo(roleRef.LogicalId);\n // Every reference must be to the custom resource and at least one reference must be present\n return (\n lambdaRefs.length >= 1 && lambdaRefs.every((lambdaRef) => lambdaRef.Type === 'Custom::CDKBucketDeployment')\n );\n }\n return false;\n });\n\n // We have determined this role is used for something else, so we can't skip the change\n if (!isRoleOnlyForS3Deployment) {\n return false;\n }\n }\n\n // We have checked that any use of this policy is only for S3Deployment and we can safely skip it\n return true;\n}\n\nfunction stringifyObject(obj: any): any {\n if (obj == null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stringifyObject);\n }\n if (typeof obj !== 'object') {\n return obj.toString();\n }\n\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(obj)) {\n ret[k] = stringifyObject(v);\n }\n return ret;\n}\n", "import { type ChangeHotswapResult, classifyChanges, type HotswappableChangeCandidate } from './common';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';\n\nexport async function isHotswappableStateMachineChange(\n logicalId: string,\n change: HotswappableChangeCandidate,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<ChangeHotswapResult> {\n if (change.newValue.Type !== 'AWS::StepFunctions::StateMachine') {\n return [];\n }\n const ret: ChangeHotswapResult = [];\n const classifiedChanges = classifyChanges(change, ['DefinitionString']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const stateMachineNameInCfnTemplate = change.newValue?.Properties?.StateMachineName;\n const stateMachineArn = stateMachineNameInCfnTemplate\n ? await evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::Sub':\n 'arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:' +\n stateMachineNameInCfnTemplate,\n })\n : await evaluateCfnTemplate.findPhysicalNameFor(logicalId);\n ret.push({\n hotswappable: true,\n resourceType: change.newValue.Type,\n propsChanged: namesOfHotswappableChanges,\n service: 'stepfunctions-service',\n resourceNames: [`${change.newValue.Type} '${stateMachineArn?.split(':')[6]}'`],\n apply: async (sdk: SDK) => {\n if (!stateMachineArn) {\n return;\n }\n\n // not passing the optional properties leaves them unchanged\n await sdk.stepFunctions().updateStateMachine({\n stateMachineArn,\n definition: await evaluateCfnTemplate.evaluateCfnExpression(change.propertyUpdates.DefinitionString.newValue),\n });\n },\n });\n }\n\n return ret;\n}\n", "import { ClientRequest } from 'http';\nimport { RequestOptions } from 'https';\nimport * as https from 'node:https';\nimport * as path from 'path';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { SdkHttpOptions } from './api';\nimport { AwsCliCompatible } from './api/aws-auth/awscli-compatible';\nimport type { Context } from './api/context';\nimport { versionNumber } from './cli/version';\nimport { debug, info, warning, error } from './logging';\nimport { ToolkitError } from './toolkit/error';\nimport { ConstructTreeNode, loadTreeFromDir } from './tree';\nimport { cdkCacheDir } from './util/directories';\nimport { formatErrorMessage } from './util/format-error';\n\nconst CACHE_FILE_PATH = path.join(cdkCacheDir(), 'notices.json');\n\nexport interface NoticesProps {\n /**\n * CDK context\n */\n readonly context: Context;\n\n /**\n * Include notices that have already been acknowledged.\n *\n * @default false\n */\n readonly includeAcknowledged?: boolean;\n\n /**\n * Global CLI option for output directory for synthesized cloud assembly\n *\n * @default 'cdk.out'\n */\n readonly output?: string;\n\n /**\n * Global CLI option for whether we show notices\n *\n * @default true\n */\n readonly shouldDisplay?: boolean;\n\n /**\n * Options for the HTTP request\n */\n readonly httpOptions?: SdkHttpOptions;\n}\n\nexport interface NoticesPrintOptions {\n\n /**\n * Whether to append the total number of unacknowledged notices to the display.\n *\n * @default false\n */\n readonly showTotal?: boolean;\n}\n\nexport interface NoticesRefreshOptions {\n /**\n * Whether to force a cache refresh regardless of expiration time.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Data source for fetch notices from.\n *\n * @default - WebsiteNoticeDataSource\n */\n readonly dataSource?: NoticeDataSource;\n}\n\nexport interface NoticesFilterFilterOptions {\n readonly data: Notice[];\n readonly cliVersion: string;\n readonly outDir: string;\n readonly bootstrappedEnvironments: BootstrappedEnvironment[];\n}\n\nexport abstract class NoticesFilter {\n public static filter(options: NoticesFilterFilterOptions): FilteredNotice[] {\n const components = [\n ...NoticesFilter.constructTreeComponents(options.outDir),\n ...NoticesFilter.otherComponents(options),\n ];\n\n return NoticesFilter.findForNamedComponents(options.data, components);\n }\n\n /**\n * From a set of input options, return the notices components we are searching for\n */\n private static otherComponents(options: NoticesFilterFilterOptions): ActualComponent[] {\n return [\n // CLI\n {\n name: 'cli',\n version: options.cliVersion,\n },\n\n // Node version\n {\n name: 'node',\n version: process.version.replace(/^v/, ''), // remove the 'v' prefix.\n dynamicName: 'node',\n },\n\n // Bootstrap environments\n ...options.bootstrappedEnvironments.flatMap(env => {\n const semverBootstrapVersion = semver.coerce(env.bootstrapStackVersion);\n if (!semverBootstrapVersion) {\n // we don't throw because notices should never crash the cli.\n warning(`While filtering notices, could not coerce bootstrap version '${env.bootstrapStackVersion}' into semver`);\n return [];\n }\n\n return [{\n name: 'bootstrap',\n version: `${semverBootstrapVersion}`,\n dynamicName: 'ENVIRONMENTS',\n dynamicValue: env.environment.name,\n }];\n }),\n ];\n }\n\n /**\n * Based on a set of component names, find all notices that match one of the given components\n */\n private static findForNamedComponents(data: Notice[], actualComponents: ActualComponent[]): FilteredNotice[] {\n return data.flatMap(notice => {\n const ors = this.resolveAliases(normalizeComponents(notice.components));\n\n // Find the first set of the disjunctions of which all components match against the actual components.\n // Return the actual components we found so that we can inject their dynamic values. A single filter\n // component can match more than one actual component\n for (const ands of ors) {\n const matched = ands.map(affected => actualComponents.filter(actual =>\n NoticesFilter.componentNameMatches(affected, actual) && semver.satisfies(actual.version, affected.version, { includePrerelease: true })));\n\n // For every clause in the filter we matched one or more components\n if (matched.every(xs => xs.length > 0)) {\n const ret = new FilteredNotice(notice);\n NoticesFilter.addDynamicValues(matched.flatMap(x => x), ret);\n return [ret];\n }\n }\n\n return [];\n });\n }\n\n /**\n * Whether the given \"affected component\" name applies to the given actual component name.\n *\n * The name matches if the name is exactly the same, or the name in the notice\n * is a prefix of the node name when the query ends in '.'.\n */\n private static componentNameMatches(pattern: Component, actual: ActualComponent): boolean {\n return pattern.name.endsWith('.') ? actual.name.startsWith(pattern.name) : pattern.name === actual.name;\n }\n\n /**\n * Adds dynamic values from the given ActualComponents\n *\n * If there are multiple components with the same dynamic name, they are joined\n * by a comma.\n */\n private static addDynamicValues(comps: ActualComponent[], notice: FilteredNotice) {\n const dynamicValues: Record<string, string[]> = {};\n for (const comp of comps) {\n if (comp.dynamicName) {\n dynamicValues[comp.dynamicName] = dynamicValues[comp.dynamicName] ?? [];\n dynamicValues[comp.dynamicName].push(comp.dynamicValue ?? comp.version);\n }\n }\n for (const [key, values] of Object.entries(dynamicValues)) {\n notice.addDynamicValue(key, values.join(','));\n }\n }\n\n /**\n * Treat 'framework' as an alias for either `aws-cdk-lib.` or `@aws-cdk/core.`.\n *\n * Because it's EITHER `aws-cdk-lib` or `@aws-cdk/core`, we need to add multiple\n * arrays at the top level.\n */\n private static resolveAliases(ors: Component[][]): Component[][] {\n return ors.flatMap(ands => {\n const hasFramework = ands.find(c => c.name === 'framework');\n if (!hasFramework) {\n return [ands];\n }\n\n return [\n ands.map(c => c.name === 'framework' ? { ...c, name: '@aws-cdk/core.' } : c),\n ands.map(c => c.name === 'framework' ? { ...c, name: 'aws-cdk-lib.' } : c),\n ];\n });\n }\n\n /**\n * Load the construct tree from the given directory and return its components\n */\n private static constructTreeComponents(manifestDir: string): ActualComponent[] {\n const tree = loadTreeFromDir(manifestDir);\n if (!tree) {\n return [];\n }\n\n const ret: ActualComponent[] = [];\n recurse(tree);\n return ret;\n\n function recurse(x: ConstructTreeNode) {\n if (x.constructInfo?.fqn && x.constructInfo?.version) {\n ret.push({\n name: x.constructInfo?.fqn,\n version: x.constructInfo?.version,\n });\n }\n\n for (const child of Object.values(x.children ?? {})) {\n recurse(child);\n }\n }\n }\n}\n\ninterface ActualComponent {\n /**\n * Name of the component\n */\n readonly name: string;\n\n /**\n * Version of the component\n */\n readonly version: string;\n\n /**\n * If matched, under what name should it be added to the set of dynamic values\n *\n * These will be used to substitute placeholders in the message string, where\n * placeholders look like `{resolve:XYZ}`.\n *\n * If there is more than one component with the same dynamic name, they are\n * joined by ','.\n *\n * @default - Don't add to the set of dynamic values.\n */\n readonly dynamicName?: string;\n\n /**\n * If matched, what we should put in the set of dynamic values insstead of the version.\n *\n * Only used if `dynamicName` is set; by default we will add the actual version\n * of the component.\n *\n * @default - The version.\n */\n readonly dynamicValue?: string;\n}\n\n/**\n * Information about a bootstrapped environment.\n */\nexport interface BootstrappedEnvironment {\n readonly bootstrapStackVersion: number;\n readonly environment: Environment;\n}\n\n/**\n * Provides access to notices the CLI can display.\n */\nexport class Notices {\n /**\n * Create an instance. Note that this replaces the singleton.\n */\n public static create(props: NoticesProps): Notices {\n this._instance = new Notices(props);\n return this._instance;\n }\n\n /**\n * Get the singleton instance. May return `undefined` if `create` has not been called.\n */\n public static get(): Notices | undefined {\n return this._instance;\n }\n\n private static _instance: Notices | undefined;\n\n private readonly context: Context;\n private readonly output: string;\n private readonly shouldDisplay: boolean;\n private readonly acknowledgedIssueNumbers: Set<Number>;\n private readonly includeAcknowlegded: boolean;\n private readonly httpOptions: SdkHttpOptions;\n\n private data: Set<Notice> = new Set();\n\n // sets don't deduplicate interfaces, so we use a map.\n private readonly bootstrappedEnvironments: Map<string, BootstrappedEnvironment> = new Map();\n\n private constructor(props: NoticesProps) {\n this.context = props.context;\n this.acknowledgedIssueNumbers = new Set(this.context.get('acknowledged-issue-numbers') ?? []);\n this.includeAcknowlegded = props.includeAcknowledged ?? false;\n this.output = props.output ?? 'cdk.out';\n this.shouldDisplay = props.shouldDisplay ?? true;\n this.httpOptions = props.httpOptions ?? {};\n }\n\n /**\n * Add a bootstrap information to filter on. Can have multiple values\n * in case of multi-environment deployments.\n */\n public addBootstrappedEnvironment(bootstrapped: BootstrappedEnvironment) {\n const key = [\n bootstrapped.bootstrapStackVersion,\n bootstrapped.environment.account,\n bootstrapped.environment.region,\n bootstrapped.environment.name,\n ].join(':');\n this.bootstrappedEnvironments.set(key, bootstrapped);\n }\n\n /**\n * Refresh the list of notices this instance is aware of.\n * To make sure this never crashes the CLI process, all failures are caught and\n * silently logged.\n *\n * If context is configured to not display notices, this will no-op.\n */\n public async refresh(options: NoticesRefreshOptions = {}) {\n if (!this.shouldDisplay) {\n return;\n }\n\n try {\n const underlyingDataSource = options.dataSource ?? new WebsiteNoticeDataSource(this.httpOptions);\n const dataSource = new CachedDataSource(CACHE_FILE_PATH, underlyingDataSource, options.force ?? false);\n const notices = await dataSource.fetch();\n this.data = new Set(this.includeAcknowlegded ? notices : notices.filter(n => !this.acknowledgedIssueNumbers.has(n.issueNumber)));\n } catch (e: any) {\n debug(`Could not refresh notices: ${e}`);\n }\n }\n\n /**\n * Display the relevant notices (unless context dictates we shouldn't).\n */\n public display(options: NoticesPrintOptions = {}) {\n if (!this.shouldDisplay) {\n return;\n }\n\n const filteredNotices = NoticesFilter.filter({\n data: Array.from(this.data),\n cliVersion: versionNumber(),\n outDir: this.output,\n bootstrappedEnvironments: Array.from(this.bootstrappedEnvironments.values()),\n });\n\n if (filteredNotices.length > 0) {\n info('');\n info('NOTICES (What\\'s this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)');\n info('');\n for (const filtered of filteredNotices) {\n const formatted = filtered.format();\n switch (filtered.notice.severity) {\n case 'warning':\n warning(formatted);\n break;\n case 'error':\n error(formatted);\n break;\n default:\n info(formatted);\n }\n info('');\n }\n info(`If you don\u2019t want to see a notice anymore, use \"cdk acknowledge <id>\". For example, \"cdk acknowledge ${filteredNotices[0].notice.issueNumber}\".`);\n }\n\n if (options.showTotal ?? false) {\n info('');\n info(`There are ${filteredNotices.length} unacknowledged notice(s).`);\n }\n }\n}\n\nexport interface Component {\n name: string;\n\n /**\n * The range of affected versions\n */\n version: string;\n}\n\nexport interface Notice {\n title: string;\n issueNumber: number;\n overview: string;\n /**\n * A set of affected components\n *\n * The canonical form of a list of components is in Disjunctive Normal Form\n * (i.e., an OR of ANDs). This is the form when the list of components is a\n * doubly nested array: the notice matches if all components of at least one\n * of the top-level array matches.\n *\n * If the `components` is a single-level array, it is evaluated as an OR; it\n * matches if any of the components matches.\n */\n components: Array<Component | Component[]>;\n schemaVersion: string;\n severity?: string;\n}\n\n/**\n * Normalizes the given components structure into DNF form\n */\nfunction normalizeComponents(xs: Array<Component | Component[]>): Component[][] {\n return xs.map(x => Array.isArray(x) ? x : [x]);\n}\n\nfunction renderConjunction(xs: Component[]): string {\n return xs.map(c => `${c.name}: ${c.version}`).join(' AND ');\n}\n\n/**\n * Notice after passing the filter. A filter can augment a notice with\n * dynamic values as it has access to the dynamic matching data.\n */\nexport class FilteredNotice {\n private readonly dynamicValues: { [key: string]: string } = {};\n\n public constructor(public readonly notice: Notice) {\n }\n\n public addDynamicValue(key: string, value: string) {\n this.dynamicValues[`{resolve:${key}}`] = value;\n }\n\n public format(): string {\n const componentsValue = normalizeComponents(this.notice.components).map(renderConjunction).join(', ');\n return this.resolveDynamicValues([\n `${this.notice.issueNumber}\\t${this.notice.title}`,\n this.formatOverview(),\n `\\tAffected versions: ${componentsValue}`,\n `\\tMore information at: https://github.com/aws/aws-cdk/issues/${this.notice.issueNumber}`,\n ].join('\\n\\n') + '\\n');\n }\n\n private formatOverview() {\n const wrap = (s: string) => s.replace(/(?![^\\n]{1,60}$)([^\\n]{1,60})\\s/g, '$1\\n');\n\n const heading = 'Overview: ';\n const separator = `\\n\\t${' '.repeat(heading.length)}`;\n const content = wrap(this.notice.overview)\n .split('\\n')\n .join(separator);\n\n return '\\t' + heading + content;\n }\n\n private resolveDynamicValues(input: string): string {\n const pattern = new RegExp(Object.keys(this.dynamicValues).join('|'), 'g');\n return input.replace(pattern, (matched) => this.dynamicValues[matched] ?? matched);\n }\n}\n\nexport interface NoticeDataSource {\n fetch(): Promise<Notice[]>;\n}\n\nexport class WebsiteNoticeDataSource implements NoticeDataSource {\n private readonly options: SdkHttpOptions;\n\n constructor(options: SdkHttpOptions = {}) {\n this.options = options;\n }\n\n fetch(): Promise<Notice[]> {\n const timeout = 3000;\n return new Promise((resolve, reject) => {\n let req: ClientRequest | undefined;\n\n let timer = setTimeout(() => {\n if (req) {\n req.destroy(new ToolkitError('Request timed out'));\n }\n }, timeout);\n\n timer.unref();\n\n const options: RequestOptions = {\n agent: AwsCliCompatible.proxyAgent(this.options),\n };\n\n try {\n req = https.get('https://cli.cdk.dev-tools.aws.dev/notices.json',\n options,\n res => {\n if (res.statusCode === 200) {\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => {\n rawData += chunk;\n });\n res.on('end', () => {\n try {\n const data = JSON.parse(rawData).notices as Notice[];\n if (!data) {\n throw new ToolkitError(\"'notices' key is missing\");\n }\n debug('Notices refreshed');\n resolve(data ?? []);\n } catch (e: any) {\n reject(new ToolkitError(`Failed to parse notices: ${formatErrorMessage(e)}`));\n }\n });\n res.on('error', e => {\n reject(new ToolkitError(`Failed to fetch notices: ${formatErrorMessage(e)}`));\n });\n } else {\n reject(new ToolkitError(`Failed to fetch notices. Status code: ${res.statusCode}`));\n }\n });\n req.on('error', reject);\n } catch (e: any) {\n reject(new ToolkitError(`HTTPS 'get' call threw an error: ${formatErrorMessage(e)}`));\n }\n });\n }\n}\n\ninterface CachedNotices {\n expiration: number;\n notices: Notice[];\n}\n\nconst TIME_TO_LIVE_SUCCESS = 60 * 60 * 1000; // 1 hour\nconst TIME_TO_LIVE_ERROR = 1 * 60 * 1000; // 1 minute\n\nexport class CachedDataSource implements NoticeDataSource {\n constructor(\n private readonly fileName: string,\n private readonly dataSource: NoticeDataSource,\n private readonly skipCache?: boolean) {\n }\n\n async fetch(): Promise<Notice[]> {\n const cachedData = await this.load();\n const data = cachedData.notices;\n const expiration = cachedData.expiration ?? 0;\n\n if (Date.now() > expiration || this.skipCache) {\n const freshData = await this.fetchInner();\n await this.save(freshData);\n return freshData.notices;\n } else {\n debug(`Reading cached notices from ${this.fileName}`);\n return data;\n }\n }\n\n private async fetchInner(): Promise<CachedNotices> {\n try {\n return {\n expiration: Date.now() + TIME_TO_LIVE_SUCCESS,\n notices: await this.dataSource.fetch(),\n };\n } catch (e) {\n debug(`Could not refresh notices: ${e}`);\n return {\n expiration: Date.now() + TIME_TO_LIVE_ERROR,\n notices: [],\n };\n }\n }\n\n private async load(): Promise<CachedNotices> {\n const defaultValue = {\n expiration: 0,\n notices: [],\n };\n\n try {\n return fs.existsSync(this.fileName)\n ? await fs.readJSON(this.fileName) as CachedNotices\n : defaultValue;\n } catch (e) {\n debug(`Failed to load notices from cache: ${e}`);\n return defaultValue;\n }\n }\n\n private async save(cached: CachedNotices): Promise<void> {\n try {\n await fs.writeJSON(this.fileName, cached);\n } catch (e) {\n debug(`Failed to store notices in the cache: ${e}`);\n }\n }\n}\n", "/* istanbul ignore file */\nimport * as path from 'path';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { debug, info } from '../logging';\nimport { ToolkitError } from '../toolkit/error';\nimport { formatAsBanner } from './util/console-formatters';\nimport { cdkCacheDir, rootDir } from '../util/directories';\nimport { getLatestVersionFromNpm } from './util/npm';\n\nconst ONE_DAY_IN_SECONDS = 1 * 24 * 60 * 60;\n\nconst UPGRADE_DOCUMENTATION_LINKS: Record<number, string> = {\n 1: 'https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html',\n};\n\nexport function displayVersion() {\n return `${versionNumber()} (build ${commit()})`;\n}\n\nexport function isDeveloperBuild(): boolean {\n return versionNumber() === '0.0.0';\n}\n\nexport function versionNumber(): string {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require(path.join(rootDir(), 'package.json')).version.replace(/\\+[0-9a-f]+$/, '');\n}\n\nfunction commit(): string {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require(path.join(rootDir(), 'build-info.json')).commit;\n}\n\nexport class VersionCheckTTL {\n public static timestampFilePath(): string {\n // Using the same path from account-cache.ts\n return path.join(cdkCacheDir(), 'repo-version-ttl');\n }\n\n private readonly file: string;\n\n // File modify times are accurate only to the second\n private readonly ttlSecs: number;\n\n constructor(file?: string, ttlSecs?: number) {\n this.file = file || VersionCheckTTL.timestampFilePath();\n try {\n fs.mkdirsSync(path.dirname(this.file));\n fs.accessSync(path.dirname(this.file), fs.constants.W_OK);\n } catch {\n throw new ToolkitError(`Directory (${path.dirname(this.file)}) is not writable.`);\n }\n this.ttlSecs = ttlSecs || ONE_DAY_IN_SECONDS;\n }\n\n public async hasExpired(): Promise<boolean> {\n try {\n const lastCheckTime = (await fs.stat(this.file)).mtimeMs;\n const today = new Date().getTime();\n\n if ((today - lastCheckTime) / 1000 > this.ttlSecs) { // convert ms to sec\n return true;\n }\n return false;\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n return true;\n } else {\n throw err;\n }\n }\n }\n\n public async update(latestVersion?: string): Promise<void> {\n if (!latestVersion) {\n latestVersion = '';\n }\n await fs.writeFile(this.file, latestVersion);\n }\n}\n\n// Export for unit testing only.\n// Don't use directly, use displayVersionMessage() instead.\nexport async function latestVersionIfHigher(currentVersion: string, cacheFile: VersionCheckTTL): Promise<string|null> {\n if (!(await cacheFile.hasExpired())) {\n return null;\n }\n\n const latestVersion = await getLatestVersionFromNpm();\n const isNewer = semver.gt(latestVersion, currentVersion);\n await cacheFile.update(latestVersion);\n\n if (isNewer) {\n return latestVersion;\n } else {\n return null;\n }\n}\n\nfunction getMajorVersionUpgradeMessage(currentVersion: string): string | void {\n const currentMajorVersion = semver.major(currentVersion);\n if (UPGRADE_DOCUMENTATION_LINKS[currentMajorVersion]) {\n return `Information about upgrading from version ${currentMajorVersion}.x to version ${currentMajorVersion + 1}.x is available here: ${UPGRADE_DOCUMENTATION_LINKS[currentMajorVersion]}`;\n }\n}\n\nfunction getVersionMessage(currentVersion: string, laterVersion: string): string[] {\n return [\n `Newer version of CDK is available [${chalk.green(laterVersion as string)}]`,\n getMajorVersionUpgradeMessage(currentVersion),\n 'Upgrade recommended (npm install -g aws-cdk)',\n ].filter(Boolean) as string[];\n}\n\nexport async function displayVersionMessage(currentVersion = versionNumber(), versionCheckCache?: VersionCheckTTL): Promise<void> {\n if (!process.stdout.isTTY || process.env.CDK_DISABLE_VERSION_CHECK) {\n return;\n }\n\n try {\n const laterVersion = await latestVersionIfHigher(currentVersion, versionCheckCache ?? new VersionCheckTTL());\n if (laterVersion) {\n const bannerMsg = formatAsBanner(getVersionMessage(currentVersion, laterVersion));\n bannerMsg.forEach((e) => info(e));\n }\n } catch (err: any) {\n debug(`Could not run version check - ${err.message}`);\n }\n}\n", "// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst stripAnsi = require('strip-ansi');\n\n/**\n * Returns a set of strings when printed on the console produces a banner msg. The message is in the following format -\n * ********************\n * *** msg line x ***\n * *** msg line xyz ***\n * ********************\n *\n * Spec:\n * - The width of every line is equal, dictated by the longest message string\n * - The first and last lines are '*'s for the full length of the line\n * - Each line in between is prepended with '*** ' and appended with ' ***'\n * - The text is indented left, i.e. whitespace is right-padded when the length is shorter than the longest.\n *\n * @param msgs array of strings containing the message lines to be printed in the banner. Returns empty string if array\n * is empty.\n * @returns array of strings containing the message formatted as a banner\n */\nexport function formatAsBanner(msgs: string[]): string[] {\n const printLen = (str: string) => stripAnsi(str).length;\n\n if (msgs.length === 0) {\n return [];\n }\n\n const leftPad = '*** ';\n const rightPad = ' ***';\n const bannerWidth = printLen(leftPad) + printLen(rightPad) +\n msgs.reduce((acc, msg) => Math.max(acc, printLen(msg)), 0);\n\n const bannerLines: string[] = [];\n bannerLines.push('*'.repeat(bannerWidth));\n\n // Improvement: If any 'msg' is wider than the terminal width, wrap message across lines.\n msgs.forEach((msg) => {\n const padding = ' '.repeat(bannerWidth - (printLen(msg) + printLen(leftPad) + printLen(rightPad)));\n bannerLines.push(''.concat(leftPad, msg, padding, rightPad));\n });\n\n bannerLines.push('*'.repeat(bannerWidth));\n return bannerLines;\n}\n", "import { exec as _exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as semver from 'semver';\nimport { debug } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\n\nconst exec = promisify(_exec);\n\n/* istanbul ignore next: not called during unit tests */\nexport async function getLatestVersionFromNpm(): Promise<string> {\n const { stdout, stderr } = await exec('npm view aws-cdk version', { timeout: 3000 });\n if (stderr && stderr.trim().length > 0) {\n debug(`The 'npm view' command generated an error stream with content [${stderr.trim()}]`);\n }\n const latestVersion = stdout.trim();\n if (!semver.valid(latestVersion)) {\n throw new ToolkitError(`npm returned an invalid semver ${latestVersion}`);\n }\n\n return latestVersion;\n}\n", "import * as path from 'path';\nimport { CloudAssembly } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { trace } from './logging';\n\n/**\n * Source information on a construct (class fqn and version)\n */\nexport interface ConstructInfo {\n readonly fqn: string;\n readonly version: string;\n}\n\n/**\n * A node in the construct tree.\n */\nexport interface ConstructTreeNode {\n readonly id: string;\n readonly path: string;\n readonly children?: { [key: string]: ConstructTreeNode };\n readonly attributes?: { [key: string]: any };\n\n /**\n * Information on the construct class that led to this node, if available\n */\n readonly constructInfo?: ConstructInfo;\n}\n\n/**\n * Whether the provided predicate is true for at least one element in the construct (sub-)tree.\n */\nexport function some(node: ConstructTreeNode | undefined, predicate: (n: ConstructTreeNode) => boolean): boolean {\n return node != null && (predicate(node) || findInChildren());\n\n function findInChildren(): boolean {\n return Object.values(node?.children ?? {}).some(child => some(child, predicate));\n }\n}\n\nexport function loadTree(assembly: CloudAssembly): ConstructTreeNode | undefined {\n try {\n const outdir = assembly.directory;\n const fileName = assembly.tree()?.file;\n return fileName ? fs.readJSONSync(path.join(outdir, fileName)).tree : {};\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n\nexport function loadTreeFromDir(outdir: string): ConstructTreeNode | undefined {\n try {\n return fs.readJSONSync(path.join(outdir, 'tree.json')).tree;\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { SDK } from './aws-auth';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BUCKET_DOMAIN_NAME_OUTPUT,\n BUCKET_NAME_OUTPUT,\n DEFAULT_BOOTSTRAP_VARIANT,\n REPOSITORY_NAME_OUTPUT,\n} from './bootstrap/bootstrap-props';\nimport { type CloudFormationStack, stabilizeStack } from './deployments/cloudformation';\nimport { debug } from '../cli/messages';\nimport { IoMessaging } from '../toolkit/cli-io-host';\nimport { ToolkitError } from '../toolkit/error';\n\nexport const DEFAULT_TOOLKIT_STACK_NAME = 'CDKToolkit';\n\n/**\n * Information on the Bootstrap stack of the environment we're deploying to.\n *\n * This class serves to:\n *\n * - Inspect the bootstrap stack, and return various properties of it for successful\n * asset deployment (in case of legacy-synthesized stacks).\n * - Validate the version of the target environment, and nothing else (in case of\n * default-synthesized stacks).\n *\n * An object of this type might represent a bootstrap stack that could not be found.\n * This is not an issue unless any members are used that require the bootstrap stack\n * to have been found, in which case an error is thrown (default-synthesized stacks\n * should never run into this as they don't need information from the bootstrap\n * stack, all information is already encoded into the Cloud Assembly Manifest).\n *\n * Nevertheless, an instance of this class exists to serve as a cache for SSM\n * parameter lookups (otherwise, the \"bootstrap stack version\" parameter would\n * need to be read repeatedly).\n *\n * Called \"ToolkitInfo\" for historical reasons.\n *\n */\nexport abstract class ToolkitInfo {\n public static determineName(overrideName?: string) {\n return overrideName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n public static async lookup(\n environment: cxapi.Environment,\n sdk: SDK,\n { ioHost, action }: IoMessaging,\n stackName: string | undefined,\n ): Promise<ToolkitInfo> {\n const cfn = sdk.cloudFormation();\n stackName = ToolkitInfo.determineName(stackName);\n try {\n const stack = await stabilizeStack(cfn, { ioHost, action }, stackName);\n if (!stack) {\n await ioHost.notify(debug(\n action,\n format(\n \"The environment %s doesn't have the CDK toolkit stack (%s) installed. Use %s to setup your environment for use with the toolkit.\",\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n if (stack.stackStatus.isCreationFailure) {\n // Treat a \"failed to create\" bootstrap stack as an absent one.\n await ioHost.notify(debug(\n action,\n format(\n 'The environment %s has a CDK toolkit stack (%s) that failed to create. Use %s to try provisioning it again.',\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n\n return new ExistingToolkitInfo(stack);\n } catch (e: any) {\n return ToolkitInfo.bootstrapStackLookupError(stackName, e);\n }\n }\n\n public static fromStack(stack: CloudFormationStack): ToolkitInfo {\n return new ExistingToolkitInfo(stack);\n }\n\n public static bootstrapStackNotFoundInfo(stackName: string): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n \"This deployment requires a bootstrap stack with a known name; pass '--toolkit-stack-name' or switch to using the 'DefaultStackSynthesizer' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)\",\n );\n }\n\n public static bootstrapStackLookupError(stackName: string, e: Error): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n `This deployment requires a bootstrap stack with a known name, but during its lookup the following error occurred: ${e}; pass \\'--toolkit-stack-name\\' or switch to using the \\'DefaultStackSynthesizer\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n\n public abstract readonly found: boolean;\n public abstract readonly bucketUrl: string;\n public abstract readonly bucketName: string;\n public abstract readonly repositoryName: string;\n public abstract readonly version: number;\n public abstract readonly variant: string;\n public abstract readonly bootstrapStack: CloudFormationStack;\n public abstract readonly stackName: string;\n\n constructor() {\n }\n}\n\n/**\n * Returned when a bootstrap stack is found\n */\nclass ExistingToolkitInfo extends ToolkitInfo {\n public readonly found = true;\n\n constructor(public readonly bootstrapStack: CloudFormationStack) {\n super();\n }\n\n public get bucketUrl() {\n return `https://${this.requireOutput(BUCKET_DOMAIN_NAME_OUTPUT)}`;\n }\n\n public get bucketName() {\n return this.requireOutput(BUCKET_NAME_OUTPUT);\n }\n\n public get repositoryName() {\n return this.requireOutput(REPOSITORY_NAME_OUTPUT);\n }\n\n public get version() {\n return parseInt(this.bootstrapStack.outputs[BOOTSTRAP_VERSION_OUTPUT] ?? '0', 10);\n }\n\n public get variant() {\n return this.bootstrapStack.parameters[BOOTSTRAP_VARIANT_PARAMETER] ?? DEFAULT_BOOTSTRAP_VARIANT;\n }\n\n public get parameters(): Record<string, string> {\n return this.bootstrapStack.parameters ?? {};\n }\n\n public get terminationProtection(): boolean {\n return this.bootstrapStack.terminationProtection ?? false;\n }\n\n public get stackName(): string {\n return this.bootstrapStack.stackName;\n }\n\n /**\n * Prepare an ECR repository for uploading to using Docker\n *\n */\n private requireOutput(output: string): string {\n if (!(output in this.bootstrapStack.outputs)) {\n throw new ToolkitError(\n `The CDK toolkit stack (${this.bootstrapStack.stackName}) does not have an output named ${output}. Use 'cdk bootstrap' to correct this.`,\n );\n }\n return this.bootstrapStack.outputs[output];\n }\n}\n\n/**\n * Returned when a bootstrap stack could not be found\n *\n * This is not an error in principle, UNTIL one of the members is called that requires\n * the bootstrap stack to have been found, in which case the lookup error is still thrown\n * belatedly.\n *\n * The errors below serve as a last stop-gap message--normally calling code should have\n * checked `toolkit.found` and produced an appropriate error message.\n */\nclass BootstrapStackNotFoundInfo extends ToolkitInfo {\n public readonly found = false;\n\n constructor(\n public readonly stackName: string,\n private readonly errorMessage: string,\n ) {\n super();\n }\n\n public get bootstrapStack(): CloudFormationStack {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketUrl(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get repositoryName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get version(): number {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get variant(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public prepareEcrRepository(): Promise<EcrRepositoryInfo> {\n throw new ToolkitError(this.errorMessage);\n }\n}\n\nexport interface EcrRepositoryInfo {\n repositoryUri: string;\n}\n\nexport interface EcrCredentials {\n username: string;\n password: string;\n endpoint: string;\n}\n", "import { BootstrapSource } from './bootstrap-environment';\nimport { Tag } from '../tags';\nimport { StringWithoutPlaceholders } from '../util/placeholders';\n\nexport const BUCKET_NAME_OUTPUT = 'BucketName';\nexport const REPOSITORY_NAME_OUTPUT = 'ImageRepositoryName';\nexport const BUCKET_DOMAIN_NAME_OUTPUT = 'BucketDomainName';\nexport const BOOTSTRAP_VERSION_OUTPUT = 'BootstrapVersion';\nexport const BOOTSTRAP_VERSION_RESOURCE = 'CdkBootstrapVersion';\nexport const BOOTSTRAP_VARIANT_PARAMETER = 'BootstrapVariant';\n\n/**\n * The assumed vendor of a template in case it is not set\n */\nexport const DEFAULT_BOOTSTRAP_VARIANT = 'AWS CDK: Default Resources';\n\n/**\n * Options for the bootstrapEnvironment operation(s)\n */\nexport interface BootstrapEnvironmentOptions {\n readonly toolkitStackName?: string;\n readonly roleArn?: StringWithoutPlaceholders;\n readonly parameters?: BootstrappingParameters;\n readonly force?: boolean;\n\n /**\n * The source of the bootstrap stack\n *\n * @default - modern v2-style bootstrapping\n */\n readonly source?: BootstrapSource;\n\n /**\n * Whether to execute the changeset or only create it and leave it in review.\n * @default true\n */\n readonly execute?: boolean;\n\n /**\n * Tags for cdktoolkit stack.\n *\n * @default - None.\n */\n readonly tags?: Tag[];\n\n /**\n * Whether the stacks created by the bootstrap process should be protected from termination.\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html\n * @default true\n */\n readonly terminationProtection?: boolean;\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n usePreviousParameters?: boolean;\n}\n\n/**\n * Parameters for the bootstrapping template\n */\nexport interface BootstrappingParameters {\n /**\n * The name to be given to the CDK Bootstrap bucket.\n *\n * @default - a name is generated by CloudFormation.\n */\n readonly bucketName?: string;\n\n /**\n * The ID of an existing KMS key to be used for encrypting items in the bucket.\n *\n * @default - use the default KMS key or create a custom one\n */\n readonly kmsKeyId?: string;\n\n /**\n * Whether or not to create a new customer master key (CMK)\n *\n * Only applies to modern bootstrapping. Legacy bootstrapping will never create\n * a CMK, only use the default S3 key.\n *\n * @default false\n */\n readonly createCustomerMasterKey?: boolean;\n\n /**\n * The list of AWS account IDs that are trusted to deploy into the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can deploy into this environment\n */\n readonly trustedAccounts?: string[];\n\n /**\n * The list of AWS account IDs that are trusted to look up values in the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can look up values in this environment\n */\n readonly trustedAccountsForLookup?: string[];\n\n /**\n * The list of AWS account IDs that should not be trusted by the bootstrapped environment.\n * If these accounts are already trusted, they will be removed on bootstrapping.\n *\n * @default - no account will be untrusted.\n */\n readonly untrustedAccounts?: string[];\n\n /**\n * The ARNs of the IAM managed policies that should be attached to the role performing CloudFormation deployments.\n * In most cases, this will be the AdministratorAccess policy.\n * At least one policy is required if `trustedAccounts` were passed.\n *\n * @default - the role will have no policies attached\n */\n readonly cloudFormationExecutionPolicies?: string[];\n\n /**\n * Identifier to distinguish multiple bootstrapped environments\n *\n * @default - Default qualifier\n */\n readonly qualifier?: string;\n\n /**\n * Whether or not to enable S3 Staging Bucket Public Access Block Configuration\n *\n * @default true\n */\n readonly publicAccessBlockConfiguration?: boolean;\n\n /**\n * Flag for using the default permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly examplePermissionsBoundary?: boolean;\n\n /**\n * Name for the customer's custom permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly customPermissionsBoundary?: string;\n}\n", "import type { Environment } from '@aws-cdk/cx-api';\nimport { debug, warn } from '../../cli/messages';\nimport { Notices } from '../../notices';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK } from '../aws-auth';\nimport { type EcrRepositoryInfo, ToolkitInfo } from '../toolkit-info';\n\n/**\n * Registry class for `EnvironmentResources`.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResourcesRegistry {\n private readonly cache = new Map<string, EnvironmentCache>();\n\n constructor(private readonly toolkitStackName?: string) {\n }\n\n public for(resolvedEnvironment: Environment, sdk: SDK, msg: IoMessaging) {\n const key = `${resolvedEnvironment.account}:${resolvedEnvironment.region}`;\n let envCache = this.cache.get(key);\n if (!envCache) {\n envCache = emptyCache();\n this.cache.set(key, envCache);\n }\n return new EnvironmentResources(resolvedEnvironment, sdk, msg, envCache, this.toolkitStackName);\n }\n}\n\n/**\n * Interface with the account and region we're deploying into\n *\n * Manages lookups for bootstrapped resources, falling back to the legacy \"CDK Toolkit\"\n * original bootstrap stack if necessary.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResources {\n constructor(\n public readonly environment: Environment,\n private readonly sdk: SDK,\n private readonly msg: IoMessaging,\n private readonly cache: EnvironmentCache,\n private readonly toolkitStackName?: string,\n ) {\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit() {\n if (!this.cache.toolkitInfo) {\n this.cache.toolkitInfo = await ToolkitInfo.lookup(this.environment, this.sdk, this.msg, this.toolkitStackName);\n }\n return this.cache.toolkitInfo;\n }\n\n /**\n * Validate that the bootstrap stack version matches or exceeds the expected version\n *\n * Use the SSM parameter name to read the version number if given, otherwise use the version\n * discovered on the bootstrap stack.\n *\n * Pass in the SSM parameter name so we can cache the lookups an don't need to do the same\n * lookup again and again for every artifact.\n */\n public async validateVersion(expectedVersion: number | undefined, ssmParameterName: string | undefined) {\n if (expectedVersion === undefined) {\n // No requirement\n return;\n }\n const defExpectedVersion = expectedVersion;\n\n if (ssmParameterName !== undefined) {\n try {\n doValidate(await this.versionFromSsmParameter(ssmParameterName), this.environment);\n return;\n } catch (e: any) {\n if (e.name !== 'AccessDeniedException') {\n throw e;\n }\n\n // This is a fallback! The bootstrap template that goes along with this change introduces\n // a new 'ssm:GetParameter' permission, but when run using the previous bootstrap template we\n // won't have the permissions yet to read the version, so we won't be able to show the\n // message telling the user they need to update! When we see an AccessDeniedException, fall\n // back to the version we read from Stack Outputs; but ONLY if the version we discovered via\n // outputs is legitimately an old version. If it's newer than that, something else must be broken,\n // so let it fail as it would if we didn't have this fallback.\n const bootstrapStack = await this.lookupToolkit();\n if (bootstrapStack.found && bootstrapStack.version < BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER) {\n await this.msg.ioHost.notify(warn(\n this.msg.action,\n `Could not read SSM parameter ${ssmParameterName}: ${formatErrorMessage(e)}, falling back to version from ${bootstrapStack}`,\n ));\n doValidate(bootstrapStack.version, this.environment);\n return;\n }\n\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', but during the confirmation via SSM parameter ${ssmParameterName} the following error occurred: ${e}`,\n );\n }\n }\n\n // No SSM parameter\n const bootstrapStack = await this.lookupToolkit();\n doValidate(bootstrapStack.version, this.environment);\n\n function doValidate(version: number, environment: Environment) {\n const notices = Notices.get();\n if (notices) {\n // if `Notices` hasn't been initialized there is probably a good\n // reason for it. handle gracefully.\n notices.addBootstrappedEnvironment({ bootstrapStackVersion: version, environment });\n }\n if (defExpectedVersion > version) {\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', found '${version}'. Please run 'cdk bootstrap'.`,\n );\n }\n }\n }\n\n /**\n * Read a version from an SSM parameter, cached\n */\n public async versionFromSsmParameter(parameterName: string): Promise<number> {\n const existing = this.cache.ssmParameters.get(parameterName);\n if (existing !== undefined) {\n return existing;\n }\n\n const ssm = this.sdk.ssm();\n\n try {\n const result = await ssm.getParameter({ Name: parameterName });\n\n const asNumber = parseInt(`${result.Parameter?.Value}`, 10);\n if (isNaN(asNumber)) {\n throw new ToolkitError(`SSM parameter ${parameterName} not a number: ${result.Parameter?.Value}`);\n }\n\n this.cache.ssmParameters.set(parameterName, asNumber);\n return asNumber;\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n throw new ToolkitError(\n `SSM parameter ${parameterName} not found. Has the environment been bootstrapped? Please run \\'cdk bootstrap\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n throw e;\n }\n }\n\n public async prepareEcrRepository(repositoryName: string): Promise<EcrRepositoryInfo> {\n if (!this.sdk) {\n throw new ToolkitError('ToolkitInfo needs to have been initialized with an sdk to call prepareEcrRepository');\n }\n const ecr = this.sdk.ecr();\n\n // check if repo already exists\n try {\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: checking if ECR repository already exists`));\n const describeResponse = await ecr.describeRepositories({\n repositoryNames: [repositoryName],\n });\n const existingRepositoryUri = describeResponse.repositories![0]?.repositoryUri;\n if (existingRepositoryUri) {\n return { repositoryUri: existingRepositoryUri };\n }\n } catch (e: any) {\n if (e.name !== 'RepositoryNotFoundException') {\n throw e;\n }\n }\n\n // create the repo (tag it so it will be easier to garbage collect in the future)\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: creating ECR repository`));\n const assetTag = { Key: 'awscdk:asset', Value: 'true' };\n const response = await ecr.createRepository({\n repositoryName,\n tags: [assetTag],\n });\n const repositoryUri = response.repository?.repositoryUri;\n if (!repositoryUri) {\n throw new ToolkitError(`CreateRepository did not return a repository URI for ${repositoryUri}`);\n }\n\n // configure image scanning on push (helps in identifying software vulnerabilities, no additional charge)\n await this.msg.ioHost.notify(debug(this.msg.action, `${repositoryName}: enable image scanning`));\n await ecr.putImageScanningConfiguration({\n repositoryName,\n imageScanningConfiguration: { scanOnPush: true },\n });\n\n return { repositoryUri };\n }\n}\n\nexport class NoBootstrapStackEnvironmentResources extends EnvironmentResources {\n constructor(environment: Environment, sdk: SDK, msg: IoMessaging) {\n super(environment, sdk, msg, emptyCache());\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit(): Promise<ToolkitInfo> {\n throw new ToolkitError(\n 'Trying to perform an operation that requires a bootstrap stack; you should not see this error, this is a bug in the CDK CLI.',\n );\n }\n}\n\n/**\n * Data that is cached on a per-environment level\n *\n * This cache may be shared between different instances of the `EnvironmentResources` class.\n */\ninterface EnvironmentCache {\n readonly ssmParameters: Map<string, number>;\n toolkitInfo?: ToolkitInfo;\n}\n\nfunction emptyCache(): EnvironmentCache {\n return {\n ssmParameters: new Map(),\n toolkitInfo: undefined,\n };\n}\n\n/**\n * The bootstrap template version that introduced ssm:GetParameter\n */\nconst BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER = 5;\n", "import { type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { Branded } from '../../util/type-brands';\nimport type { SdkProvider } from '../aws-auth/sdk-provider';\nimport { Mode } from '../plugin/mode';\n\n/**\n * Replace the {ACCOUNT} and {REGION} placeholders in all strings found in a complex object.\n */\nexport async function replaceEnvPlaceholders<A extends Record<string, string | undefined>>(\n object: A,\n env: Environment,\n sdkProvider: SdkProvider,\n): Promise<{[k in keyof A]: StringWithoutPlaceholders | undefined}> {\n return EnvironmentPlaceholders.replaceAsync(object, {\n accountId: () => Promise.resolve(env.account),\n region: () => Promise.resolve(env.region),\n partition: async () => {\n // There's no good way to get the partition!\n // We should have had it already, except we don't.\n //\n // Best we can do is ask the \"base credentials\" for this environment for their partition. Cross-partition\n // AssumeRole'ing will never work anyway, so this answer won't be wrong (it will just be slow!)\n return (await sdkProvider.baseCredentialsPartition(env, Mode.ForReading)) ?? 'aws';\n },\n });\n}\n\nexport type StringWithoutPlaceholders = Branded<string, 'NoPlaceholders'>;\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { SDK } from '../aws-auth';\nimport { EnvironmentResources, EnvironmentResourcesRegistry } from './environment-resources';\nimport { warn } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { formatErrorMessage } from '../../util/format-error';\nimport { CredentialsOptions, SdkForEnvironment, SdkProvider } from '../aws-auth/sdk-provider';\nimport { Mode } from '../plugin/mode';\nimport { replaceEnvPlaceholders, StringWithoutPlaceholders } from '../util/placeholders';\n\n/**\n * Access particular AWS resources, based on information from the CX manifest\n *\n * It is not possible to grab direct access to AWS credentials; 9 times out of 10\n * we have to allow for role assumption, and role assumption can only work if\n * there is a CX Manifest that contains a role ARN.\n *\n * This class exists so new code isn't tempted to go and get SDK credentials directly.\n */\nexport class EnvironmentAccess {\n private readonly sdkCache = new Map<string, SdkForEnvironment>();\n private readonly environmentResources: EnvironmentResourcesRegistry;\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n constructor(private readonly sdkProvider: SdkProvider, toolkitStackName: string, { ioHost, action }: IoMessaging) {\n this.environmentResources = new EnvironmentResourcesRegistry(toolkitStackName);\n this.ioHost = ioHost;\n this.action = action;\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveStackEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.sdkProvider.resolveEnvironment(stack.environment);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for readonly credentials if available, use the default\n * AWS credentials if not.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForReadOnlyStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for mutating credentials if available, use the default AWS\n * credentials if not. The `mode` parameter is only used for querying\n * plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForMutableStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForWriting);\n }\n\n /**\n * Get an SDK to access the given stack's environment for environmental lookups\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the lookup role if configured on the stack. Check the default `lookup-role`\n * policies to see what you can do with this role. It can generally read everything\n * in the account that does not require KMS access.\n *\n * ---\n *\n * For backwards compatibility reasons, there are some scenarios that are handled here:\n *\n * 1. The lookup role may not exist (it was added in bootstrap stack version 7). If so:\n * a. Return the default credentials if the default credentials are for the stack account\n * (you will notice this as `isFallbackCredentials=true`).\n * b. Throw an error if the default credentials are not for the stack account.\n *\n * 2. The lookup role may not have the correct permissions (for example, ReadOnlyAccess was added in\n * bootstrap stack version 8); the stack will have a minimum version number on it.\n * a. If it does not we throw an error which should be handled in the calling\n * function (and fallback to use a different role, etc)\n *\n * Upon success, caller will have an SDK for the right account, which may or may not have\n * the right permissions.\n */\n public async accessStackForLookup(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n const lookupEnv = await this.prepareSdk({\n environment: stack.environment,\n mode: Mode.ForReading,\n assumeRoleArn: stack.lookupRole?.arn,\n assumeRoleExternalId: stack.lookupRole?.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.lookupRole?.assumeRoleAdditionalOptions,\n });\n\n // if we succeed in assuming the lookup role, make sure we have the correct bootstrap stack version\n if (lookupEnv.didAssumeRole && stack.lookupRole?.bootstrapStackVersionSsmParameter && stack.lookupRole.requiresBootstrapStackVersion) {\n const version = await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);\n if (version < stack.lookupRole.requiresBootstrapStackVersion) {\n throw new ToolkitError(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`);\n }\n }\n if (lookupEnv.isFallbackCredentials) {\n const arn = await lookupEnv.replacePlaceholders(stack.lookupRole?.arn);\n await this.ioHost.notify(warn(this.action, `Lookup role ${arn} was not assumed. Proceeding with default credentials.`));\n }\n return lookupEnv;\n }\n\n /**\n * Get an SDK to access the given stack's environment for reading stack attributes\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will try to assume the lookup role if given, will use the regular stack operations\n * access (deploy-role) otherwise. When calling this, you should assume that you will get\n * the least privileged role, so don't try to use it for anything the `deploy-role`\n * wouldn't be able to do. Also you cannot rely on being able to read encrypted anything.\n */\n public async accessStackForLookupBestEffort(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n try {\n return await this.accessStackForLookup(stack);\n } catch (e: any) {\n await this.ioHost.notify(warn(this.action, `${formatErrorMessage(e)}`));\n }\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n private async accessStackForStackOperations(stack: cxapi.CloudFormationStackArtifact, mode: Mode): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n return this.prepareSdk({\n environment: stack.environment,\n mode,\n assumeRoleArn: stack.assumeRoleArn,\n assumeRoleExternalId: stack.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.assumeRoleAdditionalOptions,\n });\n }\n\n /**\n * Prepare an SDK for use in the given environment and optionally with a role assumed.\n */\n private async prepareSdk(\n options: PrepareSdkRoleOptions,\n ): Promise<TargetEnvironment> {\n const resolvedEnvironment = await this.sdkProvider.resolveEnvironment(options.environment);\n\n // Substitute any placeholders with information about the current environment\n const { assumeRoleArn } = await replaceEnvPlaceholders({\n assumeRoleArn: options.assumeRoleArn,\n }, resolvedEnvironment, this.sdkProvider);\n\n const stackSdk = await this.cachedSdkForEnvironment(resolvedEnvironment, options.mode, {\n assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n });\n\n return {\n sdk: stackSdk.sdk,\n resolvedEnvironment,\n resources: this.environmentResources.for(resolvedEnvironment, stackSdk.sdk, { ioHost: this.ioHost, action: this.action }),\n // If we asked for a role, did not successfully assume it, and yet got here without an exception: that\n // means we must have fallback credentials.\n isFallbackCredentials: !stackSdk.didAssumeRole && !!assumeRoleArn,\n didAssumeRole: stackSdk.didAssumeRole,\n replacePlaceholders: async <A extends string | undefined>(str: A) => {\n const ret = await replaceEnvPlaceholders({ str }, resolvedEnvironment, this.sdkProvider);\n return ret.str;\n },\n };\n }\n\n private async cachedSdkForEnvironment(\n environment: cxapi.Environment,\n mode: Mode,\n options?: CredentialsOptions,\n ) {\n const cacheKeyElements = [\n environment.account,\n environment.region,\n `${mode}`,\n options?.assumeRoleArn ?? '',\n options?.assumeRoleExternalId ?? '',\n ];\n\n if (options?.assumeRoleAdditionalOptions) {\n cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions));\n }\n\n const cacheKey = cacheKeyElements.join(':');\n const existing = this.sdkCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n const ret = await this.sdkProvider.forEnvironment(environment, mode, options);\n this.sdkCache.set(cacheKey, ret);\n return ret;\n }\n}\n\n/**\n * SDK obtained by assuming the deploy role\n * for a given environment\n */\nexport interface TargetEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The resolved environment for the stack\n * (no more 'unknown-account/unknown-region')\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * Access class for environmental resources to help the deployment\n */\n readonly resources: EnvironmentResources;\n\n /**\n * Whether or not we assumed a role in the process of getting these credentials\n */\n readonly didAssumeRole: boolean;\n\n /**\n * Whether or not these are fallback credentials\n *\n * Fallback credentials means that assuming the intended role failed, but the\n * base credentials happen to be for the right account so we just picked those\n * and hope the future SDK calls succeed.\n *\n * This is a backwards compatibility mechanism from around the time we introduced\n * deployment roles.\n */\n readonly isFallbackCredentials: boolean;\n\n /**\n * Replace environment placeholders according to the current environment\n */\n replacePlaceholders(x: string | undefined): Promise<StringWithoutPlaceholders | undefined>;\n}\n\ninterface PrepareSdkRoleOptions {\n readonly environment: cxapi.Environment;\n readonly mode: Mode;\n readonly assumeRoleArn?: string;\n readonly assumeRoleExternalId?: string;\n readonly assumeRoleAdditionalOptions?: { [key: string]: any };\n}\n", "import { ToolkitError } from '../../toolkit/error';\n\nexport type DeployStackResult =\n | SuccessfulDeployStackResult\n | NeedRollbackFirstDeployStackResult\n | ReplacementRequiresRollbackStackResult\n ;\n\n/** Successfully deployed a stack */\nexport interface SuccessfulDeployStackResult {\n readonly type: 'did-deploy-stack';\n readonly noOp: boolean;\n readonly outputs: { [name: string]: string };\n readonly stackArn: string;\n}\n\n/** The stack is currently in a failpaused state, and needs to be rolled back before the deployment */\nexport interface NeedRollbackFirstDeployStackResult {\n readonly type: 'failpaused-need-rollback-first';\n readonly reason: 'not-norollback' | 'replacement';\n readonly status: string;\n}\n\n/** The upcoming change has a replacement, which requires deploying with --rollback */\nexport interface ReplacementRequiresRollbackStackResult {\n readonly type: 'replacement-requires-rollback';\n}\n\nexport function assertIsSuccessfulDeployStackResult(x: DeployStackResult): asserts x is SuccessfulDeployStackResult {\n if (x.type !== 'did-deploy-stack') {\n throw new ToolkitError(`Unexpected deployStack result. This should not happen: ${JSON.stringify(x)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose.`);\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\n/**\n * @returns an array with the tags available in the stack metadata.\n */\nexport function tagsForStack(stack: cxapi.CloudFormationStackArtifact): Tag[] {\n return Object.entries(stack.tags).map(([Key, Value]) => ({ Key, Value }));\n}\n\nexport interface Tag {\n readonly Key: string;\n readonly Value: string;\n}\n", "import { format } from 'util';\nimport * as cfnDiff from '@aws-cdk/cloudformation-diff';\nimport { ResourceDifference } from '@aws-cdk/cloudformation-diff';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as promptly from 'promptly';\nimport { error, info, warn } from '../../cli/messages';\nimport { IIoHost, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { assertIsSuccessfulDeployStackResult, type Deployments, DeploymentMethod, ResourceIdentifierProperties, ResourcesToImport } from '../deployments';\nimport type { Tag } from '../tags';\n\nexport interface ResourceImporterProps {\n deployments: Deployments;\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\nexport interface ImportDeploymentOptions {\n /**\n * Role to pass to CloudFormation for deployment\n *\n * @default - Default stack role\n */\n readonly roleArn?: string;\n\n /**\n * Deployment method\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Stack tags (pass through to CloudFormation)\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n}\n\n/**\n * Set of parameters that uniquely identify a physical resource of a given type\n * for the import operation, example:\n *\n * ```\n * {\n * \"AWS::S3::Bucket\": [[\"BucketName\"]],\n * \"AWS::DynamoDB::GlobalTable\": [[\"TableName\"], [\"TableArn\"], [\"TableStreamArn\"]],\n * \"AWS::Route53::KeySigningKey\": [[\"HostedZoneId\", \"Name\"]],\n * }\n * ```\n */\nexport type ResourceIdentifiers = { [resourceType: string]: string[][] };\n\n/**\n * Mapping of CDK resources (L1 constructs) to physical resources to be imported\n * in their place, example:\n *\n * ```\n * {\n * \"MyStack/MyS3Bucket/Resource\": {\n * \"BucketName\": \"my-manually-created-s3-bucket\"\n * },\n * \"MyStack/MyVpc/Resource\": {\n * \"VpcId\": \"vpc-123456789\"\n * }\n * }\n * ```\n */\nexport type ResourceMap = { [logicalResource: string]: ResourceIdentifierProperties };\n\n/**\n * Resource importing utility class\n *\n * - Determines the resources added to a template (compared to the deployed version)\n * - Look up the identification information\n * - Load them from a file, or\n * - Ask the user, based on information supplied to us by CloudFormation's GetTemplateSummary\n * - Translate the input to a structure expected by CloudFormation, update the template to add the\n * importable resources, then run an IMPORT changeset.\n */\nexport class ResourceImporter {\n private _currentTemplate: any;\n\n private readonly stack: cxapi.CloudFormationStackArtifact;\n private readonly cfn: Deployments;\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n constructor(\n stack: cxapi.CloudFormationStackArtifact,\n props: ResourceImporterProps,\n ) {\n this.stack = stack;\n this.cfn = props.deployments;\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n /**\n * Ask the user for resources to import\n */\n public async askForResourceIdentifiers(available: ImportableResource[]): Promise<ImportMap> {\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n const resourceIdentifiers = await this.resourceIdentifiers();\n\n for (const resource of available) {\n const identifier = await this.askForResourceIdentifier(resourceIdentifiers, resource);\n if (!identifier) {\n continue;\n }\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = identifier;\n }\n\n return ret;\n }\n\n /**\n * Load the resources to import from a file\n */\n public async loadResourceIdentifiers(available: ImportableResource[], filename: string): Promise<ImportMap> {\n const contents = await fs.readJson(filename);\n\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n for (const resource of available) {\n const descr = this.describeResource(resource.logicalId);\n const idProps = contents[resource.logicalId];\n if (idProps) {\n await this.ioHost.notify(info(this.action, format('%s: importing using %s', chalk.blue(descr), chalk.blue(fmtdict(idProps)))));\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = idProps;\n delete contents[resource.logicalId];\n } else {\n await this.ioHost.notify(info(this.action, format('%s: skipping', chalk.blue(descr))));\n }\n }\n\n const unknown = Object.keys(contents);\n if (unknown.length > 0) {\n await this.ioHost.notify(warn(this.action, `Unrecognized resource identifiers in mapping file: ${unknown.join(', ')}`));\n }\n\n return ret;\n }\n\n /**\n * Based on the provided resource mapping, prepare CFN structures for import (template,\n * ResourcesToImport structure) and perform the import operation (CloudFormation deployment)\n *\n * @param importMap Mapping from CDK construct tree path to physical resource import identifiers\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMap(importMap: ImportMap, options: ImportDeploymentOptions = {}) {\n const resourcesToImport: ResourcesToImport = await this.makeResourcesToImport(importMap);\n const updatedTemplate = await this.currentTemplateWithAdditions(importMap.importResources);\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n /**\n * Based on the app and resources file generated by cdk migrate. Removes all items from the template that\n * cannot be included in an import change-set for new stacks and performs the import operation,\n * creating the new stack.\n *\n * @param resourcesToImport The mapping created by cdk migrate\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMigrate(resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions = {}) {\n const updatedTemplate = this.removeNonImportResources();\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n private async importResources(overrideTemplate: any, resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions) {\n try {\n const result = await this.cfn.deployStack({\n stack: this.stack,\n deployName: this.stack.stackName,\n ...options,\n overrideTemplate,\n resourcesToImport,\n });\n\n assertIsSuccessfulDeployStackResult(result);\n\n const message = result.noOp\n ? ' \u2705 %s (no changes)'\n : ' \u2705 %s';\n\n await this.ioHost.notify(info(this.action, '\\n' + chalk.green(format(message, this.stack.displayName))));\n } catch (e) {\n await this.ioHost.notify(error(this.action, format('\\n \u274C %s failed: %s', chalk.bold(this.stack.displayName), e), 'CDK_TOOLKIT_E3900'));\n throw e;\n }\n }\n\n /**\n * Perform a diff between the currently running and the new template, ensure that it is valid\n * for importing and return a list of resources that are being added in the new version\n *\n * @return mapping logicalResourceId -> resourceDifference\n */\n public async discoverImportableResources(allowNonAdditions = false): Promise<DiscoverImportableResourcesResult> {\n const currentTemplate = await this.currentTemplate();\n\n const diff = cfnDiff.fullDiff(currentTemplate, this.stack.template);\n\n // Ignore changes to CDKMetadata\n const resourceChanges = Object.entries(diff.resources.changes)\n .filter(([logicalId, _]) => logicalId !== 'CDKMetadata');\n\n // Split the changes into additions and non-additions. Imports only make sense\n // for newly-added resources.\n const nonAdditions = resourceChanges.filter(([_, dif]) => !dif.isAddition);\n const additions = resourceChanges.filter(([_, dif]) => dif.isAddition);\n\n if (nonAdditions.length) {\n const offendingResources = nonAdditions.map(([logId, _]) => this.describeResource(logId));\n\n if (allowNonAdditions) {\n await this.ioHost.notify(warn(this.action, `Ignoring updated/deleted resources (--force): ${offendingResources.join(', ')}`));\n } else {\n throw new ToolkitError('No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes ' +\n `to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(', ')} (--force to override)`);\n }\n }\n\n // Resources in the new template, that are not present in the current template, are a potential import candidates\n return {\n additions: additions.map(([logicalId, resourceDiff]) => ({\n logicalId,\n resourceDiff,\n resourceDefinition: addDefaultDeletionPolicy(this.stack.template?.Resources?.[logicalId] ?? {}),\n })),\n hasNonAdditions: nonAdditions.length > 0,\n };\n }\n\n /**\n * Resolves the environment of a stack.\n */\n public async resolveEnvironment(): Promise<cxapi.Environment> {\n return this.cfn.resolveEnvironment(this.stack);\n }\n\n /**\n * Get currently deployed template of the given stack (SINGLETON)\n *\n * @returns Currently deployed CloudFormation template\n */\n private async currentTemplate(): Promise<any> {\n if (!this._currentTemplate) {\n this._currentTemplate = await this.cfn.readCurrentTemplate(this.stack);\n }\n return this._currentTemplate;\n }\n\n /**\n * Return the current template, with the given resources added to it\n */\n private async currentTemplateWithAdditions(additions: ImportableResource[]): Promise<any> {\n const template = await this.currentTemplate();\n if (!template.Resources) {\n template.Resources = {};\n }\n\n for (const add of additions) {\n template.Resources[add.logicalId] = add.resourceDefinition;\n }\n\n return template;\n }\n\n /**\n * Get a list of import identifiers for all resource types used in the given\n * template that do support the import operation (SINGLETON)\n *\n * @returns a mapping from a resource type to a list of property names that together identify the resource for import\n */\n private async resourceIdentifiers(): Promise<ResourceIdentifiers> {\n const ret: ResourceIdentifiers = {};\n const resourceIdentifierSummaries = await this.cfn.resourceIdentifierSummaries(this.stack);\n for (const summary of resourceIdentifierSummaries) {\n if ('ResourceType' in summary && summary.ResourceType && 'ResourceIdentifiers' in summary && summary.ResourceIdentifiers) {\n ret[summary.ResourceType] = (summary.ResourceIdentifiers ?? [])?.map(x => x.split(','));\n }\n }\n return ret;\n }\n\n /**\n * Ask for the importable identifier for the given resource\n *\n * There may be more than one identifier under which a resource can be imported. The `import`\n * operation needs exactly one of them.\n *\n * - If we can get one from the template, we will use one.\n * - Otherwise, we will ask the user for one of them.\n */\n private async askForResourceIdentifier(\n resourceIdentifiers: ResourceIdentifiers,\n chg: ImportableResource,\n ): Promise<ResourceIdentifierProperties | undefined> {\n const resourceName = this.describeResource(chg.logicalId);\n\n // Skip resources that do not support importing\n const resourceType = chg.resourceDiff.newResourceType;\n if (resourceType === undefined || !(resourceType in resourceIdentifiers)) {\n await this.ioHost.notify(warn(this.action, `${resourceName}: unsupported resource type ${resourceType}, skipping import.`));\n return undefined;\n }\n\n const idPropSets = resourceIdentifiers[resourceType];\n\n // Retain only literal strings: strip potential CFN intrinsics\n const resourceProps = Object.fromEntries(Object.entries(chg.resourceDefinition.Properties ?? {})\n .filter(([_, v]) => typeof v === 'string')) as Record<string, string>;\n\n // Find property sets that are fully satisfied in the template, ask the user to confirm them\n const satisfiedPropSets = idPropSets.filter(ps => ps.every(p => resourceProps[p]));\n for (const satisfiedPropSet of satisfiedPropSets) {\n const candidateProps = Object.fromEntries(satisfiedPropSet.map(p => [p, resourceProps[p]]));\n const displayCandidateProps = fmtdict(candidateProps);\n\n if (await promptly.confirm(\n `${chalk.blue(resourceName)} (${resourceType}): import with ${chalk.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,\n { default: 'yes' },\n )) {\n return candidateProps;\n }\n }\n\n // If we got here and the user rejected any available identifiers, then apparently they don't want the resource at all\n if (satisfiedPropSets.length > 0) {\n await this.ioHost.notify(info(this.action, chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n // We cannot auto-import this, ask the user for one of the props\n // The only difference between these cases is what we print: for multiple properties, we print a preamble\n const prefix = `${chalk.blue(resourceName)} (${resourceType})`;\n let preamble;\n let promptPattern;\n if (idPropSets.length > 1) {\n preamble = `${prefix}: enter one of ${idPropSets.map(x => chalk.blue(x.join('+'))).join(', ')} to import (all empty to skip)`;\n promptPattern = `${prefix}: enter %`;\n } else {\n promptPattern = `${prefix}: enter %`;\n }\n\n // Do the input loop here\n if (preamble) {\n await this.ioHost.notify(info(this.action, preamble));\n }\n for (const idProps of idPropSets) {\n const input: Record<string, string> = {};\n for (const idProp of idProps) {\n // If we have a value from the template, use it as default. This will only be a partial\n // identifier if present, otherwise we would have done the import already above.\n const defaultValue = resourceProps[idProp] ?? '';\n\n const prompt = [\n promptPattern.replace(/%/g, chalk.blue(idProp)),\n defaultValue\n ? `[${defaultValue}]`\n : '(empty to skip)',\n ].join(' ') + ':';\n const response = await promptly.prompt(prompt,\n { default: defaultValue, trim: true },\n );\n\n if (!response) {\n break;\n }\n\n input[idProp] = response;\n // Also stick this property into 'resourceProps', so that it may be reused by a subsequent question\n // (for a different compound identifier that involves the same property). Just a small UX enhancement.\n resourceProps[idProp] = response;\n }\n\n // If the user gave inputs for all values, we are complete\n if (Object.keys(input).length === idProps.length) {\n return input;\n }\n }\n\n await this.ioHost.notify(info(this.action, chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n /**\n * Convert the internal \"resource mapping\" structure to CloudFormation accepted \"ResourcesToImport\" structure\n */\n private async makeResourcesToImport(resourceMap: ImportMap): Promise<ResourcesToImport> {\n return resourceMap.importResources.map(res => ({\n LogicalResourceId: res.logicalId,\n ResourceType: res.resourceDiff.newResourceType!,\n ResourceIdentifier: resourceMap.resourceMap[res.logicalId],\n }));\n }\n\n /**\n * Convert CloudFormation logical resource ID to CDK construct tree path\n *\n * @param logicalId CloudFormation logical ID of the resource (the key in the template's Resources section)\n * @returns Forward-slash separated path of the resource in CDK construct tree, e.g. MyStack/MyBucket/Resource\n */\n private describeResource(logicalId: string): string {\n return this.stack.template?.Resources?.[logicalId]?.Metadata?.['aws:cdk:path'] ?? logicalId;\n }\n\n /**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\n private removeNonImportResources() {\n return removeNonImportResources(this.stack);\n }\n}\n\n/**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\nexport function removeNonImportResources(stack: cxapi.CloudFormationStackArtifact) {\n const template = stack.template;\n delete template.Resources.CDKMetadata;\n delete template.Outputs;\n return template;\n}\n\n/**\n * Information about a resource in the template that is importable\n */\nexport interface ImportableResource {\n /**\n * The logical ID of the resource\n */\n readonly logicalId: string;\n\n /**\n * The resource definition in the new template\n */\n readonly resourceDefinition: any;\n\n /**\n * The diff as reported by `cloudformation-diff`.\n */\n readonly resourceDiff: ResourceDifference;\n}\n\n/**\n * The information necessary to execute an import operation\n */\nexport interface ImportMap {\n /**\n * Mapping logical IDs to physical names\n */\n readonly resourceMap: ResourceMap;\n\n /**\n * The selection of resources we are actually importing\n *\n * For each of the resources in this list, there is a corresponding entry in\n * the `resourceMap` map.\n */\n readonly importResources: ImportableResource[];\n}\n\nfunction fmtdict<A>(xs: Record<string, A>) {\n return Object.entries(xs).map(([k, v]) => `${k}=${v}`).join(', ');\n}\n\n/**\n * Add a default `DeletionPolicy` policy.\n * The default value is set to 'Retain', to lower risk of unintentionally\n * deleting stateful resources in the process of importing to CDK.\n */\nfunction addDefaultDeletionPolicy(resource: any): any {\n if (resource.DeletionPolicy) {\n return resource;\n }\n\n return {\n ...resource,\n DeletionPolicy: 'Retain',\n };\n}\n\nexport interface DiscoverImportableResourcesResult {\n readonly additions: ImportableResource[];\n readonly hasNonAdditions: boolean;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport { ImportDeploymentOptions, ResourceImporter } from './importer';\nimport { info } from '../../cli/messages';\nimport type { IIoHost, ToolkitAction } from '../../toolkit/cli-io-host';\nimport { formatTime } from '../../util/string-manipulation';\nimport { StackCollection } from '../cxapp/cloud-assembly';\nimport type { Deployments, ResourcesToImport } from '../deployments';\n\nexport interface ResourceMigratorProps {\n deployments: Deployments;\n ioHost: IIoHost;\n action: ToolkitAction;\n}\n\nexport class ResourceMigrator {\n private readonly props: ResourceMigratorProps;\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n public constructor(props: ResourceMigratorProps) {\n this.props = props;\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n /**\n * Checks to see if a migrate.json file exists. If it does and the source is either `filepath` or\n * is in the same environment as the stack deployment, a new stack is created and the resources are\n * migrated to the stack using an IMPORT changeset. The normal deployment will resume after this is complete\n * to add back in any outputs and the CDKMetadata.\n */\n public async tryMigrateResources(stacks: StackCollection, options: ImportDeploymentOptions): Promise<void> {\n const stack = stacks.stackArtifacts[0];\n const migrateDeployment = new ResourceImporter(stack, {\n deployments: this.props.deployments,\n ioHost: this.ioHost,\n action: this.action,\n });\n const resourcesToImport = await this.tryGetResources(await migrateDeployment.resolveEnvironment());\n\n if (resourcesToImport) {\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: creating stack for resource migration...`));\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: importing resources into stack...`));\n\n await this.performResourceMigration(migrateDeployment, resourcesToImport, options);\n\n fs.rmSync('migrate.json');\n await this.ioHost.notify(info(this.action, `${chalk.bold(stack.displayName)}: applying CDKMetadata and Outputs to stack (if applicable)...`));\n }\n }\n\n /**\n * Creates a new stack with just the resources to be migrated\n */\n private async performResourceMigration(\n migrateDeployment: ResourceImporter,\n resourcesToImport: ResourcesToImport,\n options: ImportDeploymentOptions,\n ) {\n const startDeployTime = new Date().getTime();\n let elapsedDeployTime = 0;\n\n // Initial Deployment\n await migrateDeployment.importResourcesFromMigrate(resourcesToImport, {\n roleArn: options.roleArn,\n deploymentMethod: options.deploymentMethod,\n usePreviousParameters: true,\n rollback: options.rollback,\n });\n\n elapsedDeployTime = new Date().getTime() - startDeployTime;\n await this.ioHost.notify(info(this.action, `'\\n\u2728 Resource migration time: ${formatTime(elapsedDeployTime)}s\\n'`, 'CDK_TOOLKIT_I5002', {\n duration: elapsedDeployTime,\n }));\n }\n\n public async tryGetResources(environment: cxapi.Environment): Promise<ResourcesToImport | undefined> {\n try {\n const migrateFile = fs.readJsonSync('migrate.json', {\n encoding: 'utf-8',\n });\n const sourceEnv = (migrateFile.Source as string).split(':');\n if (\n sourceEnv[0] === 'localfile' ||\n (sourceEnv[4] === environment.account && sourceEnv[3] === environment.region)\n ) {\n return migrateFile.Resources;\n }\n } catch (e) {\n // Nothing to do\n }\n\n return undefined;\n }\n}\n\n", "import * as util from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { info, error } from '../../logging';\nimport { flatten } from '../../util/arrays';\nimport type { SDK } from '../aws-auth';\n\n/**\n * After reading events from all CloudWatch log groups\n * how long should we wait to read more events.\n *\n * If there is some error with reading events (i.e. Throttle)\n * then this is also how long we wait until we try again\n */\nconst SLEEP = 2_000;\n\n/**\n * Represents a CloudWatch Log Event that will be\n * printed to the terminal\n */\ninterface CloudWatchLogEvent {\n /**\n * The log event message\n */\n readonly message: string;\n\n /**\n * The name of the log group\n */\n readonly logGroupName: string;\n\n /**\n * The time at which the event occurred\n */\n readonly timestamp: Date;\n}\n\n/**\n * Configuration tracking information on the log groups that are\n * being monitored\n */\ninterface LogGroupsAccessSettings {\n /**\n * The SDK for a given environment (account/region)\n */\n readonly sdk: SDK;\n\n /**\n * A map of log groups and associated startTime in a given account.\n *\n * The monitor will read events from the log group starting at the\n * associated startTime\n */\n readonly logGroupsStartTimes: { [logGroupName: string]: number };\n}\n\nexport class CloudWatchLogEventMonitor {\n /**\n * Determines which events not to display\n */\n private startTime: number;\n\n /**\n * Map of environment (account:region) to LogGroupsAccessSettings\n */\n private readonly envsLogGroupsAccessSettings = new Map<string, LogGroupsAccessSettings>();\n\n private active = false;\n\n constructor(startTime?: Date) {\n this.startTime = startTime?.getTime() ?? Date.now();\n }\n\n /**\n * resume reading/printing events\n */\n public activate(): void {\n this.active = true;\n this.scheduleNextTick(0);\n }\n\n /**\n * deactivates the monitor so no new events are read\n * use case for this is when we are in the middle of performing a deployment\n * and don't want to interweave all the logs together with the CFN\n * deployment logs\n *\n * Also resets the start time to be when the new deployment was triggered\n * and clears the list of tracked log groups\n */\n public deactivate(): void {\n this.active = false;\n this.startTime = Date.now();\n this.envsLogGroupsAccessSettings.clear();\n }\n\n /**\n * Adds CloudWatch log groups to read log events from.\n * Since we could be watching multiple stacks that deploy to\n * multiple environments (account+region), we need to store a list of log groups\n * per env along with the SDK object that has access to read from\n * that environment.\n */\n public addLogGroups(env: cxapi.Environment, sdk: SDK, logGroupNames: string[]): void {\n const awsEnv = `${env.account}:${env.region}`;\n const logGroupsStartTimes = logGroupNames.reduce(\n (acc, groupName) => {\n acc[groupName] = this.startTime;\n return acc;\n },\n {} as { [logGroupName: string]: number },\n );\n this.envsLogGroupsAccessSettings.set(awsEnv, {\n sdk,\n logGroupsStartTimes: {\n ...this.envsLogGroupsAccessSettings.get(awsEnv)?.logGroupsStartTimes,\n ...logGroupsStartTimes,\n },\n });\n }\n\n private scheduleNextTick(sleep: number): void {\n setTimeout(() => void this.tick(), sleep);\n }\n\n private async tick(): Promise<void> {\n // excluding from codecoverage because this\n // doesn't always run (depends on timing)\n /* istanbul ignore next */\n if (!this.active) {\n return;\n }\n try {\n const events = flatten(await this.readNewEvents());\n events.forEach((event) => {\n this.print(event);\n });\n } catch (e) {\n error('Error occurred while monitoring logs: %s', e);\n }\n\n this.scheduleNextTick(SLEEP);\n }\n\n /**\n * Reads all new log events from a set of CloudWatch Log Groups\n * in parallel\n */\n private async readNewEvents(): Promise<Array<Array<CloudWatchLogEvent>>> {\n const promises: Array<Promise<Array<CloudWatchLogEvent>>> = [];\n for (const settings of this.envsLogGroupsAccessSettings.values()) {\n for (const group of Object.keys(settings.logGroupsStartTimes)) {\n promises.push(this.readEventsFromLogGroup(settings, group));\n }\n }\n // Limited set of log groups\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(promises);\n }\n\n /**\n * Print out a cloudwatch event\n */\n private print(event: CloudWatchLogEvent): void {\n info(\n util.format(\n '[%s] %s %s',\n chalk.blue(event.logGroupName),\n chalk.yellow(event.timestamp.toLocaleTimeString()),\n event.message.trim(),\n ),\n );\n }\n\n /**\n * Reads all new log events from a CloudWatch Log Group\n * starting at either the time the hotswap was triggered or\n * when the last event was read on the previous tick\n */\n private async readEventsFromLogGroup(\n logGroupsAccessSettings: LogGroupsAccessSettings,\n logGroupName: string,\n ): Promise<Array<CloudWatchLogEvent>> {\n const events: CloudWatchLogEvent[] = [];\n\n // log events from some service are ingested faster than others\n // so we need to track the start/end time for each log group individually\n // to make sure that we process all events from each log group\n const startTime = logGroupsAccessSettings.logGroupsStartTimes[logGroupName] ?? this.startTime;\n let endTime = startTime;\n try {\n const response = await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({\n logGroupName: logGroupName,\n limit: 100,\n startTime: startTime,\n });\n const filteredEvents = response.events ?? [];\n\n for (const event of filteredEvents) {\n if (event.message) {\n events.push({\n message: event.message,\n logGroupName,\n timestamp: event.timestamp ? new Date(event.timestamp) : new Date(),\n });\n\n if (event.timestamp && endTime < event.timestamp) {\n endTime = event.timestamp;\n }\n }\n }\n // As long as there are _any_ events in the log group `filterLogEvents` will return a nextToken.\n // This is true even if these events are before `startTime`. So if we have 100 events and a nextToken\n // then assume that we have hit the limit and let the user know some messages have been suppressed.\n // We are essentially showing them a sampling (10000 events printed out is not very useful)\n if (filteredEvents.length === 100 && response.nextToken) {\n events.push({\n message: '>>> `watch` shows only the first 100 log messages - the rest have been truncated...',\n logGroupName,\n timestamp: new Date(endTime),\n });\n }\n } catch (e: any) {\n // with Lambda functions the CloudWatch is not created\n // until something is logged, so just keep polling until\n // there is somthing to find\n if (e.name === 'ResourceNotFoundException') {\n return [];\n }\n throw e;\n }\n logGroupsAccessSettings.logGroupsStartTimes[logGroupName] = endTime + 1;\n return events;\n }\n}\n", "import type { CloudFormationStackArtifact, Environment } from '@aws-cdk/cx-api';\nimport type { StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport { debug } from '../../logging';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { formatErrorMessage } from '../../util/format-error';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport { EnvironmentAccess } from '../environment';\nimport { EvaluateCloudFormationTemplate, LazyListStackResources } from '../evaluate-cloudformation-template';\nimport { Mode } from '../plugin/mode';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\n// resource types that have associated CloudWatch Log Groups that should _not_ be monitored\nconst IGNORE_LOGS_RESOURCE_TYPES = ['AWS::EC2::FlowLog', 'AWS::CloudTrail::Trail', 'AWS::CodeBuild::Project'];\n\n/**\n * Configuration needed to monitor CloudWatch Log Groups\n * found in a given CloudFormation Stack\n */\nexport interface FoundLogGroupsResult {\n /**\n * The resolved environment (account/region) that the log\n * groups are deployed in\n */\n readonly env: Environment;\n\n /**\n * The SDK that can be used to read events from the CloudWatch\n * Log Groups in the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The names of the relevant CloudWatch Log Groups\n * in the given CloudFormation template\n */\n readonly logGroupNames: string[];\n}\n\nexport async function findCloudWatchLogGroups(\n sdkProvider: SdkProvider,\n msg: IoMessaging,\n stackArtifact: CloudFormationStackArtifact,\n): Promise<FoundLogGroupsResult> {\n let sdk: SDK;\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // try to assume the lookup role and fallback to the default credentials\n try {\n sdk = (await new EnvironmentAccess(sdkProvider, DEFAULT_TOOLKIT_STACK_NAME, msg).accessStackForLookup(stackArtifact)).sdk;\n } catch (e: any) {\n debug(`Failed to access SDK environment: ${formatErrorMessage(e)}`);\n sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForReading)).sdk;\n }\n\n const listStackResources = new LazyListStackResources(sdk, stackArtifact.stackName);\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackName: stackArtifact.stackName,\n template: stackArtifact.template,\n parameters: {},\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n });\n\n const stackResources = await listStackResources.listStackResources();\n const logGroupNames = findAllLogGroupNames(stackResources, evaluateCfnTemplate);\n\n return {\n env: resolvedEnv,\n sdk,\n logGroupNames,\n };\n}\n\n/**\n * Determine if a CloudWatch Log Group is associated\n * with an ignored resource\n */\nfunction isReferencedFromIgnoredResource(\n logGroupResource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): boolean {\n const resourcesReferencingLogGroup = evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId!);\n return resourcesReferencingLogGroup.some((reference) => {\n return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type);\n });\n}\n\ntype CloudWatchLogsResolver = (\n resource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n) => string | undefined;\n\nconst cloudWatchLogsResolvers: Record<string, CloudWatchLogsResolver> = {\n 'AWS::Logs::LogGroup': (resource, evaluateCfnTemplate) => {\n if (isReferencedFromIgnoredResource(resource, evaluateCfnTemplate)) {\n return undefined;\n }\n return resource.PhysicalResourceId?.toString();\n },\n\n // Resource types that will create a CloudWatch log group with a specific name if one is not provided.\n // The keys are CFN resource types, and the values are the name of the physical name property of that resource\n // and the service name that is used in the automatically created CloudWatch log group.\n 'AWS::Lambda::Function': (resource, evaluateCfnTemplate) => {\n const loggingConfig = evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId!, 'LoggingConfig');\n if (loggingConfig?.LogGroup) {\n // if LogGroup is a string then use it as the LogGroupName as it is referred by LogGroup.fromLogGroupArn in CDK\n if (typeof loggingConfig.LogGroup === 'string') {\n return loggingConfig.LogGroup;\n }\n\n // if { Ref: '...' } is used then try to resolve the LogGroupName from the referenced resource in the template\n if (typeof loggingConfig.LogGroup === 'object') {\n if (loggingConfig.LogGroup.Ref) {\n return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref, 'LogGroupName');\n }\n }\n }\n\n return `/aws/lambda/${resource.PhysicalResourceId}`;\n },\n};\n\n/**\n * Find all CloudWatch Log Groups in the deployed template.\n * This will find both explicitly created Log Groups (excluding those associated with ignored resources)\n * and Log Groups created implicitly (i.e. Lambda Functions)\n */\nfunction findAllLogGroupNames(\n stackResources: StackResourceSummary[],\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): string[] {\n const logGroupNames: string[] = [];\n\n for (const resource of stackResources) {\n const logGroupResolver = cloudWatchLogsResolvers[resource.ResourceType!];\n if (logGroupResolver) {\n const logGroupName = logGroupResolver(resource, evaluateCfnTemplate);\n if (logGroupName) {\n logGroupNames.push(logGroupName);\n }\n }\n }\n\n return logGroupNames;\n}\n", "import { WorkNode, DeploymentState, StackNode, AssetBuildNode, AssetPublishNode } from './work-graph-types';\nimport { debug, trace } from '../../cli/messages';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { parallelPromises } from '../../util/parallel';\n\nexport type Concurrency = number | Record<WorkNode['type'], number>;\n\nexport interface WorkGraphProps {\n ioHost: IoMessaging['ioHost'];\n action: IoMessaging['action'];\n}\n\nexport class WorkGraph {\n public readonly nodes: Record<string, WorkNode>;\n private readonly readyPool: Array<WorkNode> = [];\n private readonly lazyDependencies = new Map<string, string[]>();\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n public error?: Error;\n\n public constructor(nodes: Record<string, WorkNode>, props: WorkGraphProps) {\n this.nodes = { ...nodes };\n\n this.ioHost = props.ioHost;\n this.action = props.action;\n }\n\n public addNodes(...nodes: WorkNode[]) {\n for (const node of nodes) {\n if (this.nodes[node.id]) {\n throw new ToolkitError(`Duplicate use of node id: ${node.id}`);\n }\n\n const ld = this.lazyDependencies.get(node.id);\n if (ld) {\n for (const x of ld) {\n node.dependencies.add(x);\n }\n this.lazyDependencies.delete(node.id);\n }\n\n this.nodes[node.id] = node;\n }\n }\n\n public removeNode(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n const removedNode = this.nodes[id];\n\n this.lazyDependencies.delete(id);\n delete this.nodes[id];\n\n if (removedNode) {\n for (const node of Object.values(this.nodes)) {\n node.dependencies.delete(removedNode.id);\n }\n }\n }\n\n /**\n * Return all nodes of a given type\n */\n public nodesOfType<T extends WorkNode['type']>(type: T): Extract<WorkNode, { type: T }>[] {\n return Object.values(this.nodes).filter(n => n.type === type) as any;\n }\n\n /**\n * Return all nodes that depend on a given node\n */\n public dependees(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n return Object.values(this.nodes).filter(n => n.dependencies.has(id));\n }\n\n /**\n * Add a dependency, that may come before or after the nodes involved\n */\n public addDependency(fromId: string, toId: string) {\n const node = this.nodes[fromId];\n if (node) {\n node.dependencies.add(toId);\n return;\n }\n let lazyDeps = this.lazyDependencies.get(fromId);\n if (!lazyDeps) {\n lazyDeps = [];\n this.lazyDependencies.set(fromId, lazyDeps);\n }\n lazyDeps.push(toId);\n }\n\n public tryGetNode(id: string): WorkNode | undefined {\n return this.nodes[id];\n }\n\n public node(id: string) {\n const ret = this.nodes[id];\n if (!ret) {\n throw new ToolkitError(`No node with id ${id} among ${Object.keys(this.nodes)}`);\n }\n return ret;\n }\n\n public absorb(graph: WorkGraph) {\n this.addNodes(...Object.values(graph.nodes));\n }\n\n private hasFailed(): boolean {\n return Object.values(this.nodes).some((n) => n.deploymentState === DeploymentState.FAILED);\n }\n\n public doParallel(concurrency: Concurrency, actions: WorkGraphActions) {\n return this.forAllArtifacts(concurrency, async (x: WorkNode) => {\n switch (x.type) {\n case 'stack':\n await actions.deployStack(x);\n break;\n case 'asset-build':\n await actions.buildAsset(x);\n break;\n case 'asset-publish':\n await actions.publishAsset(x);\n break;\n }\n });\n }\n\n /**\n * Return the set of unblocked nodes\n */\n public async ready(): Promise<ReadonlyArray<WorkNode>> {\n await this.updateReadyPool();\n return this.readyPool;\n }\n\n private forAllArtifacts(n: Concurrency, fn: (x: WorkNode) => Promise<void>): Promise<void> {\n const graph = this;\n\n // If 'n' is a number, we limit all concurrency equally (effectively we will be using totalMax)\n // If 'n' is a record, we limit each job independently (effectively we will be using max)\n const max: Record<WorkNode['type'], number> = typeof n === 'number' ?\n {\n 'asset-build': n,\n 'asset-publish': n,\n 'stack': n,\n } : n;\n const totalMax = typeof n === 'number' ? n : sum(Object.values(n));\n\n return new Promise((ok, fail) => {\n let active: Record<WorkNode['type'], number> = {\n 'asset-build': 0,\n 'asset-publish': 0,\n 'stack': 0,\n };\n function totalActive() {\n return sum(Object.values(active));\n }\n\n start();\n\n function start() {\n graph.updateReadyPool().then(() => {\n for (let i = 0; i < graph.readyPool.length; ) {\n const node = graph.readyPool[i];\n\n if (active[node.type] < max[node.type] && totalActive() < totalMax) {\n graph.readyPool.splice(i, 1);\n startOne(node);\n } else {\n i += 1;\n }\n }\n\n if (totalActive() === 0) {\n if (graph.done()) {\n ok();\n }\n // wait for other active deploys to finish before failing\n if (graph.hasFailed()) {\n fail(graph.error);\n }\n }\n }).catch((e) => {\n fail(e);\n });\n }\n\n function startOne(x: WorkNode) {\n x.deploymentState = DeploymentState.DEPLOYING;\n active[x.type]++;\n void fn(x)\n .finally(() => {\n active[x.type]--;\n })\n .then(() => {\n graph.deployed(x);\n start();\n }).catch((err) => {\n // By recording the failure immediately as the queued task exits, we prevent the next\n // queued task from starting.\n graph.failed(x, err);\n start();\n });\n }\n });\n }\n\n private done(): boolean {\n return Object.values(this.nodes).every((n) => DeploymentState.COMPLETED === n.deploymentState);\n }\n\n private deployed(node: WorkNode) {\n node.deploymentState = DeploymentState.COMPLETED;\n }\n\n private failed(node: WorkNode, error?: Error) {\n this.error = error;\n node.deploymentState = DeploymentState.FAILED;\n this.skipRest();\n this.readyPool.splice(0);\n }\n\n public toString() {\n return [\n 'digraph D {',\n ...Object.entries(this.nodes).flatMap(([id, node]) => renderNode(id, node)),\n '}',\n ].join('\\n');\n\n function renderNode(id: string, node: WorkNode): string[] {\n const ret = [];\n if (node.deploymentState === DeploymentState.COMPLETED) {\n ret.push(` ${gv(id, { style: 'filled', fillcolor: 'yellow', comment: node.note })};`);\n } else {\n ret.push(` ${gv(id, { comment: node.note })};`);\n }\n for (const dep of node.dependencies) {\n ret.push(` ${gv(id)} -> ${gv(dep)};`);\n }\n return ret;\n }\n }\n\n /**\n * Ensure all dependencies actually exist. This protects against scenarios such as the following:\n * StackA depends on StackB, but StackB is not selected to deploy. The dependency is redundant\n * and will be dropped.\n * This assumes the manifest comes uncorrupted so we will not fail if a dependency is not found.\n */\n public removeUnavailableDependencies() {\n for (const node of Object.values(this.nodes)) {\n const removeDeps = Array.from(node.dependencies).filter((dep) => this.nodes[dep] === undefined);\n\n removeDeps.forEach((d) => {\n node.dependencies.delete(d);\n });\n }\n }\n\n /**\n * Remove all asset publishing steps for assets that are already published, and then build\n * that aren't used anymore.\n *\n * Do this in parallel, because there may be a lot of assets in an application (seen in practice: >100 assets)\n */\n public async removeUnnecessaryAssets(isUnnecessary: (x: AssetPublishNode) => Promise<boolean>) {\n await this.ioHost.notify(debug(this.action, 'Checking for previously published assets'));\n\n const publishes = this.nodesOfType('asset-publish');\n\n const classifiedNodes = await parallelPromises(\n 8,\n publishes.map((assetNode) => async() => [assetNode, await isUnnecessary(assetNode)] as const));\n\n const alreadyPublished = classifiedNodes.filter(([_, unnecessary]) => unnecessary).map(([assetNode, _]) => assetNode);\n for (const assetNode of alreadyPublished) {\n this.removeNode(assetNode);\n }\n\n await this.ioHost.notify(debug(this.action, `${publishes.length} total assets, ${publishes.length - alreadyPublished.length} still need to be published`));\n\n // Now also remove any asset build steps that don't have any dependencies on them anymore\n const unusedBuilds = this.nodesOfType('asset-build').filter(build => this.dependees(build).length === 0);\n for (const unusedBuild of unusedBuilds) {\n this.removeNode(unusedBuild);\n }\n }\n\n private async updateReadyPool() {\n const activeCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.DEPLOYING).length;\n const pendingCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.PENDING).length;\n\n const newlyReady = Object.values(this.nodes).filter((x) =>\n x.deploymentState === DeploymentState.PENDING &&\n Array.from(x.dependencies).every((id) => this.node(id).deploymentState === DeploymentState.COMPLETED));\n\n // Add newly available nodes to the ready pool\n for (const node of newlyReady) {\n node.deploymentState = DeploymentState.QUEUED;\n this.readyPool.push(node);\n }\n\n // Remove nodes from the ready pool that have already started deploying\n retainOnly(this.readyPool, (node) => node.deploymentState === DeploymentState.QUEUED);\n\n // Sort by reverse priority\n this.readyPool.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n if (this.readyPool.length === 0 && activeCount === 0 && pendingCount > 0) {\n const cycle = this.findCycle() ?? ['No cycle found!'];\n await this.ioHost.notify(trace(this.action, `Cycle ${cycle.join(' -> ')} in graph ${this}`));\n throw new ToolkitError(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(' -> ')} (run with -vv for full graph)`);\n }\n }\n\n private skipRest() {\n for (const node of Object.values(this.nodes)) {\n if ([DeploymentState.QUEUED, DeploymentState.PENDING].includes(node.deploymentState)) {\n node.deploymentState = DeploymentState.SKIPPED;\n }\n }\n }\n\n /**\n * Find cycles in a graph\n *\n * Not the fastest, but effective and should be rare\n */\n public findCycle(): string[] | undefined {\n const seen = new Set<string>();\n const self = this;\n for (const nodeId of Object.keys(this.nodes)) {\n const cycle = recurse(nodeId, [nodeId]);\n if (cycle) {\n return cycle;\n }\n }\n return undefined;\n\n function recurse(nodeId: string, path: string[]): string[] | undefined {\n if (seen.has(nodeId)) {\n return undefined;\n }\n try {\n for (const dep of self.nodes[nodeId].dependencies ?? []) {\n const index = path.indexOf(dep);\n if (index > -1) {\n return [...path.slice(index), dep];\n }\n\n const cycle = recurse(dep, [...path, dep]);\n if (cycle) {\n return cycle;\n }\n }\n\n return undefined;\n } finally {\n seen.add(nodeId);\n }\n }\n }\n\n /**\n * Whether the `end` node is reachable from the `start` node, following the dependency arrows\n */\n public reachable(start: string, end: string): boolean {\n const seen = new Set<string>();\n const self = this;\n return recurse(start);\n\n function recurse(current: string) {\n if (seen.has(current)) {\n return false;\n }\n seen.add(current);\n\n if (current === end) {\n return true;\n }\n for (const dep of self.nodes[current].dependencies) {\n if (recurse(dep)) {\n return true;\n }\n }\n return false;\n }\n }\n}\n\nexport interface WorkGraphActions {\n deployStack: (stackNode: StackNode) => Promise<void>;\n buildAsset: (assetNode: AssetBuildNode) => Promise<void>;\n publishAsset: (assetNode: AssetPublishNode) => Promise<void>;\n}\n\nfunction sum(xs: number[]) {\n let ret = 0;\n for (const x of xs) {\n ret += x;\n }\n return ret;\n}\n\nfunction retainOnly<A>(xs: A[], pred: (x: A) => boolean) {\n xs.splice(0, xs.length, ...xs.filter(pred));\n}\n\nfunction gv(id: string, attrs?: Record<string, string | undefined>) {\n const attrString = Object.entries(attrs ?? {}).flatMap(([k, v]) => v !== undefined ? [`${k}=\"${v}\"`] : []).join(',');\n\n return attrString ? `\"${simplifyId(id)}\" [${attrString}]` : `\"${simplifyId(id)}\"`;\n}\n\nfunction simplifyId(id: string) {\n return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g, '$1');\n}\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { AssetManifest, type IManifestEntry } from 'cdk-assets';\nimport { WorkGraph } from './work-graph';\nimport { DeploymentState, AssetBuildNode, WorkNode } from './work-graph-types';\nimport { IoMessaging } from '../../toolkit/cli-io-host';\nimport { ToolkitError } from '../../toolkit/error';\nimport { contentHashAny } from '../../util/content-hash';\n\nexport class WorkGraphBuilder {\n /**\n * Default priorities for nodes\n *\n * Assets builds have higher priority than the other two operations, to make good on our promise that\n * '--prebuild-assets' will actually do assets before stacks (if it can). Unfortunately it is the\n * default :(\n *\n * But between stack dependencies and publish dependencies, stack dependencies go first\n */\n public static PRIORITIES: Record<WorkNode['type'], number> = {\n 'asset-build': 10,\n 'asset-publish': 0,\n 'stack': 5,\n };\n private readonly graph: WorkGraph;\n private readonly ioHost: IoMessaging['ioHost'];\n private readonly action: IoMessaging['action'];\n\n constructor(\n { ioHost, action }: IoMessaging,\n private readonly prebuildAssets: boolean,\n private readonly idPrefix = '',\n ) {\n this.graph = new WorkGraph({}, { ioHost, action });\n this.ioHost = ioHost;\n this.action = action;\n }\n\n private addStack(artifact: cxapi.CloudFormationStackArtifact) {\n this.graph.addNodes({\n type: 'stack',\n id: `${this.idPrefix}${artifact.id}`,\n dependencies: new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),\n stack: artifact,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES.stack,\n });\n }\n\n /**\n * Oof, see this parameter list\n */\n // eslint-disable-next-line max-len\n private addAsset(parentStack: cxapi.CloudFormationStackArtifact, assetManifestArtifact: cxapi.AssetManifestArtifact, assetManifest: AssetManifest, asset: IManifestEntry) {\n // Just the artifact identifier\n const assetId = asset.id.assetId;\n\n const buildId = `build-${assetId}-${contentHashAny([assetId, asset.genericSource]).substring(0, 10)}`;\n const publishId = `publish-${assetId}-${contentHashAny([assetId, asset.genericDestination]).substring(0, 10)}`;\n\n // Build node only gets added once because they are all the same\n if (!this.graph.tryGetNode(buildId)) {\n const node: AssetBuildNode = {\n type: 'asset-build',\n id: buildId,\n note: assetId,\n dependencies: new Set([\n ...this.stackArtifactIds(assetManifestArtifact.dependencies),\n // If we disable prebuild, then assets inherit (stack) dependencies from their parent stack\n ...!this.prebuildAssets ? this.stackArtifactIds(onlyStacks(parentStack.dependencies)) : [],\n ]),\n parentStack: parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-build'],\n };\n this.graph.addNodes(node);\n }\n\n const publishNode = this.graph.tryGetNode(publishId);\n if (!publishNode) {\n this.graph.addNodes({\n type: 'asset-publish',\n id: publishId,\n note: `${asset.id}`,\n dependencies: new Set([\n buildId,\n ]),\n parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-publish'],\n });\n }\n\n for (const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))) {\n // The asset publish step also depends on the stacks that the parent depends on.\n // This is purely cosmetic: if we don't do this, the progress printing of asset publishing\n // is going to interfere with the progress bar of the stack deployment. We could remove this\n // for overall faster deployments if we ever have a better method of progress displaying.\n // Note: this may introduce a cycle if one of the parent's dependencies is another stack that\n // depends on this asset. To workaround this we remove these cycles once all nodes have\n // been added to the graph.\n this.graph.addDependency(publishId, inheritedDep);\n }\n\n // This will work whether the stack node has been added yet or not\n this.graph.addDependency(`${this.idPrefix}${parentStack.id}`, publishId);\n }\n\n public build(artifacts: cxapi.CloudArtifact[]): WorkGraph {\n const parentStacks = stacksFromAssets(artifacts);\n\n for (const artifact of artifacts) {\n if (cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n this.addStack(artifact);\n } else if (cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n const manifest = AssetManifest.fromFile(artifact.file);\n\n for (const entry of manifest.entries) {\n const parentStack = parentStacks.get(artifact);\n if (parentStack === undefined) {\n throw new ToolkitError('Found an asset manifest that is not associated with a stack');\n }\n this.addAsset(parentStack, artifact, manifest, entry);\n }\n } else if (cxapi.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)) {\n const assembly = new cxapi.CloudAssembly(artifact.fullPath, { topoSort: false });\n const nestedGraph = new WorkGraphBuilder(\n { ioHost: this.ioHost, action: this.action },\n this.prebuildAssets,\n `${this.idPrefix}${artifact.id}.`,\n ).build(assembly.artifacts);\n this.graph.absorb(nestedGraph);\n } else {\n // Ignore whatever else\n }\n }\n\n this.graph.removeUnavailableDependencies();\n\n // Remove any potentially introduced cycles between asset publishing and the stacks that depend on them.\n this.removeStackPublishCycles();\n\n return this.graph;\n }\n\n private stackArtifactIds(deps: cxapi.CloudArtifact[]): string[] {\n return deps.flatMap((d) => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(d) ? [this.stackArtifactId(d)] : []);\n }\n\n private stackArtifactId(artifact: cxapi.CloudArtifact): string {\n if (!cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n throw new ToolkitError(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`);\n }\n return `${this.idPrefix}${artifact.id}`;\n }\n\n /**\n * We may have accidentally introduced cycles in an attempt to make the messages printed to the\n * console not interfere with each other too much. Remove them again.\n */\n private removeStackPublishCycles() {\n const publishSteps = this.graph.nodesOfType('asset-publish');\n for (const publishStep of publishSteps) {\n for (const dep of publishStep.dependencies) {\n if (this.graph.reachable(dep, publishStep.id)) {\n publishStep.dependencies.delete(dep);\n }\n }\n }\n }\n}\n\nfunction stacksFromAssets(artifacts: cxapi.CloudArtifact[]) {\n const ret = new Map<cxapi.AssetManifestArtifact, cxapi.CloudFormationStackArtifact>();\n for (const stack of artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x))) {\n const assetArtifacts = stack.dependencies.filter((x) => cxapi.AssetManifestArtifact.isAssetManifestArtifact(x));\n for (const art of assetArtifacts) {\n ret.set(art, stack);\n }\n }\n\n return ret;\n}\n\nfunction onlyStacks(artifacts: cxapi.CloudArtifact[]) {\n return artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x));\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { AmiContextProviderPlugin } from './ami';\nimport { AZContextProviderPlugin } from './availability-zones';\nimport { CcApiContextProviderPlugin } from './cc-api-provider';\nimport { EndpointServiceAZContextProviderPlugin } from './endpoint-service-availability-zones';\nimport { HostedZoneContextProviderPlugin } from './hosted-zones';\nimport { KeyContextProviderPlugin } from './keys';\nimport { LoadBalancerContextProviderPlugin, LoadBalancerListenerContextProviderPlugin } from './load-balancers';\nimport { SecurityGroupContextProviderPlugin } from './security-groups';\nimport { SSMContextProviderPlugin } from './ssm-parameters';\nimport { VpcNetworkContextProviderPlugin } from './vpcs';\nimport { SdkProvider } from '../api';\nimport { Context, TRANSIENT_CONTEXT_KEY } from '../api/context';\nimport { PluginHost } from '../api/plugin';\nimport { ContextProviderPlugin } from '../api/plugin/context-provider-plugin';\nimport { replaceEnvPlaceholders } from '../api/util/placeholders';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\nimport { formatErrorMessage } from '../util/format-error';\n\nexport type ContextProviderFactory = ((sdk: SdkProvider) => ContextProviderPlugin);\nexport type ProviderMap = {[name: string]: ContextProviderFactory};\n\nconst PLUGIN_PROVIDER_PREFIX = 'plugin';\n\n/**\n * Iterate over the list of missing context values and invoke the appropriate providers from the map to retrieve them\n */\nexport async function provideContextValues(\n missingValues: cxschema.MissingContext[],\n context: Context,\n sdk: SdkProvider) {\n for (const missingContext of missingValues) {\n const key = missingContext.key;\n\n const providerName = missingContext.provider === cxschema.ContextProvider.PLUGIN\n ? `${PLUGIN_PROVIDER_PREFIX}:${(missingContext.props as cxschema.PluginContextQuery).pluginName}`\n : missingContext.provider;\n\n let factory;\n if (providerName.startsWith(`${PLUGIN_PROVIDER_PREFIX}:`)) {\n const plugin = PluginHost.instance.contextProviderPlugins[providerName.substring(PLUGIN_PROVIDER_PREFIX.length + 1)];\n if (!plugin) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized plugin context provider name: ${missingContext.provider}.`);\n }\n factory = () => plugin;\n } else {\n factory = availableContextProviders[providerName];\n if (!factory) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized context provider name: ${missingContext.provider}. You might need to update the toolkit to match the version of the construct library.`);\n }\n }\n\n const provider = factory(sdk);\n\n let value;\n try {\n const environment = missingContext.props.account && missingContext.props.region\n ? cxapi.EnvironmentUtils.make(missingContext.props.account, missingContext.props.region)\n : undefined;\n\n const resolvedEnvironment: cxapi.Environment = environment\n ? await sdk.resolveEnvironment(environment)\n : { account: '?', region: '?', name: '?' };\n\n const arns = await replaceEnvPlaceholders({\n lookupRoleArn: missingContext.props.lookupRoleArn,\n }, resolvedEnvironment, sdk);\n\n value = await provider.getValue({ ...missingContext.props, lookupRoleArn: arns.lookupRoleArn });\n } catch (e: any) {\n // Set a specially formatted provider value which will be interpreted\n // as a lookup failure in the toolkit.\n value = { [cxapi.PROVIDER_ERROR_KEY]: formatErrorMessage(e), [TRANSIENT_CONTEXT_KEY]: true };\n }\n context.set(key, value);\n debug(`Setting \"${key}\" context to ${JSON.stringify(value)}`);\n }\n}\n\n/**\n * Register a context provider\n *\n * A context provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerContextProvider(name: string, provider: ContextProviderPlugin) {\n availableContextProviders[name] = () => provider;\n}\n\n/**\n * Register a plugin context provider\n *\n * A plugin provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerPluginContextProvider(name: string, provider: ContextProviderPlugin) {\n registerContextProvider(`${PLUGIN_PROVIDER_PREFIX}:${name}`, provider);\n}\n\n/**\n * Register a context provider factory\n *\n * A context provider factory takes an SdkProvider and returns the context provider plugin.\n */\nexport function registerContextProviderFactory(name: string, provider: ContextProviderFactory) {\n availableContextProviders[name] = provider;\n}\n\nconst availableContextProviders: ProviderMap = {\n [cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER]: (s) => new AZContextProviderPlugin(s),\n [cxschema.ContextProvider.SSM_PARAMETER_PROVIDER]: (s) => new SSMContextProviderPlugin(s),\n [cxschema.ContextProvider.HOSTED_ZONE_PROVIDER]: (s) => new HostedZoneContextProviderPlugin(s),\n [cxschema.ContextProvider.VPC_PROVIDER]: (s) => new VpcNetworkContextProviderPlugin(s),\n [cxschema.ContextProvider.AMI_PROVIDER]: (s) => new AmiContextProviderPlugin(s),\n [cxschema.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]: (s) => new EndpointServiceAZContextProviderPlugin(s),\n [cxschema.ContextProvider.SECURITY_GROUP_PROVIDER]: (s) => new SecurityGroupContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_PROVIDER]: (s) => new LoadBalancerContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_LISTENER_PROVIDER]: (s) => new LoadBalancerListenerContextProviderPlugin(s),\n [cxschema.ContextProvider.KEY_PROVIDER]: (s) => new KeyContextProviderPlugin(s),\n [cxschema.ContextProvider.CC_API_PROVIDER]: (s) => new CcApiContextProviderPlugin(s),\n};\n", "import type { AmiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug, info } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Plugin to search AMIs for the current account\n */\nexport class AmiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: AmiContextQuery) {\n const region = args.region;\n const account = args.account;\n\n // Normally we'd do this only as 'debug', but searching AMIs typically takes dozens\n // of seconds, so be little more verbose about it so users know what is going on.\n info(`Searching for AMI in ${account}:${region}`);\n debug(`AMI search parameters: ${JSON.stringify(args)}`);\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeImages({\n Owners: args.owners,\n Filters: Object.entries(args.filters).map(([key, values]) => ({\n Name: key,\n Values: values,\n })),\n });\n\n const images = [...(response.Images || [])].filter((i) => i.ImageId !== undefined);\n\n if (images.length === 0) {\n throw new ContextProviderError('No AMI found that matched the search criteria');\n }\n\n // Return the most recent one\n // Note: Date.parse() is not going to respect the timezone of the string,\n // but since we only care about the relative values that is okay.\n images.sort(descending((i) => Date.parse(i.CreationDate || '1970')));\n\n debug(`Selected image '${images[0].ImageId}' created at '${images[0].CreationDate}'`);\n return images[0].ImageId!;\n }\n}\n\n/**\n * Make a comparator that sorts in descending order given a sort key extractor\n */\nfunction descending<A>(valueOf: (x: A) => number) {\n return (a: A, b: A) => {\n return valueOf(b) - valueOf(a);\n };\n}\n", "import type { AvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { AvailabilityZone } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\n\n/**\n * Plugin to retrieve the Availability Zones for the current account\n */\nexport class AZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: AvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n debug(`Reading AZs for ${account}:${region}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeAvailabilityZones({});\n if (!response.AvailabilityZones) {\n return [];\n }\n const azs = response.AvailabilityZones.filter((zone: AvailabilityZone) => zone.State === 'available').map(\n (zone: AvailabilityZone) => zone.ZoneName,\n );\n return azs;\n }\n}\n", "/**\n * This gets the values of the jsonObject at the paths specified in propertiesToReturn.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * propertiesToReturn = ['key1', 'key2.foo'];\n *\n * The returned object is:\n *\n * ```\n * {\n * key1: 'abc',\n * 'key2.foo': 'qwerty',\n * Identifier: identifier\n * }\n * ```\n */\nexport function getResultObj(jsonObject: any, identifier: string, propertiesToReturn: string[]): {[key: string]: any} {\n const propsObj = {};\n propertiesToReturn.forEach((propName) => {\n Object.assign(propsObj, { [propName]: findJsonValue(jsonObject, propName) });\n });\n Object.assign(propsObj, { ['Identifier']: identifier });\n return propsObj;\n}\n\n/**\n * This finds the value of the jsonObject at the path. Path is delimited by '.'.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * If path is 'key1', then it will return 'abc'.\n * If path is 'key2.foo', then it will return 'qwerty'.\n * If path is 'key2', then it will return the object:\n * {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n *\n * If the path is not found, an Error will be thrown stating which token is missing.\n */\nexport function findJsonValue(jsonObject: any, path: string): any {\n const paths = path.split('.');\n let obj = jsonObject;\n paths.forEach(p => {\n obj = obj[p];\n if (obj === undefined) {\n throw new TypeError(`Cannot read field ${path}. ${p} is not found.`);\n }\n });\n return obj;\n}\n", "import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { ICloudControlClient } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\nimport { findJsonValue, getResultObj } from '../util/json';\n\nexport class CcApiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n /**\n * This returns a data object with the value from CloudControl API result.\n * args.typeName - see https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/supported-resources.html\n * args.exactIdentifier - use CC API getResource.\n * args.propertyMatch - use CCP API listResources to get resources and propertyMatch to search through the list.\n * args.propertiesToReturn - Properties from CC API to return.\n */\n public async getValue(args: CcApiContextQuery) {\n const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl();\n\n const result = await this.findResources(cloudControl, args);\n return result;\n }\n\n private async findResources(cc: ICloudControlClient, args: CcApiContextQuery): Promise<{[key: string]: any} []> {\n if (args.exactIdentifier && args.propertyMatch) {\n throw new ContextProviderError(`Specify either exactIdentifier or propertyMatch, but not both. Failed to find resources using CC API for type ${args.typeName}.`);\n }\n if (!args.exactIdentifier && !args.propertyMatch) {\n throw new ContextProviderError(`Neither exactIdentifier nor propertyMatch is specified. Failed to find resources using CC API for type ${args.typeName}.`);\n }\n\n if (args.exactIdentifier) {\n // use getResource to get the exact indentifier\n return this.getResource(cc, args.typeName, args.exactIdentifier, args.propertiesToReturn);\n } else {\n // use listResource\n return this.listResources(cc, args.typeName, args.propertyMatch!, args.propertiesToReturn);\n }\n }\n\n /**\n * Calls getResource from CC API to get the resource.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/get-resource.html\n *\n * If the exactIdentifier is not found, then an empty map is returned.\n * If the resource is found, then a map of the identifier to a map of property values is returned.\n */\n private async getResource(\n cc: ICloudControlClient,\n typeName: string,\n exactIdentifier: string,\n propertiesToReturn: string[],\n ): Promise<{[key: string]: any}[]> {\n const resultObjs: {[key: string]: any}[] = [];\n try {\n const result = await cc.getResource({\n TypeName: typeName,\n Identifier: exactIdentifier,\n });\n const id = result.ResourceDescription?.Identifier ?? '';\n if (id !== '') {\n const propsObject = JSON.parse(result.ResourceDescription?.Properties ?? '');\n const propsObj = getResultObj(propsObject, result.ResourceDescription?.Identifier!, propertiesToReturn);\n resultObjs.push(propsObj);\n } else {\n throw new ContextProviderError(`Could not get resource ${exactIdentifier}.`);\n }\n } catch (err) {\n throw new ContextProviderError(`Encountered CC API error while getting resource ${exactIdentifier}. Error: ${err}`);\n }\n return resultObjs;\n }\n\n /**\n * Calls listResources from CC API to get the resources and apply args.propertyMatch to find the resources.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/list-resources.html\n *\n * Since exactIdentifier is not specified, propertyMatch must be specified.\n * This returns an object where the ids are object keys and values are objects with keys of args.propertiesToReturn.\n */\n private async listResources(\n cc: ICloudControlClient,\n typeName: string,\n propertyMatch: Record<string, unknown>,\n propertiesToReturn: string[],\n ): Promise<{[key: string]: any}[]> {\n const resultObjs: {[key: string]: any}[] = [];\n\n try {\n const result = await cc.listResources({\n TypeName: typeName,\n });\n result.ResourceDescriptions?.forEach((resource) => {\n const id = resource.Identifier ?? '';\n if (id !== '') {\n const propsObject = JSON.parse(resource.Properties ?? '');\n\n const filters = Object.entries(propertyMatch);\n let match = false;\n if (filters) {\n match = filters.every((record, _index, _arr) => {\n const key = record[0];\n const expected = record[1];\n const actual = findJsonValue(propsObject, key);\n return propertyMatchesFilter(actual, expected);\n });\n\n function propertyMatchesFilter(actual: any, expected: unknown) {\n // For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later\n return expected === actual;\n }\n }\n\n if (match) {\n const propsObj = getResultObj(propsObject, resource.Identifier!, propertiesToReturn);\n resultObjs.push(propsObj);\n }\n }\n });\n } catch (err) {\n throw new ContextProviderError(`Could not get resources ${JSON.stringify(propertyMatch)}. Error: ${err}`);\n }\n return resultObjs;\n }\n}\n", "import type { EndpointServiceAvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\n\n/**\n * Plugin to retrieve the Availability Zones for an endpoint service\n */\nexport class EndpointServiceAZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: EndpointServiceAvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n const serviceName = args.serviceName;\n debug(`Reading AZs for ${account}:${region}:${serviceName}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeVpcEndpointServices({\n ServiceNames: [serviceName],\n });\n\n // expect a service in the response\n if (!response.ServiceDetails || response.ServiceDetails.length === 0) {\n debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);\n return [];\n }\n const azs = response.ServiceDetails[0].AvailabilityZones;\n debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);\n return azs;\n }\n}\n", "import { HostedZoneContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { HostedZone } from '@aws-sdk/client-route-53';\nimport type { IRoute53Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class HostedZoneContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: HostedZoneContextQuery): Promise<object> {\n const account = args.account;\n const region = args.region;\n if (!this.isHostedZoneQuery(args)) {\n throw new ContextProviderError(`HostedZoneProvider requires domainName property to be set in ${args}`);\n }\n const domainName = args.domainName;\n debug(`Reading hosted zone ${account}:${region}:${domainName}`);\n const r53 = (await initContextProviderSdk(this.aws, args)).route53();\n const response = await r53.listHostedZonesByName({ DNSName: domainName });\n if (!response.HostedZones) {\n throw new ContextProviderError(`Hosted Zone not found in account ${account}, region ${region}: ${domainName}`);\n }\n const candidateZones = await this.filterZones(r53, response.HostedZones, args);\n if (candidateZones.length !== 1) {\n const filteProps = `dns:${domainName}, privateZone:${args.privateZone}, vpcId:${args.vpcId}`;\n throw new ContextProviderError(`Found zones: ${JSON.stringify(candidateZones)} for ${filteProps}, but wanted exactly 1 zone`);\n }\n\n return {\n Id: candidateZones[0].Id,\n Name: candidateZones[0].Name,\n };\n }\n\n private async filterZones(\n r53: IRoute53Client,\n zones: HostedZone[],\n props: HostedZoneContextQuery,\n ): Promise<HostedZone[]> {\n let candidates: HostedZone[] = [];\n const domainName = props.domainName.endsWith('.') ? props.domainName : `${props.domainName}.`;\n debug(`Found the following zones ${JSON.stringify(zones)}`);\n candidates = zones.filter((zone) => zone.Name === domainName);\n debug(`Found the following matched name zones ${JSON.stringify(candidates)}`);\n if (props.privateZone) {\n candidates = candidates.filter((zone) => zone.Config && zone.Config.PrivateZone);\n } else {\n candidates = candidates.filter((zone) => !zone.Config || !zone.Config.PrivateZone);\n }\n if (props.vpcId) {\n const vpcZones: HostedZone[] = [];\n for (const zone of candidates) {\n const data = await r53.getHostedZone({ Id: zone.Id });\n if (!data.VPCs) {\n debug(`Expected VPC for private zone but no VPC found ${zone.Id}`);\n continue;\n }\n if (data.VPCs.map((vpc) => vpc.VPCId).includes(props.vpcId)) {\n vpcZones.push(zone);\n }\n }\n return vpcZones;\n }\n return candidates;\n }\n\n private isHostedZoneQuery(props: HostedZoneContextQuery | any): props is HostedZoneContextQuery {\n return (props as HostedZoneContextQuery).domainName !== undefined;\n }\n}\n", "import type { KeyContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { KeyContextResponse } from '@aws-cdk/cx-api';\nimport type { AliasListEntry, ListAliasesCommandOutput } from '@aws-sdk/client-kms';\nimport type { IKMSClient } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class KeyContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: KeyContextQuery) {\n const kms = (await initContextProviderSdk(this.aws, args)).kms();\n\n const aliasListEntry = await this.findKey(kms, args);\n\n return this.readKeyProps(aliasListEntry, args);\n }\n\n // TODO: use paginator function\n private async findKey(kms: IKMSClient, args: KeyContextQuery): Promise<AliasListEntry> {\n debug(`Listing keys in ${args.account}:${args.region}`);\n\n let response: ListAliasesCommandOutput;\n let nextMarker: string | undefined;\n do {\n response = await kms.listAliases({\n Marker: nextMarker,\n });\n\n const aliases = response.Aliases || [];\n for (const alias of aliases) {\n if (alias.AliasName == args.aliasName) {\n return alias;\n }\n }\n\n nextMarker = response.NextMarker;\n } while (nextMarker);\n\n const suppressError = 'ignoreErrorOnMissingContext' in args && args.ignoreErrorOnMissingContext as boolean;\n const hasDummyKeyId = 'dummyValue' in args && typeof args.dummyValue === 'object' && args.dummyValue !== null && 'keyId' in args.dummyValue;\n if (suppressError && hasDummyKeyId) {\n const keyId = (args.dummyValue as { keyId: string }).keyId;\n return { TargetKeyId: keyId };\n }\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n private async readKeyProps(alias: AliasListEntry, args: KeyContextQuery): Promise<KeyContextResponse> {\n if (!alias.TargetKeyId) {\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n debug(`Key found ${alias.TargetKeyId}`);\n\n return {\n keyId: alias.TargetKeyId,\n };\n }\n}\n", "import { LoadBalancerContextQuery, LoadBalancerListenerContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport {\n LoadBalancerContextResponse,\n LoadBalancerIpAddressType,\n LoadBalancerListenerContextResponse,\n} from '@aws-cdk/cx-api';\nimport { type Listener, LoadBalancer, type TagDescription } from '@aws-sdk/client-elastic-load-balancing-v2';\nimport type { IElasticLoadBalancingV2Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Provides load balancer context information.\n */\nexport class LoadBalancerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerContextQuery): Promise<LoadBalancerContextResponse> {\n if (!query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError('The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`');\n }\n\n const loadBalancer = await (await LoadBalancerProvider.getClient(this.aws, query)).getLoadBalancer();\n\n const ipAddressType =\n loadBalancer.IpAddressType === 'ipv4' ? LoadBalancerIpAddressType.IPV4 : LoadBalancerIpAddressType.DUAL_STACK;\n\n return {\n loadBalancerArn: loadBalancer.LoadBalancerArn!,\n loadBalancerCanonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!,\n loadBalancerDnsName: loadBalancer.DNSName!,\n vpcId: loadBalancer.VpcId!,\n securityGroupIds: loadBalancer.SecurityGroups ?? [],\n ipAddressType: ipAddressType,\n };\n }\n}\n\n/**\n * Provides load balancer listener context information\n */\nexport class LoadBalancerListenerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerListenerContextQuery): Promise<LoadBalancerListenerContextResponse> {\n if (!query.listenerArn && !query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError(\n 'The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`',\n );\n }\n\n return (await LoadBalancerProvider.getClient(this.aws, query)).getListener();\n }\n}\n\nclass LoadBalancerProvider {\n public static async getClient(\n aws: SdkProvider,\n query: LoadBalancerListenerContextQuery,\n ): Promise<LoadBalancerProvider> {\n const client = (await initContextProviderSdk(aws, query)).elbv2();\n\n try {\n const listener = query.listenerArn\n ? // Assert we're sure there's at least one so it throws if not\n (await client.describeListeners({ ListenerArns: [query.listenerArn] })).Listeners![0]!\n : undefined;\n return new LoadBalancerProvider(\n client,\n { ...query, loadBalancerArn: listener?.LoadBalancerArn || query.loadBalancerArn },\n listener,\n );\n } catch (err) {\n throw new ContextProviderError(`No load balancer listeners found matching arn ${query.listenerArn}`);\n }\n }\n\n constructor(\n private readonly client: IElasticLoadBalancingV2Client,\n private readonly filter: LoadBalancerListenerContextQuery,\n private readonly listener?: Listener,\n ) {\n }\n\n public async getLoadBalancer(): Promise<LoadBalancer> {\n const loadBalancers = await this.getLoadBalancers();\n\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(`No load balancers found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (loadBalancers.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancers found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return loadBalancers[0];\n }\n\n public async getListener(): Promise<LoadBalancerListenerContextResponse> {\n if (this.listener) {\n try {\n const loadBalancer = await this.getLoadBalancer();\n return {\n listenerArn: this.listener.ListenerArn!,\n listenerPort: this.listener.Port!,\n securityGroupIds: loadBalancer.SecurityGroups || [],\n };\n } catch (err) {\n throw new ContextProviderError(`No associated load balancer found for listener arn ${this.filter.listenerArn}`);\n }\n }\n\n const loadBalancers = await this.getLoadBalancers();\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(\n `No associated load balancers found for load balancer listener query ${JSON.stringify(this.filter)}`,\n );\n }\n\n const listeners = (await this.getListenersForLoadBalancers(loadBalancers)).filter((listener) => {\n return (\n (!this.filter.listenerPort || listener.Port === this.filter.listenerPort) &&\n (!this.filter.listenerProtocol || listener.Protocol === this.filter.listenerProtocol)\n );\n });\n\n if (listeners.length === 0) {\n throw new ContextProviderError(`No load balancer listeners found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (listeners.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancer listeners found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return {\n listenerArn: listeners[0].ListenerArn!,\n listenerPort: listeners[0].Port!,\n securityGroupIds:\n loadBalancers.find((lb) => listeners[0].LoadBalancerArn === lb.LoadBalancerArn)?.SecurityGroups || [],\n };\n }\n\n private async getLoadBalancers() {\n const loadBalancerArns = this.filter.loadBalancerArn ? [this.filter.loadBalancerArn] : undefined;\n const loadBalancers = (\n await this.client.paginateDescribeLoadBalancers({\n LoadBalancerArns: loadBalancerArns,\n })\n ).filter((lb) => lb.Type === this.filter.loadBalancerType);\n\n return this.filterByTags(loadBalancers);\n }\n\n private async filterByTags(loadBalancers: LoadBalancer[]): Promise<LoadBalancer[]> {\n if (!this.filter.loadBalancerTags) {\n return loadBalancers;\n }\n return (await this.describeTags(loadBalancers.map((lb) => lb.LoadBalancerArn!)))\n .filter((tagDescription) => {\n // For every tag in the filter, there is some tag in the LB that matches it.\n // In other words, the set of tags in the filter is a subset of the set of tags in the LB.\n return this.filter.loadBalancerTags!.every((filter) => {\n return tagDescription.Tags?.some((tag) =>\n filter.key === tag.Key && filter.value === tag.Value);\n });\n })\n .flatMap((tag) => loadBalancers.filter((loadBalancer) => tag.ResourceArn === loadBalancer.LoadBalancerArn));\n }\n\n /**\n * Returns tag descriptions associated with the resources. The API doesn't support\n * pagination, so this function breaks the resource list into chunks and issues\n * the appropriate requests.\n */\n private async describeTags(resourceArns: string[]): Promise<TagDescription[]> {\n // Max of 20 resource arns per request.\n const chunkSize = 20;\n const tags = Array<TagDescription>();\n for (let i = 0; i < resourceArns.length; i += chunkSize) {\n const chunk = resourceArns.slice(i, Math.min(i + chunkSize, resourceArns.length));\n const chunkTags = await this.client.describeTags({\n ResourceArns: chunk,\n });\n\n tags.push(...(chunkTags.TagDescriptions || []));\n }\n return tags;\n }\n\n private async getListenersForLoadBalancers(loadBalancers: LoadBalancer[]): Promise<Listener[]> {\n const listeners: Listener[] = [];\n for (const loadBalancer of loadBalancers.map((lb) => lb.LoadBalancerArn)) {\n listeners.push(...(await this.client.paginateDescribeListeners({ LoadBalancerArn: loadBalancer })));\n }\n return listeners;\n }\n}\n", "import type { SecurityGroupContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { SecurityGroupContextResponse } from '@aws-cdk/cx-api';\nimport type { Filter, SecurityGroup } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../toolkit/error';\n\nexport class SecurityGroupContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(args: SecurityGroupContextQuery): Promise<SecurityGroupContextResponse> {\n if (args.securityGroupId && args.securityGroupName) {\n throw new ContextProviderError(\n \"'securityGroupId' and 'securityGroupName' can not be specified both when looking up a security group\",\n );\n }\n\n if (!args.securityGroupId && !args.securityGroupName) {\n throw new ContextProviderError(\"'securityGroupId' or 'securityGroupName' must be specified to look up a security group\");\n }\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const filters: Filter[] = [];\n if (args.vpcId) {\n filters.push({\n Name: 'vpc-id',\n Values: [args.vpcId],\n });\n }\n if (args.securityGroupName) {\n filters.push({\n Name: 'group-name',\n Values: [args.securityGroupName],\n });\n }\n\n const response = await ec2.describeSecurityGroups({\n GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined,\n Filters: filters.length > 0 ? filters : undefined,\n });\n\n const securityGroups = response.SecurityGroups ?? [];\n if (securityGroups.length === 0) {\n throw new ContextProviderError(`No security groups found matching ${JSON.stringify(args)}`);\n }\n\n if (securityGroups.length > 1) {\n throw new ContextProviderError(`More than one security groups found matching ${JSON.stringify(args)}`);\n }\n\n const [securityGroup] = securityGroups;\n\n return {\n securityGroupId: securityGroup.GroupId!,\n allowAllOutbound: hasAllTrafficEgress(securityGroup),\n };\n }\n}\n\n/**\n * @internal\n */\nexport function hasAllTrafficEgress(securityGroup: SecurityGroup) {\n let hasAllTrafficCidrV4 = false;\n let hasAllTrafficCidrV6 = false;\n\n for (const ipPermission of securityGroup.IpPermissionsEgress ?? []) {\n const isAllProtocols = ipPermission.IpProtocol === '-1';\n\n if (isAllProtocols && ipPermission.IpRanges?.some((m) => m.CidrIp === '0.0.0.0/0')) {\n hasAllTrafficCidrV4 = true;\n }\n\n if (isAllProtocols && ipPermission.Ipv6Ranges?.some((m) => m.CidrIpv6 === '::/0')) {\n hasAllTrafficCidrV6 = true;\n }\n }\n\n return hasAllTrafficCidrV4 && hasAllTrafficCidrV6;\n}\n", "import type { SSMParameterContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { GetParameterCommandOutput } from '@aws-sdk/client-ssm';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\n\n/**\n * Plugin to read arbitrary SSM parameter names\n */\nexport class SSMContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: SSMParameterContextQuery) {\n const region = args.region;\n const account = args.account;\n\n if (!('parameterName' in args)) {\n throw new ContextProviderError('parameterName must be provided in props for SSMContextProviderPlugin');\n }\n const parameterName = args.parameterName;\n debug(`Reading SSM parameter ${account}:${region}:${parameterName}`);\n\n const response = await this.getSsmParameterValue(args);\n const parameterNotFound: boolean = !response.Parameter || response.Parameter.Value === undefined;\n const suppressError = 'ignoreErrorOnMissingContext' in args && (args.ignoreErrorOnMissingContext as boolean);\n if (parameterNotFound && suppressError && 'dummyValue' in args) {\n return args.dummyValue;\n }\n if (parameterNotFound) {\n throw new ContextProviderError(`SSM parameter not available in account ${account}, region ${region}: ${parameterName}`);\n }\n // will not be undefined because we've handled undefined cases above\n return response.Parameter!.Value;\n }\n\n /**\n * Gets the value of an SSM Parameter, while not throwin if the parameter does not exist.\n * @param account the account in which the SSM Parameter is expected to be.\n * @param region the region in which the SSM Parameter is expected to be.\n * @param parameterName the name of the SSM Parameter\n * @param lookupRoleArn the ARN of the lookup role.\n *\n * @returns the result of the ``GetParameter`` operation.\n *\n * @throws Error if a service error (other than ``ParameterNotFound``) occurs.\n */\n private async getSsmParameterValue(args: SSMParameterContextQuery): Promise<GetParameterCommandOutput> {\n const ssm = (await initContextProviderSdk(this.aws, args)).ssm();\n try {\n return await ssm.getParameter({ Name: args.parameterName });\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n return { $metadata: {} };\n }\n throw e;\n }\n }\n}\n", "import type { VpcContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type VpcContextResponse, type VpcSubnetGroup, VpcSubnetGroupType } from '@aws-cdk/cx-api';\nimport type { Filter, RouteTable, Tag, Vpc } from '@aws-sdk/client-ec2';\nimport type { IEC2Client } from '../api';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/sdk-provider';\nimport { ContextProviderPlugin } from '../api/plugin';\nimport { debug } from '../logging';\nimport { ContextProviderError } from '../toolkit/error';\nexport class VpcNetworkContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n public async getValue(args: VpcContextQuery) {\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const vpcId = await this.findVpc(ec2, args);\n\n return this.readVpcProps(ec2, vpcId, args);\n }\n\n private async findVpc(ec2: IEC2Client, args: VpcContextQuery): Promise<Vpc> {\n // Build request filter (map { Name -> Value } to list of [{ Name, Values }])\n const filters: Filter[] = Object.entries(args.filter).map(([tag, value]) => ({ Name: tag, Values: [value] }));\n\n debug(`Listing VPCs in ${args.account}:${args.region}`);\n const response = await ec2.describeVpcs({ Filters: filters });\n\n const vpcs = response.Vpcs || [];\n if (vpcs.length === 0) {\n throw new ContextProviderError(`Could not find any VPCs matching ${JSON.stringify(args)}`);\n }\n if (vpcs.length > 1) {\n throw new ContextProviderError(`Found ${vpcs.length} VPCs matching ${JSON.stringify(args)}; please narrow the search criteria`);\n }\n\n return vpcs[0];\n }\n\n private async readVpcProps(ec2: IEC2Client, vpc: Vpc, args: VpcContextQuery): Promise<VpcContextResponse> {\n const vpcId = vpc.VpcId!;\n\n debug(`Describing VPC ${vpcId}`);\n\n const filters = { Filters: [{ Name: 'vpc-id', Values: [vpcId] }] };\n\n const subnetsResponse = await ec2.describeSubnets(filters);\n const listedSubnets = subnetsResponse.Subnets || [];\n\n const routeTablesResponse = await ec2.describeRouteTables(filters);\n const routeTables = new RouteTables(routeTablesResponse.RouteTables || []);\n\n // Now comes our job to separate these subnets out into AZs and subnet groups (Public, Private, Isolated)\n // We have the following attributes to go on:\n // - Type tag, we tag subnets with their type. In absence of this tag, we\n // determine the subnet must be Public if either:\n // a) it has the property MapPublicIpOnLaunch\n // b) it has a route to an Internet Gateway\n // If both of the above is false but the subnet has a route to a NAT Gateway\n // and the destination CIDR block is \"0.0.0.0/0\", we assume it to be a Private subnet.\n // Anything else is considered Isolated.\n // - Name tag, we tag subnets with their subnet group name. In absence of this tag,\n // we use the type as the name.\n\n const azs = Array.from(new Set<string>(listedSubnets.map((s) => s.AvailabilityZone!)));\n azs.sort();\n\n const subnets: Subnet[] = listedSubnets.map((subnet) => {\n let type = getTag('aws-cdk:subnet-type', subnet.Tags);\n if (type === undefined && subnet.MapPublicIpOnLaunch) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToIgw(subnet.SubnetId)) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToNatGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined && routeTables.hasRouteToTransitGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined) {\n type = SubnetType.Isolated;\n }\n\n if (!isValidSubnetType(type)) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} has invalid subnet type ${type} (must be ${SubnetType.Public}, ${SubnetType.Private} or ${SubnetType.Isolated})`,\n );\n }\n\n if (args.subnetGroupNameTag && !getTag(args.subnetGroupNameTag, subnet.Tags)) {\n throw new ContextProviderError(\n `Invalid subnetGroupNameTag: Subnet ${subnet.SubnetArn} does not have an associated tag with Key='${args.subnetGroupNameTag}'`,\n );\n }\n\n const name = getTag(args.subnetGroupNameTag || 'aws-cdk:subnet-name', subnet.Tags) || type;\n const routeTableId = routeTables.routeTableIdForSubnetId(subnet.SubnetId);\n\n if (!routeTableId) {\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} does not have an associated route table (and there is no \"main\" table)`,\n );\n }\n\n return {\n az: subnet.AvailabilityZone!,\n cidr: subnet.CidrBlock!,\n type,\n name,\n subnetId: subnet.SubnetId!,\n routeTableId,\n };\n });\n\n let grouped: SubnetGroups;\n let assymetricSubnetGroups: VpcSubnetGroup[] | undefined;\n if (args.returnAsymmetricSubnets) {\n grouped = { azs: [], groups: [] };\n assymetricSubnetGroups = groupAsymmetricSubnets(subnets);\n } else {\n grouped = groupSubnets(subnets);\n assymetricSubnetGroups = undefined;\n }\n\n // Find attached+available VPN gateway for this VPC\n const vpnGatewayResponse =\n (args.returnVpnGateways ?? true)\n ? await ec2.describeVpnGateways({\n Filters: [\n {\n Name: 'attachment.vpc-id',\n Values: [vpcId],\n },\n {\n Name: 'attachment.state',\n Values: ['attached'],\n },\n {\n Name: 'state',\n Values: ['available'],\n },\n ],\n })\n : undefined;\n const vpnGatewayId =\n vpnGatewayResponse?.VpnGateways?.length === 1 ? vpnGatewayResponse.VpnGateways[0].VpnGatewayId : undefined;\n\n return {\n vpcId,\n vpcCidrBlock: vpc.CidrBlock!,\n ownerAccountId: vpc.OwnerId,\n availabilityZones: grouped.azs,\n isolatedSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n isolatedSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n isolatedSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n privateSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n privateSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n privateSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n publicSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n publicSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n publicSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n vpnGatewayId,\n subnetGroups: assymetricSubnetGroups,\n };\n }\n}\n\nclass RouteTables {\n public readonly mainRouteTable?: RouteTable;\n\n constructor(private readonly tables: RouteTable[]) {\n this.mainRouteTable = this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => !!assoc.Main),\n );\n }\n\n public routeTableIdForSubnetId(subnetId: string | undefined): string | undefined {\n const table = this.tableForSubnet(subnetId);\n return (table && table.RouteTableId) || (this.mainRouteTable && this.mainRouteTable.RouteTableId);\n }\n\n /**\n * Whether the given subnet has a route to a NAT Gateway\n */\n public hasRouteToNatGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.NatGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to a Transit Gateway\n */\n public hasRouteToTransitGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.TransitGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to an IGW\n */\n public hasRouteToIgw(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table && !!table.Routes && table.Routes.some((route) => !!route.GatewayId && route.GatewayId.startsWith('igw-'))\n );\n }\n\n public tableForSubnet(subnetId: string | undefined) {\n return this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => assoc.SubnetId === subnetId),\n );\n }\n}\n\n/**\n * Return the value of a tag from a set of tags\n */\nfunction getTag(name: string, tags?: Tag[]): string | undefined {\n for (const tag of tags || []) {\n if (tag.Key === name) {\n return tag.Value;\n }\n }\n return undefined;\n}\n\n/**\n * Group subnets of the same type together, and order by AZ\n */\nfunction groupSubnets(subnets: Subnet[]): SubnetGroups {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n const groups = Object.values(grouping).map((sns) => {\n sns.sort((a: Subnet, b: Subnet) => a.az.localeCompare(b.az));\n return {\n type: sns[0].type,\n name: sns[0].name,\n subnets: sns,\n };\n });\n\n const azs = groups[0].subnets.map((s) => s.az);\n\n for (const group of groups) {\n const groupAZs = group.subnets.map((s) => s.az);\n if (!arraysEqual(groupAZs, azs)) {\n throw new ContextProviderError(`Not all subnets in VPC have the same AZs: ${groupAZs} vs ${azs}`);\n }\n }\n\n return { azs, groups };\n}\n\nfunction groupAsymmetricSubnets(subnets: Subnet[]): VpcSubnetGroup[] {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n return Object.values(grouping).map((subnetArray) => {\n subnetArray.sort((subnet1: Subnet, subnet2: Subnet) => subnet1.az.localeCompare(subnet2.az));\n\n return {\n name: subnetArray[0].name,\n type: subnetTypeToVpcSubnetType(subnetArray[0].type),\n subnets: subnetArray.map((subnet) => ({\n subnetId: subnet.subnetId,\n cidr: subnet.cidr,\n availabilityZone: subnet.az,\n routeTableId: subnet.routeTableId,\n })),\n };\n });\n}\n\nfunction subnetTypeToVpcSubnetType(type: SubnetType): VpcSubnetGroupType {\n switch (type) {\n case SubnetType.Isolated:\n return VpcSubnetGroupType.ISOLATED;\n case SubnetType.Private:\n return VpcSubnetGroupType.PRIVATE;\n case SubnetType.Public:\n return VpcSubnetGroupType.PUBLIC;\n }\n}\n\nenum SubnetType {\n Public = 'Public',\n Private = 'Private',\n Isolated = 'Isolated',\n}\n\nfunction isValidSubnetType(val: string): val is SubnetType {\n return val === SubnetType.Public || val === SubnetType.Private || val === SubnetType.Isolated;\n}\n\ninterface Subnet {\n az: string;\n cidr: string;\n type: SubnetType;\n name: string;\n routeTableId: string;\n subnetId: string;\n}\n\ninterface SubnetGroup {\n type: SubnetType;\n name: string;\n subnets: Subnet[];\n}\n\ninterface SubnetGroups {\n azs: string[];\n groups: SubnetGroup[];\n}\n\nfunction arraysEqual(as: string[], bs: string[]): boolean {\n if (as.length !== bs.length) {\n return false;\n }\n\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction findGroups(type: SubnetType, groups: SubnetGroups): SubnetGroup[] {\n return groups.groups.filter((g) => g.type === type);\n}\n\nfunction flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[] {\n const ret = new Array<U>();\n for (const x of xs) {\n ret.push(...fn(x));\n }\n return ret;\n}\n\nfunction collapse<T>(xs: T[]): T[] | undefined {\n if (xs.length > 0) {\n return xs;\n }\n return undefined;\n}\n", "import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { ToolkitError } from '../../toolkit/error';\n\n/**\n * A single-writer/multi-reader lock on a directory\n *\n * It uses marker files with PIDs in them as a locking marker; the PIDs will be\n * checked for liveness, so that if the process exits without cleaning up the\n * files the lock is implicitly released.\n *\n * This class is not 100% race safe, but in practice it should be a lot\n * better than the 0 protection we have today.\n */\n/* istanbul ignore next: code paths are unpredictable */\nexport class RWLock {\n private readonly pidString: string;\n private readonly writerFile: string;\n private readCounter = 0;\n\n constructor(public readonly directory: string) {\n this.pidString = `${process.pid}`;\n\n this.writerFile = path.join(this.directory, 'synth.lock');\n }\n\n /**\n * Acquire a writer lock.\n *\n * No other readers or writers must exist for the given directory.\n */\n public async acquireWrite(): Promise<IWriterLock> {\n await this.assertNoOtherWriters();\n\n const readers = await this.currentReaders();\n if (readers.length > 0) {\n throw new ToolkitError(`Other CLIs (PID=${readers}) are currently reading from ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n\n await writeFileAtomic(this.writerFile, this.pidString);\n\n return {\n release: async () => {\n await deleteFile(this.writerFile);\n },\n convertToReaderLock: async () => {\n // Acquire the read lock before releasing the write lock. Slightly less\n // chance of racing!\n const ret = await this.doAcquireRead();\n await deleteFile(this.writerFile);\n return ret;\n },\n };\n }\n\n /**\n * Acquire a read lock\n *\n * Will fail if there are any writers.\n */\n public async acquireRead(): Promise<ILock> {\n await this.assertNoOtherWriters();\n return this.doAcquireRead();\n }\n\n /**\n * Obtains the name fo a (new) `readerFile` to use. This includes a counter so\n * that if multiple threads of the same PID attempt to concurrently acquire\n * the same lock, they're guaranteed to use a different reader file name (only\n * one thread will ever execute JS code at once, guaranteeing the readCounter\n * is incremented \"atomically\" from the point of view of this PID.).\n */\n private readerFile(): string {\n return path.join(this.directory, `read.${this.pidString}.${++this.readCounter}.lock`);\n }\n\n /**\n * Do the actual acquiring of a read lock.\n */\n private async doAcquireRead(): Promise<ILock> {\n const readerFile = this.readerFile();\n await writeFileAtomic(readerFile, this.pidString);\n return {\n release: async () => {\n await deleteFile(readerFile);\n },\n };\n }\n\n private async assertNoOtherWriters() {\n const writer = await this.currentWriter();\n if (writer) {\n throw new ToolkitError(`Another CLI (PID=${writer}) is currently synthing to ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n }\n\n /**\n * Check the current writer (if any)\n */\n private async currentWriter(): Promise<number | undefined> {\n const contents = await readFileIfExists(this.writerFile);\n if (!contents) {\n return undefined;\n }\n\n const pid = parseInt(contents, 10);\n if (!processExists(pid)) {\n // Do cleanup of a stray file now\n await deleteFile(this.writerFile);\n return undefined;\n }\n\n return pid;\n }\n\n /**\n * Check the current readers (if any)\n */\n private async currentReaders(): Promise<number[]> {\n const re = /^read\\.([^.]+)\\.[^.]+\\.lock$/;\n const ret = new Array<number>();\n\n let children;\n try {\n children = await fs.readdir(this.directory, { encoding: 'utf-8' });\n } catch (e: any) {\n // Can't be locked if the directory doesn't exist\n if (e.code === 'ENOENT') {\n return [];\n }\n throw e;\n }\n\n for (const fname of children) {\n const m = fname.match(re);\n if (m) {\n const pid = parseInt(m[1], 10);\n if (processExists(pid)) {\n ret.push(pid);\n } else {\n // Do cleanup of a stray file now\n await deleteFile(path.join(this.directory, fname));\n }\n }\n }\n return ret;\n }\n}\n\n/**\n * An acquired lock\n */\nexport interface ILock {\n release(): Promise<void>;\n}\n\n/**\n * An acquired writer lock\n */\nexport interface IWriterLock extends ILock {\n /**\n * Convert the writer lock to a reader lock\n */\n convertToReaderLock(): Promise<ILock>;\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nasync function readFileIfExists(filename: string): Promise<string | undefined> {\n try {\n return await fs.readFile(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return undefined;\n }\n throw e;\n }\n}\n\nlet tmpCounter = 0;\n/* istanbul ignore next: code paths are unpredictable */\nasync function writeFileAtomic(filename: string, contents: string): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n const tmpFile = `${filename}.${process.pid}_${++tmpCounter}`;\n await fs.writeFile(tmpFile, contents, { encoding: 'utf-8' });\n await fs.rename(tmpFile, filename);\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nasync function deleteFile(filename: string) {\n try {\n await fs.unlink(filename);\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n}\n\n/* istanbul ignore next: code paths are unpredictable */\nfunction processExists(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return false;\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { SynthesisMessageLevel } from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { minimatch } from 'minimatch';\nimport * as semver from 'semver';\nimport { info } from '../../logging';\nimport { AssemblyError, ToolkitError } from '../../toolkit/error';\nimport { flatten } from '../../util';\n\nexport enum DefaultSelection {\n /**\n * Returns an empty selection in case there are no selectors.\n */\n None = 'none',\n\n /**\n * If the app includes a single stack, returns it. Otherwise throws an exception.\n * This behavior is used by \"deploy\".\n */\n OnlySingle = 'single',\n\n /**\n * Returns all stacks in the main (top level) assembly only.\n */\n MainAssembly = 'main',\n\n /**\n * If no selectors are provided, returns all stacks in the app,\n * including stacks inside nested assemblies.\n */\n AllStacks = 'all',\n}\n\nexport interface SelectStacksOptions {\n /**\n * Extend the selection to upstread/downstream stacks\n * @default ExtendedStackSelection.None only select the specified stacks.\n */\n extend?: ExtendedStackSelection;\n\n /**\n * The behavior if no selectors are provided.\n */\n defaultBehavior: DefaultSelection;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @default false\n */\n ignoreNoStacks?: boolean;\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExtendedStackSelection {\n /**\n * Don't select any extra stacks\n */\n None,\n\n /**\n * Include stacks that this stack depends on\n */\n Upstream,\n\n /**\n * Include stacks that depend on this stack\n */\n Downstream,\n}\n\n/**\n * A specification of which stacks should be selected\n */\nexport interface StackSelector {\n /**\n * Whether all stacks at the top level assembly should\n * be selected and nothing else\n */\n allTopLevel?: boolean;\n\n /**\n * A list of patterns to match the stack hierarchical ids\n */\n patterns: string[];\n}\n\n/**\n * A single Cloud Assembly and the operations we do on it to deploy the artifacts inside\n */\nexport class CloudAssembly {\n /**\n * The directory this CloudAssembly was read from\n */\n public readonly directory: string;\n\n constructor(public readonly assembly: cxapi.CloudAssembly) {\n this.directory = assembly.directory;\n }\n\n public async selectStacks(selector: StackSelector, options: SelectStacksOptions): Promise<StackCollection> {\n const asm = this.assembly;\n const topLevelStacks = asm.stacks;\n const stacks = semver.major(asm.version) < 10 ? asm.stacks : asm.stacksRecursively;\n const allTopLevel = selector.allTopLevel ?? false;\n const patterns = sanitizePatterns(selector.patterns);\n\n if (stacks.length === 0) {\n if (options.ignoreNoStacks) {\n return new StackCollection(this, []);\n }\n throw new ToolkitError('This app contains no stacks');\n }\n\n if (allTopLevel) {\n return this.selectTopLevelStacks(stacks, topLevelStacks, options.extend);\n } else if (patterns.length > 0) {\n return this.selectMatchingStacks(stacks, patterns, options.extend);\n } else {\n return this.selectDefaultStacks(stacks, topLevelStacks, options.defaultBehavior);\n }\n }\n\n private selectTopLevelStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n topLevelStacks: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): StackCollection {\n if (topLevelStacks.length > 0) {\n return this.extendStacks(topLevelStacks, stacks, extend);\n } else {\n throw new ToolkitError('No stack found in the main cloud assembly. Use \"list\" to print manifest');\n }\n }\n\n protected selectMatchingStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n patterns: string[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): StackCollection {\n const matchingPattern = (pattern: string) => (stack: cxapi.CloudFormationStackArtifact) => minimatch(stack.hierarchicalId, pattern);\n const matchedStacks = flatten(patterns.map(pattern => stacks.filter(matchingPattern(pattern))));\n\n return this.extendStacks(matchedStacks, stacks, extend);\n }\n\n private selectDefaultStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n topLevelStacks: cxapi.CloudFormationStackArtifact[],\n defaultSelection: DefaultSelection,\n ) {\n switch (defaultSelection) {\n case DefaultSelection.MainAssembly:\n return new StackCollection(this, topLevelStacks);\n case DefaultSelection.AllStacks:\n return new StackCollection(this, stacks);\n case DefaultSelection.None:\n return new StackCollection(this, []);\n case DefaultSelection.OnlySingle:\n if (topLevelStacks.length === 1) {\n return new StackCollection(this, topLevelStacks);\n } else {\n throw new ToolkitError('Since this app includes more than a single stack, specify which stacks to use (wildcards are supported) or specify `--all`\\n' +\n `Stacks: ${stacks.map(x => x.hierarchicalId).join(' \u00B7 ')}`);\n }\n default:\n throw new ToolkitError(`invalid default behavior: ${defaultSelection}`);\n }\n }\n\n protected extendStacks(\n matched: cxapi.CloudFormationStackArtifact[],\n all: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ) {\n const allStacks = new Map<string, cxapi.CloudFormationStackArtifact>();\n for (const stack of all) {\n allStacks.set(stack.hierarchicalId, stack);\n }\n\n const index = indexByHierarchicalId(matched);\n\n switch (extend) {\n case ExtendedStackSelection.Downstream:\n includeDownstreamStacks(index, allStacks);\n break;\n case ExtendedStackSelection.Upstream:\n includeUpstreamStacks(index, allStacks);\n break;\n }\n\n // Filter original array because it is in the right order\n const selectedList = all.filter(s => index.has(s.hierarchicalId));\n\n return new StackCollection(this, selectedList);\n }\n\n /**\n * Select a single stack by its ID\n */\n public stackById(stackId: string) {\n return new StackCollection(this, [this.assembly.getStackArtifact(stackId)]);\n }\n}\n\n/**\n * The dependencies of a stack.\n */\nexport type StackDependency = {\n id: string;\n dependencies: StackDependency[];\n};\n\n/**\n * Details of a stack.\n */\nexport type StackDetails = {\n id: string;\n name: string;\n environment: cxapi.Environment;\n dependencies: StackDependency[];\n};\n\n/**\n * A collection of stacks and related artifacts\n *\n * In practice, not all artifacts in the CloudAssembly are created equal;\n * stacks can be selected independently, but other artifacts such as asset\n * bundles cannot.\n */\nexport class StackCollection {\n constructor(public readonly assembly: CloudAssembly, public readonly stackArtifacts: cxapi.CloudFormationStackArtifact[]) {\n }\n\n public get stackCount() {\n return this.stackArtifacts.length;\n }\n\n public get firstStack() {\n if (this.stackCount < 1) {\n throw new ToolkitError('StackCollection contains no stack artifacts (trying to access the first one)');\n }\n return this.stackArtifacts[0];\n }\n\n public get stackIds(): string[] {\n return this.stackArtifacts.map(s => s.id);\n }\n\n public get hierarchicalIds(): string[] {\n return this.stackArtifacts.map(s => s.hierarchicalId);\n }\n\n public withDependencies(): StackDetails[] {\n const allData: StackDetails[] = [];\n\n for (const stack of this.stackArtifacts) {\n const data: StackDetails = {\n id: stack.displayName ?? stack.id,\n name: stack.stackName,\n environment: stack.environment,\n dependencies: [],\n };\n\n for (const dependencyId of stack.dependencies.map(x => x.id)) {\n if (dependencyId.includes('.assets')) {\n continue;\n }\n\n const depStack = this.assembly.stackById(dependencyId);\n\n if (depStack.firstStack.dependencies.filter((dep) => !(dep.id).includes('.assets')).length > 0) {\n for (const stackDetail of depStack.withDependencies()) {\n data.dependencies.push({\n id: stackDetail.id,\n dependencies: stackDetail.dependencies,\n });\n }\n } else {\n data.dependencies.push({\n id: depStack.firstStack.displayName ?? depStack.firstStack.id,\n dependencies: [],\n });\n }\n }\n\n allData.push(data);\n }\n\n return allData;\n }\n\n public reversed() {\n const arts = [...this.stackArtifacts];\n arts.reverse();\n return new StackCollection(this.assembly, arts);\n }\n\n public filter(predicate: (art: cxapi.CloudFormationStackArtifact) => boolean): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.filter(predicate));\n }\n\n public concat(...others: StackCollection[]): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.concat(...others.map(o => o.stackArtifacts)));\n }\n\n /**\n * Extracts 'aws:cdk:warning|info|error' metadata entries from the stack synthesis\n */\n public async validateMetadata(\n failAt: 'warn' | 'error' | 'none' = 'error',\n logger: (level: 'info' | 'error' | 'warn', msg: cxapi.SynthesisMessage) => Promise<void> = async () => {\n },\n ) {\n let warnings = false;\n let errors = false;\n\n for (const stack of this.stackArtifacts) {\n for (const message of stack.messages) {\n switch (message.level) {\n case SynthesisMessageLevel.WARNING:\n warnings = true;\n await logger('warn', message);\n break;\n case SynthesisMessageLevel.ERROR:\n errors = true;\n await logger('error', message);\n break;\n case SynthesisMessageLevel.INFO:\n await logger('info', message);\n break;\n }\n }\n }\n\n if (errors && failAt != 'none') {\n throw new AssemblyError('Found errors');\n }\n\n if (warnings && failAt === 'warn') {\n throw new AssemblyError('Found warnings (--strict mode)');\n }\n }\n}\n\nexport interface MetadataMessageOptions {\n /**\n * Whether to be verbose\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Don't stop on error metadata\n *\n * @default false\n */\n ignoreErrors?: boolean;\n\n /**\n * Treat warnings in metadata as errors\n *\n * @default false\n */\n strict?: boolean;\n}\n\nfunction indexByHierarchicalId(stacks: cxapi.CloudFormationStackArtifact[]): Map<string, cxapi.CloudFormationStackArtifact> {\n const result = new Map<string, cxapi.CloudFormationStackArtifact>();\n\n for (const stack of stacks) {\n result.set(stack.hierarchicalId, stack);\n }\n\n return result;\n}\n\n/**\n * Calculate the transitive closure of stack dependents.\n *\n * Modifies `selectedStacks` in-place.\n */\nfunction includeDownstreamStacks(\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>) {\n const added = new Array<string>();\n\n let madeProgress;\n do {\n madeProgress = false;\n\n for (const [id, stack] of allStacks) {\n // Select this stack if it's not selected yet AND it depends on a stack that's in the selected set\n if (!selectedStacks.has(id) && (stack.dependencies || []).some(dep => selectedStacks.has(dep.id))) {\n selectedStacks.set(id, stack);\n added.push(id);\n madeProgress = true;\n }\n }\n } while (madeProgress);\n\n if (added.length > 0) {\n info('Including depending stacks: %s', chalk.bold(added.join(', ')));\n }\n}\n\n/**\n * Calculate the transitive closure of stack dependencies.\n *\n * Modifies `selectedStacks` in-place.\n */\nfunction includeUpstreamStacks(\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>) {\n const added = new Array<string>();\n let madeProgress = true;\n while (madeProgress) {\n madeProgress = false;\n\n for (const stack of selectedStacks.values()) {\n // Select an additional stack if it's not selected yet and a dependency of a selected stack (and exists, obviously)\n for (const dependencyId of stack.dependencies.map(x => x.manifest.displayName ?? x.id)) {\n if (!selectedStacks.has(dependencyId) && allStacks.has(dependencyId)) {\n added.push(dependencyId);\n selectedStacks.set(dependencyId, allStacks.get(dependencyId)!);\n madeProgress = true;\n }\n }\n }\n }\n\n if (added.length > 0) {\n info('Including dependency stacks: %s', chalk.bold(added.join(', ')));\n }\n}\n\nexport function sanitizePatterns(patterns: string[]): string[] {\n let sanitized = patterns.filter(s => s != null); // filter null/undefined\n sanitized = [...new Set(sanitized)]; // make them unique\n return sanitized;\n}\n", "import * as childProcess from 'child_process';\nimport * as os from 'os';\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { Configuration, PROJECT_CONFIG, USER_DEFAULTS } from '../../cli/user-configuration';\nimport { versionNumber } from '../../cli/version';\nimport { debug, warning } from '../../logging';\nimport { ToolkitError } from '../../toolkit/error';\nimport { loadTree, some } from '../../tree';\nimport { splitBySize } from '../../util/objects';\nimport { SdkProvider } from '../aws-auth';\nimport { Settings } from '../settings';\nimport { RWLock, ILock } from '../util/rwlock';\n\nexport interface ExecProgramResult {\n readonly assembly: cxapi.CloudAssembly;\n readonly lock: ILock;\n}\n\n/** Invokes the cloud executable and returns JSON output */\nexport async function execProgram(aws: SdkProvider, config: Configuration): Promise<ExecProgramResult> {\n const env = await prepareDefaultEnvironment(aws);\n const context = await prepareContext(config.settings, config.context.all, env);\n\n const build = config.settings.get(['build']);\n if (build) {\n await exec(build);\n }\n\n const app = config.settings.get(['app']);\n if (!app) {\n throw new ToolkitError(`--app is required either in command-line, in ${PROJECT_CONFIG} or in ${USER_DEFAULTS}`);\n }\n\n // bypass \"synth\" if app points to a cloud assembly\n if (await fs.pathExists(app) && (await fs.stat(app)).isDirectory()) {\n debug('--app points to a cloud assembly, so we bypass synth');\n\n // Acquire a read lock on this directory\n const lock = await new RWLock(app).acquireRead();\n\n return { assembly: createAssembly(app), lock };\n }\n\n const commandLine = await guessExecutable(app);\n\n const outdir = config.settings.get(['output']);\n if (!outdir) {\n throw new ToolkitError('unexpected: --output is required');\n }\n if (typeof outdir !== 'string') {\n throw new ToolkitError(`--output takes a string, got ${JSON.stringify(outdir)}`);\n }\n try {\n await fs.mkdirp(outdir);\n } catch (error: any) {\n throw new ToolkitError(`Could not create output directory ${outdir} (${error.message})`);\n }\n\n debug('outdir:', outdir);\n env[cxapi.OUTDIR_ENV] = outdir;\n\n // Acquire a lock on the output directory\n const writerLock = await new RWLock(outdir).acquireWrite();\n\n try {\n // Send version information\n env[cxapi.CLI_ASM_VERSION_ENV] = cxschema.Manifest.version();\n env[cxapi.CLI_VERSION_ENV] = versionNumber();\n\n debug('env:', env);\n\n const envVariableSizeLimit = os.platform() === 'win32' ? 32760 : 131072;\n const [smallContext, overflow] = splitBySize(context, spaceAvailableForContext(env, envVariableSizeLimit));\n\n // Store the safe part in the environment variable\n env[cxapi.CONTEXT_ENV] = JSON.stringify(smallContext);\n\n // If there was any overflow, write it to a temporary file\n let contextOverflowLocation;\n if (Object.keys(overflow ?? {}).length > 0) {\n const contextDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-context'));\n contextOverflowLocation = path.join(contextDir, 'context-overflow.json');\n fs.writeJSONSync(contextOverflowLocation, overflow);\n env[cxapi.CONTEXT_OVERFLOW_LOCATION_ENV] = contextOverflowLocation;\n }\n\n await exec(commandLine.join(' '));\n\n const assembly = createAssembly(outdir);\n\n contextOverflowCleanup(contextOverflowLocation, assembly);\n\n return { assembly, lock: await writerLock.convertToReaderLock() };\n } catch (e) {\n await writerLock.release();\n throw e;\n }\n\n async function exec(commandAndArgs: string) {\n return new Promise<void>((ok, fail) => {\n // We use a slightly lower-level interface to:\n //\n // - Pass arguments in an array instead of a string, to get around a\n // number of quoting issues introduced by the intermediate shell layer\n // (which would be different between Linux and Windows).\n //\n // - Inherit stderr from controlling terminal. We don't use the captured value\n // anyway, and if the subprocess is printing to it for debugging purposes the\n // user gets to see it sooner. Plus, capturing doesn't interact nicely with some\n // processes like Maven.\n const proc = childProcess.spawn(commandAndArgs, {\n stdio: ['ignore', 'inherit', 'inherit'],\n detached: false,\n shell: true,\n env: {\n ...process.env,\n ...env,\n },\n });\n\n proc.on('error', fail);\n\n proc.on('exit', code => {\n if (code === 0) {\n return ok();\n } else {\n debug('failed command:', commandAndArgs);\n return fail(new ToolkitError(`Subprocess exited with error ${code}`));\n }\n });\n });\n }\n}\n\n/**\n * Creates an assembly with error handling\n */\nexport function createAssembly(appDir: string) {\n try {\n return new cxapi.CloudAssembly(appDir, {\n // We sort as we deploy\n topoSort: false,\n });\n } catch (error: any) {\n if (error.message.includes(cxschema.VERSION_MISMATCH)) {\n // this means the CLI version is too old.\n // we instruct the user to upgrade.\n throw new ToolkitError(`This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.\\n(${error.message})`);\n }\n throw error;\n }\n}\n\n/**\n * If we don't have region/account defined in context, we fall back to the default SDK behavior\n * where region is retrieved from ~/.aws/config and account is based on default credentials provider\n * chain and then STS is queried.\n *\n * This is done opportunistically: for example, if we can't access STS for some reason or the region\n * is not configured, the context value will be 'null' and there could failures down the line. In\n * some cases, synthesis does not require region/account information at all, so that might be perfectly\n * fine in certain scenarios.\n *\n * @param context The context key/value bash.\n */\nexport async function prepareDefaultEnvironment(\n aws: SdkProvider,\n logFn: (msg: string, ...args: any) => any = debug,\n): Promise<{ [key: string]: string }> {\n const env: { [key: string]: string } = { };\n\n env[cxapi.DEFAULT_REGION_ENV] = aws.defaultRegion;\n await logFn(`Setting \"${cxapi.DEFAULT_REGION_ENV}\" environment variable to`, env[cxapi.DEFAULT_REGION_ENV]);\n\n const accountId = (await aws.defaultAccount())?.accountId;\n if (accountId) {\n env[cxapi.DEFAULT_ACCOUNT_ENV] = accountId;\n await logFn(`Setting \"${cxapi.DEFAULT_ACCOUNT_ENV}\" environment variable to`, env[cxapi.DEFAULT_ACCOUNT_ENV]);\n }\n\n return env;\n}\n\n/**\n * Settings related to synthesis are read from context.\n * The merging of various configuration sources like cli args or cdk.json has already happened.\n * We now need to set the final values to the context.\n */\nexport async function prepareContext(settings: Settings, context: {[key: string]: any}, env: { [key: string]: string | undefined}) {\n const debugMode: boolean = settings.get(['debug']) ?? true;\n if (debugMode) {\n env.CDK_DEBUG = 'true';\n }\n\n const pathMetadata: boolean = settings.get(['pathMetadata']) ?? true;\n if (pathMetadata) {\n context[cxapi.PATH_METADATA_ENABLE_CONTEXT] = true;\n }\n\n const assetMetadata: boolean = settings.get(['assetMetadata']) ?? true;\n if (assetMetadata) {\n context[cxapi.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT] = true;\n }\n\n const versionReporting: boolean = settings.get(['versionReporting']) ?? true;\n if (versionReporting) {\n context[cxapi.ANALYTICS_REPORTING_ENABLED_CONTEXT] = true;\n }\n // We need to keep on doing this for framework version from before this flag was deprecated.\n if (!versionReporting) {\n context['aws:cdk:disable-version-reporting'] = true;\n }\n\n const stagingEnabled = settings.get(['staging']) ?? true;\n if (!stagingEnabled) {\n context[cxapi.DISABLE_ASSET_STAGING_CONTEXT] = true;\n }\n\n const bundlingStacks = settings.get(['bundlingStacks']) ?? ['**'];\n context[cxapi.BUNDLING_STACKS] = bundlingStacks;\n\n debug('context:', context);\n\n return context;\n}\n\n/**\n * Make sure the 'app' is an array\n *\n * If it's a string, split on spaces as a trivial way of tokenizing the command line.\n */\nfunction appToArray(app: any) {\n return typeof app === 'string' ? app.split(' ') : app;\n}\n\ntype CommandGenerator = (file: string) => string[];\n\n/**\n * Execute the given file with the same 'node' process as is running the current process\n */\nfunction executeNode(scriptFile: string): string[] {\n return [process.execPath, scriptFile];\n}\n\n/**\n * Mapping of extensions to command-line generators\n */\nconst EXTENSION_MAP = new Map<string, CommandGenerator>([\n ['.js', executeNode],\n]);\n\n/**\n * Guess the executable from the command-line argument\n *\n * Only do this if the file is NOT marked as executable. If it is,\n * we'll defer to the shebang inside the file itself.\n *\n * If we're on Windows, we ALWAYS take the handler, since it's hard to\n * verify if registry associations have or have not been set up for this\n * file type, so we'll assume the worst and take control.\n */\nexport async function guessExecutable(app: string) {\n const commandLine = appToArray(app);\n if (commandLine.length === 1) {\n let fstat;\n\n try {\n fstat = await fs.stat(commandLine[0]);\n } catch {\n debug(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);\n return commandLine;\n }\n\n // eslint-disable-next-line no-bitwise\n const isExecutable = (fstat.mode & fs.constants.X_OK) !== 0;\n const isWindows = process.platform === 'win32';\n\n const handler = EXTENSION_MAP.get(path.extname(commandLine[0]));\n if (handler && (!isExecutable || isWindows)) {\n return handler(commandLine[0]);\n }\n }\n return commandLine;\n}\n\nfunction contextOverflowCleanup(location: string | undefined, assembly: cxapi.CloudAssembly) {\n if (location) {\n fs.removeSync(path.dirname(location));\n\n const tree = loadTree(assembly);\n const frameworkDoesNotSupportContextOverflow = some(tree, node => {\n const fqn = node.constructInfo?.fqn;\n const version = node.constructInfo?.version;\n return (fqn === 'aws-cdk-lib.App' && version != null && semver.lte(version, '2.38.0'))\n || fqn === '@aws-cdk/core.App'; // v1\n });\n\n // We're dealing with an old version of the framework here. It is unaware of the temporary\n // file, which means that it will ignore the context overflow.\n if (frameworkDoesNotSupportContextOverflow) {\n warning('Part of the context could not be sent to the application. Please update the AWS CDK library to the latest version.');\n }\n }\n}\n\nexport function spaceAvailableForContext(env: { [key: string]: string }, limit: number) {\n const size = (value: string) => value != null ? Buffer.byteLength(value) : 0;\n\n const usedSpace = Object.entries(env)\n .map(([k, v]) => k === cxapi.CONTEXT_ENV ? size(k) : size(k) + size(v))\n .reduce((a, b) => a + b, 0);\n\n return Math.max(0, limit - usedSpace);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,uBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAoBO;AACP,iCAQO;AACP,mCAmFO;AACP,oCAQO;AACP,8BAKO;AACP,wBA6BO;AACP,wBA6BO;AACP,wBAaO;AACP,8CAeO;AACP,wBAWO;AACP,wBAQO;AACP,2BAkBO;AACP,6BAWO;AACP,uBA4BO;AACP,oCAKO;AACP,wBAKO;AACP,wBAKO;AACP,wBAAoD;AACpD,yBAAuB;AACvB,iCAA4C;AAG5C,wBAAwC;;;ACnUxC,IAAAC,QAAsB;AACtB,IAAAC,MAAoB;;;ACDpB,IAAAC,QAAsB;AACtB,IAAAC,SAAuB;;;ACDvB,IAAAC,QAAsB;AACtB,IAAAC,SAAuB;AACvB,eAA0B;;;ACF1B,IAAM,uBAAuB,OAAO,IAAI,+BAA+B;AACvE,IAAM,8BAA8B,OAAO,IAAI,sCAAsC;AACrF,IAAM,wBAAwB,OAAO,IAAI,gCAAgC;AACzE,IAAM,gCAAgC,OAAO,IAAI,uCAAuC;AAKjF,IAAM,eAAN,MAAM,sBA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B,SAAS,OAAO,OAAO,WAAW,KAAK,IAAI;AAE3E,QAAM,YAAY,OAAO,QAAQ,GAAG,EACjC,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,MAAY,qBAAc,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,EACrE,OAAO,CAAC,GAAG,MAAM,IAAI,GAAG,CAAC;AAE5B,SAAO,KAAK,IAAI,GAAG,QAAQ,SAAS;AACtC;",
6
+ "names": ["CloudAssembly", "path", "fs", "util", "chalk", "util", "chalk", "error", "path", "error", "util", "chalk", "trace", "prompt", "fs", "dirname", "cached", "path", "fs", "ECRDescribeImagesCommand", "os", "import_credential_providers", "promptly", "path", "import_util", "import_util", "chalk", "import_util", "os", "fs", "path", "import_util", "import_cx_api", "import_client_cloudformation", "import_cdk_assets", "error", "info", "debug", "trace", "util", "util", "debug", "error", "path", "info", "import_client_cloudformation", "_StackStatus", "path", "import_cx_api", "import_client_s3", "import_middleware_endpoint", "chalk", "fs", "debug", "debug", "chalk", "import_cx_api", "import_cdk_assets", "debug", "import_util", "chalk", "uuid", "path", "cxschema", "cxapi", "chalk", "debug", "import_util", "chalk", "path", "fs", "HotswapMode", "error", "archiver", "resolve", "info", "error", "debug", "info", "path", "fs", "semver", "path", "chalk", "fs", "semver", "import_util", "semver", "_exec", "path", "fs", "resolve", "cached", "import_util", "chalk", "debug", "bootstrapStack", "debug", "import_cx_api", "debug", "suffixWithErrors", "import_util", "chalk", "fs", "promptly", "info", "error", "prompt", "chalk", "fs", "info", "util", "chalk", "sleep", "error", "debug", "trace", "path", "cxapi", "import_cdk_assets", "cxschema", "cxapi", "path", "propertyMatchesFilter", "import_cx_api", "import_cx_api", "flatMap", "flatMap", "path", "fs", "import_cx_api", "chalk", "semver", "ExtendedStackSelection", "CloudAssembly", "path", "cxschema", "cxapi", "fs", "semver"]
7
7
  }