@aws-cdk/toolkit-lib 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/api-extractor.json +3 -0
- package/build-info.json +2 -2
- package/db.json.gz +0 -0
- package/lib/actions/bootstrap/private/helpers.js +3 -3
- package/lib/actions/diff/index.d.ts +1 -1
- package/lib/actions/diff/index.js +1 -1
- package/lib/actions/diff/private/helpers.js +8 -8
- package/lib/actions/refactor/index.d.ts +12 -0
- package/lib/actions/refactor/index.js +1 -1
- package/lib/api/aws-auth/awscli-compatible.js +2 -2
- package/lib/api/aws-auth/credential-plugins.js +2 -2
- package/lib/api/aws-auth/sdk-provider.js +2 -2
- package/lib/api/aws-auth/sdk.js +2 -2
- package/lib/api/bootstrap/bootstrap-environment.js +2 -2
- package/lib/api/cloud-assembly/environment.js +1 -1
- package/lib/api/cloud-assembly/index.d.ts +1 -1
- package/lib/api/cloud-assembly/index.js +3 -2
- package/lib/api/cloud-assembly/private/context-aware-source.js +3 -3
- package/lib/api/cloud-assembly/private/exec.js +3 -3
- package/lib/api/cloud-assembly/private/prepare-source.js +4 -4
- package/lib/api/cloud-assembly/private/source-builder.d.ts +10 -8
- package/lib/api/cloud-assembly/private/source-builder.js +36 -19
- package/lib/api/cloud-assembly/private/stack-assembly.js +7 -7
- package/lib/api/cloud-assembly/source-builder.d.ts +19 -0
- package/lib/api/cloud-assembly/source-builder.js +1 -1
- package/lib/api/cloud-assembly/stack-collection.js +2 -2
- package/lib/api/cloudformation/evaluate-cloudformation-template.d.ts +1 -1
- package/lib/api/cloudformation/evaluate-cloudformation-template.js +2 -2
- package/lib/api/cloudformation/stack-helpers.js +2 -2
- package/lib/api/cloudformation/template-body-parameter.js +2 -2
- package/lib/api/context.js +2 -2
- package/lib/api/deployments/asset-publishing.js +2 -2
- package/lib/api/deployments/assets.js +5 -6
- package/lib/api/deployments/cfn-api.js +3 -3
- package/lib/api/deployments/checks.js +2 -2
- package/lib/api/deployments/deploy-stack.js +2 -2
- package/lib/api/deployments/deployment-result.js +2 -2
- package/lib/api/deployments/deployments.js +3 -3
- package/lib/api/diff/diff-formatter.js +2 -2
- package/lib/api/environment/environment-access.js +2 -2
- package/lib/api/environment/environment-resources.js +2 -2
- package/lib/api/environment/placeholders.js +1 -1
- package/lib/api/garbage-collection/garbage-collector.js +2 -2
- package/lib/api/garbage-collection/progress-printer.js +2 -2
- package/lib/api/garbage-collection/stack-refresh.js +2 -2
- package/lib/api/hotswap/appsync-mapping-templates.js +2 -2
- package/lib/api/hotswap/common.js +2 -2
- package/lib/api/hotswap/hotswap-deployments.js +2 -2
- package/lib/api/hotswap/lambda-functions.js +2 -2
- package/lib/api/index.d.ts +0 -1
- package/lib/api/index.js +1 -2
- package/lib/api/io/private/level-priority.js +1 -1
- package/lib/api/io/private/sdk-logger.d.ts +1 -1
- package/lib/api/io/private/sdk-logger.js +6 -6
- package/lib/api/io/private/span.js +1 -1
- package/lib/api/logs-monitor/logs-monitor.js +2 -2
- package/lib/api/notices/cached-data-source.d.ts +13 -0
- package/lib/api/notices/cached-data-source.js +77 -0
- package/lib/api/notices/filter.d.ts +59 -0
- package/lib/api/notices/filter.js +189 -0
- package/lib/api/notices/index.d.ts +1 -0
- package/lib/api/notices/index.js +18 -0
- package/lib/api/notices/notices.d.ts +111 -0
- package/lib/api/notices/notices.js +131 -0
- package/lib/api/notices/types.d.ts +37 -0
- package/lib/api/notices/types.js +3 -0
- package/lib/api/notices/web-data-source.d.ts +9 -0
- package/lib/api/notices/web-data-source.js +70 -0
- package/lib/api/plugin/context-provider-plugin.js +1 -1
- package/lib/api/plugin/plugin.d.ts +0 -2
- package/lib/api/plugin/plugin.js +4 -9
- package/lib/api/refactoring/cloudformation.d.ts +23 -0
- package/lib/api/refactoring/cloudformation.js +54 -1
- package/lib/api/refactoring/exclude.d.ts +29 -0
- package/lib/api/refactoring/exclude.js +94 -0
- package/lib/api/refactoring/index.d.ts +4 -23
- package/lib/api/refactoring/index.js +28 -60
- package/lib/api/resource-import/importer.js +2 -2
- package/lib/api/rwlock.js +2 -2
- package/lib/api/settings.js +2 -2
- package/lib/api/shared-private.js +31 -6186
- package/lib/api/toolkit-info.js +2 -2
- package/lib/api/work-graph/work-graph-builder.js +3 -3
- package/lib/api/work-graph/work-graph.js +2 -2
- package/lib/context-providers/ami.js +2 -2
- package/lib/context-providers/cc-api-provider.js +2 -2
- package/lib/context-providers/hosted-zones.js +2 -2
- package/lib/context-providers/index.js +4 -4
- package/lib/context-providers/keys.js +2 -2
- package/lib/context-providers/load-balancers.js +2 -2
- package/lib/context-providers/security-groups.js +2 -2
- package/lib/context-providers/ssm-parameters.js +2 -2
- package/lib/context-providers/vpcs.js +3 -3
- package/lib/index.d.ts +3 -1
- package/lib/index.js +4 -2
- package/lib/index_bg.wasm +0 -0
- package/lib/payloads/deploy.d.ts +7 -0
- package/lib/payloads/deploy.js +1 -1
- package/lib/payloads/hotswap.d.ts +1 -0
- package/lib/payloads/hotswap.js +1 -1
- package/lib/private/activity-printer/base.js +1 -1
- package/lib/toolkit/non-interactive-io-host.js +5 -4
- package/lib/toolkit/toolkit.d.ts +2 -2
- package/lib/toolkit/toolkit.js +40 -27
- package/lib/util/directories.js +2 -2
- package/lib/util/index.d.ts +1 -0
- package/lib/util/index.js +2 -1
- package/lib/util/json.js +1 -1
- package/lib/util/net.d.ts +9 -0
- package/lib/util/net.js +60 -0
- package/lib/util/objects.js +2 -2
- package/lib/util/types.js +1 -1
- package/lib/util/version-range.js +2 -2
- package/package.json +25 -26
- package/tsdoc.json +15 -0
- package/lib/api/notices.d.ts +0 -210
- package/lib/api/notices.js +0 -430
- package/lib/api/shared-private.js.map +0 -7
- package/lib/api/shared-public.d.ts +0 -2139
- package/lib/api/shared-public.js +0 -3272
- package/lib/api/shared-public.js.map +0 -7
- package/lib/private/util.d.ts +0 -1
- package/lib/private/util.js +0 -787
- package/lib/private/util.js.map +0 -7
- /package/lib/{api → toolkit}/toolkit-error.d.ts +0 -0
- /package/lib/{api → toolkit}/toolkit-error.js +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["shared-public.ts", "toolkit-error.ts", "cloud-assembly/stack-selector.ts", "resource-metadata/resource-metadata.ts", "plugin/plugin.ts", "plugin/context-provider-plugin.ts", "../util/archive.ts", "../util/format-error.ts", "../util/directories.ts", "../util/json.ts", "../util/types.ts", "../util/yaml-cfn.ts", "../util/string-manipulation.ts", "../util/version-range.ts", "../private/dispose-polyfill.ts", "../private/activity-printer/history.ts", "../private/activity-printer/current.ts", "../private/activity-printer/display.ts", "aws-auth/proxy-agent.ts", "aws-auth/sdk.ts", "aws-auth/account-cache.ts", "aws-auth/cached.ts", "aws-auth/tracing.ts", "aws-auth/user-agent.ts", "aws-auth/util.ts", "aws-auth/sdk-provider.ts", "aws-auth/awscli-compatible.ts", "aws-auth/provider-caching.ts", "aws-auth/credential-plugins.ts", "../context-providers/index.ts", "../context-providers/ami.ts", "../context-providers/availability-zones.ts", "../context-providers/cc-api-provider.ts", "../context-providers/endpoint-service-availability-zones.ts", "../context-providers/hosted-zones.ts", "../context-providers/keys.ts", "../context-providers/load-balancers.ts", "../context-providers/security-groups.ts", "../context-providers/ssm-parameters.ts", "../context-providers/vpcs.ts", "settings.ts", "notices.ts", "tree.ts", "toolkit-info.ts", "deployments/cfn-api.ts", "deployments/asset-manifest-builder.ts", "cloudformation/template-body-parameter.ts", "cloudformation/nested-stack-helpers.ts", "stack-events/stack-activity-monitor.ts", "stack-events/stack-status.ts", "environment/placeholders.ts", "cloud-assembly/private/stack-assembly.ts", "cloud-assembly/stack-assembly.ts", "cloud-assembly/stack-collection.ts", "cloud-assembly/private/exec.ts", "cloud-assembly/private/prepare-source.ts", "cloud-assembly/environment.ts", "cloud-assembly/private/source-builder.ts", "cloud-assembly/private/stack-selectors.ts", "io/private/span.ts", "io/private/io-helper.ts", "io/private/level-priority.ts", "io/private/message-maker.ts", "io/private/messages.ts", "io/private/io-default-messages.ts", "../payloads/diff.ts", "../payloads/hotswap.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint-disable import/no-restricted-paths */\n\nexport {\n ToolkitError,\n AuthenticationError,\n AssemblyError,\n ContextProviderError,\n} from './toolkit-error';\n\nexport {\n ExpandStackSelection,\n StackSelectionStrategy,\n StackSelector,\n} from './cloud-assembly/stack-selector';\n\nexport { ResourceMetadata } from './resource-metadata';\n\nexport type {\n IoMessageLevel,\n IoMessageCode,\n IoMessage,\n IoRequest,\n} from './io/io-message';\nexport type { IIoHost } from './io/io-host';\nexport type { ToolkitAction } from './io/toolkit-action';\nexport { PluginHost, ContextProviderPlugin } from './plugin';\n\nexport * from '../payloads';\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\nconst TOOLKIT_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.ToolkitError');\nconst AUTHENTICATION_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AuthenticationError');\nconst ASSEMBLY_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AssemblyError');\nconst CONTEXT_PROVIDER_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.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 * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): ToolkitError {\n return new ToolkitError(message, 'toolkit', error);\n }\n\n /**\n * The type of the error, defaults to \"toolkit\".\n */\n public readonly type: string;\n\n /**\n * Denotes the source of the error as the toolkit.\n */\n public readonly source: 'toolkit' | 'user';\n\n /**\n * The specific original cause of the error, if available\n */\n public readonly cause?: unknown;\n\n constructor(message: string, type: string = 'toolkit', cause?: unknown) {\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 this.source = 'toolkit';\n this.cause = cause;\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AuthenticationError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\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 error causes by cloud assembly synthesis\n *\n * This includes errors thrown during app execution, as well as failing annotations.\n */\nexport class AssemblyError extends ToolkitError {\n /**\n * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): AssemblyError {\n return new AssemblyError(message, undefined, error);\n }\n\n /**\n * An AssemblyError with a list of stacks as cause\n */\n public static withStacks(message: string, stacks?: cxapi.CloudFormationStackArtifact[]): AssemblyError {\n return new AssemblyError(message, stacks);\n }\n\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n /**\n * The stacks that caused the error, if available\n *\n * The `messages` property of each `cxapi.CloudFormationStackArtifact` will contain the respective errors.\n * Absence indicates synthesis didn't fully complete.\n */\n public readonly stacks?: cxapi.CloudFormationStackArtifact[];\n\n private constructor(message: string, stacks?: cxapi.CloudFormationStackArtifact[], cause?: unknown) {\n super(message, 'assembly', cause);\n Object.setPrototypeOf(this, AssemblyError.prototype);\n Object.defineProperty(this, ASSEMBLY_ERROR_SYMBOL, { value: true });\n this.stacks = stacks;\n }\n}\n\n/**\n * Represents an error originating from a Context Provider\n */\nexport class ContextProviderError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\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", "/**\n * Which stacks should be selected from a cloud assembly\n */\nexport enum StackSelectionStrategy {\n /**\n * Returns all stacks in the app regardless of patterns,\n * including stacks inside nested assemblies.\n */\n ALL_STACKS = 'all-stacks',\n\n /**\n * Returns all stacks in the main (top level) assembly only.\n */\n MAIN_ASSEMBLY = 'main-assembly',\n\n /**\n * If the assembly includes a single stack, returns it.\n * Otherwise throws an exception.\n */\n ONLY_SINGLE = 'only-single',\n\n /**\n * Return stacks matched by patterns.\n * If no stacks are found, execution is halted successfully.\n * Most likely you don't want to use this but `StackSelectionStrategy.MUST_MATCH_PATTERN`\n */\n PATTERN_MATCH = 'pattern-match',\n\n /**\n * Return stacks matched by patterns.\n * Throws an exception if the patterns don't match at least one stack in the assembly.\n */\n PATTERN_MUST_MATCH = 'pattern-must-match',\n\n /**\n * Returns if exactly one stack is matched by the pattern(s).\n * Throws an exception if no stack, or more than exactly one stack are matched.\n */\n PATTERN_MUST_MATCH_SINGLE = 'pattern-must-match-single',\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExpandStackSelection {\n /**\n * Don't select any extra stacks\n */\n NONE = 'none',\n\n /**\n * Include stacks that this stack depends on\n */\n UPSTREAM = 'upstream',\n\n /**\n * Include stacks that depend on this stack\n */\n DOWNSTREAM = 'downstream',\n\n /**\n * @TODO\n * Include both directions.\n * I.e. stacks that this stack depends on, and stacks that depend on this stack.\n */\n // FULL = 'full',\n}\n\n/**\n * A specification of which stacks should be selected\n */\nexport interface StackSelector {\n /**\n * The behavior if if no selectors are provided.\n */\n strategy: StackSelectionStrategy;\n\n /**\n * A list of patterns to match the stack hierarchical ids\n * Only used with `PATTERN_*` selection strategies.\n */\n patterns?: string[];\n\n /**\n * Expand the selection to upstream/downstream stacks.\n * @default ExpandStackSelection.None only select the specified/matched stacks\n */\n expand?: ExpandStackSelection;\n\n /**\n * By default, we throw an exception if the assembly contains no stacks.\n * Set to `false`, to halt execution for empty assemblies without error.\n *\n * Note that actions can still throw if a stack selection result is empty,\n * but the assembly contains stacks in principle.\n *\n * @default true\n */\n failOnEmpty?: boolean;\n}\n", "import { ArtifactMetadataEntryType, type MetadataEntry } from '@aws-cdk/cloud-assembly-schema';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\n\n/**\n * Metadata entry for a resource within a CloudFormation stack\n */\nexport interface ResourceMetadata {\n /**\n * The resource's metadata as declared in the cloud assembly\n */\n readonly entry: MetadataEntry;\n /**\n * The construct path of the resource\n */\n readonly constructPath: string;\n}\n\n/**\n * Attempts to read metadata for resources from a CloudFormation stack artifact\n *\n * @param stack The CloudFormation stack to read from\n * @param logicalId The logical ID of the resource to read\n *\n * @returns The resource metadata, or undefined if the resource was not found\n */\nexport function resourceMetadata(stack: CloudFormationStackArtifact, logicalId: string): ResourceMetadata | undefined {\n const metadata = stack.manifest?.metadata;\n if (!metadata) {\n return undefined;\n }\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: simplifyConstructPath(path, stack.stackName),\n };\n }\n }\n return undefined;\n}\n\nfunction simplifyConstructPath(path: string, stackName: string) {\n path = path.replace(/\\/Resource$/, '');\n path = path.replace(/^\\//, ''); // remove \"/\" prefix\n\n // remove \"<stack-name>/\" prefix\n if (stackName) {\n if (path.startsWith(stackName + '/')) {\n path = path.slice(stackName.length + 1);\n }\n }\n return path;\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';\nimport { type ContextProviderPlugin, isContextProviderPlugin } from './context-provider-plugin';\nimport type { IIoHost } from '../io';\nimport { IoDefaultMessages, IoHelper } from '../private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport let TESTING = false;\n\nexport function markTesting() {\n TESTING = true;\n}\n\n/**\n * Class to manage a plugin collection\n *\n * It provides a `load()` function that loads a JavaScript\n * module from disk, and gives it access to the `IPluginHost` interface\n * to register itself.\n */\nexport class PluginHost implements IPluginHost {\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 public ioHost?: IIoHost;\n\n private readonly alreadyLoaded = new Set<string>();\n\n /**\n * Loads a plug-in into this PluginHost.\n *\n * Will use `require.resolve()` to get the most accurate representation of what\n * code will get loaded in error messages. As such, it will not work in\n * unit tests with Jest virtual modules becauase of <https://github.com/jestjs/jest/issues/9543>.\n *\n * @param moduleSpec the specification (path or name) of the plug-in module to be loaded.\n * @param ioHost the I/O host to use for printing progress information\n */\n public load(moduleSpec: string, ioHost?: IIoHost) {\n try {\n const resolved = require.resolve(moduleSpec);\n if (ioHost) {\n new IoDefaultMessages(IoHelper.fromIoHost(ioHost, 'init')).debug(`Loading plug-in: ${resolved} from ${moduleSpec}`);\n }\n return this._doLoad(resolved);\n } catch (e: any) {\n // according to Node.js docs `MODULE_NOT_FOUND` is the only possible error here\n // @see https://nodejs.org/api/modules.html#requireresolverequest-options\n // Not using `withCause()` here, since the node error contains a \"Require Stack\"\n // as part of the error message that is inherently useless to our users.\n throw new ToolkitError(`Unable to resolve plug-in: Cannot find module '${moduleSpec}': ${e}`);\n }\n }\n\n /**\n * Do the loading given an already-resolved module name\n *\n * @internal\n */\n public _doLoad(resolved: string) {\n try {\n if (this.alreadyLoaded.has(resolved)) {\n return;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const plugin = require(resolved);\n /* eslint-enable */\n if (!isPlugin(plugin)) {\n throw new ToolkitError(`Module ${resolved} is not a valid plug-in, or has an unsupported version.`);\n }\n if (plugin.init) {\n plugin.init(this);\n }\n\n this.alreadyLoaded.add(resolved);\n } catch (e: any) {\n throw ToolkitError.withCause(`Unable to load plug-in '${resolved}'`, 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 { 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", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { ToolkitError } from '../api/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 /* c8 ignore start */ // will not happen in normal setups\n if (userInfoHome == '/var/empty') {\n userInfoHome = undefined;\n }\n /* c8 ignore stop */\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 start location, find the directory that contains the bundled package's package.json\n *\n * You must assume the caller of this function will be bundled and the package root dir\n * is not going to be the same as the package the caller currently lives in.\n */\nexport function bundledPackageRootDir(start: string): string;\nexport function bundledPackageRootDir(start: string, fail: true): string;\nexport function bundledPackageRootDir(start: string, fail: false): string | undefined;\nexport function bundledPackageRootDir(start: string, 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(start);\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", "/**\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 * as yaml from 'yaml';\nimport type * 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\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", "import * as semver from 'semver';\nimport { ToolkitError } from '../api/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", "// This file needs to be imported as one of the first files in the library.\n// It polyfills some symbols that the new JavaScript \"Disposable\" API introduces.\n//\n// See <https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html>\n//\n// In short, the new proposal is a `using`/`await using` statement, which will automatically\n// call methods named `[Symbol.dispose]` and `[Symbol.asyncDispose]` on objects.\n//\n// TypeScript knows about those symbols, and it will downlevel the `using` syntax to\n// plain JavaScript... but it doesn't define the Symbols themselves! They must exist\n// in the environment, or code defining objects using those Symbol names will fail.\n//\n// MDN doesn't even know that Node 22 has them already; for broadest compatibility,\n// we just polyfill them here. Their value doesn't matter, they just need to exist\n// and be unique symbols.\n(Symbol as any).dispose ??= Symbol('Symbol.dispose');\n(Symbol as any).asyncDispose ??= Symbol('Symbol.asyncDispose');\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport type { StackActivity } from '../../payloads';\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 type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport { RewritableBlock } from './display';\nimport type { StackActivity } from '../../payloads';\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-extra';\nimport { ProxyAgent } from 'proxy-agent';\nimport type { SdkHttpOptions } from './types';\nimport { IO, type IoHelper } from '../io/private';\n\nexport class ProxyAgentProvider {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n public async create(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: await this.tryGetCACert(options.caBundlePath),\n getProxyForUrl,\n });\n }\n\n private async tryGetCACert(bundlePath?: string) {\n const path = bundlePath || this.caBundlePathFromEnvironment();\n if (path) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Using CA bundle path: ${path}`));\n try {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n return fs.readFileSync(path, { encoding: 'utf-8' });\n } catch (e: any) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(String(e)));\n return undefined;\n }\n }\n return undefined;\n }\n\n /**\n * Find and return a CA certificate bundle path to be passed into the SDK.\n */\n private 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", "import type {\n FunctionConfiguration,\n GetSchemaCreationStatusCommandInput,\n GetSchemaCreationStatusCommandOutput,\n ListFunctionsCommandInput,\n StartSchemaCreationCommandInput,\n StartSchemaCreationCommandOutput,\n UpdateApiKeyCommandInput,\n UpdateApiKeyCommandOutput,\n UpdateFunctionCommandInput,\n UpdateFunctionCommandOutput,\n UpdateResolverCommandInput,\n UpdateResolverCommandOutput,\n} from '@aws-sdk/client-appsync';\nimport {\n AppSyncClient,\n GetSchemaCreationStatusCommand,\n paginateListFunctions,\n StartSchemaCreationCommand,\n UpdateApiKeyCommand,\n UpdateFunctionCommand,\n UpdateResolverCommand,\n} from '@aws-sdk/client-appsync';\nimport type {\n GetResourceCommandInput,\n GetResourceCommandOutput,\n ListResourcesCommandInput,\n ListResourcesCommandOutput,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudControlClient,\n GetResourceCommand,\n ListResourcesCommand,\n} from '@aws-sdk/client-cloudcontrol';\nimport type {\n ContinueUpdateRollbackCommandInput,\n ContinueUpdateRollbackCommandOutput,\n DescribeStackEventsCommandOutput,\n DescribeStackResourcesCommandInput,\n DescribeStackResourcesCommandOutput,\n ListStacksCommandInput,\n ListStacksCommandOutput,\n RollbackStackCommandInput,\n RollbackStackCommandOutput,\n StackResourceSummary,\n CreateChangeSetCommandInput,\n CreateChangeSetCommandOutput,\n CreateGeneratedTemplateCommandInput,\n CreateGeneratedTemplateCommandOutput,\n CreateStackCommandInput,\n CreateStackCommandOutput,\n DeleteChangeSetCommandInput,\n DeleteChangeSetCommandOutput,\n DeleteGeneratedTemplateCommandInput,\n DeleteGeneratedTemplateCommandOutput,\n DeleteStackCommandInput,\n DeleteStackCommandOutput,\n DescribeChangeSetCommandInput,\n DescribeChangeSetCommandOutput,\n DescribeGeneratedTemplateCommandInput,\n DescribeGeneratedTemplateCommandOutput,\n DescribeResourceScanCommandInput,\n DescribeResourceScanCommandOutput,\n DescribeStackEventsCommandInput,\n DescribeStacksCommandInput,\n DescribeStacksCommandOutput,\n ExecuteChangeSetCommandInput,\n ExecuteChangeSetCommandOutput,\n GetGeneratedTemplateCommandInput,\n GetGeneratedTemplateCommandOutput,\n GetTemplateCommandInput,\n GetTemplateCommandOutput,\n GetTemplateSummaryCommandInput,\n GetTemplateSummaryCommandOutput,\n ListExportsCommandInput,\n ListExportsCommandOutput,\n ListResourceScanRelatedResourcesCommandInput,\n ListResourceScanRelatedResourcesCommandOutput,\n ListResourceScanResourcesCommandInput,\n ListResourceScanResourcesCommandOutput,\n ListResourceScansCommandInput,\n ListResourceScansCommandOutput,\n ListStackResourcesCommandInput,\n StartResourceScanCommandInput,\n StartResourceScanCommandOutput,\n UpdateStackCommandInput,\n UpdateStackCommandOutput,\n UpdateTerminationProtectionCommandInput,\n UpdateTerminationProtectionCommandOutput,\n StackSummary,\n} from '@aws-sdk/client-cloudformation';\nimport {\n paginateListStacks,\n CloudFormationClient,\n ContinueUpdateRollbackCommand,\n CreateChangeSetCommand,\n CreateGeneratedTemplateCommand,\n CreateStackCommand,\n DeleteChangeSetCommand,\n DeleteGeneratedTemplateCommand,\n DeleteStackCommand,\n DescribeChangeSetCommand,\n DescribeGeneratedTemplateCommand,\n DescribeResourceScanCommand,\n DescribeStackEventsCommand,\n DescribeStackResourcesCommand,\n DescribeStacksCommand,\n ExecuteChangeSetCommand,\n GetGeneratedTemplateCommand,\n GetTemplateCommand,\n GetTemplateSummaryCommand,\n ListExportsCommand,\n ListResourceScanRelatedResourcesCommand,\n ListResourceScanResourcesCommand,\n ListResourceScansCommand,\n ListStacksCommand,\n paginateListStackResources,\n RollbackStackCommand,\n StartResourceScanCommand,\n UpdateStackCommand,\n UpdateTerminationProtectionCommand,\n} from '@aws-sdk/client-cloudformation';\nimport type {\n FilterLogEventsCommandInput,\n FilterLogEventsCommandOutput,\n DescribeLogGroupsCommandInput,\n DescribeLogGroupsCommandOutput,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CloudWatchLogsClient,\n DescribeLogGroupsCommand,\n FilterLogEventsCommand,\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 type {\n BatchDeleteImageCommandInput,\n BatchDeleteImageCommandOutput,\n ListImagesCommandInput,\n ListImagesCommandOutput,\n PutImageCommandInput,\n PutImageCommandOutput,\n BatchGetImageCommandInput,\n BatchGetImageCommandOutput,\n CreateRepositoryCommandInput,\n CreateRepositoryCommandOutput,\n DescribeImagesCommandInput as ECRDescribeImagesCommandInput,\n DescribeImagesCommandOutput as ECRDescribeImagesCommandOutput,\n DescribeRepositoriesCommandInput,\n DescribeRepositoriesCommandOutput,\n GetAuthorizationTokenCommandInput,\n GetAuthorizationTokenCommandOutput,\n PutImageScanningConfigurationCommandInput,\n PutImageScanningConfigurationCommandOutput,\n} from '@aws-sdk/client-ecr';\nimport {\n BatchDeleteImageCommand,\n CreateRepositoryCommand,\n DescribeImagesCommand as ECRDescribeImagesCommand,\n DescribeRepositoriesCommand,\n ECRClient,\n GetAuthorizationTokenCommand,\n ListImagesCommand,\n PutImageCommand,\n PutImageScanningConfigurationCommand,\n BatchGetImageCommand,\n} from '@aws-sdk/client-ecr';\nimport type {\n DescribeServicesCommandInput,\n RegisterTaskDefinitionCommandInput,\n ListClustersCommandInput,\n ListClustersCommandOutput,\n RegisterTaskDefinitionCommandOutput,\n UpdateServiceCommandInput,\n UpdateServiceCommandOutput,\n} from '@aws-sdk/client-ecs';\nimport {\n ECSClient,\n ListClustersCommand,\n RegisterTaskDefinitionCommand,\n UpdateServiceCommand,\n waitUntilServicesStable,\n} from '@aws-sdk/client-ecs';\nimport type {\n Listener,\n LoadBalancer,\n DescribeListenersCommandInput,\n DescribeListenersCommandOutput,\n DescribeLoadBalancersCommandInput,\n DescribeLoadBalancersCommandOutput,\n DescribeTagsCommandInput,\n DescribeTagsCommandOutput,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n DescribeListenersCommand,\n DescribeLoadBalancersCommand,\n DescribeTagsCommand,\n ElasticLoadBalancingV2Client,\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 type {\n DeleteObjectsCommandInput,\n DeleteObjectsCommandOutput,\n DeleteObjectTaggingCommandInput,\n DeleteObjectTaggingCommandOutput,\n GetObjectTaggingCommandInput,\n GetObjectTaggingCommandOutput,\n PutObjectTaggingCommandInput,\n PutObjectTaggingCommandOutput,\n CompleteMultipartUploadCommandOutput,\n GetBucketEncryptionCommandInput,\n GetBucketEncryptionCommandOutput,\n GetBucketLocationCommandInput,\n GetBucketLocationCommandOutput,\n GetObjectCommandInput,\n GetObjectCommandOutput,\n ListObjectsV2CommandInput,\n ListObjectsV2CommandOutput,\n PutObjectCommandInput,\n} from '@aws-sdk/client-s3';\nimport {\n DeleteObjectsCommand,\n DeleteObjectTaggingCommand,\n GetBucketEncryptionCommand,\n GetBucketLocationCommand,\n GetObjectCommand,\n GetObjectTaggingCommand,\n ListObjectsV2Command,\n PutObjectTaggingCommand,\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 type {\n UpdateStateMachineCommandInput,\n UpdateStateMachineCommandOutput,\n} from '@aws-sdk/client-sfn';\nimport {\n SFNClient,\n UpdateStateMachineCommand,\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 type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { ConfiguredRetryStrategy } from '@smithy/util-retry';\nimport type { WaiterResult } from '@smithy/util-waiter';\nimport { AccountAccessKeyCache } from './account-cache';\nimport { cachedAsync } from './cached';\nimport type { Account } from './sdk-provider';\nimport { traceMemberMethods } from './tracing';\nimport { defaultCliUserAgent } from './user-agent';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { AuthenticationError } from '../toolkit-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 paginatedListStacks(input: ListStacksCommandInput): Promise<StackSummary[]>;\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 public readonly currentRegion: string;\n\n public readonly config: ConfigurationOptions;\n\n protected readonly logger?: Logger;\n\n private readonly accountCache;\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 /**\n * A function to create debug messages\n */\n private readonly debug: (msg: string) => Promise<void>;\n\n constructor(\n private readonly credProvider: AwsCredentialIdentityProvider,\n region: string,\n requestHandler: NodeHttpHandlerOptions,\n ioHelper: IoHelper,\n logger?: Logger,\n ) {\n const debugFn = async (msg: string) => ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(msg));\n this.accountCache = new AccountAccessKeyCache(AccountAccessKeyCache.DEFAULT_PATH, debugFn);\n this.debug = debugFn;\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 paginatedListStacks: async (input: ListStacksCommandInput): Promise<StackSummary[]> => {\n const stackResources = Array<StackSummary>();\n const paginator = paginateListStacks({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackSummaries || []));\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 this.accountCache.fetch(creds.accessKeyId, async () => {\n // if we don't have one, resolve from STS and store in cache.\n await this.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 await this.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 type { Account } from './sdk-provider';\nimport { cdkCacheDir } from '../../util';\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 /**\n * The default path used for the accounts access key cache\n */\n public static get DEFAULT_PATH(): string {\n // needs to be a getter because cdkCacheDir can be set via env variable and might change\n return path.join(cdkCacheDir(), 'accounts_partitions.json');\n }\n\n private readonly cacheFile: string;\n\n private readonly debug: (msg: string) => Promise<void>;\n\n /**\n * @param filePath Path to the cache file\n */\n constructor(filePath: string = AccountAccessKeyCache.DEFAULT_PATH, debugFn: (msg: string) => Promise<void>) {\n this.cacheFile = filePath;\n this.debug = debugFn;\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 await this.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", "/**\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 { bundledPackageRootDir } from '../../util';\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 = bundledPackageRootDir(__dirname, 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';\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 return undefined;\n }\n}\n", "import * as os from 'os';\nimport type { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport { EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport type { AssumeRoleCommandInput } from '@aws-sdk/client-sts';\nimport { fromTemporaryCredentials } from '@aws-sdk/credential-providers';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport type { 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 { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { PluginHost, Mode } from '../plugin';\nimport { AuthenticationError } from '../toolkit-error';\n\nexport type AssumeRoleAdditionalOptions = Partial<Omit<AssumeRoleCommandInput, 'ExternalId' | 'RoleArn'>>;\n\n/**\n * Options for the default SDK provider\n */\nexport interface SdkProviderOptions extends SdkProviderServices {\n /**\n * Profile to read from ~/.aws\n *\n * @default - No profile\n */\n readonly profile?: 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 config = await new AwsCliCompatible(options.ioHelper, options.requestHandler ?? {}, options.logger).baseConfig(options.profile);\n return new SdkProvider(config.credentialProvider, config.defaultRegion, options);\n }\n\n public readonly defaultRegion: string;\n private readonly defaultCredentialProvider: AwsCredentialIdentityProvider;\n private readonly plugins;\n private readonly requestHandler: NodeHttpHandlerOptions;\n private readonly ioHelper: IoHelper;\n private readonly logger?: Logger;\n\n public constructor(\n defaultCredentialProvider: AwsCredentialIdentityProvider,\n defaultRegion: string | undefined,\n services: SdkProviderServices,\n ) {\n this.defaultCredentialProvider = defaultCredentialProvider;\n this.defaultRegion = defaultRegion ?? 'us-east-1';\n this.requestHandler = services.requestHandler ?? {};\n this.ioHelper = services.ioHelper;\n this.logger = services.logger;\n this.plugins = new CredentialPlugins(services.pluginHost ?? new PluginHost(), this.ioHelper);\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 = this._makeSdk(baseCreds.credentials, env.region);\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 await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(err.message));\n\n const maker = quiet ? IO.DEFAULT_SDK_DEBUG : IO.DEFAULT_SDK_WARN;\n await this.ioHelper.notify(maker.msg(\n `${fmtObtainedCredentials(baseCreds)} could not be used to assume '${options.assumeRoleArn}', but are for the right account. Proceeding anyway.`,\n ));\n return {\n sdk: this._makeSdk(baseCreds.credentials, env.region),\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 this._makeSdk(baseCreds.credentials, env.region).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 this._makeSdk(this.defaultCredentialProvider, this.defaultRegion).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 await this.ioHelper.notify(IO.DEFAULT_SDK_WARN.msg(\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 await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`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 await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`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 this._makeSdk(credentials, region);\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`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 * Factory function that creates a new SDK instance\n *\n * This is a function here, instead of all the places where this is used creating a `new SDK`\n * instance, so that it is trivial to mock from tests.\n *\n * Use like this:\n *\n * ```ts\n * const mockSdk = jest.spyOn(SdkProvider.prototype, '_makeSdk').mockReturnValue(new MockSdk());\n * // ...\n * mockSdk.mockRestore();\n * ```\n *\n * @internal\n */\n public _makeSdk(\n credProvider: AwsCredentialIdentityProvider,\n region: string,\n ) {\n return new SDK(credProvider, region, this.requestHandler, this.ioHelper, this.logger);\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\nexport interface SdkProviderServices {\n /**\n * An IO helper for emitting messages\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The request handler settings\n */\n readonly requestHandler?: NodeHttpHandlerOptions;\n\n /**\n * A plugin host\n */\n readonly pluginHost?: PluginHost;\n\n /**\n * An SDK logger\n */\n readonly logger?: Logger;\n}\n", "import { format } from 'node:util';\nimport { 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 type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport * as promptly from 'promptly';\nimport { makeCachingProvider } from './provider-caching';\nimport { ProxyAgentProvider } from './proxy-agent';\nimport type { SdkHttpOptions } from './types';\nimport { IO, type IoHelper } from '../io/private';\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 private readonly ioHelper: IoHelper;\n private readonly requestHandler: NodeHttpHandlerOptions;\n private readonly logger?: Logger;\n\n public constructor(ioHelper: IoHelper, requestHandler: NodeHttpHandlerOptions, logger?: Logger) {\n this.ioHelper = ioHelper;\n this.requestHandler = requestHandler;\n this.logger = logger;\n }\n\n public async baseConfig(profile?: string): Promise<{ credentialProvider: AwsCredentialIdentityProvider; defaultRegion: string }> {\n const credentialProvider = await this.credentialChainBuilder({\n profile,\n logger: this.logger,\n });\n const defaultRegion = await this.region(profile);\n return { credentialProvider, defaultRegion };\n }\n\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 async credentialChainBuilder(\n options: CredentialChainOptions = {},\n ): Promise<AwsCredentialIdentityProvider> {\n const clientConfig = {\n requestHandler: this.requestHandler,\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: this.tokenCodeFn.bind(this),\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: this.tokenCodeFn.bind(this),\n ignoreCache: true,\n });\n\n return shouldPrioritizeEnv()\n ? createCredentialChain(fromEnv(), nodeProviderChain).expireAfter(60 * 60_000)\n : nodeProviderChain;\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 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 this.getRegionFromIni(profile)) ||\n (await this.regionFromMetadataService());\n\n if (!region) {\n const usedProfile = !profile ? '' : ` (profile: \"${profile}\")`;\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(\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 * 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 */\n private async regionFromMetadataService() {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg('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 await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Unable to retrieve AWS region from IMDS: ${e}`));\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 */\n private async 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 this.getRegionFromIniFile(profile, sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile(profile, sharedFiles.configFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.configFile);\n }\n\n private getRegionFromIniFile(profile: string, data?: any) {\n return data?.[profile]?.region;\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 */\n private async tokenCodeFn(serialArn: string): Promise<string> {\n const debugFn = (msg: string, ...args: any[]) => this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(format(msg, ...args)));\n await debugFn('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 await debugFn('Successfully got MFA token from user');\n return token;\n } catch (err: any) {\n await debugFn('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}\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\nexport interface CredentialChainOptions {\n readonly profile?: string;\n readonly logger?: Logger;\n}\n\nexport async function makeRequestHandler(ioHelper: IoHelper, options: SdkHttpOptions = {}): Promise<NodeHttpHandlerOptions> {\n const agent = await new ProxyAgentProvider(ioHelper).create(options);\n\n return {\n connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,\n requestTimeout: DEFAULT_TIMEOUT,\n httpsAgent: agent,\n httpAgent: agent,\n };\n}\n", "import { memoize } from '@smithy/property-provider';\nimport type { 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 { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport type { PluginHost } from '../plugin';\nimport type { Mode } from '../plugin/mode';\nimport { AuthenticationError } from '../toolkit-error';\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\n constructor(private readonly host: PluginHost, private readonly ioHelper: IoHelper) {\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 await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n available = false;\n }\n\n if (!available) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Credentials source ${source.name} is not available, ignoring it.`));\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 await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n canProvide = false;\n }\n if (!canProvide) {\n continue;\n }\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`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 * 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 type { SdkProvider } from '../api/aws-auth/private';\nimport type { Context } from '../api/context';\nimport { TRANSIENT_CONTEXT_KEY } from '../api/context';\nimport { replaceEnvPlaceholders } from '../api/environment';\nimport { IO } from '../api/io/private';\nimport type { IoHelper } from '../api/io/private';\nimport type { PluginHost, ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { formatErrorMessage } from '../util';\n\ntype ContextProviderFactory = ((sdk: SdkProvider, io: IContextProviderMessages) => ContextProviderPlugin);\ntype ProviderMap = {[name: string]: ContextProviderFactory};\n\nconst PLUGIN_PROVIDER_PREFIX = 'plugin';\n\nexport interface IContextProviderMessages {\n /**\n * A message that is presented to users in normal mode of operation.\n *\n * Should be used sparingly. The Context Provider framework already provides useful output by default.\n * This can be uses in exceptionally situations, e.g. if a lookup call is expected to take a long time.\n */\n info(message: string): Promise<void>;\n\n /**\n * A message that helps users debugging the context provider.\n *\n * Should be used in most cases to note on current action.\n */\n debug(message: string): Promise<void>;\n}\n\nclass ContextProviderMessages implements IContextProviderMessages {\n private readonly ioHelper: IoHelper;\n private readonly providerName: string;\n\n public constructor(ioHelper: IoHelper, providerName: string) {\n this.ioHelper = ioHelper;\n this.providerName = providerName;\n }\n\n public async info(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0300.msg(message, {\n provider: this.providerName,\n }));\n }\n\n public async debug(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0301.msg(message, {\n provider: this.providerName,\n }));\n }\n}\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 pluginHost: PluginHost,\n ioHelper: IoHelper,\n) {\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.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, new ContextProviderMessages(ioHelper, providerName));\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 await ioHelper.notify(IO.DEFAULT_ASSEMBLY_DEBUG.msg(`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, io) => new AZContextProviderPlugin(s, io),\n [cxschema.ContextProvider.SSM_PARAMETER_PROVIDER]: (s, io) => new SSMContextProviderPlugin(s, io),\n [cxschema.ContextProvider.HOSTED_ZONE_PROVIDER]: (s, io) => new HostedZoneContextProviderPlugin(s, io),\n [cxschema.ContextProvider.VPC_PROVIDER]: (s, io) => new VpcNetworkContextProviderPlugin(s, io),\n [cxschema.ContextProvider.AMI_PROVIDER]: (s, io) => new AmiContextProviderPlugin(s, io),\n [cxschema.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]: (s, io) => new EndpointServiceAZContextProviderPlugin(s, io),\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, io) => new KeyContextProviderPlugin(s, io),\n [cxschema.ContextProvider.CC_API_PROVIDER]: (s) => new CcApiContextProviderPlugin(s),\n};\n", "import type { AmiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/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, private readonly io: IContextProviderMessages) {\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 await this.io.info(`Searching for AMI in ${account}:${region}`);\n await this.io.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 await this.io.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 { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\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, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: AvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n await this.io.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", "import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { ResourceDescription } from '@aws-sdk/client-cloudcontrol';\nimport { ResourceNotFoundException } from '@aws-sdk/client-cloudcontrol';\nimport type { ICloudControlClient, SdkProvider } from '../api/aws-auth/private';\nimport { initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { findJsonValue, getResultObj } from '../util';\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 *\n * See the documentation in the Cloud Assembly Schema for the semantics of\n * each query parameter.\n */\n public async getValue(args: CcApiContextQuery) {\n // Validate input\n if (args.exactIdentifier && args.propertyMatch) {\n throw new ContextProviderError(`Provider protocol error: specify either exactIdentifier or propertyMatch, but not both (got ${JSON.stringify(args)})`);\n }\n if (args.ignoreErrorOnMissingContext && args.dummyValue === undefined) {\n throw new ContextProviderError(`Provider protocol error: if ignoreErrorOnMissingContext is set, a dummyValue must be supplied (got ${JSON.stringify(args)})`);\n }\n if (args.dummyValue !== undefined && (!Array.isArray(args.dummyValue) || !args.dummyValue.every(isObject))) {\n throw new ContextProviderError(`Provider protocol error: dummyValue must be an array of objects (got ${JSON.stringify(args.dummyValue)})`);\n }\n\n // Do the lookup\n const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl();\n\n try {\n let resources: FoundResource[];\n if (args.exactIdentifier) {\n // use getResource to get the exact indentifier\n resources = await this.getResource(cloudControl, args.typeName, args.exactIdentifier);\n } else if (args.propertyMatch) {\n // use listResource\n resources = await this.listResources(cloudControl, args.typeName, args.propertyMatch, args.expectedMatchCount);\n } else {\n throw new ContextProviderError(`Provider protocol error: neither exactIdentifier nor propertyMatch is specified in ${JSON.stringify(args)}.`);\n }\n\n return resources.map((r) => getResultObj(r.properties, r.identifier, args.propertiesToReturn));\n } catch (err) {\n if (err instanceof ZeroResourcesFoundError && args.ignoreErrorOnMissingContext) {\n // We've already type-checked dummyValue.\n return args.dummyValue;\n }\n throw err;\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 * Will always return exactly one resource, or fail.\n */\n private async getResource(\n cc: ICloudControlClient,\n typeName: string,\n exactIdentifier: string,\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.getResource({\n TypeName: typeName,\n Identifier: exactIdentifier,\n });\n if (!result.ResourceDescription) {\n throw new ContextProviderError('Unexpected CloudControl API behavior: returned empty response');\n }\n\n return [foundResourceFromCcApi(result.ResourceDescription)];\n } catch (err: any) {\n if (err instanceof ResourceNotFoundException || (err as any).name === 'ResourceNotFoundException') {\n throw new ZeroResourcesFoundError(`No resource of type ${typeName} with identifier: ${exactIdentifier}`);\n }\n if (!(err instanceof ContextProviderError)) {\n throw new ContextProviderError(`Encountered CC API error while getting ${typeName} resource ${exactIdentifier}: ${err.message}`);\n }\n throw err;\n }\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 * Will return 0 or more resources.\n *\n * Does not currently paginate through more than one result page.\n */\n private async listResources(\n cc: ICloudControlClient,\n typeName: string,\n propertyMatch: Record<string, unknown>,\n expectedMatchCount?: CcApiContextQuery['expectedMatchCount'],\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.listResources({\n TypeName: typeName,\n\n });\n const found = (result.ResourceDescriptions ?? [])\n .map(foundResourceFromCcApi)\n .filter((r) => {\n return Object.entries(propertyMatch).every(([propPath, expected]) => {\n const actual = findJsonValue(r.properties, propPath);\n return propertyMatchesFilter(actual, expected);\n });\n });\n\n if ((expectedMatchCount === 'at-least-one' || expectedMatchCount === 'exactly-one') && found.length === 0) {\n throw new ZeroResourcesFoundError(`Could not find any resources matching ${JSON.stringify(propertyMatch)}`);\n }\n if ((expectedMatchCount === 'at-most-one' || expectedMatchCount === 'exactly-one') && found.length > 1) {\n throw new ContextProviderError(`Found ${found.length} resources matching ${JSON.stringify(propertyMatch)}; please narrow the search criteria`);\n }\n\n return found;\n } catch (err: any) {\n if (!(err instanceof ContextProviderError) && !(err instanceof ZeroResourcesFoundError)) {\n throw new ContextProviderError(`Encountered CC API error while listing ${typeName} resources matching ${JSON.stringify(propertyMatch)}: ${err.message}`);\n }\n throw err;\n }\n }\n}\n\n/**\n * Convert a CC API response object into a nicer object (parse the JSON)\n */\nfunction foundResourceFromCcApi(desc: ResourceDescription): FoundResource {\n return {\n identifier: desc.Identifier ?? '*MISSING*',\n properties: JSON.parse(desc.Properties ?? '{}'),\n };\n}\n\n/**\n * Whether the given property value matches the given filter\n *\n * For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later\n */\nfunction propertyMatchesFilter(actual: unknown, expected: unknown) {\n return expected === actual;\n}\n\nfunction isObject(x: unknown): x is {[key: string]: unknown} {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\n/**\n * A parsed version of the return value from CCAPI\n */\ninterface FoundResource {\n readonly identifier: string;\n readonly properties: Record<string, unknown>;\n}\n\n/**\n * A specific lookup failure indicating 0 resources found that can be recovered\n */\nclass ZeroResourcesFoundError extends Error {\n}\n", "import type { EndpointServiceAvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\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, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: EndpointServiceAvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n const serviceName = args.serviceName;\n await this.io.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 await this.io.debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);\n return [];\n }\n const azs = response.ServiceDetails[0].AvailabilityZones;\n await this.io.debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);\n return azs;\n }\n}\n", "import type { HostedZoneContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { HostedZone } from '@aws-sdk/client-route-53';\nimport type { IContextProviderMessages } from '.';\nimport type { IRoute53Client, SdkProvider } from '../api/aws-auth/private';\nimport { initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class HostedZoneContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\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 await this.io.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 await this.io.debug(`Found the following zones ${JSON.stringify(zones)}`);\n candidates = zones.filter((zone) => zone.Name === domainName);\n await this.io.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 await this.io.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 { IContextProviderMessages } from '.';\nimport type { IKMSClient, SdkProvider } from '../api/aws-auth/private';\nimport { initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class KeyContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\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 await this.io.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 await this.io.debug(`Key found ${alias.TargetKeyId}`);\n\n return {\n keyId: alias.TargetKeyId,\n };\n }\n}\n", "import type { LoadBalancerContextQuery, LoadBalancerListenerContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type {\n LoadBalancerContextResponse,\n LoadBalancerListenerContextResponse,\n} from '@aws-cdk/cx-api';\nimport {\n LoadBalancerIpAddressType,\n} from '@aws-cdk/cx-api';\nimport type { LoadBalancer, Listener, TagDescription } from '@aws-sdk/client-elastic-load-balancing-v2';\nimport type { IElasticLoadBalancingV2Client, SdkProvider } from '../api/aws-auth/private';\nimport { initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/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/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/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 { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Plugin to read arbitrary SSM parameter names\n */\nexport class SSMContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\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 await this.io.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 { IContextProviderMessages } from '.';\nimport { initContextProviderSdk } from '../api/aws-auth/private';\nimport type { IEC2Client, SdkProvider } from '../api/aws-auth/private';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class VpcNetworkContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\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 await this.io.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 await this.io.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 * as os from 'os';\nimport * as fs_path from 'path';\nimport * as fs from 'fs-extra';\nimport { ToolkitError } from './toolkit-error';\nimport * as util from '../util';\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 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\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 type { ClientRequest } from 'http';\nimport type { 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 type { SdkHttpOptions } from './aws-auth';\nimport { ProxyAgentProvider } from './aws-auth/private';\nimport type { Context } from './context';\nimport type { IIoHost } from './io';\nimport { cdkCacheDir, formatErrorMessage } from '../util';\nimport type { IoHelper } from './io/private';\nimport { IO, asIoHelper, IoDefaultMessages } from './io/private';\nimport { ToolkitError } from './toolkit-error';\nimport { loadTreeFromDir } from './tree';\nimport type { ConstructTreeNode } from './tree';\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 * Options for the HTTP request\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * Where messages are going to be sent\n */\n readonly ioHost: IIoHost;\n\n /**\n * The version of the CLI\n */\n readonly cliVersion: string;\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 class NoticesFilter {\n constructor(private readonly ioMessages: IoDefaultMessages) {\n }\n\n public filter(options: NoticesFilterFilterOptions): FilteredNotice[] {\n const components = [\n ...this.constructTreeComponents(options.outDir),\n ...this.otherComponents(options),\n ];\n\n return this.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 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 this.ioMessages.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 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 this.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 this.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 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 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 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 constructTreeComponents(manifestDir: string): ActualComponent[] {\n const tree = loadTreeFromDir(manifestDir, (msg: string) => void this.ioMessages.notify(IO.DEFAULT_ASSEMBLY_TRACE.msg(msg)));\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 acknowledgedIssueNumbers: Set<Number>;\n private readonly includeAcknowlegded: boolean;\n private readonly httpOptions: SdkHttpOptions;\n private readonly ioHelper: IoHelper;\n private readonly ioMessages: IoDefaultMessages;\n private readonly cliVersion: string;\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.httpOptions = props.httpOptions ?? {};\n this.ioHelper = asIoHelper(props.ioHost, 'notices' as any /* forcing a CliAction to a ToolkitAction */);\n this.ioMessages = new IoDefaultMessages(this.ioHelper);\n this.cliVersion = props.cliVersion;\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 try {\n const underlyingDataSource = options.dataSource ?? new WebsiteNoticeDataSource(this.ioHelper, this.httpOptions);\n const dataSource = new CachedDataSource(this.ioMessages, 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 this.ioMessages.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 const filteredNotices = new NoticesFilter(this.ioMessages).filter({\n data: Array.from(this.data),\n cliVersion: this.cliVersion,\n outDir: this.output,\n bootstrappedEnvironments: Array.from(this.bootstrappedEnvironments.values()),\n });\n\n if (filteredNotices.length > 0) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg([\n '',\n 'NOTICES (What\\'s this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)',\n '',\n ].join('\\n')));\n for (const filtered of filteredNotices) {\n const formatted = filtered.format() + '\\n';\n switch (filtered.notice.severity) {\n case 'warning':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_W0101.msg(formatted));\n break;\n case 'error':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_E0101.msg(formatted));\n break;\n default:\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0101.msg(formatted));\n break;\n }\n }\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `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\n if (options.showTotal ?? false) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `\\nThere are ${filteredNotices.length} unacknowledged notice(s).`,\n ));\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(private readonly ioHelper: IoHelper, options: SdkHttpOptions = {}) {\n this.options = options;\n }\n\n async fetch(): Promise<Notice[]> {\n const timeout = 3000;\n\n const options: RequestOptions = {\n agent: await new ProxyAgentProvider(this.ioHelper).create(this.options),\n };\n\n const notices = await new Promise<Notice[]>((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 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 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 await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Notices refreshed'));\n return notices;\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 ioMessages: IoDefaultMessages,\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 this.ioMessages.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 this.ioMessages.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 this.ioMessages.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 this.ioMessages.debug(`Failed to store notices in the cache: ${e}`);\n }\n }\n}\n", "import * as path from 'node:path';\nimport type { CloudAssembly } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\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 async function loadTree(assembly: CloudAssembly, trace: (msg: string) => Promise<void>): Promise<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 : ({} as ConstructTreeNode);\n } catch (e) {\n await trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n\nexport function loadTreeFromDir(outdir: string, trace: (msg: string) => void): 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 type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { SDK } from './aws-auth/private';\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 } from './cloudformation';\nimport { stabilizeStack } from './deployments/cfn-api';\nimport { IO, type IoHelper } from './io/private';\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 ioHelper: IoHelper,\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, ioHelper, stackName);\n if (!stack) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\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 { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { SSMPARAM_NO_INVALIDATE } from '@aws-cdk/cx-api';\nimport type {\n DescribeChangeSetCommandOutput,\n Parameter,\n ResourceToImport,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport {\n ChangeSetStatus,\n} from '@aws-sdk/client-cloudformation';\nimport type { FileManifestEntry } from 'cdk-assets';\nimport { AssetManifest } from 'cdk-assets';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { Deployments } from './deployments';\nimport type { ICloudFormationClient, SdkProvider } from '../aws-auth/private';\nimport type { Template, TemplateBodyParameter, TemplateParameter } from '../cloudformation';\nimport { CloudFormationStack, makeBodyParameter } from '../cloudformation';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourcesToImport } from '../resource-import';\nimport { ToolkitError } from '../toolkit-error';\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 ioHelper: IoHelper,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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 parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourcesToImport;\n /**\n * Default behavior is to log AWS CloudFormation errors and move on. Set this property to true to instead\n * fail on errors received by AWS CloudFormation.\n *\n * @default false\n */\n failOnError?: boolean;\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 ioHelper: IoHelper,\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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('This stack contains one or more nested stacks, falling back to template-only diff...'));\n\n return undefined;\n }\n }\n\n return uploadBodyParameterAndCreateChangeSet(ioHelper, 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 ioHelper: IoHelper,\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 ioHelper,\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 await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\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(ioHelper, {\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 // This function is currently only used by diff so these messages are diff-specific\n if (!options.failOnError) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(String(e)));\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\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 throw new ToolkitError('Could not create a change set and failOnError is set. (run again with failOnError off to base the diff on template differences)\\n', e);\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 ioHelper: IoHelper,\n options: CreateChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput> {\n await cleanupOldChangeset(options.cfn, ioHelper, options.changeSetName, options.stack.stackName);\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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, ioHelper, options.stack.stackName, options.changeSetName, {\n fetchAll: options.willExecute,\n });\n await cleanupOldChangeset(options.cfn, ioHelper, 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 ioHelper: IoHelper,\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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`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 ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, 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 ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, 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 ioHelper: IoHelper,\n stackName: string,\n) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s does not exist', stackName)));\n return null;\n }\n const status = stack.stackStatus;\n if (status.isInProgress) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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 ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(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", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as util from 'node:util';\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 { contentHash, toYAML } from '../../util';\nimport type { AssetManifestBuilder } from '../deployments';\nimport type { EnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\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 ioHelper: IoHelper,\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 await ioHelper.notify(\n IO.DEFAULT_TOOLKIT_ERROR.msg(util.format(\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\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 await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`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 path from 'path';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { LazyListStackResources, type ListStackResources } from './evaluate-cloudformation-template';\nimport { CloudFormationStack, type Template } from './stack-helpers';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK } from '../aws-auth/private';\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\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\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 * as util from 'util';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as uuid from 'uuid';\nimport { StackEventPoller } from './stack-event-poller';\nimport { StackProgressMonitor } from './stack-progress-monitor';\nimport type { StackActivity } from '../../payloads/stack-activity';\nimport { stackEventHasErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth/private';\nimport { IO, type IoHelper } from '../io/private';\nimport { resourceMetadata } from '../resource-metadata/resource-metadata';\n\nexport interface StackActivityMonitorProps {\n /**\n * The CloudFormation client\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * The IoHelper used for messaging\n */\n readonly ioHelper: IoHelper;\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 ioHelper: IoHelper;\n private readonly stackName: string;\n private readonly stack: CloudFormationStackArtifact;\n\n constructor({\n cfn,\n ioHelper,\n stack,\n stackName,\n resourcesTotal,\n changeSetCreationTime,\n pollingInterval = 2_000,\n }: StackActivityMonitorProps) {\n this.ioHelper = ioHelper;\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.ioHelper.notify(IO.CDK_TOOLKIT_I5501.msg(`Deploying ${this.stackName}`, {\n deployment: this.monitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\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.ioHelper.notify(IO.CDK_TOOLKIT_I5503.msg(`Completed ${this.stackName}`, {\n deployment: oldMonitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\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.ioHelper.notify(IO.CDK_TOOLKIT_E5500.msg(\n util.format('Error occurred while monitoring stack: %s', e),\n { error: e as any },\n ));\n }\n this.scheduleNextTick();\n }\n\n private findMetadataFor(logicalId: string | undefined) {\n const metadata = this.stack.manifest?.metadata;\n if (!logicalId || !metadata) {\n return undefined;\n }\n return resourceMetadata(this.stack, logicalId);\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.ioHelper.notify(IO.CDK_TOOLKIT_I5502.msg(this.formatActivity(activity, true), 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", "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 { type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport type { Branded } from '../../util';\nimport type { SdkProvider } from '../aws-auth/private';\nimport { Mode } from '../plugin';\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 '../../../private/dispose-polyfill';\nimport { major } from 'semver';\nimport type { IoHelper } from '../../shared-private';\nimport { ToolkitError } from '../../shared-public';\nimport { BaseStackAssembly, ExtendedStackSelection as CliExtendedStackSelection } from '../stack-assembly';\nimport { StackCollection } from '../stack-collection';\nimport type { StackSelector } from '../stack-selector';\nimport { ExpandStackSelection, StackSelectionStrategy } from '../stack-selector';\nimport type { IReadableCloudAssembly } from '../types';\n\n/**\n * A single Cloud Assembly wrapped to provide additional stack operations.\n */\nexport class StackAssembly extends BaseStackAssembly implements IReadableCloudAssembly {\n constructor(private readonly _asm: IReadableCloudAssembly, ioHelper: IoHelper) {\n super(_asm.cloudAssembly, ioHelper);\n }\n\n public get cloudAssembly() {\n return this._asm.cloudAssembly;\n }\n\n public async _unlock() {\n return this._asm._unlock();\n }\n\n public async dispose() {\n return this._asm.dispose();\n }\n\n public async [Symbol.asyncDispose]() {\n return this.dispose();\n }\n\n /**\n * Improved stack selection interface with a single selector\n * @throws when the assembly does not contain any stacks, unless `selector.failOnEmpty` is `false`\n * @throws when individual selection strategies are not satisfied\n */\n public async selectStacksV2(selector: StackSelector): Promise<StackCollection> {\n const asm = this.assembly;\n const topLevelStacks = asm.stacks;\n const allStacks = major(asm.version) < 10 ? asm.stacks : asm.stacksRecursively;\n\n if (allStacks.length === 0 && (selector.failOnEmpty ?? true)) {\n throw new ToolkitError('This app contains no stacks');\n }\n\n const extend = expandToExtendEnum(selector.expand);\n const patterns = StackAssembly.sanitizePatterns(selector.patterns ?? []);\n\n switch (selector.strategy) {\n case StackSelectionStrategy.ALL_STACKS:\n return new StackCollection(this, allStacks);\n case StackSelectionStrategy.MAIN_ASSEMBLY:\n if (topLevelStacks.length < 1) {\n // @todo text should probably be handled in io host\n throw new ToolkitError('No stack found in the main cloud assembly. Use \"list\" to print manifest');\n }\n return this.extendStacks(topLevelStacks, allStacks, extend);\n case StackSelectionStrategy.ONLY_SINGLE:\n if (topLevelStacks.length !== 1) {\n // @todo text should probably be handled in io host\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: ${allStacks.map(x => x.hierarchicalId).join(' \u00B7 ')}`);\n }\n return new StackCollection(this, topLevelStacks);\n default:\n const matched = await this.selectMatchingStacks(allStacks, patterns, extend);\n if (\n selector.strategy === StackSelectionStrategy.PATTERN_MUST_MATCH_SINGLE\n && matched.stackCount !== 1\n ) {\n // @todo text should probably be handled in io host\n throw new ToolkitError(\n `Stack selection is ambiguous, please choose a specific stack for import [${allStacks.map(x => x.hierarchicalId).join(',')}]`,\n );\n }\n if (\n selector.strategy === StackSelectionStrategy.PATTERN_MUST_MATCH\n && matched.stackCount < 1\n ) {\n // @todo text should probably be handled in io host\n throw new ToolkitError(\n `Stack selection is ambiguous, please choose a specific stack for import [${allStacks.map(x => x.hierarchicalId).join(',')}]`,\n );\n }\n\n return matched;\n }\n }\n\n /**\n * Select all stacks.\n *\n * This method never throws and can safely be used as a basis for other calculations.\n *\n * @returns a `StackCollection` of all stacks\n */\n public selectAllStacks() {\n const allStacks = major(this.assembly.version) < 10 ? this.assembly.stacks : this.assembly.stacksRecursively;\n return new StackCollection(this, allStacks);\n }\n\n /**\n * Select all stacks that have the validateOnSynth flag et.\n *\n * @returns a `StackCollection` of all stacks that needs to be validated\n */\n public selectStacksForValidation() {\n const allStacks = this.selectAllStacks();\n return allStacks.filter((art) => art.validateOnSynth ?? false);\n }\n}\n\nfunction expandToExtendEnum(extend?: ExpandStackSelection): CliExtendedStackSelection | undefined {\n switch (extend) {\n case ExpandStackSelection.DOWNSTREAM:\n return CliExtendedStackSelection.Downstream;\n case ExpandStackSelection.UPSTREAM:\n return CliExtendedStackSelection.Upstream;\n case ExpandStackSelection.NONE:\n return CliExtendedStackSelection.None;\n default:\n return undefined;\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { minimatch } from 'minimatch';\nimport { StackCollection } from './stack-collection';\nimport { flatten } from '../../util';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private/io-helper';\n\nexport interface IStackAssembly {\n /**\n * The directory this CloudAssembly was read from\n */\n directory: string;\n\n /**\n * Select a single stack by its ID\n */\n stackById(stackId: string): StackCollection;\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 single Cloud Assembly and the operations we do on it to deploy the artifacts inside\n */\nexport abstract class BaseStackAssembly implements IStackAssembly {\n /**\n * Sanitize a list of stack match patterns\n */\n protected static 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\n /**\n * The directory this CloudAssembly was read from\n */\n public readonly directory: string;\n\n /**\n * The IoHelper used for messaging\n */\n protected readonly ioHelper: IoHelper;\n\n constructor(public readonly assembly: cxapi.CloudAssembly, ioHelper: IoHelper) {\n this.directory = assembly.directory;\n this.ioHelper = ioHelper;\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 protected async selectMatchingStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n patterns: string[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): Promise<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 protected async 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 await includeDownstreamStacks(this.ioHelper, index, allStacks);\n break;\n case ExtendedStackSelection.Upstream:\n await includeUpstreamStacks(this.ioHelper, 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\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 */\nasync function includeDownstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\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 await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including depending stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n\n/**\n * Calculate the transitive closure of stack dependencies.\n *\n * Modifies `selectedStacks` in-place.\n */\nasync function includeUpstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\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 await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including dependency stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { SynthesisMessageLevel } from '@aws-cdk/cx-api';\nimport { AssemblyError, ToolkitError } from '../toolkit-error';\nimport type { IStackAssembly } from './stack-assembly';\nimport { type StackDetails } from '../../payloads/stack-details';\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: IStackAssembly, 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 AssemblyError.withStacks('Found errors', this.stackArtifacts);\n }\n\n if (warnings && failAt === 'warn') {\n throw AssemblyError.withStacks('Found warnings (--strict mode)', this.stackArtifacts);\n }\n }\n}\n", "import * as child_process from 'node:child_process';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport split = require('split2');\nimport { ToolkitError } from '../../shared-public';\n\ntype EventPublisher = (event: 'open' | 'data_stdout' | 'data_stderr' | 'close', line: string) => void;\n\ninterface ExecOptions {\n eventPublisher?: EventPublisher;\n extraEnv?: { [key: string]: string | undefined };\n cwd?: string;\n}\n\n/**\n * Execute a command and args in a child process\n */\nexport async function execInChildProcess(commandAndArgs: string, options: ExecOptions = {}) {\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 // - We have to capture any output to stdout and stderr sp we can pass it on to the IoHost\n // To ensure messages get to the user fast, we will emit every full line we receive.\n const proc = child_process.spawn(commandAndArgs, {\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: false,\n shell: true,\n cwd: options.cwd,\n env: {\n ...process.env,\n ...(options.extraEnv ?? {}),\n },\n });\n\n const eventPublisher: EventPublisher = options.eventPublisher ?? ((type, line) => {\n switch (type) {\n case 'data_stdout':\n process.stdout.write(line);\n return;\n case 'data_stderr':\n process.stderr.write(line);\n return;\n case 'open':\n case 'close':\n return;\n }\n });\n proc.stdout.pipe(split()).on('data', (line) => eventPublisher('data_stdout', line));\n proc.stderr.pipe(split()).on('data', (line) => eventPublisher('data_stderr', line));\n\n proc.on('error', fail);\n\n proc.on('exit', code => {\n if (code === 0) {\n return ok();\n } else {\n return fail(new ToolkitError(`Subprocess exited with error ${code}`));\n }\n });\n });\n}\n", "import '../../../private/dispose-polyfill';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { format } from 'node:util';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { lte } from 'semver';\nimport type { SdkProvider, IoHelper } from '../../../api/shared-private';\nimport { splitBySize, versionNumber } from '../../../private/util';\nimport type { ToolkitServices } from '../../../toolkit/private';\nimport { IO } from '../../io/private';\nimport type { IReadLock, IWriteLock } from '../../rwlock';\nimport { RWLock } from '../../rwlock';\nimport { Settings } from '../../settings';\nimport { ToolkitError } from '../../shared-public';\nimport { loadTree, some } from '../../tree';\nimport { prepareDefaultEnvironment as oldPrepare, prepareContext, spaceAvailableForContext, guessExecutable } from '../environment';\nimport type { AppSynthOptions, LoadAssemblyOptions } from '../source-builder';\n\ntype Env = { [key: string]: string };\ntype Context = { [key: string]: any };\n\nexport class ExecutionEnvironment implements AsyncDisposable {\n /**\n * Create an ExecutionEnvironment\n *\n * An ExecutionEnvironment holds a writer lock on the given directory which will\n * be cleaned up when the object is disposed.\n *\n * A temporary directory will be created if none is supplied, which will be cleaned\n * up when this object is disposed.\n *\n * If `markSuccessful()` is called, the writer lock is converted to a reader lock\n * and temporary directories will not be cleaned up anymore.\n */\n public static async create(services: ToolkitServices, props: { outdir?: string } = {}) {\n let tempDir = false;\n let dir = props.outdir;\n if (!dir) {\n tempDir = true;\n dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'cdk.out'));\n }\n\n const lock = await new RWLock(dir).acquireWrite();\n return new ExecutionEnvironment(services, dir, tempDir, lock);\n }\n\n private readonly ioHelper: IoHelper;\n private readonly sdkProvider: SdkProvider;\n private readonly debugFn: (msg: string) => Promise<void>;\n private lock: IWriteLock | undefined;\n private shouldClean: boolean;\n\n private constructor(\n services: ToolkitServices,\n public readonly outdir: string,\n public readonly outDirIsTemporary: boolean,\n lock: IWriteLock,\n ) {\n this.ioHelper = services.ioHelper;\n this.sdkProvider = services.sdkProvider;\n this.debugFn = (msg: string) => this.ioHelper.notify(IO.DEFAULT_ASSEMBLY_DEBUG.msg(msg));\n this.lock = lock;\n this.shouldClean = outDirIsTemporary;\n }\n\n public async [Symbol.asyncDispose]() {\n await this.lock?.release();\n\n if (this.shouldClean) {\n await fs.rm(this.outdir, { recursive: true, force: true });\n }\n }\n\n /**\n * Mark the execution as successful, which stops the writer lock from being released upon disposal\n */\n public async markSuccessful() {\n if (!this.lock) {\n throw new TypeError('Cannot mark successful more than once');\n }\n const readLock = await this.lock.convertToReaderLock();\n this.lock = undefined;\n this.shouldClean = false;\n return { readLock };\n }\n\n /**\n * Begin an execution in this environment\n *\n * This will acquire a write lock on the given environment. The write lock\n * will be released automatically when the return object is disposed, unless it\n * is converted to a reader lock.\n */\n public async beginExecution(): Promise<{ writeToReadLock(): Promise<IReadLock> } & AsyncDisposable> {\n const lock = await new RWLock(this.outdir).acquireWrite();\n\n let converted = false;\n return {\n async writeToReadLock() {\n converted = true;\n return lock.convertToReaderLock();\n },\n [Symbol.asyncDispose]: async () => {\n // Release if not converted\n if (!converted) {\n await lock.release();\n }\n },\n };\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 */\n public guessExecutable(app: string) {\n return guessExecutable(app, this.debugFn);\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 public async defaultEnvVars(): Promise<Env> {\n const debugFn = (msg: string) => this.ioHelper.notify(IO.CDK_ASSEMBLY_I0010.msg(msg));\n const env = await oldPrepare(this.sdkProvider, debugFn);\n\n env[cxapi.OUTDIR_ENV] = this.outdir;\n await debugFn(format('outdir:', this.outdir));\n\n // CLI version information\n env[cxapi.CLI_ASM_VERSION_ENV] = cxschema.Manifest.version();\n env[cxapi.CLI_VERSION_ENV] = versionNumber();\n\n await debugFn(format('env:', env));\n return env;\n }\n\n /**\n * Run code from a different working directory\n */\n public async changeDir<T>(block: () => Promise<T>, workingDir?: string) {\n const originalWorkingDir = process.cwd();\n try {\n if (workingDir) {\n process.chdir(workingDir);\n }\n\n return await block();\n } finally {\n if (workingDir) {\n process.chdir(originalWorkingDir);\n }\n }\n }\n\n /**\n * Run code with additional environment variables\n */\n public async withEnv<T>(env: Env = {}, block: () => Promise<T>) {\n const originalEnv = process.env;\n try {\n process.env = {\n ...originalEnv,\n ...env,\n };\n\n return await block();\n } finally {\n process.env = originalEnv;\n }\n }\n\n /**\n * Run code with context setup inside the environment\n */\n public async withContext<T>(\n inputContext: Context,\n env: Env,\n synthOpts: AppSynthOptions = {},\n block: (env: Env, context: Context) => Promise<T>,\n ) {\n const context = await prepareContext(synthOptsDefaults(synthOpts), inputContext, env, this.debugFn);\n let contextOverflowLocation = null;\n\n try {\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 if (Object.keys(overflow ?? {}).length > 0) {\n const contextDir = fs.mkdtempSync(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 // call the block code with new environment\n return await block(env, context);\n } finally {\n if (contextOverflowLocation) {\n fs.removeSync(path.dirname(contextOverflowLocation));\n }\n }\n }\n}\n\n/**\n * Checks if a given assembly supports context overflow, warn otherwise.\n *\n * @param assembly the assembly to check\n */\nasync function checkContextOverflowSupport(assembly: cxapi.CloudAssembly, ioHelper: IoHelper): Promise<void> {\n const traceFn = (msg: string) => ioHelper.notify(IO.DEFAULT_ASSEMBLY_TRACE.msg(msg));\n const tree = await loadTree(assembly, traceFn);\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 && lte(version, '2.38.0')) // v2\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 await ioHelper.notify(IO.CDK_ASSEMBLY_W0010.msg('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/**\n * Safely create an assembly from a cloud assembly directory\n */\nexport async function assemblyFromDirectory(assemblyDir: string, ioHelper: IoHelper, loadOptions: LoadAssemblyOptions = {}) {\n try {\n const assembly = new cxapi.CloudAssembly(assemblyDir, {\n skipVersionCheck: !(loadOptions.checkVersion ?? true),\n skipEnumCheck: !(loadOptions.checkEnums ?? true),\n // We sort as we deploy\n topoSort: false,\n });\n await checkContextOverflowSupport(assembly, ioHelper);\n return assembly;\n } catch (err: any) {\n if (err.message.includes(cxschema.VERSION_MISMATCH)) {\n // this means the CLI version is too old.\n // we instruct the user to upgrade.\n const message = 'This AWS CDK Toolkit is not compatible with the AWS CDK library used by your application. Please upgrade to the latest version.';\n await ioHelper.notify(IO.CDK_ASSEMBLY_E1111.msg(message, { error: err }));\n throw new ToolkitError(`${message}\\n(${err.message}`);\n }\n throw err;\n }\n}\n\nfunction synthOptsDefaults(synthOpts: AppSynthOptions = {}): Settings {\n return new Settings({\n debug: false,\n pathMetadata: true,\n versionReporting: true,\n assetMetadata: true,\n assetStaging: true,\n ...synthOpts,\n }, true);\n}\n", "import * as path from 'path';\nimport { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { SdkProvider } from '../aws-auth/private';\nimport type { Settings } from '../settings';\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 debugFn: (msg: string) => Promise<void>,\n): Promise<{ [key: string]: string }> {\n const env: { [key: string]: string } = { };\n\n env[cxapi.DEFAULT_REGION_ENV] = aws.defaultRegion;\n await debugFn(`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 debugFn(`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(\n settings: Settings,\n context: {[key: string]: any},\n env: { [key: string]: string | undefined},\n debugFn: (msg: string) => Promise<void>,\n) {\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 await debugFn(format('context:', context));\n\n return context;\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\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, debugFn: (msg: string) => Promise<void>) {\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 await debugFn(`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\n/**\n * Mapping of extensions to command-line generators\n */\nconst EXTENSION_MAP = new Map<string, CommandGenerator>([\n ['.js', executeNode],\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 * 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", "import * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { AssemblyDirectoryProps, AssemblySourceProps, ICloudAssemblySource } from '../';\nimport type { ContextAwareCloudAssemblyProps } from './context-aware-source';\nimport { ContextAwareCloudAssemblySource } from './context-aware-source';\nimport { execInChildProcess } from './exec';\nimport { ExecutionEnvironment, assemblyFromDirectory } from './prepare-source';\nimport type { ToolkitServices } from '../../../toolkit/private';\nimport { IO } from '../../io/private';\nimport { ToolkitError, AssemblyError } from '../../shared-public';\nimport type { AssemblyBuilder } from '../source-builder';\nimport { ReadableCloudAssembly } from './readable-assembly';\nimport { Context } from '../../context';\nimport { RWLock } from '../../rwlock';\nimport { Settings } from '../../settings';\n\nexport abstract class CloudAssemblySourceBuilder {\n /**\n * Helper to provide the CloudAssemblySourceBuilder with required toolkit services\n * @internal\n * @deprecated this should move to the toolkit really.\n */\n protected abstract sourceBuilderServices(): Promise<ToolkitServices>;\n\n /**\n * Create a Cloud Assembly from a Cloud Assembly builder function.\n *\n * A temporary output directory will be created if no output directory is\n * explicitly given. This directory will be cleaned up if synthesis fails, or\n * when the Cloud Assembly produced by this source is disposed.\n *\n * A write lock will be acquired on the output directory for the duration of\n * the CDK app synthesis (which means that no two apps can synthesize at the\n * same time), and after synthesis a read lock will be acquired on the\n * directory. This means that while the CloudAssembly is being used, no CDK\n * app synthesis can take place into that directory.\n *\n * @param builder the builder function\n * @param props additional configuration properties\n * @returns the CloudAssembly source\n */\n public async fromAssemblyBuilder(\n builder: AssemblyBuilder,\n props: AssemblySourceProps = {},\n ): Promise<ICloudAssemblySource> {\n const services = await this.sourceBuilderServices();\n const context = new Context({ bag: new Settings(props.context ?? {}) });\n const contextAssemblyProps: ContextAwareCloudAssemblyProps = {\n services,\n context,\n lookups: props.lookups,\n };\n\n return new ContextAwareCloudAssemblySource(\n {\n produce: async () => {\n await using execution = await ExecutionEnvironment.create(services, { outdir: props.outdir });\n\n const env = await execution.defaultEnvVars();\n const assembly = await execution.changeDir(async () =>\n execution.withContext(context.all, env, props.synthOptions ?? {}, async (envWithContext, ctx) =>\n execution.withEnv(envWithContext, async () => {\n try {\n return await builder({\n outdir: execution.outdir,\n context: ctx,\n });\n } catch (error: unknown) {\n // re-throw toolkit errors unchanged\n if (ToolkitError.isToolkitError(error)) {\n throw error;\n }\n // otherwise, wrap into an assembly error\n throw AssemblyError.withCause('Assembly builder failed', error);\n }\n }),\n ), props.workingDirectory);\n\n // Convert what we got to the definitely correct type we're expecting, a cxapi.CloudAssembly\n const asm = cxapi.CloudAssembly.isCloudAssembly(assembly)\n ? assembly\n : await assemblyFromDirectory(assembly.directory, services.ioHelper, props.loadAssemblyOptions);\n\n const success = await execution.markSuccessful();\n return new ReadableCloudAssembly(asm, success.readLock, { deleteOnDispose: execution.outDirIsTemporary });\n },\n },\n contextAssemblyProps,\n );\n }\n\n /**\n * Creates a Cloud Assembly from an existing assembly directory.\n *\n * A read lock will be acquired for the directory. This means that while\n * the CloudAssembly is being used, no CDK app synthesis can take place into\n * that directory.\n *\n * @param directory the directory of a already produced Cloud Assembly.\n * @returns the CloudAssembly source\n */\n public async fromAssemblyDirectory(directory: string, props: AssemblyDirectoryProps = {}): Promise<ICloudAssemblySource> {\n const services: ToolkitServices = await this.sourceBuilderServices();\n const contextAssemblyProps: ContextAwareCloudAssemblyProps = {\n services,\n context: new Context(), // @todo there is probably a difference between contextaware and contextlookup sources\n lookups: false,\n };\n\n return new ContextAwareCloudAssemblySource(\n {\n produce: async () => {\n // @todo build\n await services.ioHelper.notify(IO.CDK_ASSEMBLY_I0150.msg('--app points to a cloud assembly, so we bypass synth'));\n\n const readLock = await new RWLock(directory).acquireRead();\n try {\n const asm = await assemblyFromDirectory(directory, services.ioHelper, props.loadAssemblyOptions);\n return new ReadableCloudAssembly(asm, readLock, { deleteOnDispose: false });\n } catch (e) {\n await readLock.release();\n throw e;\n }\n },\n },\n contextAssemblyProps,\n );\n }\n /**\n * Use a directory containing an AWS CDK app as source.\n *\n * A temporary output directory will be created if no output directory is\n * explicitly given. This directory will be cleaned up if synthesis fails, or\n * when the Cloud Assembly produced by this source is disposed.\n *\n * A write lock will be acquired on the output directory for the duration of\n * the CDK app synthesis (which means that no two apps can synthesize at the\n * same time), and after synthesis a read lock will be acquired on the\n * directory. This means that while the CloudAssembly is being used, no CDK\n * app synthesis can take place into that directory.\n *\n * @param props additional configuration properties\n * @returns the CloudAssembly source\n */\n public async fromCdkApp(app: string, props: AssemblySourceProps = {}): Promise<ICloudAssemblySource> {\n const services: ToolkitServices = await this.sourceBuilderServices();\n // @todo this definitely needs to read files from the CWD\n const context = new Context({ bag: new Settings(props.context ?? {}) });\n const contextAssemblyProps: ContextAwareCloudAssemblyProps = {\n services,\n context,\n lookups: props.lookups,\n };\n\n return new ContextAwareCloudAssemblySource(\n {\n produce: async () => {\n // @todo build\n // const build = this.props.configuration.settings.get(['build']);\n // if (build) {\n // await execInChildProcess(build, { cwd: props.workingDirectory });\n // }\n\n const outdir = props.outdir ?? 'cdk.out';\n try {\n fs.mkdirpSync(outdir);\n } catch (e: any) {\n throw new ToolkitError(`Could not create output directory at '${outdir}' (${e.message}).`);\n }\n\n await using execution = await ExecutionEnvironment.create(services, { outdir });\n\n const commandLine = await execution.guessExecutable(app);\n const env = await execution.defaultEnvVars();\n return await execution.withContext(context.all, env, props.synthOptions, async (envWithContext, _ctx) => {\n await execInChildProcess(commandLine.join(' '), {\n eventPublisher: async (type, line) => {\n switch (type) {\n case 'data_stdout':\n await services.ioHelper.notify(IO.CDK_ASSEMBLY_I1001.msg(line));\n break;\n case 'data_stderr':\n await services.ioHelper.notify(IO.CDK_ASSEMBLY_E1002.msg(line));\n break;\n }\n },\n extraEnv: envWithContext,\n cwd: props.workingDirectory,\n });\n\n const asm = await assemblyFromDirectory(outdir, services.ioHelper, props.loadAssemblyOptions);\n\n const success = await execution.markSuccessful();\n return new ReadableCloudAssembly(asm, success.readLock, { deleteOnDispose: execution.outDirIsTemporary });\n });\n },\n },\n contextAssemblyProps,\n );\n }\n}\n\n", "import type { StackSelector } from '../stack-selector';\nimport { StackSelectionStrategy } from '../stack-selector';\n\nexport const ALL_STACKS: StackSelector = {\n strategy: StackSelectionStrategy.ALL_STACKS,\n};\n", "import * as util from 'node:util';\nimport * as uuid from 'uuid';\nimport type { ActionLessMessage, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport type { Duration } from '../../../payloads/types';\nimport { formatTime } from '../../../util';\n\nexport interface SpanEnd {\n readonly duration: number;\n}\n\n/**\n * Describes a specific span\n *\n * A span definition is a pair of `IoMessageMaker`s to create a start and end message of the span respectively.\n * It also has a display name, that is used for auto-generated message text when they are not provided.\n */\nexport interface SpanDefinition<S extends object, E extends SpanEnd> {\n readonly name: string;\n readonly start: IoMessageMaker<S>;\n readonly end: IoMessageMaker<E>;\n}\n\n/**\n * Used in conditional types to check if a type (e.g. after omitting fields) is an empty object\n * This is needed because counter-intuitive neither `object` nor `{}` represent that.\n */\ntype EmptyObject = {\n [index: string | number | symbol]: never;\n}\n\n/**\n * Helper type to force a parameter to be not present of the computed type is an empty object\n */\ntype VoidWhenEmpty<T> = T extends EmptyObject ? void : T\n\n/**\n * Helper type to force a parameter to be an empty object if the computed type is an empty object\n * This is weird, but some computed types (e.g. using `Omit`) don't end up enforcing this.\n */\ntype ForceEmpty<T> = T extends EmptyObject ? EmptyObject : T\n\n/**\n * Make some properties optional\n */\ntype Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;\n\n/**\n * Ending the span returns the observed duration\n */\ninterface ElapsedTime {\n readonly asMs: number;\n readonly asSec: number;\n}\n\n/**\n * A message span that can be ended and read times from\n */\nexport interface IMessageSpan<E extends SpanEnd> {\n /**\n * Get the time elapsed since the start\n */\n elapsedTime(): Promise<ElapsedTime>;\n /**\n * Sends a simple, generic message with the current timing\n * For more complex intermediate messages, get the `elapsedTime` and use `notify`\n */\n timing(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime>;\n /**\n * Sends an arbitrary intermediate message as part of the span\n */\n notify(message: ActionLessMessage<unknown>): Promise<void>;\n /**\n * End the span with a payload\n */\n end(payload: VoidWhenEmpty<Omit<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a payload, overwriting\n */\n end(payload: VoidWhenEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a message and payload\n */\n end(message: string, payload: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n}\n\n/**\n * Helper class to make spans around blocks of work\n *\n * Blocks are enclosed by a start and end message.\n * All messages of the span share a unique id.\n * The end message contains the time passed between start and end.\n */\nexport class SpanMaker<S extends object, E extends SpanEnd> {\n private readonly definition: SpanDefinition<S, E>;\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper, definition: SpanDefinition<S, E>) {\n this.definition = definition;\n this.ioHelper = ioHelper;\n }\n\n /**\n * Starts the span and initially notifies the IoHost\n * @returns a message span\n */\n public async begin(payload: VoidWhenEmpty<S>): Promise<IMessageSpan<E>>;\n public async begin(message: string, payload: S): Promise<IMessageSpan<E>>;\n public async begin(a: any, b?: S): Promise<IMessageSpan<E>> {\n const spanId = uuid.v4();\n const startTime = new Date().getTime();\n\n const notify = (msg: ActionLessMessage<unknown>): Promise<void> => {\n return this.ioHelper.notify(withSpanId(spanId, msg));\n };\n\n const startInput = parseArgs<S>(a, b);\n const startMsg = startInput.message ?? `Starting ${this.definition.name} ...`;\n const startPayload = startInput.payload;\n\n await notify(this.definition.start.msg(\n startMsg,\n startPayload,\n ));\n\n const timingMsgTemplate = '\\n\u2728 %s time: %ds\\n';\n const time = () => {\n const elapsedTime = new Date().getTime() - startTime;\n return {\n asMs: elapsedTime,\n asSec: formatTime(elapsedTime),\n };\n };\n\n return {\n elapsedTime: async (): Promise<ElapsedTime> => {\n return time();\n },\n\n notify: async(msg: ActionLessMessage<unknown>): Promise<void> => {\n await notify(msg);\n },\n\n timing: async(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime> => {\n const duration = time();\n const timingMsg = message ? message : util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n await notify(maker.msg(timingMsg, {\n duration: duration.asMs,\n }));\n return duration;\n },\n\n end: async (x: any, y?: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime> => {\n const duration = time();\n\n const endInput = parseArgs<ForceEmpty<Optional<E, keyof SpanEnd>>>(x, y);\n const endMsg = endInput.message ?? util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n const endPayload = endInput.payload;\n\n await notify(this.definition.end.msg(\n endMsg, {\n duration: duration.asMs,\n ...endPayload,\n } as E));\n\n return duration;\n },\n };\n }\n}\n\nfunction parseArgs<S extends object>(first: any, second?: S): { message: string | undefined; payload: S } {\n const firstIsMessage = typeof first === 'string';\n\n // When the first argument is a string or we have a second argument, then the first arg is the message\n const message = (firstIsMessage || second) ? first : undefined;\n\n // When the first argument is a string or we have a second argument,\n // then the second arg is the payload, otherwise the first arg is the payload\n const payload = (firstIsMessage || second) ? second : first;\n\n return {\n message,\n payload,\n };\n}\n\nfunction withSpanId(span: string, message: ActionLessMessage<unknown>): ActionLessMessage<unknown> {\n return {\n ...message,\n span,\n };\n}\n", "import type { IIoHost } from '../io-host';\nimport type { IoMessage, IoRequest } from '../io-message';\nimport type { ToolkitAction } from '../toolkit-action';\nimport type { SpanEnd, SpanDefinition } from './span';\nimport { SpanMaker } from './span';\n\nexport type ActionLessMessage<T> = Omit<IoMessage<T>, 'action'>;\nexport type ActionLessRequest<T, U> = Omit<IoRequest<T, U>, 'action'>;\n\n/**\n * A class containing helper tools to interact with IoHost\n */\nexport class IoHelper implements IIoHost {\n public static fromIoHost(ioHost: IIoHost, action: ToolkitAction) {\n return new IoHelper(ioHost, action);\n }\n\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n private constructor(ioHost: IIoHost, action: ToolkitAction) {\n this.ioHost = ioHost;\n this.action = action;\n }\n\n /**\n * Forward a message to the IoHost, while injection the current action\n */\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHost.notify({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Forward a request to the IoHost, while injection the current action\n */\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHost.requestResponse({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Create a new marker from a given registry entry\n */\n public span<S extends object, E extends SpanEnd>(definition: SpanDefinition<S, E>) {\n return new SpanMaker(this, definition);\n }\n}\n\n/**\n * Wraps an IoHost and creates an IoHelper from it\n */\nexport function asIoHelper(ioHost: IIoHost, action: ToolkitAction): IoHelper {\n return IoHelper.fromIoHost(ioHost, action);\n}\n", "import type { IoMessageLevel } from '../';\n\n/**\n * Keep this list ordered from most to least verbose.\n * Every level \"includes\" all of the levels below it.\n * This is used to compare levels of messages to determine what should be logged.\n */\nconst levels = [\n 'trace',\n 'debug',\n 'info',\n 'warn',\n 'result',\n 'error',\n] as const;\n\n// compare levels helper\n// helper to convert the array into a map with numbers\nconst orderedLevels: Record<typeof levels[number], number> = Object.fromEntries(Object.entries(levels).map(a => a.reverse()));\nfunction compareFn(a: IoMessageLevel, b: IoMessageLevel): number {\n return orderedLevels[a] - orderedLevels[b];\n}\n\n/**\n * Determines if a message is relevant for the given log level.\n *\n * @param msg The message to compare.\n * @param level The level to compare against.\n * @returns true if the message is relevant for the given level.\n */\nexport function isMessageRelevantForLevel(msg: { level: IoMessageLevel}, level: IoMessageLevel): boolean {\n return compareFn(msg.level, level) >= 0;\n}\n\n", "import type { IoMessage, IoMessageCode, IoMessageLevel } from '../io-message';\nimport type { ActionLessMessage, ActionLessRequest } from './io-helper';\n\n/**\n * Information for each IO Message Code.\n */\ninterface CodeInfo {\n /**\n * The message code.\n */\n readonly code: IoMessageCode;\n\n /**\n * A brief description of the meaning of this IO Message.\n */\n readonly description: string;\n\n /**\n * The name of the payload interface, if applicable.\n * Some Io Messages include a payload, with a specific interface. The name of\n * the interface is specified here so that it can be linked with the message\n * when documentation is generated.\n *\n * The interface _must_ be exposed directly from toolkit-lib, so that it will\n * have a documentation page generated (that can be linked to).\n */\n readonly interface?: string;\n}\n\n/**\n * Information for each IO Message\n */\ninterface MessageInfo extends CodeInfo {\n /**\n * The message level\n */\n readonly level: IoMessageLevel;\n}\n\n/**\n * An interface that can produce messages for a specific code.\n */\nexport interface IoMessageMaker<T> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n msg: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessMessage<T>;\n\n /**\n * Returns whether the given `IoMessage` instance matches the current message definition\n */\n is(x: IoMessage<unknown>): x is IoMessage<T>;\n}\n\n/**\n * Produce an IoMessageMaker for the provided level and code info.\n */\nfunction message<T = AbsentData>(level: IoMessageLevel, details: CodeInfo): IoMessageMaker<T> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n } as ActionLessMessage<T>);\n\n return {\n ...details,\n level,\n msg: maker as any,\n is: (m): m is IoMessage<T> => m.code === details.code,\n };\n}\n\n/**\n * A type that is impossible for a user to replicate\n * This is used to ensure that results always have a proper type generic declared.\n */\ndeclare const privateKey: unique symbol;\nexport type ImpossibleType = {\n readonly [privateKey]: typeof privateKey;\n};\n\n// Create `IoMessageMaker`s for a given level and type check that calls with payload are using the correct interface\ntype CodeInfoMaybeInterface<T> = [T] extends [AbsentData] ? Omit<CodeInfo, 'interface'> : Required<CodeInfo>;\n\n/**\n * The type we use to represent an absent data field\n *\n * This is here to make it easy to change between `undefined`, `void`\n * and `never`.\n *\n * Not a lot of difference between `undefined` and `void`, but `void`\n * reads better.\n */\ntype AbsentData = void;\n\nexport const trace = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('trace', details);\nexport const debug = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('debug', details);\nexport const info = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('info', details);\nexport const warn = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('warn', details);\nexport const error = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('error', details);\nexport const result = <T extends object = ImpossibleType>(details: Required<CodeInfo>) => message<T>('result', details);\n\ninterface RequestInfo<U> extends CodeInfo {\n readonly defaultResponse: U;\n}\n\n/**\n * An interface that can produce requests for a specific code.\n */\nexport interface IoRequestMaker<T, U> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n req: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessRequest<T, U>;\n}\n\n/**\n * Produce an IoRequestMaker for the provided level and request info.\n */\nfunction request<T = AbsentData, U = ImpossibleType>(level: IoMessageLevel, details: RequestInfo<U>): IoRequestMaker<T, U> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n defaultResponse: details.defaultResponse,\n } as ActionLessRequest<T, U>);\n\n return {\n ...details,\n level,\n req: maker as any,\n };\n}\n\n/**\n * A request that is a simple yes/no question, with the expectation that 'yes' is the default.\n */\nexport const confirm = <T extends object = ImpossibleType>(details: Required<Omit<RequestInfo<boolean>, 'defaultResponse'>>) => request<T, boolean>('info', {\n ...details,\n defaultResponse: true,\n});\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as make from './message-maker';\nimport type { SpanDefinition } from './span';\nimport type { DiffResult } from '../../../payloads';\nimport type { BootstrapEnvironmentProgress } from '../../../payloads/bootstrap-environment-progress';\nimport type { MissingContext, UpdatedContext } from '../../../payloads/context';\nimport type { BuildAsset, DeployConfirmationRequest, PublishAsset, StackDeployProgress, SuccessfulDeployStackResult } from '../../../payloads/deploy';\nimport type { StackDestroy, StackDestroyProgress } from '../../../payloads/destroy';\nimport type { HotswapDeploymentDetails, HotswapDeploymentAttempt, HotswappableChange, HotswapResult } from '../../../payloads/hotswap';\nimport type { StackDetailsPayload } from '../../../payloads/list';\nimport type { CloudWatchLogEvent, CloudWatchLogMonitorControlEvent } from '../../../payloads/logs-monitor';\nimport type { RefactorResult } from '../../../payloads/refactor';\nimport type { StackRollbackProgress } from '../../../payloads/rollback';\nimport type { SdkTrace } from '../../../payloads/sdk-trace';\nimport type { StackActivity, StackMonitoringControlEvent } from '../../../payloads/stack-activity';\nimport type { StackSelectionDetails } from '../../../payloads/synth';\nimport type { AssemblyData, ConfirmationRequest, ContextProviderMessageSource, Duration, ErrorPayload, StackAndAssemblyData } from '../../../payloads/types';\nimport type { FileWatchEvent, WatchSettings } from '../../../payloads/watch';\n\n/**\n * We have a rough system by which we assign message codes:\n * - First digit groups messages by action, e.g. synth or deploy\n * - X000-X009 are reserved for timings\n * - X900-X999 are reserved for results\n */\nexport const IO = {\n // Defaults (0000)\n DEFAULT_TOOLKIT_INFO: make.info({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default info messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_DEBUG: make.debug({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default debug messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_WARN: make.warn({\n code: 'CDK_TOOLKIT_W0000',\n description: 'Default warning messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_ERROR: make.error({\n code: 'CDK_TOOLKIT_E0000',\n description: 'Default error messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_TRACE: make.trace({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default trace messages emitted from the Toolkit',\n }),\n\n // warnings & errors\n CDK_TOOLKIT_W0100: make.warn({\n code: 'CDK_TOOLKIT_W0100',\n description: 'Credential plugin warnings',\n }),\n\n // 1: Synth (1xxx)\n CDK_TOOLKIT_I1000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I1000',\n description: 'Provides synthesis times.',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I1001: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I1001',\n description: 'Cloud Assembly synthesis is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I1901: make.result<StackAndAssemblyData>({\n code: 'CDK_TOOLKIT_I1901',\n description: 'Provides stack data',\n interface: 'StackAndAssemblyData',\n }),\n CDK_TOOLKIT_I1902: make.result<AssemblyData>({\n code: 'CDK_TOOLKIT_I1902',\n description: 'Successfully deployed stacks',\n interface: 'AssemblyData',\n }),\n\n // 2: List (2xxx)\n CDK_TOOLKIT_I2901: make.result<StackDetailsPayload>({\n code: 'CDK_TOOLKIT_I2901',\n description: 'Provides details on the selected stacks and their dependencies',\n interface: 'StackDetailsPayload',\n }),\n\n // 3: Import & Migrate\n CDK_TOOLKIT_E3900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E3900',\n description: 'Resource import failed',\n interface: 'ErrorPayload',\n }),\n\n // 4: Diff (4xxx)\n CDK_TOOLKIT_I4000: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I4000',\n description: 'Diff stacks is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I4001: make.info<DiffResult>({\n code: 'CDK_TOOLKIT_I4001',\n description: 'Output of the diff command',\n interface: 'DiffResult',\n }),\n\n // 5: Deploy & Watch (5xxx)\n CDK_TOOLKIT_I5000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5000',\n description: 'Provides deployment times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5001: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5001',\n description: 'Provides total time in deploy action, including synth and rollback',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5002: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5002',\n description: 'Provides time for resource migration',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_W5021: make.warn({\n code: 'CDK_TOOLKIT_W5021',\n description: 'Empty non-existent stack, deployment is skipped',\n }),\n CDK_TOOLKIT_W5022: make.warn({\n code: 'CDK_TOOLKIT_W5022',\n description: 'Empty existing stack, stack will be destroyed',\n }),\n CDK_TOOLKIT_I5031: make.info({\n code: 'CDK_TOOLKIT_I5031',\n description: 'Informs about any log groups that are traced as part of the deployment',\n }),\n CDK_TOOLKIT_I5032: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5032',\n description: 'Start monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_I5033: make.info<CloudWatchLogEvent>({\n code: 'CDK_TOOLKIT_I5033',\n description: 'A log event received from Cloud Watch',\n interface: 'CloudWatchLogEvent',\n }),\n CDK_TOOLKIT_I5034: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5034',\n description: 'Stop monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_E5035: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5035',\n description: 'A log monitoring error',\n interface: 'ErrorPayload',\n }),\n CDK_TOOLKIT_I5050: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5050',\n description: 'Confirm rollback during deployment',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I5060: make.confirm<DeployConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5060',\n description: 'Confirm deploy security sensitive changes',\n interface: 'DeployConfirmationRequest',\n }),\n CDK_TOOLKIT_I5100: make.info<StackDeployProgress>({\n code: 'CDK_TOOLKIT_I5100',\n description: 'Stack deploy progress',\n interface: 'StackDeployProgress',\n }),\n\n // Assets (52xx)\n CDK_TOOLKIT_I5210: make.trace<BuildAsset>({\n code: 'CDK_TOOLKIT_I5210',\n description: 'Started building a specific asset',\n interface: 'BuildAsset',\n }),\n CDK_TOOLKIT_I5211: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5211',\n description: 'Building the asset has completed',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5220: make.trace<PublishAsset>({\n code: 'CDK_TOOLKIT_I5220',\n description: 'Started publishing a specific asset',\n interface: 'PublishAsset',\n }),\n CDK_TOOLKIT_I5221: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5221',\n description: 'Publishing the asset has completed',\n interface: 'Duration',\n }),\n\n // Watch (53xx)\n CDK_TOOLKIT_I5310: make.debug<WatchSettings>({\n code: 'CDK_TOOLKIT_I5310',\n description: 'The computed settings used for file watching',\n interface: 'WatchSettings',\n }),\n CDK_TOOLKIT_I5311: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5311',\n description: 'File watching started',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5312: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5312',\n description: 'File event detected, starting deployment',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5313: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5313',\n description: 'File event detected during active deployment, changes are queued',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5314: make.info({\n code: 'CDK_TOOLKIT_I5314',\n description: 'Initial watch deployment started',\n }),\n CDK_TOOLKIT_I5315: make.info({\n code: 'CDK_TOOLKIT_I5315',\n description: 'Queued watch deployment started',\n }),\n\n // Hotswap (54xx)\n CDK_TOOLKIT_I5400: make.trace<HotswapDeploymentAttempt>({\n code: 'CDK_TOOLKIT_I5400',\n description: 'Attempting a hotswap deployment',\n interface: 'HotswapDeploymentAttempt',\n }),\n CDK_TOOLKIT_I5401: make.trace<HotswapDeploymentDetails>({\n code: 'CDK_TOOLKIT_I5401',\n description: 'Computed details for the hotswap deployment',\n interface: 'HotswapDeploymentDetails',\n }),\n CDK_TOOLKIT_I5402: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5402',\n description: 'A hotswappable change is processed as part of a hotswap deployment',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5403: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5403',\n description: 'The hotswappable change has completed processing',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5410: make.info<HotswapResult>({\n code: 'CDK_TOOLKIT_I5410',\n description: 'Hotswap deployment has ended, a full deployment might still follow if needed',\n interface: 'HotswapResult',\n }),\n\n // Stack Monitor (55xx)\n CDK_TOOLKIT_I5501: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5501',\n description: 'Stack Monitoring: Start monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n CDK_TOOLKIT_I5502: make.info<StackActivity>({\n code: 'CDK_TOOLKIT_I5502',\n description: 'Stack Monitoring: Activity event for a single stack',\n interface: 'StackActivity',\n }),\n CDK_TOOLKIT_I5503: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5503',\n description: 'Stack Monitoring: Finished monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n\n // Success (59xx)\n CDK_TOOLKIT_I5900: make.result<SuccessfulDeployStackResult>({\n code: 'CDK_TOOLKIT_I5900',\n description: 'Deployment results on success',\n interface: 'SuccessfulDeployStackResult',\n }),\n CDK_TOOLKIT_I5901: make.info({\n code: 'CDK_TOOLKIT_I5901',\n description: 'Generic deployment success messages',\n }),\n CDK_TOOLKIT_W5400: make.warn({\n code: 'CDK_TOOLKIT_W5400',\n description: 'Hotswap disclosure message',\n }),\n\n CDK_TOOLKIT_E5001: make.error({\n code: 'CDK_TOOLKIT_E5001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E5500: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5500',\n description: 'Stack Monitoring error',\n interface: 'ErrorPayload',\n }),\n\n // 6: Rollback (6xxx)\n CDK_TOOLKIT_I6000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I6000',\n description: 'Provides rollback times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I6100: make.info<StackRollbackProgress>({\n code: 'CDK_TOOLKIT_I6100',\n description: 'Stack rollback progress',\n interface: 'StackRollbackProgress',\n }),\n\n CDK_TOOLKIT_E6001: make.error({\n code: 'CDK_TOOLKIT_E6001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E6900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E6900',\n description: 'Rollback failed',\n interface: 'ErrorPayload',\n }),\n\n // 7: Destroy (7xxx)\n CDK_TOOLKIT_I7000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I7000',\n description: 'Provides destroy times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7001: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I7001',\n description: 'Provides destroy time for a single stack',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7010: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I7010',\n description: 'Confirm destroy stacks',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I7100: make.info<StackDestroyProgress>({\n code: 'CDK_TOOLKIT_I7100',\n description: 'Stack destroy progress',\n interface: 'StackDestroyProgress',\n }),\n CDK_TOOLKIT_I7101: make.trace<StackDestroy>({\n code: 'CDK_TOOLKIT_I7101',\n description: 'Start stack destroying',\n interface: 'StackDestroy',\n }),\n\n CDK_TOOLKIT_I7900: make.result<cxapi.CloudFormationStackArtifact>({\n code: 'CDK_TOOLKIT_I7900',\n description: 'Stack deletion succeeded',\n interface: 'cxapi.CloudFormationStackArtifact',\n }),\n\n CDK_TOOLKIT_E7010: make.error({\n code: 'CDK_TOOLKIT_E7010',\n description: 'Action was aborted due to negative confirmation of request',\n }),\n CDK_TOOLKIT_E7900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E7900',\n description: 'Stack deletion failed',\n interface: 'ErrorPayload',\n }),\n\n // 8. Refactor (8xxx)\n CDK_TOOLKIT_I8900: make.result<RefactorResult>({\n code: 'CDK_TOOLKIT_I8900',\n description: 'Refactor result',\n interface: 'RefactorResult',\n }),\n\n CDK_TOOLKIT_W8010: make.warn({\n code: 'CDK_TOOLKIT_W8010',\n description: 'Refactor execution not yet supported',\n }),\n\n // 9: Bootstrap (9xxx)\n CDK_TOOLKIT_I9000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I9000',\n description: 'Provides bootstrap times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I9100: make.info<BootstrapEnvironmentProgress>({\n code: 'CDK_TOOLKIT_I9100',\n description: 'Bootstrap progress',\n interface: 'BootstrapEnvironmentProgress',\n }),\n\n CDK_TOOLKIT_I9900: make.result<{ environment: cxapi.Environment }>({\n code: 'CDK_TOOLKIT_I9900',\n description: 'Bootstrap results on success',\n interface: 'cxapi.Environment',\n }),\n CDK_TOOLKIT_E9900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E9900',\n description: 'Bootstrap failed',\n interface: 'ErrorPayload',\n }),\n\n // Notices\n CDK_TOOLKIT_I0100: make.info({\n code: 'CDK_TOOLKIT_I0100',\n description: 'Notices decoration (the header or footer of a list of notices)',\n }),\n CDK_TOOLKIT_W0101: make.warn({\n code: 'CDK_TOOLKIT_W0101',\n description: 'A notice that is marked as a warning',\n }),\n CDK_TOOLKIT_E0101: make.error({\n code: 'CDK_TOOLKIT_E0101',\n description: 'A notice that is marked as an error',\n }),\n CDK_TOOLKIT_I0101: make.info({\n code: 'CDK_TOOLKIT_I0101',\n description: 'A notice that is marked as informational',\n }),\n\n // Assembly codes\n DEFAULT_ASSEMBLY_TRACE: make.trace({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default trace messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_DEBUG: make.debug({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default debug messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_INFO: make.info({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default info messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_WARN: make.warn({\n code: 'CDK_ASSEMBLY_W0000',\n description: 'Default warning messages emitted from Cloud Assembly operations',\n }),\n\n CDK_ASSEMBLY_I0010: make.debug({\n code: 'CDK_ASSEMBLY_I0010',\n description: 'Generic environment preparation debug messages',\n }),\n CDK_ASSEMBLY_W0010: make.warn({\n code: 'CDK_ASSEMBLY_W0010',\n description: 'Emitted if the found framework version does not support context overflow',\n }),\n CDK_ASSEMBLY_I0042: make.debug<UpdatedContext>({\n code: 'CDK_ASSEMBLY_I0042',\n description: 'Writing updated context',\n interface: 'UpdatedContext',\n }),\n CDK_ASSEMBLY_I0240: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0240',\n description: 'Context lookup was stopped as no further progress was made. ',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I0241: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0241',\n description: 'Fetching missing context. This is an iterative message that may appear multiple times with different missing keys.',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I1000: make.debug({\n code: 'CDK_ASSEMBLY_I1000',\n description: 'Cloud assembly output starts',\n }),\n CDK_ASSEMBLY_I1001: make.info({\n code: 'CDK_ASSEMBLY_I1001',\n description: 'Output lines emitted by the cloud assembly to stdout',\n }),\n CDK_ASSEMBLY_E1002: make.error({\n code: 'CDK_ASSEMBLY_E1002',\n description: 'Output lines emitted by the cloud assembly to stderr',\n }),\n CDK_ASSEMBLY_I1003: make.info({\n code: 'CDK_ASSEMBLY_I1003',\n description: 'Cloud assembly output finished',\n }),\n CDK_ASSEMBLY_E1111: make.error<ErrorPayload>({\n code: 'CDK_ASSEMBLY_E1111',\n description: 'Incompatible CDK CLI version. Upgrade needed.',\n interface: 'ErrorPayload',\n }),\n\n CDK_ASSEMBLY_I0150: make.debug<never>({\n code: 'CDK_ASSEMBLY_I0150',\n description: 'Indicates the use of a pre-synthesized cloud assembly directory',\n }),\n\n CDK_ASSEMBLY_I0300: make.info<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0300',\n description: 'An info message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n CDK_ASSEMBLY_I0301: make.debug<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0301',\n description: 'A debug message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n\n // Assembly Annotations\n CDK_ASSEMBLY_I9999: make.info<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_I9999',\n description: 'Annotations emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_W9999: make.warn<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_W9999',\n description: 'Warnings emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_E9999: make.error<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_E9999',\n description: 'Errors emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n\n // SDK codes\n DEFAULT_SDK_TRACE: make.trace({\n code: 'CDK_SDK_I0000',\n description: 'An SDK trace message.',\n }),\n DEFAULT_SDK_DEBUG: make.debug({\n code: 'CDK_SDK_I0000',\n description: 'An SDK debug message.',\n }),\n DEFAULT_SDK_WARN: make.warn({\n code: 'CDK_SDK_W0000',\n description: 'An SDK warning message.',\n }),\n CDK_SDK_I0100: make.trace<SdkTrace>({\n code: 'CDK_SDK_I0100',\n description: 'An SDK trace. SDK traces are emitted as traces to the IoHost, but contain the original SDK logging level.',\n interface: 'SdkTrace',\n }),\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Payload type of the end message must extend Duration\n */\nexport const SPAN = {\n SYNTH_ASSEMBLY: {\n name: 'Synthesis',\n start: IO.CDK_TOOLKIT_I1001,\n end: IO.CDK_TOOLKIT_I1000,\n },\n DEPLOY_STACK: {\n name: 'Deployment',\n start: IO.CDK_TOOLKIT_I5100,\n end: IO.CDK_TOOLKIT_I5001,\n },\n ROLLBACK_STACK: {\n name: 'Rollback',\n start: IO.CDK_TOOLKIT_I6100,\n end: IO.CDK_TOOLKIT_I6000,\n },\n DIFF_STACK: {\n name: 'Diff',\n start: IO.CDK_TOOLKIT_I4000,\n end: IO.CDK_TOOLKIT_I4001,\n },\n DESTROY_STACK: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7100,\n end: IO.CDK_TOOLKIT_I7001,\n },\n DESTROY_ACTION: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7101,\n end: IO.CDK_TOOLKIT_I7000,\n },\n BOOTSTRAP_SINGLE: {\n name: 'Bootstrap',\n start: IO.CDK_TOOLKIT_I9100,\n end: IO.CDK_TOOLKIT_I9000,\n },\n BUILD_ASSET: {\n name: 'Build Asset',\n start: IO.CDK_TOOLKIT_I5210,\n end: IO.CDK_TOOLKIT_I5211,\n },\n PUBLISH_ASSET: {\n name: 'Publish Asset',\n start: IO.CDK_TOOLKIT_I5220,\n end: IO.CDK_TOOLKIT_I5221,\n },\n HOTSWAP: {\n name: 'hotswap-deployment',\n start: IO.CDK_TOOLKIT_I5400,\n end: IO.CDK_TOOLKIT_I5410,\n },\n} satisfies Record<string, SpanDefinition<any, any>>;\n", "import * as util from 'util';\nimport type { ActionLessMessage, ActionLessRequest, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport { IO } from './messages';\n\n/**\n * Helper class to emit standard log messages to an IoHost\n *\n * It wraps an `IoHelper`, and adds convenience methods to emit default messages\n * for the various log levels.\n */\nexport class IoDefaultMessages {\n constructor(private readonly ioHelper: IoHelper) {\n }\n\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHelper.notify(msg);\n }\n\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHelper.requestResponse(msg);\n }\n\n public error(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_ERROR, input, ...args);\n }\n\n public warn(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public warning(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public info(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_INFO, input, ...args);\n }\n\n public debug(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_DEBUG, input, ...args);\n }\n\n public trace(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_TRACE, input, ...args);\n }\n\n public result(input: string, ...args: unknown[]) {\n const message = args.length > 0 ? util.format(input, ...args) : input;\n // This is just the default \"info\" message but with a level of \"result\"\n void this.ioHelper.notify({\n time: new Date(),\n code: IO.DEFAULT_TOOLKIT_INFO.code,\n level: 'result',\n message,\n data: undefined,\n });\n }\n\n private emitMessage(maker: IoMessageMaker<void>, input: string, ...args: unknown[]) {\n // Format message if args are provided\n const message = args.length > 0 ? util.format(input, ...args) : input;\n void this.ioHelper.notify(maker.msg(message));\n }\n}\n", "import type { Duration } from './types';\n\n/**\n * Different types of permission related changes in a diff\n */\nexport enum PermissionChangeType {\n /**\n * No permission changes\n */\n NONE = 'none',\n\n /**\n * Permissions are broadening\n */\n BROADENING = 'broadening',\n\n /**\n * Permissions are changed but not broadening\n */\n NON_BROADENING = 'non-broadening',\n}\n\n/**\n * Output of the diff command\n */\nexport interface DiffResult extends Duration {\n /**\n * Stack diff formatted as a string\n */\n readonly formattedStackDiff: string;\n\n /**\n * Security diff formatted as a string\n */\n readonly formattedSecurityDiff: string;\n}\n", "import type { PropertyDifference, Resource } from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { Duration } from './types';\nimport type { ResourceMetadata } from '../api/resource-metadata/resource-metadata';\n\n/**\n * A resource affected by a change\n */\nexport interface AffectedResource {\n /**\n * The logical ID of the affected resource in the template\n */\n readonly logicalId: string;\n /**\n * The CloudFormation type of the resource\n * This could be a custom type.\n */\n readonly resourceType: string;\n /**\n * The friendly description of the affected resource\n */\n readonly description?: string;\n /**\n * The physical name of the resource when deployed.\n *\n * A physical name is not always available, e.g. new resources will not have one until after the deployment\n */\n readonly physicalName?: string;\n /**\n * Resource metadata attached to the logical id from the cloud assembly\n *\n * This is only present if the resource is present in the current Cloud Assembly,\n * i.e. resource deletions will not have metadata.\n */\n readonly metadata?: ResourceMetadata;\n}\n\n/**\n * Represents a change in a resource\n */\nexport interface ResourceChange {\n /**\n * The logical ID of the resource which is being changed\n */\n readonly logicalId: string;\n /**\n * The value the resource is being updated from\n */\n readonly oldValue: Resource;\n /**\n * The value the resource is being updated to\n */\n readonly newValue: Resource;\n /**\n * The changes made to the resource properties\n */\n readonly propertyUpdates: Record<string, PropertyDifference<unknown>>;\n /**\n * Resource metadata attached to the logical id from the cloud assembly\n *\n * This is only present if the resource is present in the current Cloud Assembly,\n * i.e. resource deletions will not have metadata.\n */\n readonly metadata?: ResourceMetadata;\n}\n\n/**\n * A change that can be hotswapped\n */\nexport interface HotswappableChange {\n /**\n * The resource change that is causing the hotswap.\n */\n readonly cause: ResourceChange;\n /**\n * A list of resources that are being hotswapped as part of the change\n */\n readonly resources: AffectedResource[];\n}\n\nexport enum NonHotswappableReason {\n /**\n * Tags are not hotswappable\n */\n TAGS = 'tags',\n /**\n * Changed resource properties are not hotswappable on this resource type\n */\n PROPERTIES = 'properties',\n /**\n * A stack output has changed\n */\n OUTPUT = 'output',\n /**\n * A dependant resource is not hotswappable\n */\n DEPENDENCY_UNSUPPORTED = 'dependency-unsupported',\n /**\n * The resource type is not hotswappable\n */\n RESOURCE_UNSUPPORTED = 'resource-unsupported',\n /**\n * The resource is created in the deployment\n */\n RESOURCE_CREATION = 'resource-creation',\n /**\n * The resource is removed in the deployment\n */\n RESOURCE_DELETION = 'resource-deletion',\n /**\n * The resource identified by the logical id has its type changed\n */\n RESOURCE_TYPE_CHANGED = 'resource-type-changed',\n /**\n * The nested stack is created in the deployment\n */\n NESTED_STACK_CREATION = 'nested-stack-creation',\n}\n\nexport interface RejectionSubject {\n /**\n * The type of the rejection subject, e.g. Resource or Output\n */\n readonly type: string;\n\n /**\n * The logical ID of the change that is not hotswappable\n */\n readonly logicalId: string;\n /**\n * Resource metadata attached to the logical id from the cloud assembly\n *\n * This is only present if the resource is present in the current Cloud Assembly,\n * i.e. resource deletions will not have metadata.\n */\n readonly metadata?: ResourceMetadata;\n}\n\nexport interface ResourceSubject extends RejectionSubject {\n /**\n * A rejected resource\n */\n readonly type: 'Resource';\n /**\n * The type of the rejected resource\n */\n readonly resourceType: string;\n /**\n * The list of properties that are cause for the rejection\n */\n readonly rejectedProperties?: string[];\n}\n\nexport interface OutputSubject extends RejectionSubject {\n /**\n * A rejected output\n */\n readonly type: 'Output';\n}\n\n/**\n * A change that can not be hotswapped\n */\nexport interface NonHotswappableChange {\n /**\n * The subject of the change that was rejected\n */\n readonly subject: ResourceSubject | OutputSubject;\n /**\n * Why was this change was deemed non-hotswappable\n */\n readonly reason: NonHotswappableReason;\n /**\n * Tells the user exactly why this change was deemed non-hotswappable and what its logical ID is.\n * If not specified, `displayReason` default to state that the properties listed in `rejectedChanges` are not hotswappable.\n */\n readonly description: string;\n}\n\nexport interface HotswapDeploymentAttempt {\n /**\n * The stack that's currently being deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The mode the hotswap deployment was initiated with.\n */\n readonly mode: 'hotswap-only' | 'fall-back';\n}\n\n/**\n * Information about a hotswap deployment\n */\nexport interface HotswapDeploymentDetails {\n /**\n * The stack that's currently being deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The mode the hotswap deployment was initiated with.\n */\n readonly mode: 'hotswap-only' | 'fall-back';\n /**\n * The changes that were deemed hotswappable\n */\n readonly hotswappableChanges: HotswappableChange[];\n /**\n * The changes that were deemed not hotswappable\n */\n readonly nonHotswappableChanges: NonHotswappableChange[];\n}\n\n/**\n * The result of an attempted hotswap deployment\n */\nexport interface HotswapResult extends Duration, HotswapDeploymentDetails {\n /**\n * Whether hotswapping happened or not.\n *\n * `false` indicates that the deployment could not be hotswapped and full deployment may be attempted as fallback.\n */\n readonly hotswapped: boolean;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAM,uBAAuB,OAAO,IAAI,mCAAmC;AAC3E,IAAM,8BAA8B,OAAO,IAAI,0CAA0C;AACzF,IAAM,wBAAwB,OAAO,IAAI,oCAAoC;AAC7E,IAAM,gCAAgC,OAAO,IAAI,2CAA2C;AAKrF,IAAM,eAAN,MAAM,sBAAqB,MAAM;AAAA;AAAA;AAAA;AAAA,EAItC,OAAc,eAAe,GAA2B;AACtD,WAAO,MAAM,QAAQ,OAAO,MAAO,YAAY,wBAAwB;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,sBAAsB,GAAkC;AACpE,WAAO,KAAK,eAAe,CAAC,KAAK,+BAA+B;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,gBAAgB,GAA4B;AACxD,WAAO,KAAK,eAAe,CAAC,KAAK,yBAAyB;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,uBAAuB,GAAmC;AACtE,WAAO,KAAK,eAAe,CAAC,KAAK,iCAAiC;AAAA,EACpE;AAAA;AAAA;AA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IvB,EAAAA,uBAAA,uBAAoB;AAIpB,EAAAA,uBAAA,uBAAoB;AAIpB,EAAAA,uBAAA,2BAAwB;AAIxB,EAAAA,uBAAA,2BAAwB;AApCd,SAAAA;AAAA,GAAA;",
|
|
6
|
-
"names": ["message", "error", "StackSelectionStrategy", "ExpandStackSelection", "import_util", "error", "dirname", "path", "chalk", "fs", "path", "fs", "cached", "path", "fs", "ECRDescribeImagesCommand", "result", "os", "import_credential_providers", "import_util", "cxschema", "cxapi", "import_client_cloudcontrol", "isObject", "result", "import_cx_api", "import_cx_api", "fs", "path", "fs", "semver", "fs", "chalk", "import_cx_api", "import_client_cloudformation", "import_cdk_assets", "import_cx_api", "import_client_s3", "import_middleware_endpoint", "chalk", "fs", "import_client_cloudformation", "import_cx_api", "chalk", "import_cx_api", "cxschema", "cxapi", "fs", "import_semver", "cxapi", "fs", "cxapi", "fs", "uuid", "message", "util", "message", "PermissionChangeType", "NonHotswappableReason"]
|
|
7
|
-
}
|