@go-to-k/cdkd 0.298.6 → 0.298.7

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.
@@ -2,8 +2,8 @@ import { a as runWithStackAwsClients, i as resetAwsClients, o as setAwsClients,
2
2
  import { A as UNRENDERABLE, B as stringifyJsonPayload, D as SAFE_MSG_ALTERED_CHAR, F as displayStackName, H as truncateCodePoints, I as isPasteableIdent, M as displayAwsMessage, N as displayIdent, O as SECRET_REF_MAX_CODE_POINTS, P as displaySafe, R as plainIdentOr, T as withStackName, _ as derivesPatternBName, a as getLogger, f as getLiveRenderer, h as PATTERN_B_RESOURCE_TYPES, j as cutMarker, k as STACK_REF_MAX_CODE_POINTS, l as runStackBuffered, m as PATTERN_B_NAME_PROPERTIES, o as isStdoutReservedForPayload, p as PATTERN_B_NAME_OPTIONS, r as safeStringify, s as reserveStdoutForPayload, t as describeAwsFailure, v as explicitNamePropertyFor, w as withSkipPrefix, y as generateResourceName, z as safeMsg } from "./aws-failure-text-DtvlUugx.js";
3
3
  import { $n as isAmbiguousOutcomeError, $t as credentialFingerprint, Bn as withheldTargetClause, D as VALUE_NOT_SHOWN, Dn as TIMEOUT_FLAG_RESOURCE_TYPE, E as assertRegionMatch, En as withErrorHandling, Ft as buildLockContentionMessage, G as runDeleteAttempt, Hn as setPasteableVerbFlags, Ht as CUSTOM_RESOURCE_RESPONSE_PREFIX, In as plainOrDescribed, It as forceQuitRecoveryClause, Jt as setPasteableAwsProfile, Kt as producerCoordinateKey, Ln as quotedOrDescribed, Lt as formatLockExpiry, Nn as isInertUnquoted, Nt as UNREPRODUCIBLE_LOCK_CLAUSE, P as remedyLogicalId, Pn as pasteableCommand, Pt as buildForceUnlockCommand, Qt as clientDefaultsFor, Rn as shellBoundedDisplay, Rt as formatLockOperation, Sn as SynthesisError, T as RESOURCE_NOT_FOUND, Tn as normalizeAwsError, Ut as DEFAULT_STATE_PREFIX, Vn as setPasteableRunFlags, Wt as injectiveKey, Xt as ambientClientDefaults, Yt as withPasteableAwsProfile, Z as isAwsCliLiteral, Zt as ambientCredentialConfig, _n as ResourceTimeoutError, ar as isMarkedNonRetryable, bn as StackTerminationProtectionError, cn as IntrinsicResolutionRefusalError, en as AccountIdUnavailableError, ft as logicalIdShown, gn as ProvisioningError, hn as PartialFailureError, in as CrossAccountSecretRefusalError, it as isInterruptedWaitError, jn as commandHole, kn as SHELL_ACTIVE_WHY, ln as LocalInvokeBuildError$1, mn as NestedStackChildDirectDestroyError, mt as resourceTypeShown, n as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, nn as CdkdError, nr as isTransientServerError, nt as endCommandInterruptScope, on as DeployCancelledError, or as isThrottlingError, pn as MalformedProducerRecordRefusalError, qt as producerRecordKey, rr as retryClassificationText, rt as interruptWatchListenerCount, s as readRecordedPrincipals, sn as DynamicReferenceRegionAmbiguousError, sr as markNonRetryable, t as IAM_PRINCIPAL_NAME, tr as isRetryableTransientError, tt as beginCommandInterruptScope, un as LocalStartServiceError, vn as ResourceUpdateNotSupportedError, yn as StackHasActiveImportsError, zn as shellQuote, zt as formatLockOwner } from "./iam-policy-targets-CwKiK9nS.js";
4
4
  import { a as setAssumedRoleCredentials, n as awsClientDefaults, r as getAssumedRoleCredentials, u as formatAuthority } from "./aws-client-defaults-D0q0z4dG.js";
5
- import { $a as isStatefulRecreateTargetForReplace, $c as warnDeprecatedNoPrefixCliFlag, $i as malformedOrphansRefusalMessage, $n as ledgerForStack, $o as markSameGenerationBag, $r as sendableAssumeRoleCommand, $s as AssetPublisher, $t as seedsDeleteFirstGuard, A as noEchoComparisonForTemplate, Aa as refuseMalformedResourcesForDeploy, Ac as redactDockerArgvValues, Ai as declaresNoEcho, An as journaledOrphanPrintingBag, Ao as maskWholeValue, Ar as deleteIndeterminateGuards, As as LockManager, At as dropFailedHint, Ba as unpreviewableOrphanRecords, Bc as Synthesizer, Bi as hasReadableOutputs, Bn as PRE_DELETE_SNAPSHOT_TYPES, Bo as carryLogOnlyValues, Bs as splitImportedOps, C as recordRetainedForReadoption, Ca as refuseMalformedResourceEntriesForImport, Cc as dockerSpawnEnvWithSensitive, Ci as cfnRefValueFromPhysicalId, Cl as renderAssemblyPathEscape, Cn as collectDeclaredOutputNames, Cr as applyCustomResourceResponseExpiration, Cs as wholeStringLeavesOf, D as withResourceDeadline, Da as refuseMalformedResourcePropertiesForDrift, Dc as isDockerClientEnvKey, Di as withSharedDrainBudget, Dn as DEFAULT_RESOURCE_TIMEOUT_MS, Do as isMarkedCoordinate, Ds as TEMPLATE_SOURCED_RULES, E as serviceTokenBlockingReason, Ea as refuseMalformedResourcePropertiesForDestroy, Ec as getDockerCmd, El as resolveBucketRegion, En as bindingSkippedOutputs, Eo as canonicalCoordinates, Er as slowCcOperationTimeoutMs, Es as STATE_SOURCED_READBACK_RULES, Et as collectNestedChildUnaddressed, F as PROTECTION_PROPERTY_BY_TYPE, Fa as repairMalformedOrphansForReadOnly, Fc as escapeRegExp, Fi as UNREADABLE_RESOURCES_MAP_ROW, Fn as secretNamedRecordNeedles, Fs as CrossPrefixScanCache, Ft as sameJournaledOrphans, Gc as resolveApp, Gi as malformedExportNamesWarning, Gn as isFinalSnapshotError, Go as printingCorpusOf, Gr as poisonRenderedSpellingsCollidingIn, Gs as hasReasonlessBaselineRefusal, Gt as isJournaledOrphan, Ha as unreadableResourceEntries, Hc as getDefaultStateBucketName, Hi as isReadableOrphanRecord, Hn as ccRoutedFinalSnapshotError, Ho as hasMaskableValues, Hr as DiffCalculator, Hs as describeRegionValueKind, Ht as removeProtectionTypeList, I as isProtectionValueActive, Ia as repairMalformedOutputsForReadOnly, Ic as stripControlChars, Ii as accountArgs, In as stateSecretNameNeedles, Io as readbackPathFor, Is as applyCrossPrefixScan, It as replayFailedOperations, Ja as NO_CC_HANDLERS_REASON, Jc as resolveSkipPrefix, Ji as malformedLocalResourceEntriesWarning, Jn as maskingRetryLogger, Jo as shareLogOnlyValues, Jr as applyRoleArnIfSet, Js as importableOutputs, Jt as planRollback, Ka as unwrittenCreateOnlyReplacement, Kc as resolveAutoAssetStorage, Ki as malformedExportSourceWarning, Kn as refusesFinalSnapshot, Ko as recordLogOnlyParameterValue, Kr as producerLookupOver, Ks as hasUnverifiableParameterRefusal, Kt as isReplacementOrphan, L as perType, La as repairMalformedResourceEntriesForReadOnly, Lc as stripForDisplay, Li as deployRefusesOrphanRowsReason, Ln as storedSecretNameNeedles, Lo as readsNoEchoSource, Ls as crossPrefixDeniedWarning, Lt as replayRollback, M as noEchoParameterNamesOf, Ma as refuseMalformedResourcesForExport, Mc as runDockerForeground, Mi as STATE_REGION_DIVERGED, Mn as orphanRecordsPrintingBag, Mo as noEchoCoordinatesOf, Mr as deleteSkipReason, Ms as S3StateBackend, Mt as journaledOrphanLines, N as recordedProtectionEvidence, Na as refuseMalformedState, Nc as runDockerStreaming, Ni as STATE_RESOURCES_MALFORMED, Nn as secretNamePrintingBag, No as noEchoLeavesOf, Ns as rebuildClientForBucketRegion, Nt as loadJournaledOrphans, O as diffSecurity, Oa as refuseMalformedResourcePropertiesForExport, Oc as isMalformedEnvKey, Oi as parameterInputsFor, On as DEFAULT_RESOURCE_WARN_AFTER_MS, Oo as maskAtCoordinates, Or as RollbackInlinePolicyWriters, Os as WHOLE_DYNAMIC_REFERENCE_PATTERN, Ot as withNestedStackContext, P as recordedProtectionNote, Pa as repairMalformedOrphanRecordsForReadOnly, Pc as warnFinchArgvExposure, Pi as UNREADABLE_ORPHANS_CONTAINER_ROW, Pn as secretNamePrintingBags, Po as noEchoOutputsComparison, Pr as isWaitAbandonedError, Ps as CrossPrefixReadError, Pt as makeForeignHolderScan, Qa as MULTI_REGION_RECREATE_BLOCKED_TYPES, Qc as stateBucketExistenceConfirmed, Qi as malformedOrphanRowsKeptWarning, Qo as maskSecretsInText, Qr as isIamRoleArn, Qs as shouldRetainResource, Qt as resolveReplacementOldType, R as readProtection, Ra as repairMalformedResourcePropertiesForReadOnly, Rc as AssetManifestLoader, Ri as displayLogicalId, Rn as extractDeploymentEventError, Ro as valueAtCoordinate, Rs as isAccessDenied, S as keptForReadoption, Sa as refuseMalformedResourceEntriesForDestroy, Sc as describeDockerFailure, Si as AWS_NO_VALUE, Sl as displayAssemblyPath, Sn as noEchoParameterValueSeed, Sr as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, Ss as recordProvenPublicExpression, St as recordDisplacedSkips, T as findServiceTokenRefusals, Ta as refuseMalformedResourceEntriesForOrphan, Tc as formatDockerLoginError, Ti as refStateLookupFromResource, Tn as isExportAliasCollision, To as TemplateParser, Tr as CloudControlProvider, Ts as STATE_SOURCED_CROSS_GENERATION_RULES, Tt as withNestedRevertRun, Ua as withheldAccountClause, Uc as getLegacyStateBucketName, Ui as isReadableResourceEntry, Un as createPreDeleteFinalSnapshot, Uo as literalSplitDelimitersOf, Ur as INTRINSIC_KEYS, Us as exportNamesCarriedFrom, Ut as recordAfterRollbackUpdate, Va as unreadableOrphanRecords, Vc as synthesisStatusMessage, Vi as hasReadableResources, Vn as buildFinalSnapshotIdentifier, Vo as createUnionSecretMasker, Vs as acceptedCreateOnlyDropsOf, Vt as withStackRecords, Wa as findActionableSilentDrops, Wc as loadCdkJson, Wi as malformedDriftResourcePropertiesWarning, Wn as effectiveDeletionPolicy, Wo as logOnlyValueCount, Wr as IntrinsicFunctionResolver, Ws as hasReadableExportSet, Wt as demoteSupersededOrphans, Xa as findReplacedReadersOfRecreateTargets, Xc as resolveStateBucketWithDefaultAndSource, Xi as malformedOrphanRecordsRefusalMessage, Xn as findDestructiveChanges, Xo as errorCauseChain, Xr as assertSendableRoleArn, Xs as orphansAfterRollback, Xt as recordUnderIdIsNotOwn, Ya as hasNoCloudControlHandlers, Yc as resolveStateBucketWithDefault, Yi as malformedLocalResourcesWarning, Yn as constructPathOf, Yo as createSecretMasker, Yr as assertFlagRoleArn, Ys as isReadableBag, Yt as recheckFailedPlan, Za as shownType, Zc as resolveUseCdkBootstrapAssets, Zi as malformedOrphanRecordsWarning, Zn as formatDestructiveChange, Zo as maskSecretsInError, Zr as explicitRoleArnOrThrow, Zs as orphansCarriedFrom, Zt as replacementNeverSwapped, _ as makeCanonicalizePropertiesFn, _a as refuseMalformedOutputs, _c as buildDenyExternalAccessPolicy, _i as isImpossibleEmptyStoredAttribute, _l as hasPlainPrototype, _n as secretSafeKeyDisplay, _o as prefetchCreateOnlyPropertyPaths, _r as TemplateNoEchoReresolver, _s as provenPublicValue, _t as displacedOpClause, a as findNestedTemplateTreeDefect, aa as malformedResourcePropertiesWarning, ac as loadPublishableAssetManifest, al as uploadCfnTemplate, as as dynamicReferenceTokens, at as cyan, ba as refuseMalformedResourceEntries, bc as describeDockerCapturedOutput, bi as isNamelessDynamicReferenceError, bl as absoluteAssemblyPathEscape, bn as exportNameSecretExposure, bo as withRetry, bs as recordNoEchoAttributeValues, c as renderNestedTemplateTreeDefect, ca as malformedStateRefusalMessage, cc as BOOTSTRAP_MARKER_PREFIX, cl as expectedOwnerParam, cn as updatePartialMessage, cs as identityKeyFor, ct as red, d as conditionInputsFrom, dc as getBootstrapMarkerKey, di as producerRegionsFromState, dl as derivePartitionAndUrlSuffix, dn as DeploymentEventsStore, dt as namesAnyDeclaredParameter, ea as malformedOrphansWarning, ec as isSensitiveAttributeName, ei as AWS_CREDENTIAL_ENV_KEYS, el as ssmResolvedValueType, en as orphanDeleteNeedsIdentity, eo as isStatefulRecreateTargetSync, es as redactSecretsForState, f as parentSuppliedValues, fa as refuseMalformedOrphanRecords, fc as isCrossRegionRedirect, fi as regionLessSecretName, fl as AssemblyReader, fn as WITHHELD_NAME_DISPLAY, fr as CC_BROKEN_REASON, fs as physicalNameCopiesOf, ft as reachableDivergentParameters, g as mergeNoChangeOutputs, ga as refuseMalformedOrphansForOrphan, gc as validateContainerRepoName, gi as getAccountInfo, gl as hasOwnKey, gn as secretBearingStateKeyWarning, gr as wouldReturnToSdkProvider, gs as carriesSecretMask, gt as NESTED_PENDING_PARENT_REASON, h as keptWholeReasonText, ha as refuseMalformedOrphansForDestroy, hc as validateAssetBucketName, hi as parameterTypeMayLoseSecretIdentity, hl as defineOwnKey, hn as secretBearing, hr as isCustomResource, hs as splitGetAttStringForm, ht as planOrphanAdoption, i as childTemplateLoader, ia as malformedResourceEntriesWarning, ic as createAssetRedirectResolver, il as findLargeInlineResources, is as DYNAMIC_REFERENCE_TOKEN_SCAN, it as bold, j as noEchoExactEchoLeavesOf, ja as refuseMalformedResourcesForDestroy, jc as redactedDockerCause, ji as JSON_LISTING_HOLE_VALUE, jn as maskEventTextWithBoundBags, jo as maskedLeafCoordinatesOf, jr as deleteLeftInPlace, js as isLockInfoExpired, jt as isHandledOrphan, k as noEchoAttributeNamesOf, ka as refuseMalformedResourcePropertiesForOrphan, kc as partitionSensitiveEnv, kn as completedReplayEntries, ko as maskReadbackAtCoordinates, kr as UNSPECIFIED_SKIP_REASON, ks as isSingleDynamicReferenceToken, kt as deleteJournaledOrphans, l as templateIdentity, la as previewableOrphanRecords, lc as assertAssetBucketRegion, ll as PARTITION_TABLE, ln as updatePartialReason, ls as inheritNestedStackParameterAssociations, lt as yellow, m as isSecretBearingReferenceString, ma as refuseMalformedOrphans, mc as readBootstrapMarkerBody, mi as isUnboundTemplateParameter, ml as processStackMessages, mn as exportAliasCollisionScrubWarning, mr as ccBrokenReason, ms as recordPhysicalNameCopy, mt as makeSiblingClaimReader, n as IMPLICIT_DELETE_DEPENDENCIES, na as malformedOutputsWarning, nc as WorkGraph, ni as callerEnvCredentials, nl as CFN_TEMPLATE_URL_LIMIT, ns as withPhysicalNameCopies, nt as formatResourceLine, o as isAbsoluteAssetPath, oa as malformedResourcesWarning, oc as rewriteTemplateAssetReferences, ol as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, os as isUncertifiedBaselineMaskPosition, ot as gray, p as readRecordedConditionVerdicts, pa as refuseMalformedOrphanRecordsForDestroy, pc as parseBootstrapMarker, pi as coerceParameterTypedValue, pl as StageLoadError, pn as displayTextOrWithheld, pr as ProviderRegistry, pt as resourcesNamingDeclaredParameter, qc as resolveCaptureObservedState, qi as malformedLocalOutputsWarning, qn as unsupportedFinalSnapshotError, qo as recordLogOnlyValue, qr as refuseUnreadableCdkCrossAccountRefs, qs as importableOutputKeys, qt as planFailedOps, r as computeImplicitDeleteEdges, ra as malformedRenderedContainersWarning, rc as buildAssetRedirectMap, ri as envCredentialsAreAssumedRole, rl as MIGRATE_TMP_PREFIX, rn as inheritProducerRegions, rt as createReadOnlyAttributeHealerFactory, s as listNestedTemplateRows, sa as malformedScrubResourceEntriesRefusalMessage, sc as AssetModeResolver, sl as decodeListingKey, ss as pathCrossesDottedKey, st as green, t as DeployEngine, ta as malformedOutputsRefusalMessage, tc as stringifyValue, ti as applyCallerIdentityCredentials, tl as CFN_TEMPLATE_BODY_LIMIT, tn as findNestedStackTypeChanges, to as renderStatefulReason, tr as withCreateTokenLedger, ts as scrubResourceRecord, u as conditionFingerprint, ua as refuseDivergentRecordRegionForDestroy, uc as ensureAssetStorage, ui as classifyReplaySecretRegion, ul as canonicalizeRegion, un as DeploymentEventsReader, us as recordNestedStackParameterExpressions, ut as computeParameterTaint, va as refuseMalformedOutputsForDestroy, vc as buildDockerImage, vi as carriesDynamicReference, vl as nullPrototypeRecord, vn as carriedExportAliasExposure, vo as templateResourceTypes, vr as readsNoEchoDeleteValues, vs as recordMaskOnlyValue, vt as displacedPhysicalIdShown, w as deferredServiceTokenWarning, wa as refuseMalformedResourceEntriesForImportSave, wc as finchSecretArgvRefusal, wi as isStalePlaceholderArnAttribute, wl as resolveAssemblyPath, wn as collectPublishedOutputNames, wo as DagBuilder, wr as customResourceResponseExpirationWarning, ws as STATE_SOURCED_BASELINE_RULES, wt as revertedNestedRowIds, xa as refuseMalformedResourceEntriesForDeploy, xc as describeDockerExecFailure, xi as keepsSecretReferenceToken, xl as describeFileReadFailure, xn as isWholeDynamicReferenceValue, xr as withPrintingSecrets, xs as recordNoEchoParameterFreshValue, xt as nestedChildStackName$1, ya as refuseMalformedResourceAttributesForOrphan, yc as resolveDockerContextDirectory, yi as carriesFetchableDynamicReference, yl as ownValue, yn as exportNameNoEchoParameters, yo as describeTypeWithThrottleRetry, yr as isCustomResourceType$1, ys as recordMaskOnlyValuesIn, yt as dropSettledNestedJournals, za as repairMalformedResourcesForReadOnly, zc as getDockerImageBySourceHash, zi as hasReadableOrphans, zn as ATOMIC_FINAL_SNAPSHOT_TYPES, zo as liveMatchesUnresolvedTokenFrame, zs as isNotImplemented, zt as destroyStackRecordsView } from "./deploy-engine-BhJ7GrCh.js";
6
- import { t as getCdkdVersion } from "./version-B28nhaco.js";
5
+ import { $a as isStatefulRecreateTargetForReplace, $c as warnDeprecatedNoPrefixCliFlag, $i as malformedOrphansRefusalMessage, $n as ledgerForStack, $o as markSameGenerationBag, $r as sendableAssumeRoleCommand, $s as AssetPublisher, $t as seedsDeleteFirstGuard, A as noEchoComparisonForTemplate, Aa as refuseMalformedResourcesForDeploy, Ac as redactDockerArgvValues, Ai as declaresNoEcho, An as journaledOrphanPrintingBag, Ao as maskWholeValue, Ar as deleteIndeterminateGuards, As as LockManager, At as dropFailedHint, Ba as unpreviewableOrphanRecords, Bc as Synthesizer, Bi as hasReadableOutputs, Bn as PRE_DELETE_SNAPSHOT_TYPES, Bo as carryLogOnlyValues, Bs as splitImportedOps, C as recordRetainedForReadoption, Ca as refuseMalformedResourceEntriesForImport, Cc as dockerSpawnEnvWithSensitive, Ci as cfnRefValueFromPhysicalId, Cl as renderAssemblyPathEscape, Cn as collectDeclaredOutputNames, Cr as applyCustomResourceResponseExpiration, Cs as wholeStringLeavesOf, D as withResourceDeadline, Da as refuseMalformedResourcePropertiesForDrift, Dc as isDockerClientEnvKey, Di as withSharedDrainBudget, Dn as DEFAULT_RESOURCE_TIMEOUT_MS, Do as isMarkedCoordinate, Ds as TEMPLATE_SOURCED_RULES, E as serviceTokenBlockingReason, Ea as refuseMalformedResourcePropertiesForDestroy, Ec as getDockerCmd, El as injectedAwsRegionValue, En as bindingSkippedOutputs, Eo as canonicalCoordinates, Er as slowCcOperationTimeoutMs, Es as STATE_SOURCED_READBACK_RULES, Et as collectNestedChildUnaddressed, F as PROTECTION_PROPERTY_BY_TYPE, Fa as repairMalformedOrphansForReadOnly, Fc as escapeRegExp, Fi as UNREADABLE_RESOURCES_MAP_ROW, Fn as secretNamedRecordNeedles, Fs as CrossPrefixScanCache, Ft as sameJournaledOrphans, Gc as resolveApp, Gi as malformedExportNamesWarning, Gn as isFinalSnapshotError, Go as printingCorpusOf, Gr as poisonRenderedSpellingsCollidingIn, Gs as hasReasonlessBaselineRefusal, Gt as isJournaledOrphan, Ha as unreadableResourceEntries, Hc as getDefaultStateBucketName, Hi as isReadableOrphanRecord, Hn as ccRoutedFinalSnapshotError, Ho as hasMaskableValues, Hr as DiffCalculator, Hs as describeRegionValueKind, Ht as removeProtectionTypeList, I as isProtectionValueActive, Ia as repairMalformedOutputsForReadOnly, Ic as stripControlChars, Ii as accountArgs, In as stateSecretNameNeedles, Io as readbackPathFor, Is as applyCrossPrefixScan, It as replayFailedOperations, Ja as NO_CC_HANDLERS_REASON, Jc as resolveSkipPrefix, Ji as malformedLocalResourceEntriesWarning, Jn as maskingRetryLogger, Jo as shareLogOnlyValues, Jr as applyRoleArnIfSet, Js as importableOutputs, Jt as planRollback, Ka as unwrittenCreateOnlyReplacement, Kc as resolveAutoAssetStorage, Ki as malformedExportSourceWarning, Kn as refusesFinalSnapshot, Ko as recordLogOnlyParameterValue, Kr as producerLookupOver, Ks as hasUnverifiableParameterRefusal, Kt as isReplacementOrphan, L as perType, La as repairMalformedResourceEntriesForReadOnly, Lc as stripForDisplay, Li as deployRefusesOrphanRowsReason, Ln as storedSecretNameNeedles, Lo as readsNoEchoSource, Ls as crossPrefixDeniedWarning, Lt as replayRollback, M as noEchoParameterNamesOf, Ma as refuseMalformedResourcesForExport, Mc as runDockerForeground, Mi as STATE_REGION_DIVERGED, Mn as orphanRecordsPrintingBag, Mo as noEchoCoordinatesOf, Mr as deleteSkipReason, Ms as S3StateBackend, Mt as journaledOrphanLines, N as recordedProtectionEvidence, Na as refuseMalformedState, Nc as runDockerStreaming, Ni as STATE_RESOURCES_MALFORMED, Nn as secretNamePrintingBag, No as noEchoLeavesOf, Ns as rebuildClientForBucketRegion, Nt as loadJournaledOrphans, O as diffSecurity, Oa as refuseMalformedResourcePropertiesForExport, Oc as isMalformedEnvKey, Oi as parameterInputsFor, Ol as resolveBucketRegion, On as DEFAULT_RESOURCE_WARN_AFTER_MS, Oo as maskAtCoordinates, Or as RollbackInlinePolicyWriters, Os as WHOLE_DYNAMIC_REFERENCE_PATTERN, Ot as withNestedStackContext, P as recordedProtectionNote, Pa as repairMalformedOrphanRecordsForReadOnly, Pc as warnFinchArgvExposure, Pi as UNREADABLE_ORPHANS_CONTAINER_ROW, Pn as secretNamePrintingBags, Po as noEchoOutputsComparison, Pr as isWaitAbandonedError, Ps as CrossPrefixReadError, Pt as makeForeignHolderScan, Qa as MULTI_REGION_RECREATE_BLOCKED_TYPES, Qc as stateBucketExistenceConfirmed, Qi as malformedOrphanRowsKeptWarning, Qo as maskSecretsInText, Qr as isIamRoleArn, Qs as shouldRetainResource, Qt as resolveReplacementOldType, R as readProtection, Ra as repairMalformedResourcePropertiesForReadOnly, Rc as AssetManifestLoader, Ri as displayLogicalId, Rn as extractDeploymentEventError, Ro as valueAtCoordinate, Rs as isAccessDenied, S as keptForReadoption, Sa as refuseMalformedResourceEntriesForDestroy, Sc as describeDockerFailure, Si as AWS_NO_VALUE, Sl as displayAssemblyPath, Sn as noEchoParameterValueSeed, Sr as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, Ss as recordProvenPublicExpression, St as recordDisplacedSkips, T as findServiceTokenRefusals, Ta as refuseMalformedResourceEntriesForOrphan, Tc as formatDockerLoginError, Ti as refStateLookupFromResource, Tl as injectAwsRegion, Tn as isExportAliasCollision, To as TemplateParser, Tr as CloudControlProvider, Ts as STATE_SOURCED_CROSS_GENERATION_RULES, Tt as withNestedRevertRun, Ua as withheldAccountClause, Uc as getLegacyStateBucketName, Ui as isReadableResourceEntry, Un as createPreDeleteFinalSnapshot, Uo as literalSplitDelimitersOf, Ur as INTRINSIC_KEYS, Us as exportNamesCarriedFrom, Ut as recordAfterRollbackUpdate, Va as unreadableOrphanRecords, Vc as synthesisStatusMessage, Vi as hasReadableResources, Vn as buildFinalSnapshotIdentifier, Vo as createUnionSecretMasker, Vs as acceptedCreateOnlyDropsOf, Vt as withStackRecords, Wa as findActionableSilentDrops, Wc as loadCdkJson, Wi as malformedDriftResourcePropertiesWarning, Wn as effectiveDeletionPolicy, Wo as logOnlyValueCount, Wr as IntrinsicFunctionResolver, Ws as hasReadableExportSet, Wt as demoteSupersededOrphans, Xa as findReplacedReadersOfRecreateTargets, Xc as resolveStateBucketWithDefaultAndSource, Xi as malformedOrphanRecordsRefusalMessage, Xn as findDestructiveChanges, Xo as errorCauseChain, Xr as assertSendableRoleArn, Xs as orphansAfterRollback, Xt as recordUnderIdIsNotOwn, Ya as hasNoCloudControlHandlers, Yc as resolveStateBucketWithDefault, Yi as malformedLocalResourcesWarning, Yn as constructPathOf, Yo as createSecretMasker, Yr as assertFlagRoleArn, Ys as isReadableBag, Yt as recheckFailedPlan, Za as shownType, Zc as resolveUseCdkBootstrapAssets, Zi as malformedOrphanRecordsWarning, Zn as formatDestructiveChange, Zo as maskSecretsInError, Zr as explicitRoleArnOrThrow, Zs as orphansCarriedFrom, Zt as replacementNeverSwapped, _ as makeCanonicalizePropertiesFn, _a as refuseMalformedOutputs, _c as buildDenyExternalAccessPolicy, _i as isImpossibleEmptyStoredAttribute, _l as hasPlainPrototype, _n as secretSafeKeyDisplay, _o as prefetchCreateOnlyPropertyPaths, _r as TemplateNoEchoReresolver, _s as provenPublicValue, _t as displacedOpClause, a as findNestedTemplateTreeDefect, aa as malformedResourcePropertiesWarning, ac as loadPublishableAssetManifest, al as uploadCfnTemplate, as as dynamicReferenceTokens, at as cyan, ba as refuseMalformedResourceEntries, bc as describeDockerCapturedOutput, bi as isNamelessDynamicReferenceError, bl as absoluteAssemblyPathEscape, bn as exportNameSecretExposure, bo as withRetry, bs as recordNoEchoAttributeValues, c as renderNestedTemplateTreeDefect, ca as malformedStateRefusalMessage, cc as BOOTSTRAP_MARKER_PREFIX, cl as expectedOwnerParam, cn as updatePartialMessage, cs as identityKeyFor, ct as red, d as conditionInputsFrom, dc as getBootstrapMarkerKey, di as producerRegionsFromState, dl as derivePartitionAndUrlSuffix, dn as DeploymentEventsStore, dt as namesAnyDeclaredParameter, ea as malformedOrphansWarning, ec as isSensitiveAttributeName, ei as AWS_CREDENTIAL_ENV_KEYS, el as ssmResolvedValueType, en as orphanDeleteNeedsIdentity, eo as isStatefulRecreateTargetSync, es as redactSecretsForState, f as parentSuppliedValues, fa as refuseMalformedOrphanRecords, fc as isCrossRegionRedirect, fi as regionLessSecretName, fl as AssemblyReader, fn as WITHHELD_NAME_DISPLAY, fr as CC_BROKEN_REASON, fs as physicalNameCopiesOf, ft as reachableDivergentParameters, g as mergeNoChangeOutputs, ga as refuseMalformedOrphansForOrphan, gc as validateContainerRepoName, gi as getAccountInfo, gl as hasOwnKey, gn as secretBearingStateKeyWarning, gr as wouldReturnToSdkProvider, gs as carriesSecretMask, gt as NESTED_PENDING_PARENT_REASON, h as keptWholeReasonText, ha as refuseMalformedOrphansForDestroy, hc as validateAssetBucketName, hi as parameterTypeMayLoseSecretIdentity, hl as defineOwnKey, hn as secretBearing, hr as isCustomResource, hs as splitGetAttStringForm, ht as planOrphanAdoption, i as childTemplateLoader, ia as malformedResourceEntriesWarning, ic as createAssetRedirectResolver, il as findLargeInlineResources, is as DYNAMIC_REFERENCE_TOKEN_SCAN, it as bold, j as noEchoExactEchoLeavesOf, ja as refuseMalformedResourcesForDestroy, jc as redactedDockerCause, ji as JSON_LISTING_HOLE_VALUE, jn as maskEventTextWithBoundBags, jo as maskedLeafCoordinatesOf, jr as deleteLeftInPlace, js as isLockInfoExpired, jt as isHandledOrphan, k as noEchoAttributeNamesOf, ka as refuseMalformedResourcePropertiesForOrphan, kc as partitionSensitiveEnv, kn as completedReplayEntries, ko as maskReadbackAtCoordinates, kr as UNSPECIFIED_SKIP_REASON, ks as isSingleDynamicReferenceToken, kt as deleteJournaledOrphans, l as templateIdentity, la as previewableOrphanRecords, lc as assertAssetBucketRegion, ll as PARTITION_TABLE, ln as updatePartialReason, ls as inheritNestedStackParameterAssociations, lt as yellow, m as isSecretBearingReferenceString, ma as refuseMalformedOrphans, mc as readBootstrapMarkerBody, mi as isUnboundTemplateParameter, ml as processStackMessages, mn as exportAliasCollisionScrubWarning, mr as ccBrokenReason, ms as recordPhysicalNameCopy, mt as makeSiblingClaimReader, n as IMPLICIT_DELETE_DEPENDENCIES, na as malformedOutputsWarning, nc as WorkGraph, ni as callerEnvCredentials, nl as CFN_TEMPLATE_URL_LIMIT, ns as withPhysicalNameCopies, nt as formatResourceLine, o as isAbsoluteAssetPath, oa as malformedResourcesWarning, oc as rewriteTemplateAssetReferences, ol as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, os as isUncertifiedBaselineMaskPosition, ot as gray, p as readRecordedConditionVerdicts, pa as refuseMalformedOrphanRecordsForDestroy, pc as parseBootstrapMarker, pi as coerceParameterTypedValue, pl as StageLoadError, pn as displayTextOrWithheld, pr as ProviderRegistry, pt as resourcesNamingDeclaredParameter, qc as resolveCaptureObservedState, qi as malformedLocalOutputsWarning, qn as unsupportedFinalSnapshotError, qo as recordLogOnlyValue, qr as refuseUnreadableCdkCrossAccountRefs, qs as importableOutputKeys, qt as planFailedOps, r as computeImplicitDeleteEdges, ra as malformedRenderedContainersWarning, rc as buildAssetRedirectMap, ri as envCredentialsAreAssumedRole, rl as MIGRATE_TMP_PREFIX, rn as inheritProducerRegions, rt as createReadOnlyAttributeHealerFactory, s as listNestedTemplateRows, sa as malformedScrubResourceEntriesRefusalMessage, sc as AssetModeResolver, sl as decodeListingKey, ss as pathCrossesDottedKey, st as green, t as DeployEngine, ta as malformedOutputsRefusalMessage, tc as stringifyValue, ti as applyCallerIdentityCredentials, tl as CFN_TEMPLATE_BODY_LIMIT, tn as findNestedStackTypeChanges, to as renderStatefulReason, tr as withCreateTokenLedger, ts as scrubResourceRecord, u as conditionFingerprint, ua as refuseDivergentRecordRegionForDestroy, uc as ensureAssetStorage, ui as classifyReplaySecretRegion, ul as canonicalizeRegion, un as DeploymentEventsReader, us as recordNestedStackParameterExpressions, ut as computeParameterTaint, va as refuseMalformedOutputsForDestroy, vc as buildDockerImage, vi as carriesDynamicReference, vl as nullPrototypeRecord, vn as carriedExportAliasExposure, vo as templateResourceTypes, vr as readsNoEchoDeleteValues, vs as recordMaskOnlyValue, vt as displacedPhysicalIdShown, w as deferredServiceTokenWarning, wa as refuseMalformedResourceEntriesForImportSave, wc as finchSecretArgvRefusal, wi as isStalePlaceholderArnAttribute, wl as resolveAssemblyPath, wn as collectPublishedOutputNames, wo as DagBuilder, wr as customResourceResponseExpirationWarning, ws as STATE_SOURCED_BASELINE_RULES, wt as revertedNestedRowIds, xa as refuseMalformedResourceEntriesForDeploy, xc as describeDockerExecFailure, xi as keepsSecretReferenceToken, xl as describeFileReadFailure, xn as isWholeDynamicReferenceValue, xr as withPrintingSecrets, xs as recordNoEchoParameterFreshValue, xt as nestedChildStackName$1, ya as refuseMalformedResourceAttributesForOrphan, yc as resolveDockerContextDirectory, yi as carriesFetchableDynamicReference, yl as ownValue, yn as exportNameNoEchoParameters, yo as describeTypeWithThrottleRetry, yr as isCustomResourceType$1, ys as recordMaskOnlyValuesIn, yt as dropSettledNestedJournals, za as repairMalformedResourcesForReadOnly, zc as getDockerImageBySourceHash, zi as hasReadableOrphans, zn as ATOMIC_FINAL_SNAPSHOT_TYPES, zo as liveMatchesUnresolvedTokenFrame, zs as isNotImplemented, zt as destroyStackRecordsView } from "./deploy-engine-CO0EOAem.js";
6
+ import { t as getCdkdVersion } from "./version-B3Ymd4cN.js";
7
7
  import { randomBytes, randomUUID } from "node:crypto";
8
8
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
9
9
  import { GetRoleCommand, GetUserCommand } from "@aws-sdk/client-iam";
@@ -345,6 +345,10 @@ async function resolveEffectiveRegion(options) {
345
345
  source: "flag"
346
346
  };
347
347
  const awsRegion = canonicalizeRegion(process.env["AWS_REGION"]);
348
+ if (awsRegion && awsRegion === injectedAwsRegionValue()) return {
349
+ region: awsRegion,
350
+ source: "default-env"
351
+ };
348
352
  if (awsRegion) return {
349
353
  region: awsRegion,
350
354
  source: "env"
@@ -364,6 +368,10 @@ async function resolveEffectiveRegion(options) {
364
368
  source: "default"
365
369
  };
366
370
  }
371
+ function exportInferredRegionForSdk(effective) {
372
+ if (effective.source !== "default-env") return;
373
+ injectAwsRegion(effective.region);
374
+ }
367
375
  const LEGACY_DEFAULT_REGION = "us-east-1";
368
376
  async function resolveSdkDefaultRegion(profile) {
369
377
  const { STSClient } = await import("@aws-sdk/client-sts");
@@ -380,6 +388,113 @@ async function resolveSdkDefaultRegion(profile) {
380
388
  client?.destroy?.();
381
389
  }
382
390
  }
391
+ function ownedByLegacyDefault(probe) {
392
+ return { stateExists: (stackName, region) => probe.stateExistsOwnedBy(stackName, region, LEGACY_DEFAULT_REGION) };
393
+ }
394
+ async function placeStack(effective, stackName, probe) {
395
+ const [inResolved, inLegacy] = await Promise.all([probe.stateExists(stackName, effective.region), probe.stateExists(stackName, LEGACY_DEFAULT_REGION)]);
396
+ if (inResolved && inLegacy) return "both";
397
+ if (inResolved) return "resolved";
398
+ return inLegacy ? "legacy" : "none";
399
+ }
400
+ function bothRegionsMessage(effective, stackName) {
401
+ return `Stack ${quoteStackName(stackName)} has state in both ${LEGACY_DEFAULT_REGION} and ${displayIdent(effective.region)} (which ${inferredFrom(effective)} resolves). Continuing to use ${LEGACY_DEFAULT_REGION}, as a command with no region named did before. Set AWS_REGION=${displayIdent(effective.region)} to work on the ${displayIdent(effective.region)} one, or AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`;
402
+ }
403
+ function inferredFrom(effective) {
404
+ return effective.source === "default-env" ? "AWS_DEFAULT_REGION" : "your AWS profile";
405
+ }
406
+ function holdMessage(effective, stackName) {
407
+ return `Stack ${quoteStackName(stackName)} has existing state in ${LEGACY_DEFAULT_REGION}, but ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing stack is not duplicated. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message, or AWS_REGION=${displayIdent(effective.region)} to work in ${displayIdent(effective.region)} instead (where this stack has no state).`;
408
+ }
409
+ function quoteStackName(stackName) {
410
+ return displayIdent(stackName) === stackName ? `'${stackName}'` : "a stack whose name is not a plain identifier";
411
+ }
412
+ function stackRegionResolver(input) {
413
+ const { effective, logger } = input;
414
+ const probe = ownedByLegacyDefault(input.probe);
415
+ const placements = /* @__PURE__ */ new Map();
416
+ const place = (stackName) => {
417
+ let placement = placements.get(stackName);
418
+ if (placement === void 0) {
419
+ placement = placeStack(effective, stackName, probe);
420
+ placement.catch(() => placements.delete(stackName));
421
+ placements.set(stackName, placement);
422
+ }
423
+ return placement;
424
+ };
425
+ const answers = /* @__PURE__ */ new Map();
426
+ const answer = async (stackName) => {
427
+ const placement = await place(stackName);
428
+ if (placement === "legacy" || placement === "both") {
429
+ logger.info(placement === "both" ? bothRegionsMessage(effective, stackName) : holdMessage(effective, stackName));
430
+ return LEGACY_DEFAULT_REGION;
431
+ }
432
+ if (placement === "resolved") return effective.region;
433
+ const others = (input.siblings ?? []).filter((name) => name !== stackName);
434
+ const siblingPlacements = await Promise.all(others.map(place));
435
+ if (siblingPlacements.some((p) => p === "legacy" || p === "both") && !siblingPlacements.includes("resolved")) {
436
+ logger.info(`Stack ${quoteStackName(stackName)} has no state yet, and the other stacks of this app that have state all stay in ${LEGACY_DEFAULT_REGION}, while ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Using ${LEGACY_DEFAULT_REGION} for it too, so the app stays in one region. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`);
437
+ return LEGACY_DEFAULT_REGION;
438
+ }
439
+ return effective.region;
440
+ };
441
+ return (stackName, pinned) => {
442
+ if (pinned) return Promise.resolve(pinned);
443
+ if (!regionNeedsReconciliation(effective)) return Promise.resolve(effective.region);
444
+ let result = answers.get(stackName);
445
+ if (result === void 0) {
446
+ result = answer(stackName);
447
+ result.catch(() => answers.delete(stackName));
448
+ answers.set(stackName, result);
449
+ }
450
+ return result;
451
+ };
452
+ }
453
+ function stateWithRegion(state, region) {
454
+ return state.region ? state : {
455
+ ...state,
456
+ region
457
+ };
458
+ }
459
+ function legacyStateBucketFallbackRegion(effective) {
460
+ return regionNeedsReconciliation(effective) ? LEGACY_DEFAULT_REGION : void 0;
461
+ }
462
+ async function reconcileExportIndexRegion(input) {
463
+ const { effective, probe, statePrefix, logger } = input;
464
+ if (!regionNeedsReconciliation(effective)) return effective.region;
465
+ const indexKey = (region) => `${statePrefix}/_index/${region}/exports.json`;
466
+ try {
467
+ if (!await probe.rawObjectExists(indexKey("us-east-1"))) return effective.region;
468
+ } catch (error) {
469
+ logger.warn(safeMsg`[region] could not probe the exports index (${error.name ?? "error"}); using ${effective.region}.`);
470
+ return effective.region;
471
+ }
472
+ logger.debug(safeMsg`[region] exports index exists in ${LEGACY_DEFAULT_REGION}; using it rather than ${effective.region} (inferred).`);
473
+ return LEGACY_DEFAULT_REGION;
474
+ }
475
+ function withOtherIndexRemoval(runStore, input) {
476
+ const { effective, runIndexRegion, statePrefix, probe, createStore, logger } = input;
477
+ const other = runIndexRegion === "us-east-1" ? effective.region : LEGACY_DEFAULT_REGION;
478
+ if (!regionNeedsReconciliation(effective) || other === runIndexRegion) return runStore;
479
+ let otherStore;
480
+ const removeFromOther = async (stackName, region) => {
481
+ try {
482
+ otherStore ??= probe.rawObjectExists(`${statePrefix}/_index/${other}/exports.json`).then((exists) => exists ? createStore(other) : void 0);
483
+ await (await otherStore)?.removeStackIfPresent(stackName, region);
484
+ } catch (error) {
485
+ otherStore = void 0;
486
+ logger.warn(safeMsg`Could not remove ${stackName}'s entries from the ${other} exports index (${error.name ?? "error"}); a later Fn::ImportValue may read a stale value from it.`);
487
+ }
488
+ };
489
+ return new Proxy(runStore, { get(target, prop, receiver) {
490
+ if (prop === "removeStack") return async (stackName, region) => {
491
+ await target.removeStack(stackName, region);
492
+ await removeFromOther(stackName, region);
493
+ };
494
+ const value = Reflect.get(target, prop, receiver);
495
+ return typeof value === "function" ? value.bind(target) : value;
496
+ } });
497
+ }
383
498
  async function reconcileMarkerRegionWithLegacyDefault(input) {
384
499
  const { effective, probe, markerKeyFor, logger } = input;
385
500
  if (!regionNeedsReconciliation(effective)) return effective.region;
@@ -926,7 +1041,7 @@ async function bootstrapCommand(options) {
926
1041
  }
927
1042
  }
928
1043
  function createBootstrapCommand() {
929
- const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead.").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION env, else us-east-1)")).action(withErrorHandling(async (options) => {
1044
+ const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead.").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION, AWS_DEFAULT_REGION, the profile's region, else us-east-1; an inferred region keeps existing us-east-1 asset storage)")).action(withErrorHandling(async (options) => {
930
1045
  if (options.destroy) {
931
1046
  if (options.assetBucket !== void 0 || options.containerRepo !== void 0) throw new CdkdError("--asset-bucket / --container-repo cannot be combined with --destroy. The teardown reads the region's asset storage names from the bootstrap marker.", "INVALID_OPTIONS");
932
1047
  if (!options.assets) throw new CdkdError("--no-assets cannot be combined with --destroy. The teardown scope is the asset storage itself; use --include-state-bucket to also delete the state bucket.", "INVALID_OPTIONS");
@@ -2110,6 +2225,14 @@ var ExportIndexStore = class {
2110
2225
  async removeStack(stackName, producerRegion) {
2111
2226
  await this.enqueueWrite("remove", () => this.applyRemoveStack(stackName, producerRegion));
2112
2227
  }
2228
+ async removeStackIfPresent(stackName, producerRegion) {
2229
+ await this.enqueueWrite("remove-if-present", async () => {
2230
+ if (this.loadState.kind !== "loaded") {
2231
+ if ((await this.loadPersisted()).kind !== "loaded") return true;
2232
+ }
2233
+ return this.applyRemoveStack(stackName, producerRegion);
2234
+ });
2235
+ }
2113
2236
  async enqueueWrite(label, op) {
2114
2237
  const next = this.writeChain.then(() => this.runWithRetry(label, op));
2115
2238
  this.writeChain = next.then(() => {}, () => {});
@@ -2438,7 +2561,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
2438
2561
  //#region src/provisioning/register-providers.ts
2439
2562
  let providerClasses;
2440
2563
  function loadProviderClasses() {
2441
- providerClasses ??= import("./provider-classes-BRNQRRLh.js");
2564
+ providerClasses ??= import("./provider-classes-BEIwSimv.js");
2442
2565
  return providerClasses;
2443
2566
  }
2444
2567
  function registerAllProviders(registry, classes) {
@@ -2950,7 +3073,7 @@ async function deployCommand(stacks, options) {
2950
3073
  applyWaitFlagEnv(options);
2951
3074
  const requireApproval = resolveRequireApproval(options.requireApproval);
2952
3075
  const approveDeployment = requireApproval !== "never" && !options.dryRun ? createApprovalPrompter({ yes: options.yes ?? false }) : void 0;
2953
- const rawBaseRegion = rawCliRegion(options.region) ?? "us-east-1";
3076
+ const rawNamedRegion = rawCliRegion(options.region);
2954
3077
  foldRegionOption(options);
2955
3078
  await applyRoleArnIfSet({
2956
3079
  roleArn: options.roleArn,
@@ -2963,7 +3086,9 @@ async function deployCommand(stacks, options) {
2963
3086
  const app = resolveApp(options.app);
2964
3087
  if (!app) throw new Error("No app command specified. Use --app, set CDKD_APP env var, or add \"app\" to cdk.json");
2965
3088
  options.app = app;
2966
- const region = namedCliRegion(options.region) ?? "us-east-1";
3089
+ const effectiveRegion = await resolveEffectiveRegion(options);
3090
+ exportInferredRegionForSdk(effectiveRegion);
3091
+ const region = effectiveRegion.region;
2967
3092
  logger.debug("Starting deployment...");
2968
3093
  logger.debug("Options:", options);
2969
3094
  if (options.region) {
@@ -2971,12 +3096,12 @@ async function deployCommand(stacks, options) {
2971
3096
  process.env["AWS_DEFAULT_REGION"] = options.region;
2972
3097
  }
2973
3098
  const awsClients = new AwsClients({
2974
- ...options.region && { region: options.region },
3099
+ region: effectiveRegion.region,
2975
3100
  ...options.profile && { profile: options.profile }
2976
3101
  });
2977
3102
  setAwsClients(awsClients);
2978
3103
  const statePrepPromise = (async () => {
2979
- const resolvedStateBucket = await resolveStateBucketWithDefaultAndSource(options.stateBucket, region);
3104
+ const resolvedStateBucket = await resolveStateBucketWithDefaultAndSource(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
2980
3105
  const stateBucket = resolvedStateBucket.bucket;
2981
3106
  const preflightStateBackend = new S3StateBackend(awsClients.s3, {
2982
3107
  bucket: stateBucket,
@@ -2986,10 +3111,24 @@ async function deployCommand(stacks, options) {
2986
3111
  ...options.profile && { profile: options.profile }
2987
3112
  });
2988
3113
  await preflightStateBackend.verifyBucketExists({ existenceAlreadyProbed: stateBucketExistenceConfirmed(resolvedStateBucket) });
3114
+ const runIndexRegion = await reconcileExportIndexRegion({
3115
+ effective: effectiveRegion,
3116
+ probe: preflightStateBackend,
3117
+ statePrefix: options.statePrefix,
3118
+ logger
3119
+ });
3120
+ const newIndexStore = (indexRegion) => new ExportIndexStore(awsClients.s3, stateBucket, options.statePrefix, indexRegion, preflightStateBackend, { profile: options.profile });
2989
3121
  return {
2990
3122
  stateBucket,
2991
3123
  preflightStateBackend,
2992
- exportIndexStore: new ExportIndexStore(awsClients.s3, stateBucket, options.statePrefix, region, preflightStateBackend, { profile: options.profile })
3124
+ exportIndexStore: withOtherIndexRemoval(newIndexStore(runIndexRegion), {
3125
+ effective: effectiveRegion,
3126
+ runIndexRegion,
3127
+ statePrefix: options.statePrefix,
3128
+ probe: preflightStateBackend,
3129
+ createStore: newIndexStore,
3130
+ logger
3131
+ })
2993
3132
  };
2994
3133
  })();
2995
3134
  let deployInterrupted = false;
@@ -3095,17 +3234,24 @@ Force-quit: stack locks may not be released. If the next run reports a lock, run
3095
3234
  if (roleArnReferences.length > 0) {
3096
3235
  const stackByName = new Map(allStacks.map((s) => [s.stackName, s]));
3097
3236
  refuseUnreadableCdkCrossAccountRefs(roleArnReferences, new Set(targetStacks.map((s) => s.stackName)), (name) => ({
3098
- region: stackByName.get(name)?.region ?? namedCliRegion(options.region),
3237
+ region: stackByName.get(name)?.region ?? (regionNeedsReconciliation(effectiveRegion) ? void 0 : namedCliRegion(options.region)),
3099
3238
  account: stackByName.get(name)?.account
3100
3239
  }), producerLookup);
3101
3240
  }
3102
- const baseRegion = namedCliRegion(options.region) ?? "us-east-1";
3241
+ const baseRegion = region;
3242
+ const regionForStack = stackRegionResolver({
3243
+ effective: effectiveRegion,
3244
+ probe: preflightStateBackend,
3245
+ logger,
3246
+ siblings: allStacks.filter((s) => !s.region).map((s) => s.stackName)
3247
+ });
3248
+ const stackRegions = new Map(await Promise.all(targetStacks.map(async (s) => [s.stackName, await regionForStack(s.stackName, s.region)])));
3103
3249
  const crossPrefixGuard = new CrossPrefixGuard(preflightStateBackend, { readOnly: options.dryRun === true });
3104
3250
  await synthesizer.expandMacrosForStacks(targetStacks, synthOptions);
3105
3251
  const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
3106
3252
  const stsClient = new STSClient({
3107
3253
  ...awsClientDefaults(),
3108
- region: namedCliRegion(options.region) ?? "us-east-1"
3254
+ region
3109
3255
  });
3110
3256
  const accountId = (await stsClient.send(new GetCallerIdentityCommand({}))).Account;
3111
3257
  stsClient.destroy();
@@ -3137,10 +3283,10 @@ Force-quit: stack locks may not be released. If the next run reports a lock, run
3137
3283
  const stackNodeId = `stack:${stack.stackName}`;
3138
3284
  const stackDeps = /* @__PURE__ */ new Set();
3139
3285
  if (stack.assetManifestPath) {
3140
- const assetRegion = stack.region || baseRegion;
3286
+ const assetRegion = stackRegions.get(stack.stackName) ?? deployStackRegion(stack, baseRegion);
3141
3287
  const manifest = loadPublishableAssetManifest(stack.assetManifestPath);
3142
3288
  if (manifest) {
3143
- const assetMode = await assetModeResolver.resolve(stack.region || rawBaseRegion);
3289
+ const assetMode = await assetModeResolver.resolve(stack.region || rawNamedRegion || assetRegion);
3144
3290
  logger.debug(`Asset mode for region ${assetRegion}: ${assetMode.mode} (stack ${stack.stackName})`);
3145
3291
  let redirect;
3146
3292
  if (assetMode.mode === "cdkd-assets") {
@@ -3184,7 +3330,7 @@ Force-quit: stack locks may not be released. If the next run reports a lock, run
3184
3330
  };
3185
3331
  const runStackInner = async (stackInfo) => {
3186
3332
  if (deployInterrupted) throw new DeployCancelledError(`Deploy interrupted before stack '${stackInfo.stackName}' started — not starting it.`);
3187
- const stackRegion = deployStackRegion(stackInfo, baseRegion);
3333
+ const stackRegion = stackRegions.get(stackInfo.stackName) ?? deployStackRegion(stackInfo, baseRegion);
3188
3334
  logger.info(`\n${cyan("Deploying stack:")} ${bold(cyan(stackInfo.stackName))}${stackRegion !== baseRegion ? gray(` (region: ${stackRegion})`) : ""}`);
3189
3335
  const stackAwsClients = new AwsClients({
3190
3336
  region: stackRegion,
@@ -5772,12 +5918,14 @@ async function diffCommand(stacks, options) {
5772
5918
  const app = resolveApp(options.app);
5773
5919
  if (!app) throw new Error("No app command specified. Use --app, set CDKD_APP env var, or add \"app\" to cdk.json");
5774
5920
  options.app = app;
5775
- const region = namedCliRegion(options.region) ?? "us-east-1";
5776
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
5921
+ const effectiveRegion = await resolveEffectiveRegion(options);
5922
+ exportInferredRegionForSdk(effectiveRegion);
5923
+ const region = effectiveRegion.region;
5924
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
5777
5925
  logger.info("Calculating diff...");
5778
5926
  logger.debug("Options:", options);
5779
5927
  const awsClients = new AwsClients({
5780
- ...options.region && { region: options.region },
5928
+ region: effectiveRegion.region,
5781
5929
  ...options.profile && { profile: options.profile }
5782
5930
  });
5783
5931
  setAwsClients(awsClients);
@@ -5819,6 +5967,12 @@ async function diffCommand(stacks, options) {
5819
5967
  region,
5820
5968
  ...options.profile && { profile: options.profile }
5821
5969
  });
5970
+ const regionForStack = stackRegionResolver({
5971
+ effective: effectiveRegion,
5972
+ probe: stateBackend,
5973
+ logger,
5974
+ siblings: allStacks.filter((s) => !s.region).map((s) => s.stackName)
5975
+ });
5822
5976
  const diffCalculator = new DiffCalculator();
5823
5977
  const refusalRecovery = {
5824
5978
  profile: options.profile,
@@ -5897,7 +6051,7 @@ async function diffCommand(stacks, options) {
5897
6051
  const producerLookup = producerLookupOver(allStacks);
5898
6052
  for (const stackInfo of targetStacks) {
5899
6053
  logger.info(`\nCalculating diff for stack: ${stackInfo.stackName}`);
5900
- const stackRegion = stackInfo.region || region;
6054
+ const stackRegion = await regionForStack(stackInfo.stackName, stackInfo.region);
5901
6055
  const assetRedirect = await resolveAssetRedirect(stackInfo.assetManifestPath, stackRegion);
5902
6056
  if (assetRedirect) {
5903
6057
  const rewritten = rewriteTemplateAssetReferences(stackInfo.template, assetRedirect);
@@ -6346,10 +6500,12 @@ async function scrubCommand(stacks, options) {
6346
6500
  });
6347
6501
  const app = resolveApp(options.app);
6348
6502
  if (!app) throw new Error("CDK app is required (scrub needs the template to identify secret references). Pass --app, set CDKD_APP, or add \"app\" to cdk.json.");
6349
- const region = namedCliRegion(options.region) ?? "us-east-1";
6350
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
6503
+ const effectiveRegion = await resolveEffectiveRegion(options);
6504
+ exportInferredRegionForSdk(effectiveRegion);
6505
+ const region = effectiveRegion.region;
6506
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
6351
6507
  const awsClients = new AwsClients({
6352
- ...options.region && { region: options.region },
6508
+ region: effectiveRegion.region,
6353
6509
  ...options.profile && { profile: options.profile }
6354
6510
  });
6355
6511
  setAwsClients(awsClients);
@@ -6453,9 +6609,16 @@ async function scrubCommand(stacks, options) {
6453
6609
  const indexUnwritten = [];
6454
6610
  const indexUnreadable = [];
6455
6611
  const indexRegionsWritten = /* @__PURE__ */ new Set();
6612
+ const regionForStack = stackRegionResolver({
6613
+ effective: effectiveRegion,
6614
+ probe: stateBackend,
6615
+ logger,
6616
+ siblings: allStacks.filter((s) => !s.region).map((s) => s.stackName)
6617
+ });
6618
+ const stackRegions = new Map(await Promise.all(targetStacks.map(async (stack) => [stack.stackName, await regionForStack(stack.stackName, stack.region)])));
6456
6619
  const work = targetStacks.map((stack) => ({
6457
6620
  stackName: stack.stackName,
6458
- region: stack.region || region,
6621
+ region: stackRegions.get(stack.stackName) ?? region,
6459
6622
  load: () => {
6460
6623
  const defect = stack.nestedTemplates ? findNestedTemplateTreeDefect(stack.nestedTemplates) : void 0;
6461
6624
  if (defect) throw new ScrubRefusalError(renderNestedTemplateTreeDefect(defect, stack.stackName, "scrub it or any stack nested under it; no state was written"), "SCRUB_NESTED_TEMPLATE_TREE_MALFORMED");
@@ -9073,15 +9236,17 @@ async function driftCommand(stacks, options) {
9073
9236
  roleArn: options.roleArn,
9074
9237
  region: options.region
9075
9238
  });
9239
+ const effectiveRegion = await resolveEffectiveRegion(options);
9240
+ exportInferredRegionForSdk(effectiveRegion);
9076
9241
  const awsClients = new AwsClients({
9077
- ...options.region && { region: options.region },
9242
+ region: effectiveRegion.region,
9078
9243
  ...options.profile && { profile: options.profile }
9079
9244
  });
9080
9245
  setAwsClients(awsClients);
9081
9246
  const stackRegionScopes = /* @__PURE__ */ new Map();
9082
9247
  try {
9083
- const region = namedCliRegion(options.region) ?? "us-east-1";
9084
- const bucket = await resolveStateBucketWithDefault(options.stateBucket, region);
9248
+ const region = effectiveRegion.region;
9249
+ const bucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
9085
9250
  const prefix = options.statePrefix;
9086
9251
  const stateConfig = {
9087
9252
  bucket,
@@ -12098,8 +12263,10 @@ async function destroyCommand(stackArgs, options) {
12098
12263
  roleArn: options.roleArn,
12099
12264
  region: options.region
12100
12265
  });
12101
- const region = namedCliRegion(options.region) ?? "us-east-1";
12102
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
12266
+ const effectiveRegion = await resolveEffectiveRegion(options);
12267
+ exportInferredRegionForSdk(effectiveRegion);
12268
+ const region = effectiveRegion.region;
12269
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
12103
12270
  const accountRecovery = {
12104
12271
  profile: options.profile,
12105
12272
  stateBucket,
@@ -12116,7 +12283,7 @@ async function destroyCommand(stackArgs, options) {
12116
12283
  process.env["AWS_DEFAULT_REGION"] = options.region;
12117
12284
  }
12118
12285
  const awsClients = new AwsClients({
12119
- ...options.region && { region: options.region },
12286
+ region: effectiveRegion.region,
12120
12287
  ...options.profile && { profile: options.profile }
12121
12288
  });
12122
12289
  setAwsClients(awsClients);
@@ -12143,7 +12310,26 @@ async function destroyCommand(stackArgs, options) {
12143
12310
  stateBackendForCleanup = stateBackend;
12144
12311
  await stateBackend.verifyBucketExists();
12145
12312
  const lockManager = new LockManager(awsClients.s3, stateConfig);
12146
- const exportIndexStore = new ExportIndexStore(awsClients.s3, stateBucket, options.statePrefix, region, stateBackend, { profile: options.profile });
12313
+ const runIndexRegion = await reconcileExportIndexRegion({
12314
+ effective: effectiveRegion,
12315
+ probe: stateBackend,
12316
+ statePrefix: options.statePrefix,
12317
+ logger
12318
+ });
12319
+ const newIndexStore = (indexRegion) => new ExportIndexStore(awsClients.s3, stateBucket, options.statePrefix, indexRegion, stateBackend, { profile: options.profile });
12320
+ const exportIndexStore = withOtherIndexRemoval(newIndexStore(runIndexRegion), {
12321
+ effective: effectiveRegion,
12322
+ runIndexRegion,
12323
+ statePrefix: options.statePrefix,
12324
+ probe: stateBackend,
12325
+ createStore: newIndexStore,
12326
+ logger
12327
+ });
12328
+ const regionForStack = stackRegionResolver({
12329
+ effective: effectiveRegion,
12330
+ probe: stateBackend,
12331
+ logger
12332
+ });
12147
12333
  const providerRegistry = new ProviderRegistry();
12148
12334
  registerAllProviders(providerRegistry, providerClasses);
12149
12335
  providerRegistry.setCustomResourceResponseBucket(stateBucket);
@@ -12257,7 +12443,7 @@ async function destroyCommand(stackArgs, options) {
12257
12443
  if (pattern.includes("*") || pattern.includes("?") || pattern.includes("/")) continue;
12258
12444
  if (!allStateNamesSet.has(pattern)) continue;
12259
12445
  if (namesAppStack.has(pattern)) continue;
12260
- const refRegion = allStateRefs.find((r) => r.stackName === pattern)?.region ?? region;
12446
+ const refRegion = allStateRefs.find((r) => r.stackName === pattern)?.region ?? await regionForStack(pattern);
12261
12447
  const stateOnlyResult = await stateBackend.getState(pattern, refRegion);
12262
12448
  if (stateOnlyResult?.state.parentStack) {
12263
12449
  const err = new NestedStackChildDirectDestroyError(pattern, stateOnlyResult.state.parentStack, stateOnlyResult.state.parentLogicalId, void 0, stateCommandAccount);
@@ -12286,10 +12472,12 @@ async function destroyCommand(stackArgs, options) {
12286
12472
  }
12287
12473
  const crossPrefixCheck = { cache: new CrossPrefixGuard(stateBackend) };
12288
12474
  if (stackNames.length > 1) deferRegistryTail = (released) => deferredTails.push(released);
12475
+ const fallbackRegionByName = /* @__PURE__ */ new Map();
12476
+ for (const name of stackNames) if ((stateRefsByName.get(name) ?? []).some((r) => !r.region)) fallbackRegionByName.set(name, await regionForStack(name));
12289
12477
  for (const name of stackNames) {
12290
12478
  const synth = appStacks.find((s) => s.stackName === name);
12291
12479
  if (synth?.terminationProtection === true && !options.removeProtection) continue;
12292
- const planned = plannedDestroyRegion(stateRefsByName.get(name) ?? [], synth?.region, region);
12480
+ const planned = plannedDestroyRegion(stateRefsByName.get(name) ?? [], synth?.region, fallbackRegionByName.get(name) ?? region);
12293
12481
  if (planned !== void 0) crossPrefixCheck.cache.full(name, planned, "prestart");
12294
12482
  }
12295
12483
  for (const [stackIndex, stackName] of stackNames.entries()) {
@@ -12309,7 +12497,7 @@ async function destroyCommand(stackArgs, options) {
12309
12497
  continue;
12310
12498
  }
12311
12499
  }
12312
- const plannedRegion = plannedDestroyRegion(refs, synthRegion, region);
12500
+ const plannedRegion = plannedDestroyRegion(refs, synthRegion, fallbackRegionByName.get(stackName) ?? region);
12313
12501
  let stackTargetRegion;
12314
12502
  if (refs.length === 0) {
12315
12503
  logger.warn(`No state found for stack ${displaySafe(stackName)}, skipping`);
@@ -12377,7 +12565,7 @@ async function destroyCommand(stackArgs, options) {
12377
12565
  ...options.resourceWarnAfter?.perTypeMs && { resourceWarnAfterByType: options.resourceWarnAfter.perTypeMs },
12378
12566
  ...options.resourceTimeout?.perTypeMs && { resourceTimeoutByType: options.resourceTimeout.perTypeMs }
12379
12567
  }
12380
- }, () => runDestroyForStack(stackName, stateResult.state, {
12568
+ }, () => runDestroyForStack(stackName, stateWithRegion(stateResult.state, stackTargetRegion), {
12381
12569
  stateBackend,
12382
12570
  lockManager,
12383
12571
  providerRegistry,
@@ -13150,14 +13338,16 @@ async function orphanCommand(pathArgs, options) {
13150
13338
  });
13151
13339
  if (pathArgs.length === 0) throw new Error("'cdkd orphan' requires at least one construct path, e.g. 'cdkd orphan MyStack/MyTable'.\n To remove a stack's state record (the previous behavior), use:\n cdkd state orphan MyStack");
13152
13340
  for (const p of pathArgs) if (!p.includes("/")) throw new Error(`'cdkd orphan' now expects a construct path like 'MyStack/MyTable'.\n Got: '${p}'\n To remove a stack's state record (the previous behavior), use:\n cdkd state orphan ${p}`);
13153
- const region = namedCliRegion(options.region) ?? "us-east-1";
13154
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
13341
+ const effectiveRegion = await resolveEffectiveRegion(options);
13342
+ exportInferredRegionForSdk(effectiveRegion);
13343
+ const region = effectiveRegion.region;
13344
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
13155
13345
  if (options.region) {
13156
13346
  process.env["AWS_REGION"] = options.region;
13157
13347
  process.env["AWS_DEFAULT_REGION"] = options.region;
13158
13348
  }
13159
13349
  const awsClients = new AwsClients({
13160
- ...options.region && { region: options.region },
13350
+ region: effectiveRegion.region,
13161
13351
  ...options.profile && { profile: options.profile }
13162
13352
  });
13163
13353
  setAwsClients(awsClients);
@@ -13369,7 +13559,9 @@ async function stateMigrateCommand(options) {
13369
13559
  roleArn: options.roleArn,
13370
13560
  region: options.region
13371
13561
  });
13372
- const region = namedCliRegion(options.region) ?? "us-east-1";
13562
+ const effectiveRegion = await resolveEffectiveRegion(options);
13563
+ exportInferredRegionForSdk(effectiveRegion);
13564
+ const region = effectiveRegion.region;
13373
13565
  const awsClients = new AwsClients({
13374
13566
  region,
13375
13567
  ...options.profile && { profile: options.profile }
@@ -13378,26 +13570,39 @@ async function stateMigrateCommand(options) {
13378
13570
  try {
13379
13571
  const accountId = (await awsClients.sts.send(new GetCallerIdentityCommand({}))).Account;
13380
13572
  if (!accountId) throw new Error("STS GetCallerIdentity returned no Account id.");
13381
- const legacyBucket = options.legacyBucket ?? getLegacyStateBucketName(accountId, region);
13382
13573
  const newBucket = options.newBucket ?? getDefaultStateBucketName(accountId);
13383
- if (legacyBucket === newBucket) {
13384
- logger.warn(`Source and destination resolve to the same bucket (${legacyBucket}); nothing to do.`);
13385
- return;
13386
- }
13387
- logger.info("Migrating state bucket:");
13388
- logger.info(` source: ${legacyBucket} (resolved for --region ${region})`);
13389
- logger.info(` destination: ${newBucket}`);
13390
13574
  const probeRegion = "us-east-1";
13391
13575
  const probe = new S3Client({
13392
13576
  ...ambientClientDefaults(),
13393
13577
  region: probeRegion
13394
13578
  });
13579
+ let legacyBucket;
13580
+ let sourceRegionLabel = region;
13395
13581
  let sourceExists;
13396
13582
  try {
13397
- sourceExists = await bucketExists(probe, legacyBucket);
13583
+ legacyBucket = options.legacyBucket ?? getLegacyStateBucketName(accountId, region);
13584
+ const sourceProbe = await probeBucket(probe, legacyBucket);
13585
+ sourceExists = sourceProbe !== "missing";
13586
+ const fallbackRegion = legacyStateBucketFallbackRegion(effectiveRegion);
13587
+ if (options.legacyBucket === void 0 && fallbackRegion !== void 0) {
13588
+ const fallbackBucket = getLegacyStateBucketName(accountId, fallbackRegion);
13589
+ const fallbackProbe = fallbackBucket === newBucket ? "missing" : await probeBucket(probe, fallbackBucket);
13590
+ if (fallbackProbe !== "missing" && (!sourceExists || !(sourceProbe === "ok" && fallbackProbe === "access-denied") && await bucketHasState(probe, fallbackBucket))) {
13591
+ legacyBucket = fallbackBucket;
13592
+ sourceRegionLabel = fallbackRegion;
13593
+ sourceExists = true;
13594
+ }
13595
+ }
13398
13596
  } finally {
13399
13597
  probe.destroy();
13400
13598
  }
13599
+ if (legacyBucket === newBucket) {
13600
+ logger.warn(`Source and destination resolve to the same bucket (${legacyBucket}); nothing to do.`);
13601
+ return;
13602
+ }
13603
+ logger.info("Migrating state bucket:");
13604
+ logger.info(` source: ${legacyBucket} (resolved for --region ${sourceRegionLabel})`);
13605
+ logger.info(` destination: ${newBucket}`);
13401
13606
  if (!sourceExists) throw new Error(`Source bucket '${legacyBucket}' does not exist. Nothing to migrate. (Tip: run \`cdkd state info\` to confirm which bucket cdkd is reading from.)`);
13402
13607
  const legacyRegion = await resolveBucketRegion(legacyBucket);
13403
13608
  logger.info(` source bucket actual region: ${legacyRegion}`);
@@ -13464,20 +13669,37 @@ async function stateMigrateCommand(options) {
13464
13669
  }
13465
13670
  }
13466
13671
  async function bucketExists(s3, bucketName) {
13672
+ return await probeBucket(s3, bucketName) !== "missing";
13673
+ }
13674
+ async function probeBucket(s3, bucketName) {
13467
13675
  try {
13468
13676
  await s3.send(new HeadBucketCommand({
13469
13677
  Bucket: bucketName,
13470
13678
  ...await expectedOwnerParam(s3)
13471
13679
  }));
13472
- return true;
13680
+ return "ok";
13473
13681
  } catch (error) {
13474
13682
  const err = error;
13475
13683
  const status = err.$metadata?.httpStatusCode;
13476
- if (err.name === "NotFound" || err.name === "NoSuchBucket" || status === 404) return false;
13477
- if (status === 301 || status === 403) return true;
13684
+ if (err.name === "NotFound" || err.name === "NoSuchBucket" || status === 404) return "missing";
13685
+ if (status === 301) return "ok";
13686
+ if (status === 403) return "access-denied";
13478
13687
  throw error;
13479
13688
  }
13480
13689
  }
13690
+ async function bucketHasState(s3, bucket) {
13691
+ try {
13692
+ const resp = await s3.send(new ListObjectsV2Command({
13693
+ EncodingType: "url",
13694
+ Bucket: bucket,
13695
+ MaxKeys: 1,
13696
+ ...await expectedOwnerParam(s3)
13697
+ }));
13698
+ return (resp.KeyCount ?? resp.Contents?.length ?? 0) > 0;
13699
+ } catch {
13700
+ return true;
13701
+ }
13702
+ }
13481
13703
  async function listAllObjects(s3, bucket) {
13482
13704
  const all = [];
13483
13705
  let continuationToken;
@@ -13596,7 +13818,7 @@ async function confirmPrompt$3(prompt) {
13596
13818
  return confirmOrRefuse(prompt, { refusal: "The cdkd state migrate confirmation prompt cannot run in a non-interactive environment. Pass -y / --yes to confirm the migration, or run the command from a real terminal." });
13597
13819
  }
13598
13820
  function createStateMigrateCommand() {
13599
- const cmd = new Command("migrate").description("Migrate state from the legacy region-suffixed bucket (cdkd-state-{account}-{region}) to the new region-free default (cdkd-state-{account}). Source bucket is kept by default; pass --remove-legacy to delete it after a successful migration.").option("--region <region>", "Region of the legacy bucket to migrate. Defaults to AWS_REGION or us-east-1. Run once per region for multi-region setups.").option("--legacy-bucket <name>", "Override the legacy (source) bucket name (default: derived from STS account + --region).").option("--new-bucket <name>", "Override the new (destination) bucket name (default: cdkd-state-{accountId}).").option("--dry-run", "Show planned actions without making changes", false).option("--remove-legacy", "Delete the source bucket after successful migration. Default: keep it.", false).action(withErrorHandling(stateMigrateCommand));
13821
+ const cmd = new Command("migrate").description("Migrate state from the legacy region-suffixed bucket (cdkd-state-{account}-{region}) to the new region-free default (cdkd-state-{account}). Source bucket is kept by default; pass --remove-legacy to delete it after a successful migration.").option("--region <region>", "Region of the legacy bucket to migrate. Defaults to AWS_REGION, AWS_DEFAULT_REGION, then the profile's region (the us-east-1 legacy bucket instead when that region has none, or when the us-east-1 one holds state), else us-east-1. Run once per region for multi-region setups.").option("--legacy-bucket <name>", "Override the legacy (source) bucket name (default: derived from STS account + --region).").option("--new-bucket <name>", "Override the new (destination) bucket name (default: cdkd-state-{accountId}).").option("--dry-run", "Show planned actions without making changes", false).option("--remove-legacy", "Delete the source bucket after successful migration. Default: keep it.", false).action(withErrorHandling(stateMigrateCommand));
13600
13822
  commonOptions.forEach((o) => cmd.addOption(o));
13601
13823
  return cmd;
13602
13824
  }
@@ -14330,14 +14552,16 @@ async function exportCommand(stackArg, options) {
14330
14552
  roleArn: options.roleArn,
14331
14553
  region: options.region
14332
14554
  });
14333
- const region = namedCliRegion(options.region) ?? "us-east-1";
14334
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
14555
+ const effectiveRegion = await resolveEffectiveRegion(options);
14556
+ exportInferredRegionForSdk(effectiveRegion);
14557
+ const region = effectiveRegion.region;
14558
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
14335
14559
  if (options.region) {
14336
14560
  process.env["AWS_REGION"] = options.region;
14337
14561
  process.env["AWS_DEFAULT_REGION"] = options.region;
14338
14562
  }
14339
14563
  const awsClients = new AwsClients({
14340
- ...options.region && { region: options.region },
14564
+ region: effectiveRegion.region,
14341
14565
  ...options.profile && { profile: options.profile }
14342
14566
  });
14343
14567
  setAwsClients(awsClients);
@@ -17054,13 +17278,15 @@ async function setupStateBackend(options) {
17054
17278
  roleArn: options.roleArn,
17055
17279
  region: options.region
17056
17280
  });
17281
+ const effectiveRegion = await resolveEffectiveRegion(options);
17282
+ exportInferredRegionForSdk(effectiveRegion);
17057
17283
  const awsClients = new AwsClients({
17058
- ...options.region && { region: options.region },
17284
+ region: effectiveRegion.region,
17059
17285
  ...options.profile && { profile: options.profile }
17060
17286
  });
17061
17287
  setAwsClients(awsClients);
17062
- const region = namedCliRegion(options.region) ?? "us-east-1";
17063
- const bucket = await resolveStateBucketWithDefault(options.stateBucket, region);
17288
+ const region = effectiveRegion.region;
17289
+ const bucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
17064
17290
  const prefix = options.statePrefix;
17065
17291
  const stateConfig = {
17066
17292
  bucket,
@@ -17072,14 +17298,34 @@ async function setupStateBackend(options) {
17072
17298
  });
17073
17299
  const lockManager = new LockManager(awsClients.s3, stateConfig);
17074
17300
  await stateBackend.verifyBucketExists();
17301
+ const runIndexRegion = await reconcileExportIndexRegion({
17302
+ effective: effectiveRegion,
17303
+ probe: stateBackend,
17304
+ statePrefix: prefix,
17305
+ logger: getLogger()
17306
+ });
17307
+ const newIndexStore = (indexRegion) => new ExportIndexStore(awsClients.s3, stateConfig.bucket, stateConfig.prefix, indexRegion, stateBackend, { profile: options.profile });
17308
+ const exportIndexStore = withOtherIndexRemoval(newIndexStore(runIndexRegion), {
17309
+ effective: effectiveRegion,
17310
+ runIndexRegion,
17311
+ statePrefix: prefix,
17312
+ probe: stateBackend,
17313
+ createStore: newIndexStore,
17314
+ logger: getLogger()
17315
+ });
17075
17316
  return {
17076
17317
  stateBackend,
17077
17318
  lockManager,
17078
17319
  awsClients,
17079
17320
  region,
17321
+ regionFor: stackRegionResolver({
17322
+ effective: effectiveRegion,
17323
+ probe: stateBackend,
17324
+ logger: getLogger()
17325
+ }),
17080
17326
  bucket,
17081
17327
  prefix,
17082
- exportIndexStore: new ExportIndexStore(awsClients.s3, bucket, prefix, region, stateBackend, { profile: options.profile }),
17328
+ exportIndexStore,
17083
17329
  dispose: () => {
17084
17330
  awsClients.destroy();
17085
17331
  stateBackend.destroyClient();
@@ -17803,7 +18049,7 @@ async function stateDestroyCommand(stackArgs, options) {
17803
18049
  if (stackNames.length > 1) deferRegistryTail = (released) => deferredTails.push(released);
17804
18050
  for (const name of stackNames) {
17805
18051
  const refs = stateRefs.filter((r) => r.stackName === name);
17806
- for (const ref of stateDestroyTargets(refs, options.stackRegion) ?? []) crossPrefixCheck.cache.full(name, ref.region ?? setup.region, "prestart");
18052
+ for (const ref of stateDestroyTargets(refs, options.stackRegion) ?? []) crossPrefixCheck.cache.full(name, ref.region ?? await setup.regionFor(name), "prestart");
17807
18053
  }
17808
18054
  for (const [stackIndex, stackName] of stackNames.entries()) {
17809
18055
  const refs = stateRefs.filter((r) => r.stackName === stackName);
@@ -17819,7 +18065,8 @@ async function stateDestroyCommand(stackArgs, options) {
17819
18065
  else throw multipleRegionsError(stackName, refs, `Use --stack-region ${commandHole("region")} to pick one.`);
17820
18066
  for (const [refIndex, ref] of targets.entries()) {
17821
18067
  logger.info(safeMsg`\nPreparing to destroy stack: ${formatStackRefSafe(ref)}`);
17822
- const stateResult = await setup.stateBackend.getState(stackName, ref.region ?? setup.region);
18068
+ const refRegion = ref.region ?? await setup.regionFor(stackName);
18069
+ const stateResult = await setup.stateBackend.getState(stackName, refRegion);
17823
18070
  if (!stateResult) {
17824
18071
  logger.warn(safeMsg`No state found for stack ${displayStackName(stackName)}` + (ref.region ? safeMsg` in ${displayIdent(ref.region)}` : "") + ", skipping");
17825
18072
  continue;
@@ -17831,7 +18078,7 @@ async function stateDestroyCommand(stackArgs, options) {
17831
18078
  const eventRecorder = startRunRecorder({
17832
18079
  backend: setup.stateBackend,
17833
18080
  stackName,
17834
- region: ref.region ?? setup.region,
18081
+ region: refRegion,
17835
18082
  command: "destroy"
17836
18083
  });
17837
18084
  let destroyRunResult = "SUCCEEDED";
@@ -17842,7 +18089,7 @@ async function stateDestroyCommand(stackArgs, options) {
17842
18089
  lockManager: setup.lockManager,
17843
18090
  providerRegistry,
17844
18091
  parentStackName: stackName,
17845
- parentRegion: ref.region ?? setup.region,
18092
+ parentRegion: refRegion,
17846
18093
  accountId: "unknown",
17847
18094
  awsClients: setup.awsClients,
17848
18095
  stateBucket: setup.bucket,
@@ -17857,7 +18104,7 @@ async function stateDestroyCommand(stackArgs, options) {
17857
18104
  ...options.resourceWarnAfter?.perTypeMs && { resourceWarnAfterByType: options.resourceWarnAfter.perTypeMs },
17858
18105
  ...options.resourceTimeout?.perTypeMs && { resourceTimeoutByType: options.resourceTimeout.perTypeMs }
17859
18106
  }
17860
- }, () => runDestroyForStack(stackName, stateResult.state, {
18107
+ }, () => runDestroyForStack(stackName, stateWithRegion(stateResult.state, refRegion), {
17861
18108
  stateBackend: setup.stateBackend,
17862
18109
  lockManager: setup.lockManager,
17863
18110
  providerRegistry,
@@ -18054,8 +18301,10 @@ async function stateInfoCommand(options) {
18054
18301
  setAwsClients(awsClients);
18055
18302
  let regionCorrectedS3 = null;
18056
18303
  try {
18057
- const region = namedCliRegion(options.region) ?? "us-east-1";
18058
- const resolved = await resolveStateBucketWithDefaultAndSource(options.stateBucket, region);
18304
+ const effectiveRegion = await resolveEffectiveRegion(options);
18305
+ exportInferredRegionForSdk(effectiveRegion);
18306
+ const region = effectiveRegion.region;
18307
+ const resolved = await resolveStateBucketWithDefaultAndSource(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
18059
18308
  const bucket = resolved.bucket;
18060
18309
  const prefix = options.statePrefix;
18061
18310
  await new S3StateBackend(awsClients.s3, {
@@ -18620,7 +18869,7 @@ async function rollbackCommand(stackArg, options) {
18620
18869
  ref = scoped[0];
18621
18870
  }
18622
18871
  const stackName = ref.stackName;
18623
- const region = ref.region ?? setup.region;
18872
+ const region = ref.region ?? await setup.regionFor(ref.stackName);
18624
18873
  if (options.dropFailed !== void 0) {
18625
18874
  await dropFailedJournalEntry({
18626
18875
  stateBackend: setup.stateBackend,
@@ -19093,8 +19342,10 @@ async function eventsCommand(stackName, options) {
19093
19342
  });
19094
19343
  setAwsClients(awsClients);
19095
19344
  try {
19096
- const region = namedCliRegion(options.region) ?? "us-east-1";
19097
- const bucket = await resolveStateBucketWithDefault(options.stateBucket, region);
19345
+ const effectiveRegion = await resolveEffectiveRegion(options);
19346
+ exportInferredRegionForSdk(effectiveRegion);
19347
+ const region = effectiveRegion.region;
19348
+ const bucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
19098
19349
  const prefix = options.statePrefix ?? "cdkd";
19099
19350
  const stateBackend = new S3StateBackend(awsClients.s3, {
19100
19351
  bucket,
@@ -19161,8 +19412,10 @@ async function eventsPruneCommand(stackName, options) {
19161
19412
  });
19162
19413
  setAwsClients(awsClients);
19163
19414
  try {
19164
- const region = namedCliRegion(options.region) ?? "us-east-1";
19165
- const bucket = await resolveStateBucketWithDefault(options.stateBucket, region);
19415
+ const effectiveRegion = await resolveEffectiveRegion(options);
19416
+ exportInferredRegionForSdk(effectiveRegion);
19417
+ const region = effectiveRegion.region;
19418
+ const bucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
19166
19419
  const prefix = options.statePrefix ?? "cdkd";
19167
19420
  const stateBackend = new S3StateBackend(awsClients.s3, {
19168
19421
  bucket,
@@ -19848,7 +20101,7 @@ async function publishAssetsCommand(stacks, options) {
19848
20101
  const logger = getLogger();
19849
20102
  if (options.verbose) logger.setLevel("debug");
19850
20103
  warnIfDeprecatedRegion(options);
19851
- const rawBaseRegion = rawCliRegion(options.region) ?? "us-east-1";
20104
+ const rawNamedRegion = rawCliRegion(options.region);
19852
20105
  foldRegionOption(options);
19853
20106
  await applyRoleArnIfSet({
19854
20107
  roleArn: options.roleArn,
@@ -19876,7 +20129,9 @@ async function publishAssetsCommand(stacks, options) {
19876
20129
  else if (allStacks.length === 1) targetStacks = allStacks;
19877
20130
  else throw new Error(`Multiple stacks found: ${allStacks.map(describeStack).join(", ")}. Specify stack name(s) or use --all`);
19878
20131
  if (targetStacks.length === 0) throw new Error(renderNoStackMatch(stackPatterns, allStacks));
19879
- const baseRegion = namedCliRegion(options.region) ?? "us-east-1";
20132
+ const effectiveRegion = await resolveEffectiveRegion(options);
20133
+ exportInferredRegionForSdk(effectiveRegion);
20134
+ const baseRegion = effectiveRegion.region;
19880
20135
  const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
19881
20136
  const stsClient = new STSClient({
19882
20137
  ...ambientClientDefaults(),
@@ -19890,7 +20145,7 @@ async function publishAssetsCommand(stacks, options) {
19890
20145
  if (markerAccess !== void 0) return markerAccess?.resolver ?? null;
19891
20146
  let bucket;
19892
20147
  try {
19893
- bucket = await resolveStateBucketWithDefault(options.stateBucket, baseRegion);
20148
+ bucket = await resolveStateBucketWithDefault(options.stateBucket, baseRegion, legacyStateBucketFallbackRegion(effectiveRegion));
19894
20149
  } catch {
19895
20150
  logger.info("No cdkd state bucket found — publishing to the asset-manifest destinations (CDK bootstrap storage) verbatim. Run 'cdkd bootstrap' to opt into cdkd-owned asset storage that 'cdk gc' never touches.");
19896
20151
  markerAccess = null;
@@ -19910,10 +20165,22 @@ async function publishAssetsCommand(stacks, options) {
19910
20165
  const resolver = new AssetModeResolver(backend, accountId, { ...options.profile && { profile: options.profile } });
19911
20166
  markerAccess = {
19912
20167
  resolver,
20168
+ regionFor: stackRegionResolver({
20169
+ effective: effectiveRegion,
20170
+ probe: backend,
20171
+ logger,
20172
+ siblings: allStacks.filter((s) => !s.region).map((s) => s.stackName)
20173
+ }),
19913
20174
  dispose: () => markerClients.destroy()
19914
20175
  };
19915
20176
  return resolver;
19916
20177
  };
20178
+ const regionForStack = async (stack) => {
20179
+ if (stack.region) return stack.region;
20180
+ if (!regionNeedsReconciliation(effectiveRegion)) return baseRegion;
20181
+ await getModeResolver();
20182
+ return markerAccess ? markerAccess.regionFor(stack.stackName) : baseRegion;
20183
+ };
19917
20184
  const assetPublisher = new AssetPublisher();
19918
20185
  const results = [];
19919
20186
  try {
@@ -19934,13 +20201,13 @@ async function publishAssetsCommand(stacks, options) {
19934
20201
  }
19935
20202
  logger.info(`\nPublishing assets for stack: ${describeStack(stack)}`);
19936
20203
  let redirect;
20204
+ const stackRegion = await regionForStack(stack);
19937
20205
  if (!useCdkBootstrapAssets) {
19938
20206
  const manifest = loadPublishableAssetManifest(stack.assetManifestPath);
19939
20207
  if (manifest) {
19940
20208
  const modeResolver = await getModeResolver();
19941
20209
  if (modeResolver) {
19942
- const stackRegion = stack.region || baseRegion;
19943
- const assetMode = await modeResolver.resolve(stack.region || rawBaseRegion);
20210
+ const assetMode = await modeResolver.resolve(stack.region || rawNamedRegion || stackRegion);
19944
20211
  if (assetMode.mode === "cdkd-assets") {
19945
20212
  const map = buildAssetRedirectMap(manifest, assetMode.marker, accountId, stackRegion);
19946
20213
  if (map.entries.length > 0) redirect = map;
@@ -19953,7 +20220,7 @@ async function publishAssetsCommand(stacks, options) {
19953
20220
  try {
19954
20221
  nodeIds = assetPublisher.addAssetsToGraph(workGraph, stack.assetManifestPath, {
19955
20222
  accountId,
19956
- region: stack.region || baseRegion,
20223
+ region: stackRegion,
19957
20224
  ...options.profile && { profile: options.profile },
19958
20225
  nodePrefix: `${stack.stackName}:`,
19959
20226
  ...redirect && { redirect },
@@ -20047,8 +20314,10 @@ async function forceUnlockCommand(stackArgs, options) {
20047
20314
  ...options.profile && { profile: options.profile }
20048
20315
  });
20049
20316
  setAwsClients(awsClients);
20050
- const region = namedCliRegion(options.region) ?? "us-east-1";
20051
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
20317
+ const effectiveRegion = await resolveEffectiveRegion(options);
20318
+ exportInferredRegionForSdk(effectiveRegion);
20319
+ const region = effectiveRegion.region;
20320
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
20052
20321
  const failures = [];
20053
20322
  try {
20054
20323
  const stateConfig = {
@@ -20057,12 +20326,17 @@ async function forceUnlockCommand(stackArgs, options) {
20057
20326
  };
20058
20327
  const lockManager = new LockManager(awsClients.s3, stateConfig);
20059
20328
  const stateBackend = new S3StateBackend(awsClients.s3, stateConfig);
20329
+ const regionForLock = stackRegionResolver({
20330
+ effective: effectiveRegion,
20331
+ probe: { stateExistsOwnedBy: async (name, r, regionlessOwner) => await lockManager.isLocked(name, r) || await stateBackend.stateExistsOwnedBy(name, r, regionlessOwner) },
20332
+ logger
20333
+ });
20060
20334
  for (const stackName of stackPatterns) {
20061
20335
  let regionsToTry;
20062
20336
  if (options.stackRegion) regionsToTry = [options.stackRegion];
20063
20337
  else {
20064
20338
  const matched = (await stateBackend.listStacks()).filter((r) => r.stackName === stackName);
20065
- if (matched.length === 0) regionsToTry = [region];
20339
+ if (matched.length === 0) regionsToTry = [await regionForLock(stackName)];
20066
20340
  else regionsToTry = matched.map((r) => r.region);
20067
20341
  }
20068
20342
  for (const r of regionsToTry) {
@@ -20218,17 +20492,20 @@ async function importCommand(stackArg, options) {
20218
20492
  roleArn: options.roleArn,
20219
20493
  region: options.region
20220
20494
  });
20221
- const region = namedCliRegion(options.region) ?? "us-east-1";
20222
- const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region);
20495
+ const effectiveRegion = await resolveEffectiveRegion(options);
20496
+ exportInferredRegionForSdk(effectiveRegion);
20497
+ const region = effectiveRegion.region;
20498
+ const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
20223
20499
  if (options.region) {
20224
20500
  process.env["AWS_REGION"] = options.region;
20225
20501
  process.env["AWS_DEFAULT_REGION"] = options.region;
20226
20502
  }
20227
20503
  const awsClients = new AwsClients({
20228
- ...options.region && { region: options.region },
20504
+ region: effectiveRegion.region,
20229
20505
  ...options.profile && { profile: options.profile }
20230
20506
  });
20231
20507
  setAwsClients(awsClients);
20508
+ let targetClients;
20232
20509
  try {
20233
20510
  const stateConfig = {
20234
20511
  bucket: stateBucket,
@@ -20245,8 +20522,6 @@ async function importCommand(stackArg, options) {
20245
20522
  });
20246
20523
  await stateBackend.verifyBucketExists();
20247
20524
  const lockManager = new LockManager(awsClients.s3, stateConfig);
20248
- const providerRegistry = new ProviderRegistry();
20249
- registerAllProviders(providerRegistry, providerClasses);
20250
20525
  const appCmd = options.app || resolveApp();
20251
20526
  if (!appCmd) throw new Error("`cdkd state import` requires a CDK app: pass --app or set it in cdk.json. The template is read to find logical IDs, resource types, and dependencies.");
20252
20527
  logger.info(synthesisStatusMessage(appCmd, "Synthesizing CDK app to read template..."));
@@ -20270,8 +20545,25 @@ async function importCommand(stackArg, options) {
20270
20545
  }
20271
20546
  } else if (result.stacks.length === 1) stackInfo = result.stacks[0];
20272
20547
  else throw new Error(`Multiple stacks found: ${result.stacks.map(describeStack).join(", ")}. Specify the stack name as a positional argument.`);
20273
- const targetRegion = stackInfo.region || region;
20548
+ const targetRegion = await stackRegionResolver({
20549
+ effective: effectiveRegion,
20550
+ probe: stateBackend,
20551
+ logger,
20552
+ siblings: result.stacks.filter((s) => !s.region).map((s) => s.stackName)
20553
+ })(stackInfo.stackName, stackInfo.region);
20274
20554
  logger.info(`Target stack: ${stackInfo.stackName} (${targetRegion})`);
20555
+ if (targetRegion !== effectiveRegion.region) {
20556
+ targetClients = new AwsClients({
20557
+ region: targetRegion,
20558
+ ...options.profile && { profile: options.profile }
20559
+ });
20560
+ setAwsClients(targetClients);
20561
+ process.env["AWS_REGION"] = targetRegion;
20562
+ process.env["AWS_DEFAULT_REGION"] = targetRegion;
20563
+ }
20564
+ const regionClients = targetClients ?? awsClients;
20565
+ const providerRegistry = new ProviderRegistry();
20566
+ registerAllProviders(providerRegistry, providerClasses);
20275
20567
  const assetRedirect = await createAssetRedirectResolver({
20276
20568
  stateBackend,
20277
20569
  stsRegion: region,
@@ -20298,7 +20590,7 @@ async function importCommand(stackArg, options) {
20298
20590
  let migrationTree;
20299
20591
  if (migrationCfnStackName) {
20300
20592
  logger.info(`Resolving physical IDs from CloudFormation stack '${migrationCfnStackName}' (recursive)...`);
20301
- migrationTree = await getCloudFormationResourceTree(migrationCfnStackName, awsClients.cloudFormation);
20593
+ migrationTree = await getCloudFormationResourceTree(migrationCfnStackName, regionClients.cloudFormation);
20302
20594
  const mergeStats = mergeCfnDerivedOverrides({
20303
20595
  cfnMapping: migrationTree.resources,
20304
20596
  template,
@@ -20318,7 +20610,7 @@ async function importCommand(stackArg, options) {
20318
20610
  const selectiveMode = overrides.size > 0 && !options.auto && !options.migrateFromCloudformation;
20319
20611
  if (selectiveMode) logger.info(`Selective mode: only importing the ${overrides.size} resource(s) you listed (${[...overrides.keys()].join(", ")}). Pass --auto to also auto-resolve the rest.`);
20320
20612
  if (!selectiveMode && !migrationCfnStackName) {
20321
- const cfnResources = await tryGetCloudFormationResourceMap(stackInfo.stackName, awsClients.cloudFormation);
20613
+ const cfnResources = await tryGetCloudFormationResourceMap(stackInfo.stackName, regionClients.cloudFormation);
20322
20614
  if (cfnResources) {
20323
20615
  const mergeStats = mergeCfnDerivedOverrides({
20324
20616
  cfnMapping: cfnResources,
@@ -20418,7 +20710,7 @@ async function importCommand(stackArg, options) {
20418
20710
  return;
20419
20711
  }
20420
20712
  }
20421
- const deployedParameters = !namesAnyDeclaredParameter(stateTemplate) ? void 0 : migrationCfnStackName !== void 0 ? await readDeployedParameters(migrationCfnStackName, awsClients.cloudFormation, logger, displaySafe(migrationCfnStackName)) : await readDeployedParameters(stackInfo.stackName, awsClients.cloudFormation, logger, displaySafe(stackInfo.stackName), { absentStackIsNoSource: true });
20713
+ const deployedParameters = !namesAnyDeclaredParameter(stateTemplate) ? void 0 : migrationCfnStackName !== void 0 ? await readDeployedParameters(migrationCfnStackName, regionClients.cloudFormation, logger, displaySafe(migrationCfnStackName)) : await readDeployedParameters(stackInfo.stackName, regionClients.cloudFormation, logger, displaySafe(stackInfo.stackName), { absentStackIsNoSource: true });
20422
20714
  await captureObservedForImportedResources(stackState, providerRegistry, logger, await withSharedDrainBudget(() => resolveImportedProperties(stackState, stateTemplate, targetRegion, stateBackend, logger, deployedParameters)), rebuiltLogicalIdsFrom(rows, stateTemplate));
20423
20715
  const saveOptions = {};
20424
20716
  if (existingEtag) saveOptions.expectedEtag = existingEtag;
@@ -20442,14 +20734,14 @@ async function importCommand(stackArg, options) {
20442
20734
  accountId: accountIdForNestedSynth,
20443
20735
  logger,
20444
20736
  assetRedirect,
20445
- cfnClient: awsClients.cloudFormation
20737
+ cfnClient: regionClients.cloudFormation
20446
20738
  });
20447
20739
  if (migrationCfnStackName) {
20448
20740
  const orphaned = resources.length - importedRows.length;
20449
20741
  if (orphaned > 0) logger.warn(`--migrate-from-cloudformation: ${orphaned} of ${resources.length} template resource(s) were NOT imported into cdkd. After the CloudFormation stack is retired, those resources remain in AWS but are unmanaged by both CloudFormation and cdkd.`);
20450
20742
  await retireCloudFormationStack({
20451
20743
  cfnStackName: migrationCfnStackName,
20452
- cfnClient: awsClients.cloudFormation,
20744
+ cfnClient: regionClients.cloudFormation,
20453
20745
  yes: options.yes,
20454
20746
  stateBucket,
20455
20747
  ...options.profile && { s3ClientOpts: { profile: options.profile } },
@@ -20462,6 +20754,7 @@ async function importCommand(stackArg, options) {
20462
20754
  });
20463
20755
  }
20464
20756
  } finally {
20757
+ targetClients?.destroy();
20465
20758
  awsClients.destroy();
20466
20759
  }
20467
20760
  }
@@ -28850,4 +29143,4 @@ function collectVerbFlags(program) {
28850
29143
 
28851
29144
  //#endregion
28852
29145
  export { canonicalizeIpProtocolValue as a, buildProgram, resolveSecretDerivedPrincipals as i, runDestroyForStack as n, resolvedResourceTimeoutMs as o, isResolvableSecretPrincipalList as r, canonicalizeIpv4Cidr as t };
28853
- //# sourceMappingURL=program-BYoddGM7.js.map
29146
+ //# sourceMappingURL=program-BgDt3OZh.js.map