@cdkd/cli 0.334.2 → 0.335.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/ambient-client-defaults-B9bnuob2.js +960 -0
  2. package/dist/ambient-client-defaults-B9bnuob2.js.map +1 -0
  3. package/dist/{asg-provider-DTZ_iFWa.js → asg-provider-pl5tnbiA.js} +4 -3
  4. package/dist/asg-provider-pl5tnbiA.js.map +1 -0
  5. package/dist/cli.js +2 -2
  6. package/dist/{db-instance-modify-retry-zm23duXt.js → db-instance-modify-retry-CD7NSyq4.js} +10 -9
  7. package/dist/{db-instance-modify-retry-zm23duXt.js.map → db-instance-modify-retry-CD7NSyq4.js.map} +1 -1
  8. package/dist/{deploy-engine-Dq_RyFZd.js → deploy-engine-iQpILlcZ.js} +13365 -13039
  9. package/dist/deploy-engine-iQpILlcZ.js.map +1 -0
  10. package/dist/{iam-role-provider-DwAhjMfG.js → iam-role-provider-jC3_bsf-.js} +4 -3
  11. package/dist/iam-role-provider-jC3_bsf-.js.map +1 -0
  12. package/dist/index.d.ts +34 -42
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +3 -3
  15. package/dist/{neptune-provider-BFDPuF1_.js → neptune-provider-CNEMvt4t.js} +69 -24
  16. package/dist/neptune-provider-CNEMvt4t.js.map +1 -0
  17. package/dist/{program-Be87SvBg.js → program-DaGdaozO.js} +901 -731
  18. package/dist/program-DaGdaozO.js.map +1 -0
  19. package/dist/{provider-classes-D0isRHVc.js → provider-classes-ZpRORGt2.js} +45 -20
  20. package/dist/provider-classes-ZpRORGt2.js.map +1 -0
  21. package/dist/{rds-provider-CYwGhhxE.js → rds-provider-Ce7ua-ww.js} +289 -31
  22. package/dist/rds-provider-Ce7ua-ww.js.map +1 -0
  23. package/dist/read-replica-BJAUZwWe.js +201 -0
  24. package/dist/read-replica-BJAUZwWe.js.map +1 -0
  25. package/dist/{update-removal-C_x1-FM4.js → update-removal-Dh6W86TO.js} +148 -1097
  26. package/dist/update-removal-Dh6W86TO.js.map +1 -0
  27. package/dist/{version-CagOv0Ke.js → version-BxcTCG5i.js} +2 -2
  28. package/dist/{version-CagOv0Ke.js.map → version-BxcTCG5i.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/asg-provider-DTZ_iFWa.js.map +0 -1
  31. package/dist/deploy-engine-Dq_RyFZd.js.map +0 -1
  32. package/dist/iam-role-provider-DwAhjMfG.js.map +0 -1
  33. package/dist/neptune-provider-BFDPuF1_.js.map +0 -1
  34. package/dist/program-Be87SvBg.js.map +0 -1
  35. package/dist/provider-classes-D0isRHVc.js.map +0 -1
  36. package/dist/rds-provider-CYwGhhxE.js.map +0 -1
  37. package/dist/update-removal-C_x1-FM4.js.map +0 -1
@@ -1,9 +1,10 @@
1
1
  import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefaults, o as setAwsClients, s as resolveS3ClientDefaults, t as AwsClients, u as setS3ClientDefaultsDebugLog } from "./aws-clients-ez_oXu6x.js";
2
2
  import { $ as safeMsg, B as SAFE_MSG_ALTERED_CHAR, C as PATTERN_B_RESOURCE_TYPES, F as isNameGeneration, G as cutMarker, H as STACK_REF_MAX_CODE_POINTS, J as displaySafe, K as displayAwsMessage, L as withSkipPrefix, Q as plainIdentOr, R as withStackScope, S as PATTERN_B_NAME_PROPERTIES, T as generateResourceName, U as UNRENDERABLE, V as SECRET_REF_MAX_CODE_POINTS, W as asIsMessage, X as isPasteableIdent, Y as displayStackName, _ as explicitNamePropertyFor, a as safeStringify, c as isStdoutReservedForPayload, d as runStackBuffered, et as stringifyJsonPayload, l as reserveStdoutForPayload, m as getLiveRenderer, n as describeAwsFailure, nt as truncateCodePoints, q as displayIdent, s as getLogger, tt as terminalSafe, w as derivesPatternBName, x as PATTERN_B_NAME_OPTIONS } from "./aws-failure-text-CoS1huLy.js";
3
- import { $n as markNonRetryable, $t as formatLockExpiry, Ar as shellQuote, Bn as stripForDisplay, Dn as StackHasActiveImportsError, Dr as plainOrDescribed, En as ResourceUpdateNotSupportedError, Et as logicalIdShown, H as assertRegionMatch, Jn as isTransientServerError, M as VALUE_NOT_SHOWN, Mr as setPasteableRunFlags, Nr as setPasteableVerbFlags, On as StackTerminationProtectionError, Or as quotedOrDescribed, Ot as resourceTypeShown, Qn as isThrottlingError, Qt as forceQuitRecoveryClause, Rn as escapeRegExp, Sr as commandHole, Tn as PartialFailureError, Tr as pasteableCommand, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Wn as isAmbiguousOutcomeError, Xt as buildForceUnlockCommand, Yn as retryClassificationText, Yt as UNREPRODUCIBLE_LOCK_CLAUSE, Zn as isMarkedNonRetryable, Zt as buildLockContentionMessage, _n as formatError, _t as beginCommandInterruptScope, an as DEFAULT_STATE_PREFIX, ar as MalformedProducerRecordRefusalError, bn as LocalStartServiceError, br as SHELL_ACTIVE_WHY, bt as isInterruptedWaitError, cn as producerCoordinateKey, cr as CdkdError, dn as withPasteableAwsProfile, dr as LocalInvokeBuildError$1, en as formatLockOperation, fn as ambientClientDefaults, gn as normalizeAwsError, gr as SynthesisError, hn as credentialFingerprint, hr as StateError, in as CUSTOM_RESOURCE_RESPONSE_PREFIX, ir as IntrinsicResolutionRefusalError, it as runDeleteAttempt, jr as withheldTargetClause, kr as shellBoundedDisplay, ln as producerRecordKey, lr as DeployCancelledError, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mn as clientDefaultsFor, mr as ResourceTimeoutError, nr as CrossAccountSecretRefusalError, on as injectiveKey, or as AccountIdUnavailableError, p as IAM_PRINCIPAL_NAME, pn as ambientCredentialConfig, pr as ProvisioningError, qn as isRetryableTransientError, rr as DynamicReferenceRegionAmbiguousError, tn as formatLockOwner, un as setPasteableAwsProfile, ut as isAwsCliLiteral, vr as TIMEOUT_FLAG_RESOURCE_TYPE, vt as endCommandInterruptScope, wn as NestedStackChildDirectDestroyError, wr as isInertUnquoted, y as readRecordedPrincipals, yn as withErrorHandling, yt as interruptWatchListenerCount, z as remedyLogicalId, zn as stripControlChars } from "./update-removal-C_x1-FM4.js";
3
+ import { B as isMarkedNonRetryable, D as escapeRegExp, G as CrossAccountSecretRefusalError, H as markNonRetryable, I as isRetryableTransientError, J as MalformedProducerRecordRefusalError, K as DynamicReferenceRegionAmbiguousError, L as isTransientServerError, N as isAmbiguousOutcomeError, O as stripControlChars, Q as DeployCancelledError, R as retryClassificationText, St as setPasteableVerbFlags, V as isThrottlingError, Y as AccountIdUnavailableError, Z as CdkdError, _ as StackTerminationProtectionError, _t as quotedOrDescribed, a as normalizeAwsError, at as SynthesisError, bt as withheldTargetClause, c as withErrorHandling, dt as commandHole, et as LocalInvokeBuildError$1, g as StackHasActiveImportsError, gt as plainOrDescribed, h as ResourceUpdateNotSupportedError, i as credentialFingerprint, it as StateError, k as stripForDisplay, l as LocalStartServiceError, lt as SHELL_ACTIVE_WHY, m as PartialFailureError, mt as pasteableCommand, n as ambientCredentialConfig, nt as ProvisioningError, o as formatError, p as NestedStackChildDirectDestroyError, pt as isInertUnquoted, q as IntrinsicResolutionRefusalError, r as clientDefaultsFor, rt as ResourceTimeoutError, st as TIMEOUT_FLAG_RESOURCE_TYPE, t as ambientClientDefaults, vt as shellBoundedDisplay, xt as setPasteableRunFlags, yt as shellQuote } from "./ambient-client-defaults-B9bnuob2.js";
4
4
  import { a as setAssumedRoleCredentials, d as formatAuthority, i as getPreAssumeEnvCredentials, n as awsClientDefaults, r as getAssumedRoleCredentials, u as runInStackAwsScope } from "./aws-client-defaults-BLXFsfMa.js";
5
- import { $a as classifyRecordedSecretRegion, $l as importableOutputKeys, $n as demoteSupersededOrphans, $r as gray, $s as malformedOutputsWarning, $t as deleteJournaledOrphans, $u as runDockerForeground, Ad as AssemblyReader, Ai as extractDeploymentEventError, Al as recordPhysicalNameCopy, An as isPairableType, Ao as unsettledItemsField, Ar as secretBearing, As as refuseMalformedResourceEntriesForImport, At as recordRetainedForReadoption, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bl as wholeStringLeavesOf, Bn as calculateResourceDrift, Bo as renderStatefulReason, Br as isExportAliasCollision, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as sameMove, Bu as describeDockerExecFailure, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as orphanRecordsPrintingBag, Cl as spelledKeysOf, Cn as findDestructiveChanges, Co as carriesFetchableDynamicReference, Cr as computeParameterTaint, Cs as malformedLocalResourcesWarning, Ct as withResourceDeadline, Cu as createAssetRedirectResolver, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as secretNamedRecordNeedles, Dn as movedToHint, Do as withSharedDrainBudget, Dr as WITHHELD_NAME_DISPLAY, Ds as refuseMalformedResourceEntries, Dt as mergeNoChangeOutputs, Du as ensureAssetStorage, Ed as PARTITION_TABLE, El as inheritNestedStackParameterAssociations, En as hintSidesOf, Eo as keepsSecretReferenceToken, Er as resourcesNamingDeclaredParameter, Es as refuseMalformedResourceAttributesForOrphan, Et as keptWholeReasonText, Eu as AssetModeResolver, Fa as DiffCalculator, Fd as utf8ByteLength, Fi as isFinalSnapshotError, Fl as recordMaskOnlyValue, Fn as replayFailedOperations, Fo as findReplacedReadersOfRecreateTargets, Fr as exportNameSecretExposure, Fs as malformedDriftResourcePropertiesWarning, Ft as readRefactorMarker, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gl as S3StateBackend, Gn as updatePartialReason, Gs as malformedOrphansWarning, Gt as refusePendingMovesOut, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as secretSegmentsOfState, Hl as isSingleDynamicReferenceToken, Hn as equalModuloMask, Hr as DEFAULT_RESOURCE_TIMEOUT_MS, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as hasPendingMovesOut, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Ii as refusesFinalSnapshot, Il as recordMaskOnlyValuesIn, In as replayRollback, Io as shownType, Ir as isWholeDynamicReferenceValue, Is as malformedResourcePropertiesWarning, It as readRefactorMarkerOnce, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as describeRegionValueKind, Js as repairMalformedOrphansForReadOnly, Jt as formatResourceLine, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Kl as splitImportedOps, Ko as coerceCfnBoolean, Ks as refuseMalformedOrphans, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as unsupportedFinalSnapshotError, Ll as recordNoEchoAttributeValues, Ln as recordAfterRollbackUpdate, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as noEchoParameterValueSeed, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as refactorMarkerMovesOf, Lu as buildDockerImage, Md as processStackMessages, Mi as PRE_DELETE_SNAPSHOT_TYPES, Ml as splitGetAttStringForm, Mn as mappingPairs, Mo as unsettledPropertiesOf, Mr as secretSafeKeyDisplay, Ms as refuseMalformedResourceEntriesForOrphan, Mu as parseBootstrapMarker, Nd as describeJsonParseFailure, Ni as ccRoutedFinalSnapshotError, Nl as carriesSecretMask, Nn as parseMappingFile, No as withUnsettledProperties, Nr as carriedExportAliasExposure, Ns as repairMalformedResourceEntriesForReadOnly, Nu as readBootstrapMarkerBody, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as stateSecretNameNeedles, Ol as physicalNameCopiesOf, On as rollbackOrphanIds, Oo as INTRINSIC_KEYS, Or as displayTextOrWithheld, Os as refuseMalformedResourceEntriesForDeploy, Ot as makeCanonicalizePropertiesFn, Ou as buildDenyExternalAccessPolicy, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as effectiveDeletionPolicy, Pl as provenPublicValue, Pn as proposeRenames, Po as withoutUnsettledProperties, Pr as exportNameNoEchoParameters, Ps as unreadableResourceEntries, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as hasUnverifiableParameterRefusal, Qn as seedsDeleteFirstGuard, Qr as cyan, Qs as malformedOutputsRefusalMessage, Qt as resolvePendingCloudControlRequests, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Ri as createPreDeleteFinalSnapshot, Rl as recordNoEchoParameterFreshValue, Rn as settleUnsettledPrevious, Ro as isStatefulRecreateTargetForReplace, Rr as collectDeclaredOutputNames, Rs as refuseMalformedResourcePropertiesForDrift, Rt as refactorMarkerRefusalMessage, Ru as resolveDockerContextDirectory, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Si as namingSecretsWithRecordedNoEcho, Sl as isUncertifiedBaselineMaskPosition, Sn as constructPathOf$1, So as isImpossibleEmptyStoredAttribute, Sr as inheritProducerRegions, Ss as malformedLocalResourceEntriesWarning, Su as buildAssetRedirectMap, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as secretNamePrintingBags, Tl as identityKeyFor, Tn as findRefactorHints, To as carriesDynamicReference, Tr as reachableDivergentParameters, Ts as malformedScrubResourceEntriesRefusalMessage, Tt as isSecretBearingReferenceString, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ui as withSecretPhysicalIdsMaskedInState, Ul as LockManager, Un as undeclaredEmptyObservedKeys, Ur as DEFAULT_RESOURCE_WARN_AFTER_MS, Us as hasReadableOrphans, Ut as pendingMovesOutOf, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as equalModuloMarkedMask, Vr as bindingSkippedOutputs, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as updateRefactorMarker, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wl as isLockInfoExpired, Wn as updatePartialMessage, Wr as maskingRetryLogger, Ws as malformedOrphansRefusalMessage, Wt as pendingMovesRefusalMessage, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as hasReadableExportSet, Xs as malformedExportSourceWarning, Xt as planOrphanAdoption, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as exportNamesCarriedFrom, Yn as withCreateTokenLedger, Yr as withStackRecords, Ys as malformedExportNamesWarning, Yt as makeSiblingClaimReader, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as hasReasonlessBaselineRefusal, Zn as planRollback, Zr as bold, Zs as malformedLocalOutputsWarning, Zt as pendingRequestCount, Zu as formatDockerLoginError, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as withAttemptedItemsMasked, _l as scrubResourceRecord, _n as collectNestedChildUnaddressed, _o as keepHeldTokenProvenance, _r as retiredAfterRollback, _s as refuseMalformedOrphansForOrphan, _t as conditionFingerprint, _u as withStackInstanceIdWithheld, a as isProtectionValueActive, aa as wouldReturnToSdkProvider, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as holdsSupersededResources, al as hasMaskableValues, an as sameJournaledOrphans, ar as replacementNeverSwapped, as as withRetry, at as computeImplicitDeleteEdges, au as stackInstanceIdCarriedFrom, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as journaledOrphanPrintingBag, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as DeploymentEventsReader, bo as recordedReferenceRegions, br as withNameGenerationReached, bs as unreadableOrphanRecords, bt as readRecordedConditionVerdicts, bu as stringifyValue, ca as customResourceResponseExpirationWarning, cc as malformedStateRefusalMessage, cd as resolveApp, ci as supersededAfterRollback, cl as printingCorpusOf, cn as displacedOpClause, co as coerceParameterTypedValue, cs as declaresNoEcho, ct as deferredServiceTokenWarning, cu as timePhase, da as isCustomResourceType$1, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as supersededResourcesOf, dl as shareLogOnlyValues, do as AWS_NO_VALUE, ds as malformedOrphanRecordsRefusalMessage, dt as childTemplateLoader, du as CrossPrefixScanCache, ed as runDockerStreaming, ei as green, el as redactForState, en as dropFailedCommands, eo as classifyReplaySecretRegion, er as isJournaledOrphan, eu as importableOutputs, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as withoutSuperseded, fl as unionOfSecretBags, fn as nestedChildStackName$1, fo as cfnRefValueFromPhysicalId, fr as removeProtectionTypeList, fs as malformedOrphanRecordsWarning, ft as findNestedTemplateTreeDefect, fu as applyCrossPrefixScan, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as noEchoParameterNamesOf, gl as maskSecretsInText, gn as withNestedRevertRun, gr as nameScopeOf, gs as refuseMalformedOrphanRecordsForDestroy, gt as templateIdentity, gu as stackInstanceIdOf, ha as CloudControlProvider, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as noEchoExactEchoLeavesOf, hl as maskSecretsInError, hn as revertedNestedRowIds, ho as refStateLookupFromResource, hr as nameGenerationHighWaterOf, hs as refuseMalformedOrphanRecords, ht as renderNestedTemplateTreeDefect, hu as isNotImplemented, i as PROTECTION_PROPERTY_BY_TYPE, ia as isCustomResource, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as deleteSupersededEntry, il as createUnionSecretMasker, in as loadJournaledOrphans, ir as recordUnderIdIsNotOwn, is as describeTypeWithThrottleRetry, it as IMPLICIT_DELETE_DEPENDENCIES, iu as shouldRetainResource, jd as StageLoadError, ji as ATOMIC_FINAL_SNAPSHOT_TYPES, jl as recordNestedStackParameterExpressions, jn as looselyEqual, jo as unsettledItemsOf, jr as secretBearingStateKeyWarning, js as refuseMalformedResourceEntriesForImportSave, ju as getBootstrapMarkerKey, kd as refuseFailedLookups, ki as storedSecretNameNeedles, kn as withMovedTo, kr as exportAliasCollisionScrubWarning, ks as refuseMalformedResourceEntriesForDestroy, kt as keptForRetainedRecord, ku as assertAssetBucketRegion, la as TemplateNoEchoReresolver, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as supersededHeldByOtherTypeWarning, ll as recordLogOnlyParameterValue, ln as displacedPhysicalIdShown, lo as isUnboundTemplateParameter, ls as deployRefusesOrphanRowsReason, lt as findServiceTokenRefusals, lu as rebuildClientForBucketRegion, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as noEchoComparisonForTemplate, ml as errorCauseChain, mo as lacksRecordedTableArn, mr as nameGenerationCarriedFrom, ms as previewableOrphanRecords, mt as listNestedTemplateRows, mu as isAccessDenied, n as recordedProtectionEvidence, na as ProviderRegistry, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as yellow, nn as isHandledOrphan, no as regionLessSecretName, nr as planFailedOps, ns as prefetchCreateOnlyPropertyPaths, nu as orphansAfterRollback, o as perType, oa as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as isSupersededResourceRecord, ol as literalSplitDelimitersOf, on as makeForeignHolderScan, or as resolveReplacementOldType, os as parameterInputsFor, ot as crossStackOutputProvenanceSource, ou as PhaseClock, pa as withPrintingSecrets, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as noEchoAttributeNamesOf, pl as createSecretMasker, pn as recordDisplacedSkips, po as isStalePlaceholderArnAttribute, pr as orphanNeedsIdentity, ps as malformedOrphanRowsKeptWarning, pt as isAbsoluteAssetPath, pu as crossPrefixDeniedWarning, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as acceptedCreateOnlyDropsOf, qn as ledgerForStack, qr as destroyStackRecordsView, qs as refuseMalformedOrphansForDestroy, qu as partitionSensitiveEnv, r as recordedProtectionNote, ra as ccBrokenReason, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as addSuperseded, rl as carryLogOnlyValues, rn as journaledOrphanLines, rr as recheckFailedPlan, rs as templateResourceTypes, ru as orphansCarriedFrom, s as readProtection, sa as applyCustomResourceResponseExpiration, sc as malformedResourcesWarning, sd as loadCdkJson, si as removeSuperseded, sl as logOnlyValueCount, sn as NESTED_PENDING_PARENT_REASON, sr as findNestedStackTypeChanges, st as inheritedProvenanceForChildDiff, su as renderPhaseTimings, t as DeployEngine, ta as CC_BROKEN_REASON, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as red, tn as dropFailedHint, to as producerRegionsFromState, tr as isReplacementOrphan, tu as isReadableBag, ua as readsNoEchoDeleteValues, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as supersededHolderOf, ul as recordLogOnlyValue, un as dropSettledNestedJournals, uo as parameterTypeMayLoseSecretIdentity, us as isReadableOrphanRecord, ut as serviceTokenBlockingReason, uu as CrossPrefixReadError, va as setResolvedResourceTimeouts, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as createReadOnlyAttributeHealerFactory, vl as withPhysicalNameCopies, vn as getCurrentNestedStackContext, vr as retiredNameGenerationsAfter, vs as repairMalformedOrphanRecordsForReadOnly, vt as conditionInputsFrom, vu as AssetPublisher, wa as deleteSkipReason, wd as decodeListingKey, wi as secretNamePrintingBag, wl as pathCrossesDottedKey, wn as formatDestructiveChange, wo as isNamelessDynamicReferenceError, wr as namesAnyDeclaredParameter, ws as malformedResourceEntriesWarning, wt as diffSecurity, wu as loadPublishableAssetManifest, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as maskEventTextWithBoundBags, xl as dynamicReferenceTokens, xn as DeploymentEventsStore, xo as getAccountInfo, xs as isReadableResourceEntry, xu as WorkGraph, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yi as completedReplayEntries, yn as withNestedStackContext, yo as recordedOutputReferenceRegions, yr as retiredNameGenerationsLeaving, ys as unpreviewableOrphanRecords, yt as parentSuppliedValues, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zi as buildFinalSnapshotIdentifier, zl as recordProvenPublicExpression, zn as withUnprovenUnsettled, zo as isStatefulRecreateTargetSync, zr as collectPublishedOutputNames, zs as refuseMalformedResourcePropertiesForExport, zt as refuseRefactorMarker, zu as describeDockerCapturedOutput } from "./deploy-engine-Dq_RyFZd.js";
6
- import { t as getCdkdVersion } from "./version-CagOv0Ke.js";
5
+ import { $a as envCredentialsAreAssumedRole, $c as liveMatchesUnresolvedTokenFrame, $l as importableOutputs, $n as demoteSupersededOrphans, $r as isSupersededResourceRecord, $s as malformedOutputsRefusalMessage, $t as displacedPhysicalIdShown, $u as getDockerCmd, A as recordedProtectionEvidence, Ad as refuseFailedLookups, Ai as extractDeploymentEventError, An as isPairableType, Ar as secretBearing, As as refuseMalformedResourceEntriesForDestroy, Au as assertAssetBucketRegion, Bc as isMarkedCoordinate, Bd as nullPrototypeRecord, Bi as isFinalSnapshotError, Bl as recordProvenPublicExpression, Bn as calculateResourceDrift, Bo as isStatefulRecreateTargetSync, Br as isExportAliasCollision, Bs as refuseMalformedResourcePropertiesForExport, Bt as readRefactorMarkerOnce, Bu as describeDockerCapturedOutput, C as pendingMovesOutOf, Ca as deleteIndeterminateGuards, Cc as findActionableSdkUnwired, Cd as uploadCfnTemplate, Ci as orphanRecordsPrintingBag, Cl as isUncertifiedBaselineMaskPosition, Cn as findDestructiveChanges, Co as isImpossibleEmptyStoredAttribute, Cr as computeParameterTaint, Cs as malformedLocalResourceEntriesWarning, Cu as buildAssetRedirectMap, D as findServiceTokenRefusals, Dd as PARTITION_TABLE, Di as secretNamedRecordNeedles, Dl as inheritNestedStackParameterAssociations, Dn as movedToHint, Do as keepsSecretReferenceToken, Dr as WITHHELD_NAME_DISPLAY, Ds as refuseMalformedResourceAttributesForOrphan, Du as AssetModeResolver, E as deferredServiceTokenWarning, Ec as unwrittenCreateOnlyReplacement, Ed as expectedOwnerParam, El as identityKeyFor, En as hintSidesOf, Eo as carriesDynamicReference, Er as resourcesNamingDeclaredParameter, Es as malformedScrubResourceEntriesRefusalMessage, Eu as rewriteTemplateAssetReferences, F as readProtection, Fa as isWaitAbandonedError, Fd as parseFailureDebugDetail, Fi as ATOMIC_FINAL_SNAPSHOT_TYPES, Fl as provenPublicValue, Fn as replayFailedOperations, Fo as withoutUnsettledProperties, Fr as exportNameSecretExposure, Fs as unreadableResourceEntries, Ft as IMPLICIT_DELETE_DEPENDENCIES, Fu as validateAssetBucketName, Ga as assertFlagRoleArn, Gc as noEchoCoordinatesOf, Gd as renderAssemblyPathEscape, Gl as isLockInfoExpired, Gn as updatePartialReason, Gs as malformedOrphansRefusalMessage, Gt as updateRefactorMarker, Gu as redactDockerArgvValues, Ha as producerLookupOver, Hc as maskReadbackAtCoordinates, Hd as absoluteAssemblyPathEscape, Hi as unsupportedFinalSnapshotError, Hl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Hn as equalModuloMask, Hr as DEFAULT_RESOURCE_TIMEOUT_MS, Hs as repairMalformedResourcePropertiesForReadOnly, Ht as refactorMarkerRefusalMessage, Hu as describeDockerFailure, Ia as DiffCalculator, Id as utf8ByteLength, Ii as PRE_DELETE_SNAPSHOT_TYPES, Il as recordMaskOnlyValue, In as replayRollback, Io as findReplacedReadersOfRecreateTargets, Ir as isWholeDynamicReferenceValue, Is as malformedDriftResourcePropertiesWarning, It as computeImplicitDeleteEdges, Iu as validateContainerRepoName, Ja as isIamRoleArn, Jd as injectedAwsRegionValue, Jl as acceptedCreateOnlyDropsOf, Jr as withStackRecords, Js as refuseMalformedOrphansForDestroy, Jt as formatResourceLine, Ju as partitionSensitiveEnv, Ka as assertSendableRoleArn, Kc as noEchoLeavesOf, Kd as resolveAssemblyPath, Kl as S3StateBackend, Kr as destroyStackRecordsView, Ks as malformedOrphansWarning, Ku as dockerSpawnEnvWithSensitive, La as IntrinsicFunctionResolver, Lc as DagBuilder, Ld as defineOwnKey, Li as ccRoutedFinalSnapshotError, Ll as recordMaskOnlyValuesIn, Ln as recordAfterRollbackUpdate, Lo as shownType, Lr as noEchoParameterValueSeed, Ls as malformedResourcePropertiesWarning, Lt as keptForRetainedRecord, Lu as BOOTSTRAP_MARKER_PREFIX, M as PROTECTION_PROPERTY_BY_TYPE, Md as StageLoadError, Ml as recordNestedStackParameterExpressions, Mn as mappingPairs, Mo as unsettledItemsOf, Mr as secretSafeKeyDisplay, Ms as refuseMalformedResourceEntriesForImportSave, Mu as getBootstrapMarkerKey, N as isProtectionValueActive, Nd as processStackMessages, Ni as secretSegmentsOfState, Nl as splitGetAttStringForm, Nn as parseMappingFile, No as unsettledPropertiesOf, Nr as carriedExportAliasExposure, Ns as refuseMalformedResourceEntriesForOrphan, Nu as parseBootstrapMarker, O as serviceTokenBlockingReason, Oc as NO_CC_HANDLERS_REASON, Od as canonicalizeRegion, Oi as stateSecretNameNeedles, On as rollbackOrphanIds, Oo as withSharedDrainBudget, Or as displayTextOrWithheld, Os as refuseMalformedResourceEntries, Ou as ensureAssetStorage, P as perType, Pd as describeJsonParseFailure, Pi as withSecretPhysicalIdsMaskedInState, Pl as carriesSecretMask, Pn as proposeRenames, Po as withUnsettledProperties, Pr as exportNameNoEchoParameters, Ps as repairMalformedResourceEntriesForReadOnly, Pt as withResourceDeadline, Pu as readBootstrapMarkerBody, Qa as callerEnvCredentials, Qc as valueAtCoordinate, Ql as importableOutputKeys, Qn as seedsDeleteFirstGuard, Qr as holdsSupersededResources, Qs as malformedLocalOutputsWarning, Qt as displacedOpClause, Qu as formatDockerLoginError, Ra as isAlwaysLiveAttribute, Rc as TemplateParser, Rd as hasOwnKey, Ri as ccRoutedInstanceTakesNoSnapshot, Rl as recordNoEchoAttributeValues, Rn as settleUnsettledPrevious, Ro as MULTI_REGION_RECREATE_BLOCKED_TYPES, Rr as collectDeclaredOutputNames, Rs as refuseMalformedResourcePropertiesForDestroy, Rt as recordRetainedForReadoption, Ru as buildDockerImage, S as hasPendingMovesOut, Sa as UNSPECIFIED_SKIP_REASON, Sc as hasReadableResources, Sd as findLargeInlineResources, Si as namingSecretsWithRecordedNoEcho, Sl as dynamicReferenceTokens, Sn as constructPathOf$1, So as getAccountInfo, Sr as inheritProducerRegions, Ss as isReadableResourceEntry, Su as WorkGraph, T as refusePendingMovesOut, Ta as deleteSkipReason, Td as decodeListingKey, Ti as secretNamePrintingBags, Tl as pathCrossesDottedKey, Tn as findRefactorHints, To as isNamelessDynamicReferenceError, Tr as reachableDivergentParameters, Ts as malformedResourceEntriesWarning, Tu as loadPublishableAssetManifest, Ua as refuseUnreadableCdkCrossAccountRefs, Uc as maskWholeValue, Ud as describeFileReadFailure, Ui as createPreDeleteFinalSnapshot, Ul as isSingleDynamicReferenceToken, Un as undeclaredEmptyObservedKeys, Ur as DEFAULT_RESOURCE_WARN_AFTER_MS, Us as UNREADABLE_ORPHANS_CONTAINER_ROW, Ut as refuseRefactorMarker, Uu as redactedCause, Va as resolveDynamicReferences, Vc as maskAtCoordinates, Vd as ownValue, Vi as refusesFinalSnapshot, Vl as wholeStringLeavesOf, Vn as equalModuloMarkedMask, Vo as renderStatefulReason, Vr as bindingSkippedOutputs, Vs as refuseMalformedResourcePropertiesForOrphan, Vt as refactorMarkerMovesOf, Vu as describeDockerExecFailure, Wa as applyRoleArnIfSet, Wc as maskedLeafCoordinatesOf, Wd as displayAssemblyPath, Wi as buildFinalSnapshotIdentifier, Wl as LockManager, Wn as updatePartialMessage, Wr as maskingRetryLogger, Ws as hasReadableOrphans, Wt as sameMove, Wu as redactedDockerCause, Xa as AWS_CREDENTIAL_ENV_KEYS, Xc as readsNoEchoSource, Xd as resolveBucketRegion, Xl as exportNamesCarriedFrom, Xr as addSuperseded, Xs as malformedExportNamesWarning, Xt as resolvePendingCloudControlRequests, Xu as isDockerClientEnvKey, Ya as sendableAssumeRoleCommand, Yc as readbackPathFor, Yl as describeRegionValueKind, Yn as withCreateTokenLedger, Ys as repairMalformedOrphansForReadOnly, Yt as pendingRequestCount, Yu as warnFinchArgvExposure, Za as applyCallerIdentityCredentials, Zc as recordedNoEchoValuesOf, Zl as hasReadableExportSet, Zn as planRollback, Zr as deleteSupersededEntry, Zs as malformedExportSourceWarning, Zt as NESTED_PENDING_PARENT_REASON, Zu as isMalformedEnvKey, _ as findNestedTemplateTreeDefect, _c as withheldAccountClause, _d as warnDeprecatedNoPrefixCliFlag, _i as withAttemptedItemsMasked, _l as maskSecretsInText, _n as makeForeignHolderScan, _r as retiredAfterRollback, _s as refuseMalformedOrphanRecordsForDestroy, _u as stackInstanceIdOf, aa as isCustomResource, ac as STATE_REGION_DIVERGED, ad as synthesisStatusMessage, ai as withoutSuperseded, al as createUnionSecretMasker, an as revertedNestedRowIds, ar as replacementNeverSwapped, as as describeTypeWithThrottleRetry, au as hasReasonlessBaselineRefusal, b as renderNestedTemplateTreeDefect, ba as slowCcOperationTimeoutMs, bc as displayLogicalId, bd as CFN_TEMPLATE_URL_LIMIT, bi as journaledOrphanPrintingBag, bn as DeploymentEventsReader, bo as recordedOutputReferenceRegions, br as withNameGenerationReached, bs as unpreviewableOrphanRecords, bu as isSensitiveAttributeName, c as mergeNoChangeOutputs, ca as applyCustomResourceResponseExpiration, cc as malformedResourcesWarning, cd as loadCdkJson, ci as cyan, cl as logOnlyValueCount, cn as getCurrentNestedStackContext, cu as renderPhaseTimings, d as makeCanonicalizePropertiesFn, da as readsNoEchoDeleteValues, dc as refuseMalformedResourcesForDestroy, dd as resolveCaptureObservedState, di as red, dl as recordLogOnlyValue, dn as dropFailedCommands, do as parameterTypeMayLoseSecretIdentity, ds as isReadableOrphanRecord, du as CrossPrefixReadError, ec as malformedOutputsWarning, ed as runDockerForeground, ei as removeSuperseded, en as dropSettledNestedJournals, eo as classifyRecordedSecretRegion, er as isJournaledOrphan, eu as isReadableBag, f as conditionFingerprint, fa as isCustomResourceType$1, fc as refuseMalformedResourcesForExport, fd as resolveSkipPrefix, fi as yellow, fl as shareLogOnlyValues, fn as dropFailedHint, fo as AWS_NO_VALUE, fr as removeProtectionTypeList, fs as malformedOrphanRecordsRefusalMessage, fu as CrossPrefixScanCache, g as childTemplateLoader, ga as CloudControlProvider, gc as accountArgs, gd as stateBucketExistenceConfirmed, gi as noEchoParameterNamesOf, gl as maskSecretsInError, gn as sameJournaledOrphans, go as refStateLookupFromResource, gr as nameScopeOf, gs as refuseMalformedOrphanRecords, gu as isNotImplemented, h as readRecordedConditionVerdicts, hc as JSON_LISTING_HOLE_VALUE, hd as resolveUseCdkBootstrapAssets, hi as noEchoExactEchoLeavesOf, hl as errorCauseChain, hn as loadJournaledOrphans, ho as lacksRecordedTableArn, hr as nameGenerationHighWaterOf, hs as previewableOrphanRecords, hu as isAccessDenied, ia as ccBrokenReason, ic as repairMalformedOutputsForReadOnly, id as Synthesizer, ii as supersededResourcesOf, il as carryLogOnlyValues, ir as recordUnderIdIsNotOwn, is as templateResourceTypes, iu as stackInstanceIdCarriedFrom, j as recordedProtectionNote, jd as AssemblyReader, jl as recordPhysicalNameCopy, jn as looselyEqual, jo as unsettledItemsField, jr as secretBearingStateKeyWarning, js as refuseMalformedResourceEntriesForImport, ju as isCrossRegionRedirect, k as diffSecurity, kc as hasNoCloudControlHandlers, kd as derivePartitionAndUrlSuffix, ki as storedSecretNameNeedles, kl as physicalNameCopiesOf, kn as withMovedTo, ko as INTRINSIC_KEYS, kr as exportAliasCollisionScrubWarning, ks as refuseMalformedResourceEntriesForDeploy, ku as buildDenyExternalAccessPolicy, l as crossStackOutputProvenanceSource, la as customResourceResponseExpirationWarning, lc as malformedStateRefusalMessage, ld as resolveApp, li as gray, ll as printingCorpusOf, ln as withNestedStackContext, lo as coerceParameterTypedValue, ls as declaresNoEcho, lu as timePhase, m as parentSuppliedValues, ma as withPrintingSecrets, mc as repairMalformedResourcesForReadOnly, md as resolveStateBucketWithDefaultAndSource, mi as noEchoComparisonForTemplate, ml as createSecretMasker, mn as journaledOrphanLines, mo as isStalePlaceholderArnAttribute, mr as nameGenerationCarriedFrom, ms as malformedOrphanRowsKeptWarning, mu as crossPrefixDeniedWarning, na as CC_BROKEN_REASON, nc as refuseMalformedOutputs, nd as AssetManifestLoader, ni as supersededHeldByOtherTypeWarning, nn as nestedChildStackName$1, no as producerRegionsFromState, nr as planFailedOps, nu as orphansCarriedFrom, o as isSecretBearingReferenceString, oa as wouldReturnToSdkProvider, oc as refuseDivergentRecordRegionForDestroy, od as getDefaultStateBucketName, ol as hasMaskableValues, on as withNestedRevertRun, or as resolveReplacementOldType, os as withRetry, ou as hasUnverifiableParameterRefusal, p as conditionInputsFrom, pc as refuseMalformedState, pd as resolveStateBucketWithDefault, pi as noEchoAttributeNamesOf, pl as unionOfSecretBags, pn as isHandledOrphan, po as cfnRefValueFromPhysicalId, pr as orphanNeedsIdentity, ps as malformedOrphanRecordsWarning, pu as applyCrossPrefixScan, qa as explicitRoleArnOrThrow, qc as noEchoOutputsComparison, qd as injectAwsRegion, ql as splitImportedOps, qn as ledgerForStack, qo as coerceCfnBoolean, qs as refuseMalformedOrphans, qu as finchSecretArgvRefusal, ra as ProviderRegistry, rc as refuseMalformedOutputsForDestroy, rd as getDockerImageBySourceHash, ri as supersededHolderOf, rn as recordDisplacedSkips, ro as regionLessSecretName, rr as recheckFailedPlan, rs as prefetchCreateOnlyPropertyPaths, ru as shouldRetainResource, s as keptWholeReasonText, sa as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, sc as malformedRenderedContainersWarning, sd as getLegacyStateBucketName, si as bold, sl as literalSplitDelimitersOf, sn as collectNestedChildUnaddressed, sr as findNestedStackTypeChanges, ss as parameterInputsFor, su as PhaseClock, t as DeployEngine, td as runDockerStreaming, ti as supersededAfterRollback, tl as redactForState, to as classifyReplaySecretRegion, tr as isReplacementOrphan, tu as orphansAfterRollback, u as inheritedProvenanceForChildDiff, ua as TemplateNoEchoReresolver, uc as refuseMalformedResourcesForDeploy, ud as resolveAutoAssetStorage, ui as green, ul as recordLogOnlyParameterValue, un as deleteJournaledOrphans, uo as isUnboundTemplateParameter, us as deployRefusesOrphanRowsReason, uu as rebuildClientForBucketRegion, v as isAbsoluteAssetPath, vc as STATE_RESOURCES_MALFORMED, vd as ssmResolvedValueType, vi as createReadOnlyAttributeHealerFactory, vl as scrubResourceRecord, vn as makeSiblingClaimReader, vo as keepHeldTokenProvenance, vr as retiredNameGenerationsAfter, vs as refuseMalformedOrphansForOrphan, vu as withStackInstanceIdWithheld, w as pendingMovesRefusalMessage, wa as deleteLeftInPlace, wc as findHandledUnwrittenCreateOnly, wd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, wi as secretNamePrintingBag, wl as spelledKeysOf, wn as formatDestructiveChange, wo as carriesFetchableDynamicReference, wr as namesAnyDeclaredParameter, ws as malformedLocalResourcesWarning, wu as createAssetRedirectResolver, x as templateIdentity, xa as RollbackInlinePolicyWriters, xc as hasReadableOutputs, xd as MIGRATE_TMP_PREFIX, xi as maskEventTextWithBoundBags, xl as DYNAMIC_REFERENCE_TOKEN_SCAN, xn as DeploymentEventsStore, xo as recordedReferenceRegions, xs as unreadableOrphanRecords, xu as stringifyValue, y as listNestedTemplateRows, ya as setResolvedResourceTimeouts, yc as UNREADABLE_RESOURCES_MAP_ROW, yd as CFN_TEMPLATE_BODY_LIMIT, yi as completedReplayEntries, yl as withPhysicalNameCopies, yn as planOrphanAdoption, yr as retiredNameGenerationsLeaving, ys as repairMalformedOrphanRecordsForReadOnly, yu as AssetPublisher, za as poisonRenderedSpellingsCollidingIn, zc as canonicalCoordinates, zd as hasPlainPrototype, zi as effectiveDeletionPolicy, zl as recordNoEchoParameterFreshValue, zn as withUnprovenUnsettled, zo as isStatefulRecreateTargetForReplace, zr as collectPublishedOutputNames, zs as refuseMalformedResourcePropertiesForDrift, zt as readRefactorMarker, zu as resolveDockerContextDirectory } from "./deploy-engine-iQpILlcZ.js";
6
+ import { $t as forceQuitRecoveryClause, Dt as logicalIdShown, H as assertRegionMatch, M as VALUE_NOT_SHOWN, Qt as buildLockContentionMessage, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, bt as interruptWatchListenerCount, dn as setPasteableAwsProfile, en as formatLockExpiry, fn as withPasteableAwsProfile, kt as resourceTypeShown, ln as producerCoordinateKey, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mt as isAwsCliLiteral, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, p as IAM_PRINCIPAL_NAME, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, un as producerRecordKey, vt as beginCommandInterruptScope, xt as isInterruptedWaitError, y as readRecordedPrincipals, yt as endCommandInterruptScope, z as remedyLogicalId } from "./update-removal-Dh6W86TO.js";
7
+ import { t as getCdkdVersion } from "./version-BxcTCG5i.js";
7
8
  import { t as cdkdCacheHome } from "./cli.js";
8
9
  import { randomBytes, randomUUID } from "node:crypto";
9
10
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
@@ -273,7 +274,7 @@ function guardStackRegionOptions(cmd) {
273
274
  for (const sub of cmd.commands) guardStackRegionOptions(sub);
274
275
  }
275
276
  const noWaitOption = new Option("--no-wait", "Skip waiting for async resources to stabilize (RDS, ElastiCache, NAT Gateway, EC2 Instance, ELBv2 LoadBalancer, Lambda MicroVM Image, ECS Service steady state)");
276
- const fullWaitOption = new Option("--full-wait", "Also wait for stabilizations cdkd skips by default, matching CloudFormation (CloudFront Distribution Deployed)");
277
+ const fullWaitOption = new Option("--full-wait", "Also wait for stabilizations cdkd skips by default, matching CloudFormation (CloudFront Distribution Deployed, RDS Multi-AZ DB cluster storage optimization; raise --resource-timeout AWS::RDS::DBCluster for a long one)");
277
278
  function validateWaitFlags(opts) {
278
279
  if (opts.wait === false && opts.fullWait === true) throw new Error("--no-wait and --full-wait cannot be combined: --no-wait skips stabilization waits, --full-wait adds them. Pick one.");
279
280
  }
@@ -1852,7 +1853,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
1852
1853
  // src/provisioning/register-providers.ts
1853
1854
  let providerClasses;
1854
1855
  function loadProviderClasses() {
1855
- providerClasses ??= import("./provider-classes-D0isRHVc.js");
1856
+ providerClasses ??= import("./provider-classes-ZpRORGt2.js");
1856
1857
  return providerClasses;
1857
1858
  }
1858
1859
  function registerAllProviders(registry, classes) {
@@ -12251,6 +12252,85 @@ function createDriftCommand() {
12251
12252
  return cmd;
12252
12253
  }
12253
12254
 
12255
+ // src/cli/commands/destroy-runner/types.ts
12256
+ const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12257
+
12258
+ // src/cli/commands/destroy-runner/helpers.ts
12259
+ async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12260
+ if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12261
+ }
12262
+ const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12263
+ function maskedSnapshotLogger(logger, mask) {
12264
+ return {
12265
+ info: (message) => logger.info(mask(message)),
12266
+ debug: (message) => logger.debug(mask(message))
12267
+ };
12268
+ }
12269
+ function recordDestroyEvent(recorder, event) {
12270
+ recorder?.record(maskEventTextWithBoundBags(event));
12271
+ }
12272
+ const SKIPPED_REMEDY = "Each 'skipped (...)' line above names its cause, and its warning says whether repairing the record in state.json helps. Where it does, repair it and re-run. Otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand, then drop the records.";
12273
+ function countProtectedResources(state) {
12274
+ let count = 0;
12275
+ const records = [...Object.values(state.resources ?? {}), ...supersededResourcesOf(state).map((entry) => entry.state)];
12276
+ for (const resource of records) {
12277
+ const locator = perType(PROTECTION_PROPERTY_BY_TYPE, resource.resourceType);
12278
+ if (locator) {
12279
+ const isActive = (recorded) => isProtectionValueActive(resource.resourceType, recorded);
12280
+ if (isActive(readProtection(resource.properties, locator, state.region)) || isActive(readProtection(resource.observedProperties, locator, state.region))) count++;
12281
+ continue;
12282
+ }
12283
+ }
12284
+ return count;
12285
+ }
12286
+ function countProtectedJournaledOrphans(orphans, region) {
12287
+ let count = 0;
12288
+ for (const { ops } of orphans.segments) for (const op of ops) {
12289
+ if (op.physicalIdRecoveredFromError !== true || op.deletionPolicy === "Retain") continue;
12290
+ if (orphanNeedsIdentity(op) && !op.createdResourceIdentity) continue;
12291
+ const locator = perType(PROTECTION_PROPERTY_BY_TYPE, op.resourceType);
12292
+ if (locator && isProtectionValueActive(op.resourceType, readProtection(op.attemptedProperties, locator, region))) count++;
12293
+ }
12294
+ return count;
12295
+ }
12296
+ async function releaseRegistryMarkerAfterDestroy(ctx, stackName, region, logger) {
12297
+ if (ctx.crossPrefixCheck === void 0) return;
12298
+ try {
12299
+ const known = await ctx.crossPrefixCheck.cache.knownMarker?.(stackName, region);
12300
+ const released = await ctx.stateBackend.releaseRegistryMarker(stackName, region, known);
12301
+ logger.debug(safeMsg`Stack registry marker: ${released}`);
12302
+ } catch (error) {
12303
+ logger.warn(safeMsg`Could not delete the stack registry marker of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}). It names this state prefix, which no longer ` + `records the stack, so a deploy under another prefix treats it as stale.`);
12304
+ }
12305
+ }
12306
+ function holdsSameResourcesAs(snapshot, current) {
12307
+ return isDeepStrictEqual(snapshot.resources, current.resources) && isDeepStrictEqual(snapshot.supersededResources, current.supersededResources);
12308
+ }
12309
+ async function scanActiveConsumers(producerStack, producerRegion, ctx) {
12310
+ const refs = await ctx.stateBackend.listStacks();
12311
+ return (await Promise.all(refs.map(async (ref) => {
12312
+ const region = ref.region ?? ctx.baseRegion;
12313
+ if (ref.stackName === producerStack && region === producerRegion) return null;
12314
+ try {
12315
+ const imports = (await ctx.stateBackend.getState(ref.stackName, region))?.state.imports;
12316
+ if (!imports || imports.length === 0) return null;
12317
+ const matches = imports.filter((entry) => entry.sourceStack === producerStack && canonicalizeRegion(entry.sourceRegion) === canonicalizeRegion(producerRegion));
12318
+ if (matches.length === 0) return null;
12319
+ return matches.map((entry) => ({
12320
+ consumerStack: ref.stackName,
12321
+ consumerRegion: region,
12322
+ exportName: entry.exportName
12323
+ }));
12324
+ } catch {
12325
+ return null;
12326
+ }
12327
+ }))).filter((r) => r !== null).flat();
12328
+ }
12329
+ function refuseNewPendingRequests(read, stackName, region) {
12330
+ if ((read.pendingRequests ?? 0) === 0) return;
12331
+ throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(region, { asciiOnly: true })}) now records a Cloud Control CREATE a failed deploy stopped waiting for — another cdkd process wrote to it. Nothing was deleted; re-run the destroy, which checks how that CREATE ended first.`);
12332
+ }
12333
+
12254
12334
  // src/cli/commands/stack-lock-guard.ts
12255
12335
  async function acquireStackLock(opts) {
12256
12336
  const { lockManager, stackName, region, recovery } = opts;
@@ -12332,6 +12412,129 @@ async function acquireStackLock(opts) {
12332
12412
  };
12333
12413
  }
12334
12414
 
12415
+ // src/cli/commands/destroy-runner/preflight.ts
12416
+ async function refuseMalformedRecordAndLoadJournaledOrphans({ state, stackName, regionForState, refusalRecovery, ctx, logger, stackLockBase }) {
12417
+ refuseMalformedResourcesForDestroy(state, stackName, regionForState, refusalRecovery);
12418
+ refuseMalformedResourceEntriesForDestroy(state, stackName, regionForState, refusalRecovery);
12419
+ refuseMalformedResourcePropertiesForDestroy(state, stackName, regionForState, refusalRecovery);
12420
+ refuseMalformedOrphansForDestroy(state, stackName, regionForState, refusalRecovery);
12421
+ refuseMalformedOrphanRecordsForDestroy(state, stackName, regionForState, refusalRecovery);
12422
+ refusePendingMovesOut(state, stackName, regionForState, "cdkd destroy");
12423
+ let journalAtEntry;
12424
+ try {
12425
+ journalAtEntry = { journal: await ctx.stateBackend.loadRollbackJournal(stackName, regionForState) };
12426
+ } catch (error) {
12427
+ journalAtEntry = { error };
12428
+ }
12429
+ if (ctx.divergentBodyRegion !== void 0 && "journal" in journalAtEntry && pendingRequestCount(journalAtEntry.journal) > 0) {
12430
+ const ids = (journalAtEntry.journal?.segments ?? []).flatMap((segment) => segment.failedOperations ?? []).filter((op) => op.pendingCloudControlRequest !== void 0).map((op) => op.logicalId);
12431
+ const drop = dropFailedCommands(stackName, regionForState, ids);
12432
+ throw new CdkdError(`Stack ${displayStackName(stackName)}'s state record names another region than its key, and its rollback journal records a Cloud Control CREATE a failed deploy stopped waiting for. cdkd cannot tell which region to check it in. Nothing was deleted. Check the request in each region with aws cloudcontrol get-resource-request-status --request-token <token> --region <region> (the token is in the stack's rollback-journal.json), reconcile what it made by hand, then drop the entry and re-run:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")), "DESTROY_CC_PENDING_REQUEST_DIVERGENT_REGION");
12433
+ }
12434
+ const journalRewritten = await resolvePendingCloudControlRequests({
12435
+ journal: ctx.stateBackend,
12436
+ loaded: "journal" in journalAtEntry ? journalAtEntry.journal : null,
12437
+ reader: () => new CloudControlProvider(),
12438
+ stackName,
12439
+ region: regionForState,
12440
+ command: "destroy",
12441
+ logger,
12442
+ stateResources: state.resources,
12443
+ stackInstanceId: stackInstanceIdOf(state, displayStackName(stackName)),
12444
+ underLock: async (settle) => {
12445
+ const held = await acquireStackLock({
12446
+ ...stackLockBase,
12447
+ onFirstSignal: () => {
12448
+ process.stderr.write(`\nInterrupt received - finishing the Cloud Control request check for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12449
+ }
12450
+ });
12451
+ try {
12452
+ return await settle();
12453
+ } finally {
12454
+ await held.release({ failureMessage: "Failed to release lock after settling an abandoned Cloud Control request" });
12455
+ }
12456
+ }
12457
+ });
12458
+ const entryRead = journalAtEntry;
12459
+ const journaledOrphans = await loadJournaledOrphans(journalRewritten ? ctx.stateBackend : { loadRollbackJournal: () => "journal" in entryRead ? Promise.resolve(entryRead.journal) : Promise.reject(entryRead.error) }, stackName, regionForState, state.orphans, logger);
12460
+ refuseDivergentRecordRegionForDestroy(state, stackName, regionForState, ctx.divergentBodyRegion, refusalRecovery, journaledOrphans.segments.flatMap((g) => g.ops).filter((op) => op.physicalIdRecoveredFromError === true).length);
12461
+ return journaledOrphans;
12462
+ }
12463
+ async function destroyEmptyStack({ stackName, ctx, logger, stackLockBase, regionForState, refusalRecovery, journaledOrphans, result }) {
12464
+ logger.info(`Stack ${displayStackName(stackName)} has no resources, cleaning up state...`);
12465
+ const emptyLock = await acquireStackLock({
12466
+ ...stackLockBase,
12467
+ onFirstSignal: () => {
12468
+ process.stderr.write(`\nInterrupt received - finishing the state cleanup for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12469
+ }
12470
+ });
12471
+ try {
12472
+ const recheck = await ctx.stateBackend.getState(stackName, regionForState);
12473
+ if (recheck) {
12474
+ refuseMalformedResourcesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12475
+ refuseMalformedResourceEntriesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12476
+ refuseMalformedOrphansForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12477
+ refuseMalformedOrphanRecordsForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12478
+ refusePendingMovesOut(recheck.state, stackName, regionForState, "cdkd destroy");
12479
+ }
12480
+ refuseRefactorMarker(await readRefactorMarker(ctx.stateBackend), stackName, regionForState, "cdkd destroy");
12481
+ const recheckResources = recheck ? Object.keys(recheck.state.resources).length : 0;
12482
+ const recheckOrphans = recheck ? (recheck.state.orphans ?? []).length : 0;
12483
+ const recheckRead = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, recheck?.state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12484
+ const recheckJournaled = recheckRead.count;
12485
+ refuseNewPendingRequests(recheckRead, stackName, regionForState);
12486
+ if (recheckJournaled > 0) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but its rollback journal now records ${recheckJournaled} resource(s) a failed deploy created — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12487
+ if (!(!recheck || recheckResources === 0 && recheckOrphans === 0 && !holdsSupersededResources(recheck.state))) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but now has ${recheckResources} resource(s) and ${recheckOrphans} rollback-orphaned resource(s) — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12488
+ await ctx.stateBackend.deleteState(stackName, regionForState);
12489
+ result.stateDeleted = true;
12490
+ logger.info(`${green("✓")} State deleted`);
12491
+ await Promise.all([recordRetainedForReadoption(ctx.stateBackend, stackName, regionForState, [], logger).then(() => purgeStateHistoryIfOptedIn(ctx, stackName, regionForState)), releaseRegistryMarkerAfterDestroy(ctx, stackName, regionForState, logger)]);
12492
+ } finally {
12493
+ await emptyLock.release({ failureMessage: "Failed to release lock after empty-state cleanup" });
12494
+ }
12495
+ result.skippedEmpty = true;
12496
+ return result;
12497
+ }
12498
+ async function announceOrphansAndConfirm({ state, logger, stackNoEchoValues, journaledOrphans, ctx, stackName, resourceCount, protectedCount, result }) {
12499
+ const orphansAtDestroy = state.orphans ?? [];
12500
+ if (orphansAtDestroy.length > 0) {
12501
+ logger.info(`\n${orphansAtDestroy.length} resource(s) are still in AWS from an earlier failed deploy. cdkd left them there because their DeletionPolicy is Retain (CDK's RemovalPolicy.RETAIN), and has been tracking them so a later deploy of this stack could adopt them back instead of colliding with their names.`);
12502
+ logger.info("Destroying this stack deletes that record. The resources stay in AWS, may continue to incur charges, and cdkd will no longer know about them:");
12503
+ const orphanListing = orphanRecordsPrintingBag(orphansAtDestroy, await stackNoEchoValues());
12504
+ for (const entry of orphansAtDestroy) withPrintingSecrets(orphanListing, () => logger.info(` - ${displaySafe(entry.logicalId)} (${displaySafe(entry.state.resourceType)}) ${displaySafe(entry.state.physicalId)}`));
12505
+ }
12506
+ if (journaledOrphans.count > 0) {
12507
+ logger.info(`\n${journaledOrphans.count} resource(s) were created by a failed deploy and are recorded only in the rollback journal. Each is deleted first as its DeletionPolicy directs (Retain keeps it in AWS, Snapshot takes the final snapshot), unless state or a later deploy may own it, which is warned about instead:`);
12508
+ const listing = journaledOrphanPrintingBag(journaledOrphans.segments.flatMap(({ ops }) => ops), state.resources, await stackNoEchoValues());
12509
+ withPrintingSecrets(listing, () => {
12510
+ for (const line of journaledOrphanLines(journaledOrphans, logger)) logger.info(line);
12511
+ });
12512
+ }
12513
+ if (!ctx.skipConfirmation) {
12514
+ if (process.stdin.isTTY !== true) throw new CdkdError(`The destroy confirmation prompt for stack ${displayStackName(stackName)} cannot run in a non-interactive environment. Pass --yes / -y to confirm the destroy (cdkd destroy also accepts -f / --force), or run the command from a real terminal.`, "NON_INTERACTIVE_CONFIRM");
12515
+ const rl = readline$1.createInterface({
12516
+ input: process.stdin,
12517
+ output: process.stdout
12518
+ });
12519
+ const journaledClause = journaledOrphans.count > 0 ? ` and ${journaledOrphans.count} recorded only in its rollback journal` : "";
12520
+ const prompt = ctx.removeProtection ? `\nAbout to destroy ${resourceCount} resources${journaledClause} from stack ${displayStackName(stackName)}, REMOVING DELETION PROTECTION on ${protectedCount} of them. Continue? (y/N): ` : `\nAre you sure you want to destroy stack ${displayStackName(stackName)} and delete all ${resourceCount} resources${journaledClause}? (Y/n): `;
12521
+ const answer = await rl.question(prompt);
12522
+ rl.close();
12523
+ const trimmed = answer.trim().toLowerCase();
12524
+ if (ctx.removeProtection) {
12525
+ if (trimmed !== "y" && trimmed !== "yes") {
12526
+ logger.info("Destroy cancelled");
12527
+ result.cancelled = true;
12528
+ return result;
12529
+ }
12530
+ } else if (trimmed === "n" || trimmed === "no") {
12531
+ logger.info("Destroy cancelled");
12532
+ result.cancelled = true;
12533
+ return result;
12534
+ }
12535
+ }
12536
+ }
12537
+
12335
12538
  // src/provisioning/secret-principal-resolution.ts
12336
12539
  const TRANSIENT_RESOLUTION_MESSAGE = "Resolving a secret-derived IAM principal list was throttled or hit a server error";
12337
12540
  function resolvableVerdict(verdict) {
@@ -12444,313 +12647,471 @@ function resolvablePrincipalLists(resource) {
12444
12647
  return keys.map((key) => props[key]).filter((value) => isResolvableSecretPrincipalList(value));
12445
12648
  }
12446
12649
 
12447
- // src/cli/commands/destroy-runner.ts
12448
- const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12449
- async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12450
- if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12650
+ // src/cli/commands/destroy-runner/under-lock-steps.ts
12651
+ async function recheckUnderLock({ ctx, stackName, state, regionForState, refusalRecovery, lock, restoreBaseRegionAndClients, needsStrongRefCheck }) {
12652
+ try {
12653
+ const [current, marker] = await Promise.all([ctx.stateBackend.getState(stackName, regionForState), readRefactorMarker(ctx.stateBackend)]);
12654
+ if (current === null || !holdsSameResourcesAs(state, current.state)) throw new CdkdError(safeMsg`cdkd destroy refused stack ${stackName} (${regionForState}): its state ` + "changed after it was read (another command wrote it while this one waited for confirmation), so nothing was deleted. Re-run cdkd destroy.", "STATE_CHANGED");
12655
+ if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12656
+ args: accountArgs(refusalRecovery),
12657
+ clause: withheldAccountClause(refusalRecovery, "the command below prints")
12658
+ }, {
12659
+ command: ctx.stateDestroy === true ? "cdkd state destroy" : "cdkd destroy",
12660
+ stackRegion: regionForState
12661
+ });
12662
+ refusePendingMovesOut(current.state, stackName, regionForState, "cdkd destroy");
12663
+ refuseRefactorMarker(marker, stackName, regionForState, "cdkd destroy");
12664
+ } catch (error) {
12665
+ await lock.release({ failureMessage: "Failed to release lock after a state re-check refusal" });
12666
+ restoreBaseRegionAndClients();
12667
+ throw error;
12668
+ }
12669
+ if (needsStrongRefCheck) {
12670
+ const releaseThenUnregister = async () => {
12671
+ await lock.release({ failureMessage: "Failed to release lock after strong-ref refusal/failure" });
12672
+ restoreBaseRegionAndClients();
12673
+ };
12674
+ let consumers;
12675
+ try {
12676
+ consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12677
+ } catch (error) {
12678
+ await releaseThenUnregister();
12679
+ throw error;
12680
+ }
12681
+ if (consumers.length > 0) {
12682
+ await releaseThenUnregister();
12683
+ throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12684
+ }
12685
+ }
12451
12686
  }
12452
- const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12453
- function maskedSnapshotLogger(logger, mask) {
12687
+ function makeSummaryHints(regionForState, refusalRecovery) {
12688
+ const hintCommand = (command, t) => pasteableCommand(command, [
12689
+ {
12690
+ value: t,
12691
+ hole: "stack",
12692
+ opts: { plainIdent: true }
12693
+ },
12694
+ {
12695
+ flag: "--stack-region",
12696
+ value: regionForState,
12697
+ hole: "region",
12698
+ opts: { plainIdent: true }
12699
+ },
12700
+ ...accountArgs(refusalRecovery)
12701
+ ]);
12702
+ const hintFor = (command, targets, label) => [...new Set(targets.map((t) => `\n${label}: ${hintCommand(command, t).command}`))].join("");
12703
+ const hintHolesClause = (targets) => (targets.every((t) => hintCommand("cdkd state show", t).withheld.every((w) => w.hole !== "stack" && w.hole !== "region")) ? "" : " A target that is not a plain identifier is printed as a quoted '<stack>' or '<region>' placeholder; list the records as stored with 'cdkd state list --long'.") + (targets.length === 0 ? "" : ((clause) => clause === "" ? "" : ` ${clause}`)(withheldAccountClause(refusalRecovery, "the command lines below print").trimEnd()));
12454
12704
  return {
12455
- info: (message) => logger.info(mask(message)),
12456
- debug: (message) => logger.debug(mask(message))
12705
+ hintFor,
12706
+ hintHolesClause
12457
12707
  };
12458
12708
  }
12459
- function recordDestroyEvent(recorder, event) {
12460
- recorder?.record(maskEventTextWithBoundBags(event));
12709
+ async function reReadJournaledOrphansUnderLock({ ctx, stackName, regionForState, state, journaledOrphans, logger }) {
12710
+ const journaledUnderLock = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12711
+ if (journaledUnderLock.unreadable === true && journaledOrphans.unreadable !== true) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was readable when this run started and cannot be read now (see the warning above). Nothing was deleted; re-run the destroy once it can be read.`);
12712
+ refuseNewPendingRequests(journaledUnderLock, stackName, regionForState);
12713
+ if (!sameJournaledOrphans(journaledUnderLock, journaledOrphans)) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) recorded ${journaledOrphans.count} resource(s) a failed deploy created when this run started and ${journaledUnderLock.count} now, not the same ones — another cdkd process wrote to it. Nothing was deleted; re-run the destroy to act on the current journal.`);
12714
+ return journaledUnderLock;
12461
12715
  }
12462
- const SKIPPED_REMEDY = "Each 'skipped (...)' line above names its cause, and its warning says whether repairing the record in state.json helps. Where it does, repair it and re-run. Otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand, then drop the records.";
12463
- function countProtectedResources(state) {
12464
- let count = 0;
12465
- const records = [...Object.values(state.resources ?? {}), ...supersededResourcesOf(state).map((entry) => entry.state)];
12466
- for (const resource of records) {
12467
- const locator = perType(PROTECTION_PROPERTY_BY_TYPE, resource.resourceType);
12468
- if (locator) {
12469
- const isActive = (recorded) => isProtectionValueActive(resource.resourceType, recorded);
12470
- if (isActive(readProtection(resource.properties, locator, state.region)) || isActive(readProtection(resource.observedProperties, locator, state.region))) count++;
12471
- continue;
12716
+ function buildDeleteGraph(state, logger) {
12717
+ logger.info("Building dependency graph...");
12718
+ const template = {
12719
+ AWSTemplateFormatVersion: "2010-09-09",
12720
+ Resources: {}
12721
+ };
12722
+ for (const [logicalId, resource] of Object.entries(state.resources)) template.Resources[logicalId] = {
12723
+ Type: resource.resourceType,
12724
+ Properties: resource.properties || {},
12725
+ ...resource.dependencies && resource.dependencies.length > 0 && { DependsOn: resource.dependencies }
12726
+ };
12727
+ const blockingResources = { ...template.Resources };
12728
+ const typeToLogicalIds = /* @__PURE__ */ new Map();
12729
+ for (const [logicalId, resource] of Object.entries(state.resources)) {
12730
+ const ids = typeToLogicalIds.get(resource.resourceType) ?? [];
12731
+ ids.push(logicalId);
12732
+ typeToLogicalIds.set(resource.resourceType, ids);
12733
+ }
12734
+ for (const [logicalId, resource] of Object.entries(state.resources)) {
12735
+ const mustDeleteAfter = IMPLICIT_DELETE_DEPENDENCIES[resource.resourceType];
12736
+ if (!mustDeleteAfter) continue;
12737
+ for (const depType of mustDeleteAfter) {
12738
+ const depIds = typeToLogicalIds.get(depType);
12739
+ if (!depIds) continue;
12740
+ for (const depId of depIds) {
12741
+ const existing = template.Resources[depId]?.DependsOn ?? [];
12742
+ const depsArray = Array.isArray(existing) ? existing : [existing];
12743
+ if (!depsArray.includes(logicalId)) {
12744
+ template.Resources[depId] = {
12745
+ ...template.Resources[depId],
12746
+ DependsOn: [...depsArray, logicalId]
12747
+ };
12748
+ logger.debug(`Implicit delete dependency: ${displaySafe(depId)} (${displaySafe(depType)}) must be deleted before ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12749
+ }
12750
+ }
12472
12751
  }
12473
12752
  }
12474
- return count;
12475
- }
12476
- function countProtectedJournaledOrphans(orphans, region) {
12477
- let count = 0;
12478
- for (const { ops } of orphans.segments) for (const op of ops) {
12479
- if (op.physicalIdRecoveredFromError !== true || op.deletionPolicy === "Retain") continue;
12480
- if (orphanNeedsIdentity(op) && !op.createdResourceIdentity) continue;
12481
- const locator = perType(PROTECTION_PROPERTY_BY_TYPE, op.resourceType);
12482
- if (locator && isProtectionValueActive(op.resourceType, readProtection(op.attemptedProperties, locator, region))) count++;
12483
- }
12484
- return count;
12485
- }
12486
- async function releaseRegistryMarkerAfterDestroy(ctx, stackName, region, logger) {
12487
- if (ctx.crossPrefixCheck === void 0) return;
12488
- try {
12489
- const known = await ctx.crossPrefixCheck.cache.knownMarker?.(stackName, region);
12490
- const released = await ctx.stateBackend.releaseRegistryMarker(stackName, region, known);
12491
- logger.debug(safeMsg`Stack registry marker: ${released}`);
12492
- } catch (error) {
12493
- logger.warn(safeMsg`Could not delete the stack registry marker of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}). It names this state prefix, which no longer ` + `records the stack, so a deploy under another prefix treats it as stale.`);
12494
- }
12495
- }
12496
- function holdsSameResourcesAs(snapshot, current) {
12497
- return isDeepStrictEqual(snapshot.resources, current.resources) && isDeepStrictEqual(snapshot.supersededResources, current.supersededResources);
12498
- }
12499
- async function runDestroyForStack(stackName, state, ctx) {
12500
- const stackRegion = state.region;
12501
- if (!stackRegion || stackRegion === ctx.baseRegion) return destroyStackInRegion(stackName, state, ctx, void 0);
12502
- const scopeClients = new AwsClients({
12503
- region: stackRegion,
12504
- ...ctx.profile && { profile: ctx.profile }
12505
- });
12506
- try {
12507
- const awsScope = {
12508
- region: stackRegion,
12509
- clients: scopeClients
12753
+ for (const { before, after } of computeImplicitDeleteEdges(state.resources)) {
12754
+ const blocking = blockingResources[before]?.DependsOn ?? [];
12755
+ const blockingArray = Array.isArray(blocking) ? blocking : [blocking];
12756
+ if (!blockingArray.includes(after)) blockingResources[before] = {
12757
+ ...blockingResources[before],
12758
+ DependsOn: [...blockingArray, after]
12510
12759
  };
12511
- const nestedContext = getCurrentNestedStackContext();
12512
- return await runInStackAwsScope(awsScope, () => {
12513
- const registry = new ProviderRegistry();
12514
- const destroyInScope = () => destroyStackInRegion(stackName, state, ctx, {
12515
- clients: scopeClients,
12516
- registry
12517
- });
12518
- return nestedContext === void 0 ? destroyInScope() : withNestedStackContext({
12519
- ...nestedContext,
12520
- providerRegistry: registry,
12521
- awsClients: scopeClients
12522
- }, destroyInScope);
12523
- });
12524
- } finally {
12525
- try {
12526
- scopeClients.destroy();
12527
- } catch (destroyError) {
12528
- getLogger().debug(`Failed to destroy region-scoped AWS clients: ${describeAwsFailure(destroyError).detail}`);
12760
+ const existing = template.Resources[before]?.DependsOn ?? [];
12761
+ const depsArray = Array.isArray(existing) ? existing : [existing];
12762
+ if (!depsArray.includes(after)) {
12763
+ template.Resources[before] = {
12764
+ ...template.Resources[before],
12765
+ DependsOn: [...depsArray, after]
12766
+ };
12767
+ logger.debug(`Implicit delete dependency: ${displaySafe(before)} (${displaySafe(state.resources[before]?.resourceType)}) must be deleted before ${displaySafe(after)} (${displaySafe(state.resources[after]?.resourceType)})`);
12529
12768
  }
12530
12769
  }
12531
- }
12532
- async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12533
- const providerClasses = await loadProviderClasses();
12534
- const logger = getLogger();
12535
- const result = {
12536
- stackName,
12537
- cancelled: false,
12538
- skippedEmpty: false,
12539
- deletedCount: 0,
12540
- retainedCount: 0,
12541
- skippedCount: 0,
12542
- guardIndeterminateCount: 0,
12543
- journaledOrphanSkips: 0,
12544
- stateDeleted: false,
12545
- blockedCount: 0,
12546
- errorCount: 0,
12547
- interrupted: false
12548
- };
12549
- const retainedForReadoption = [];
12550
- let retainedEarlier;
12551
- const guardIndeterminateTargets = /* @__PURE__ */ new Set();
12552
- const regionForState = state.region ?? ctx.baseRegion;
12553
- const crossPrefixScan = ctx.crossPrefixCheck?.cache.full(stackName, regionForState);
12554
- const refusalRecovery = {
12555
- profile: ctx.profile,
12556
- stateBucket: ctx.stateBucket,
12557
- statePrefix: ctx.statePrefix
12558
- };
12559
- const stackLockBase = {
12560
- lockManager: ctx.lockManager,
12561
- stackName,
12562
- region: regionForState,
12563
- operation: "destroy",
12564
- recovery: refusalRecovery
12770
+ const dagBuilder = new DagBuilder();
12771
+ const graph = dagBuilder.buildGraph(template);
12772
+ const blockingGraph = dagBuilder.buildGraph({
12773
+ ...template,
12774
+ Resources: blockingResources
12775
+ });
12776
+ const executionLevels = dagBuilder.getExecutionLevels(graph);
12777
+ logger.debug(`Dependency graph: ${executionLevels.length} level(s)`);
12778
+ return {
12779
+ dagBuilder,
12780
+ blockingGraph,
12781
+ executionLevels
12565
12782
  };
12566
- refuseMalformedResourcesForDestroy(state, stackName, regionForState, refusalRecovery);
12567
- refuseMalformedResourceEntriesForDestroy(state, stackName, regionForState, refusalRecovery);
12568
- refuseMalformedResourcePropertiesForDestroy(state, stackName, regionForState, refusalRecovery);
12569
- refuseMalformedOrphansForDestroy(state, stackName, regionForState, refusalRecovery);
12570
- refuseMalformedOrphanRecordsForDestroy(state, stackName, regionForState, refusalRecovery);
12571
- refusePendingMovesOut(state, stackName, regionForState, "cdkd destroy");
12572
- let journalAtEntry;
12573
- try {
12574
- journalAtEntry = { journal: await ctx.stateBackend.loadRollbackJournal(stackName, regionForState) };
12575
- } catch (error) {
12576
- journalAtEntry = { error };
12783
+ }
12784
+ function makePrintingBagOf({ ctx, state, noEchoValues, stackName, logger }) {
12785
+ const reresolver = ctx.noEchoReresolver;
12786
+ const judgedBagOf = secretNamePrintingBags(state.resources, reresolver === void 0 ? noEchoValues : namingSecretsWithRecordedNoEcho(noEchoValues, (logicalId) => {
12787
+ try {
12788
+ return reresolver.recordedNoEchoValuesFor(logicalId, Object.hasOwn(state.resources, logicalId) ? state.resources[logicalId] : void 0);
12789
+ } catch (error) {
12790
+ logger.debug(safeMsg`Could not read ${logicalId}'s stored NoEcho values for its printing bag (${error instanceof Error ? error.name : typeof error}).`);
12791
+ return;
12792
+ }
12793
+ }));
12794
+ const namingScope = nameScopeOf(stackName, stackInstanceIdOf(state, displayStackName(stackName)), state);
12795
+ const printingBagOf = (logicalId) => withStackScope(namingScope, () => judgedBagOf(logicalId));
12796
+ return printingBagOf;
12797
+ }
12798
+ function printDestroySummary({ result, ctx, stackName, logger, preserveState, guardIndeterminateTargets, skippedStateTargets, failedStateTargets, hintFor, hintHolesClause, journaledOrphanFailures }) {
12799
+ const retainedSuffix = result.retainedCount > 0 ? `, ${result.retainedCount} retained` : "";
12800
+ const skippedSuffix = (result.skippedCount > 0 ? `, ${yellow(result.skippedCount)} skipped` : "") + (result.blockedCount > 0 ? `, ${yellow(result.blockedCount)} blocked` : "");
12801
+ const guardSuffix = result.guardIndeterminateCount > 0 ? `, ${yellow(result.guardIndeterminateCount)} unverified` : "";
12802
+ if (result.guardIndeterminateCount > 0) {
12803
+ const eventsCommand = pasteableCommand("cdkd events", [{
12804
+ value: stackName,
12805
+ hole: "stack",
12806
+ opts: { plainIdent: true }
12807
+ }]);
12808
+ const durablePointer = ctx.eventRecorder === void 0 ? "This summary is the only record: this run wrote no deployment events, because it destroyed a nested-stack child, which threads no event recorder." : "The RESOURCE_GUARD_INDETERMINATE entries name the check and the reason and survive the run." + withheldTargetClause(eventsCommand, "stack", "cdkd events", "This stack's name") + `\nRead them with: ${eventsCommand.command}`;
12809
+ logger.warn(`\n${yellow("⚠")} ${result.guardIndeterminateCount} pre-flight safety check(s) could NOT be completed during this destroy and cdkd proceeded anyway: ${[...guardIndeterminateTargets].map((t) => plainOrDescribed(t, "logical id")).join(", ")}. A check can be suppressed by DENYING the permission it needs, so treat this as unconfirmed rather than benign. ${durablePointer}`);
12810
+ }
12811
+ if (result.journaledOrphanSkips > 0) logger.warn(safeMsg`${result.journaledOrphanSkips} resource(s) a failed deploy created were left in AWS (each named in a ` + "warning above, which says what to do with it). This stack no longer records them.");
12812
+ if (!preserveState) {
12813
+ const leftInAws = result.journaledOrphanSkips > 0;
12814
+ logger.info(`\n${leftInAws ? yellow("⚠") : green("✓")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} ${leftInAws ? "destroyed, with resources left in AWS" : "destroyed"}`)} (${green(result.deletedCount)} deleted${retainedSuffix}${leftInAws ? skippedSuffix : ""}${guardSuffix}, ${result.errorCount} errors)`);
12815
+ } else if (result.interrupted && result.errorCount === 0) logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} destroy interrupted`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to finish.`);
12816
+ else if (result.errorCount === 0) {
12817
+ const targets = [...skippedStateTargets];
12818
+ const showHint = hintFor("cdkd state show", targets, "Inspect it with");
12819
+ const orphanHint = hintFor("cdkd state orphan", targets, "Drop the record with");
12820
+ logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). cdkd did not confirm the skipped resource(s) were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` + hintHolesClause(targets) + showHint + orphanHint);
12821
+ } else {
12822
+ const failedTargets = failedStateTargets.size > 0 ? [...failedStateTargets] : [stackName];
12823
+ const orphanHint = journaledOrphanFailures > 0 ? "" : hintFor("cdkd state orphan", failedTargets, "Drop the record with");
12824
+ const skippedTargets = [...skippedStateTargets];
12825
+ const skippedClause = skippedTargets.length > 0 ? ` Separately, ${result.skippedCount} resource(s) were SKIPPED — cdkd did not confirm they were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` : "";
12826
+ const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
12827
+ const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
12828
+ const dedupedCommands = (lines) => [...new Set(lines.split("\n").filter((l) => l !== ""))].map((l) => `\n${l}`).join("");
12829
+ logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${red(result.errorCount)} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to clean up. ` + (journaledOrphanFailures > 0 ? `${journaledOrphanFailures} of the failures are resources a failed deploy created that only the rollback journal records: re-run the destroy to retry them. Do not drop this stack's state record — that also deletes the journal, their only record.` : "If the same resource keeps failing, dropping the state record is the last resort: it removes the record without deleting AWS resources.") + skippedClause + hintHolesClause([...orphanHint === "" ? [] : failedTargets, ...skippedTargets]) + dedupedCommands(orphanHint + skippedCommands));
12830
+ }
12831
+ }
12832
+
12833
+ // src/cli/commands/destroy-runner/delete-resource.ts
12834
+ async function deleteStackResource({ lock, state, ctx, stackName, logger, result, renderer, blockedBy, blockedIds, blockDependenciesOf, retainedForReadoption, startRetainedEarlierRead, skippedStateTargets, failedStateTargets, stateTargetFor, guardIndeterminateTargets, remainingResources, persistStateAfterDelete, printingBagOf, destroyProviderRegistry, destroyAwsClients, secretPrincipalRegions, secretPrincipalRegionsIncomplete }, logicalId, stackRegion) {
12835
+ if (lock.interrupted) return;
12836
+ const resource = state.resources[logicalId];
12837
+ if (!resource) {
12838
+ logger.warn(`Resource ${displaySafe(logicalId)} not found in state, skipping`);
12839
+ return;
12577
12840
  }
12578
- if (ctx.divergentBodyRegion !== void 0 && "journal" in journalAtEntry && pendingRequestCount(journalAtEntry.journal) > 0) {
12579
- const ids = (journalAtEntry.journal?.segments ?? []).flatMap((segment) => segment.failedOperations ?? []).filter((op) => op.pendingCloudControlRequest !== void 0).map((op) => op.logicalId);
12580
- const drop = dropFailedCommands(stackName, regionForState, ids);
12581
- throw new CdkdError(`Stack ${displayStackName(stackName)}'s state record names another region than its key, and its rollback journal records a Cloud Control CREATE a failed deploy stopped waiting for. cdkd cannot tell which region to check it in. Nothing was deleted. Check the request in each region with aws cloudcontrol get-resource-request-status --request-token <token> --region <region> (the token is in the stack's rollback-journal.json), reconcile what it made by hand, then drop the entry and re-run:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")), "DESTROY_CC_PENDING_REQUEST_DIVERGENT_REGION");
12841
+ const blocker = blockedBy.get(logicalId);
12842
+ if (blocker !== void 0) {
12843
+ const blockReason = `${blocker} depends on it and its delete failed`;
12844
+ logger.info(safeMsg` ${formatResourceLine("skipped", logicalId, resource.resourceType, `not deleted (${blockReason})`)}`);
12845
+ result.blockedCount++;
12846
+ blockedIds.push(logicalId);
12847
+ recordDestroyEvent(ctx.eventRecorder, {
12848
+ eventType: "RESOURCE_SKIPPED",
12849
+ stackName,
12850
+ operation: "DELETE",
12851
+ logicalId,
12852
+ resourceType: resource.resourceType,
12853
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12854
+ ...resource.physicalId && { physicalId: resource.physicalId },
12855
+ reason: blockReason
12856
+ });
12857
+ return;
12582
12858
  }
12583
- const journalRewritten = await resolvePendingCloudControlRequests({
12584
- journal: ctx.stateBackend,
12585
- loaded: "journal" in journalAtEntry ? journalAtEntry.journal : null,
12586
- reader: () => new CloudControlProvider(),
12587
- stackName,
12588
- region: regionForState,
12589
- command: "destroy",
12590
- logger,
12591
- stateResources: state.resources,
12592
- stackInstanceId: stackInstanceIdOf(state, displayStackName(stackName)),
12593
- underLock: async (settle) => {
12594
- const held = await acquireStackLock({
12595
- ...stackLockBase,
12596
- onFirstSignal: () => {
12597
- process.stderr.write(`\nInterrupt received - finishing the Cloud Control request check for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12598
- }
12859
+ if (shouldRetainResource(resource.deletionPolicy)) {
12860
+ logger.info(` ⊘ ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) retained — DeletionPolicy: ${displaySafe(resource.deletionPolicy)}`);
12861
+ result.retainedCount++;
12862
+ if (keptForRetainedRecord(resource)) {
12863
+ retainedForReadoption.push({
12864
+ logicalId,
12865
+ resourceType: resource.resourceType,
12866
+ physicalId: resource.physicalId
12599
12867
  });
12600
- try {
12601
- return await settle();
12602
- } finally {
12603
- await held.release({ failureMessage: "Failed to release lock after settling an abandoned Cloud Control request" });
12604
- }
12868
+ startRetainedEarlierRead();
12605
12869
  }
12606
- });
12607
- const entryRead = journalAtEntry;
12608
- const journaledOrphans = await loadJournaledOrphans(journalRewritten ? ctx.stateBackend : { loadRollbackJournal: () => "journal" in entryRead ? Promise.resolve(entryRead.journal) : Promise.reject(entryRead.error) }, stackName, regionForState, state.orphans, logger);
12609
- refuseDivergentRecordRegionForDestroy(state, stackName, regionForState, ctx.divergentBodyRegion, refusalRecovery, journaledOrphans.segments.flatMap((g) => g.ops).filter((op) => op.physicalIdRecoveredFromError === true).length);
12610
- const resourceCount = Object.keys(state.resources).length;
12611
- const orphanCount = (state.orphans ?? []).length;
12612
- const supersededCount = supersededResourcesOf(state).length;
12613
- refuseMalformedOutputsForDestroy(state, stackName, regionForState, refusalRecovery);
12614
- if (crossPrefixScan) applyCrossPrefixScan(await crossPrefixScan, {
12870
+ recordDestroyEvent(ctx.eventRecorder, {
12871
+ eventType: "RESOURCE_RETAINED",
12872
+ stackName,
12873
+ operation: "DELETE",
12874
+ logicalId,
12875
+ resourceType: resource.resourceType,
12876
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
12877
+ });
12878
+ return;
12879
+ }
12880
+ if (resource.resourceType !== "AWS::CloudFormation::Stack" && (typeof resource.physicalId !== "string" || resource.physicalId.trim() === "")) {
12881
+ const skipReason = "state record has no physical id";
12882
+ logger.warn(`Resource ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has no non-empty string 'physicalId' in its state record, so cdkd cannot address it in AWS and did not try to delete it. Repairing the record in state.json and re-running helps; the record is kept.`);
12883
+ logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
12884
+ result.skippedCount++;
12885
+ skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
12886
+ recordDestroyEvent(ctx.eventRecorder, {
12887
+ eventType: "RESOURCE_SKIPPED",
12888
+ stackName,
12889
+ operation: "DELETE",
12890
+ logicalId,
12891
+ resourceType: resource.resourceType,
12892
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12893
+ reason: skipReason
12894
+ });
12895
+ return;
12896
+ }
12897
+ const baseLabel = `Deleting ${logicalId} (${resource.resourceType})`;
12898
+ renderer.addTask(logicalId, baseLabel);
12899
+ const resourceStartedAt = Date.now();
12900
+ recordDestroyEvent(ctx.eventRecorder, {
12901
+ eventType: "RESOURCE_STARTED",
12615
12902
  stackName,
12616
- region: regionForState,
12617
- bucket: ctx.stateBucket,
12618
- recovery: {
12619
- profile: ctx.profile,
12620
- stateBucket: ctx.stateBucket
12903
+ operation: "DELETE",
12904
+ logicalId,
12905
+ resourceType: resource.resourceType,
12906
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
12907
+ });
12908
+ try {
12909
+ let finalSnapshotIdentifier;
12910
+ const policy = effectiveDeletionPolicy(resource.resourceType, resource.deletionPolicy, resource.properties);
12911
+ if (policy === "Snapshot" && ctx.skipFinalSnapshot !== true) {
12912
+ if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType) && resource.provisionedBy !== "cc-api") finalSnapshotIdentifier = buildFinalSnapshotIdentifier(resource.physicalId, resource.resourceType);
12913
+ else if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType)) {
12914
+ if (!await ccRoutedInstanceTakesNoSnapshot({
12915
+ resourceType: resource.resourceType,
12916
+ logicalId,
12917
+ physicalId: resource.physicalId,
12918
+ region: stackRegion,
12919
+ logger,
12920
+ mask: createUnionSecretMasker([printingBagOf(logicalId)])
12921
+ })) throw ccRoutedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
12922
+ } else if (PRE_DELETE_SNAPSHOT_TYPES.has(resource.resourceType)) await createPreDeleteFinalSnapshot(resource.resourceType, resource.physicalId, logicalId, destroyAwsClients ?? ctx.baseAwsClients, maskedSnapshotLogger(logger, createUnionSecretMasker([printingBagOf(logicalId)])));
12923
+ else throw unsupportedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
12621
12924
  }
12622
- }, "destroy", (message) => logger.warn(message), (message) => logger.info(message));
12623
- if (resourceCount === 0 && orphanCount === 0 && !holdsSupersededResources(state) && journaledOrphans.count === 0) {
12624
- logger.info(`Stack ${displayStackName(stackName)} has no resources, cleaning up state...`);
12625
- const emptyLock = await acquireStackLock({
12626
- ...stackLockBase,
12627
- onFirstSignal: () => {
12628
- process.stderr.write(`\nInterrupt received - finishing the state cleanup for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12629
- }
12925
+ const provider = destroyProviderRegistry.getProviderFor({
12926
+ resourceType: resource.resourceType,
12927
+ provisionedBy: resource.provisionedBy
12928
+ }).provider;
12929
+ const providerMinTimeoutMs = provider.getMinResourceTimeoutMs?.() ?? 0;
12930
+ const warnAfterMs = ctx.resourceWarnAfterByType?.[resource.resourceType] ?? ctx.resourceWarnAfterMs ?? 3e5;
12931
+ const globalTimeoutMs = ctx.resourceTimeoutMs ?? 18e5;
12932
+ const slowTypeMinTimeoutMs = slowCcOperationTimeoutMs(resource.resourceType, "DELETE");
12933
+ const timeoutMs = ctx.resourceTimeoutByType?.[resource.resourceType] ?? Math.max(providerMinTimeoutMs, slowTypeMinTimeoutMs, globalTimeoutMs);
12934
+ let deleteResult;
12935
+ let childLeftInAws = 0;
12936
+ const recordedRegions = secretPrincipalRegions !== void 0 ? recordedReferenceRegions(resource) : void 0;
12937
+ const secretPrincipalOptIn = secretPrincipalRegions !== void 0 ? {
12938
+ importedProducerRegions: secretPrincipalRegions,
12939
+ ...secretPrincipalRegionsIncomplete && { producerRegionsIncomplete: true },
12940
+ retryMemo: { detached: /* @__PURE__ */ new Set() },
12941
+ ...recordedRegions !== void 0 && { recordedRegions }
12942
+ } : void 0;
12943
+ await withResourceDeadline(async () => {
12944
+ const maxAttempts = provider.disableOuterRetry ? 0 : 3;
12945
+ const noEchoDeleteValues = readsNoEchoDeleteValues(resource.resourceType) ? await ctx.noEchoReresolver?.valuesFor(logicalId, resource) : void 0;
12946
+ let lastDeleteError;
12947
+ for (let attempt = 0; attempt <= maxAttempts; attempt++) try {
12948
+ const { value: outcome, unaddressed } = await runDeleteAttempt(attempt >= maxAttempts, () => collectNestedChildUnaddressed(() => withStackRecords(destroyStackRecordsView(state.resources), () => provider.delete(logicalId, resource.physicalId, resource.resourceType, resource.properties, {
12949
+ ...state.region !== void 0 && { expectedRegion: state.region },
12950
+ ...ctx.removeProtection === true && { removeProtection: true },
12951
+ ...finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier },
12952
+ deletionPolicy: policy ?? "Delete",
12953
+ ...ctx.skipFinalSnapshot === true && { skipFinalSnapshot: true },
12954
+ ...secretPrincipalOptIn !== void 0 && { resolveSecretDerivedPrincipals: secretPrincipalOptIn },
12955
+ recordedAttributes: resource.attributes,
12956
+ recordedNoEchoLeaves: resource.noEchoLeaves,
12957
+ ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
12958
+ ...ctx.noEchoReresolver !== void 0 && { noEchoReresolver: ctx.noEchoReresolver },
12959
+ ...ctx.stackDestroy === true && { stackDestroy: true },
12960
+ maskSecrets: createUnionSecretMasker([printingBagOf(logicalId)])
12961
+ }))));
12962
+ deleteResult = outcome ?? void 0;
12963
+ childLeftInAws = unaddressed?.deleteSkipped ?? 0;
12964
+ lastDeleteError = null;
12965
+ break;
12966
+ } catch (retryError) {
12967
+ lastDeleteError = retryError;
12968
+ const classify = retryClassificationText(retryError);
12969
+ if (!(!isMarkedNonRetryable(retryError) && (isRetryableTransientError(retryError, classify) || classify.includes("Too Many Requests"))) || attempt >= maxAttempts) break;
12970
+ const delay = 5e3 * Math.pow(2, attempt);
12971
+ logger.debug(` ⏳ Retrying delete ${displaySafe(logicalId)} in ${delay / 1e3}s (attempt ${attempt + 1}/${maxAttempts})`);
12972
+ await new Promise((resolve) => setTimeout(resolve, delay));
12973
+ }
12974
+ if (lastDeleteError) throw lastDeleteError;
12975
+ }, {
12976
+ warnAfterMs,
12977
+ timeoutMs,
12978
+ onWarn: (elapsedMs) => {
12979
+ const minutes = Math.max(1, Math.round(elapsedMs / 6e4));
12980
+ renderer.updateTaskLabel(logicalId, `${baseLabel} [taking longer than expected, ${minutes}m+]`);
12981
+ renderer.printAbove(() => {
12982
+ logger.warn(`${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has been deleting for ${minutes}m — still waiting`);
12983
+ });
12984
+ },
12985
+ onTimeout: (elapsedMs) => new ResourceTimeoutError(logicalId, resource.resourceType, stackRegion, elapsedMs, "DELETE", timeoutMs)
12630
12986
  });
12631
- try {
12632
- const recheck = await ctx.stateBackend.getState(stackName, regionForState);
12633
- if (recheck) {
12634
- refuseMalformedResourcesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12635
- refuseMalformedResourceEntriesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12636
- refuseMalformedOrphansForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12637
- refuseMalformedOrphanRecordsForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12638
- refusePendingMovesOut(recheck.state, stackName, regionForState, "cdkd destroy");
12639
- }
12640
- refuseRefactorMarker(await readRefactorMarker(ctx.stateBackend), stackName, regionForState, "cdkd destroy");
12641
- const recheckResources = recheck ? Object.keys(recheck.state.resources).length : 0;
12642
- const recheckOrphans = recheck ? (recheck.state.orphans ?? []).length : 0;
12643
- const recheckRead = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, recheck?.state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12644
- const recheckJournaled = recheckRead.count;
12645
- refuseNewPendingRequests(recheckRead, stackName, regionForState);
12646
- if (recheckJournaled > 0) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but its rollback journal now records ${recheckJournaled} resource(s) a failed deploy created — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12647
- if (!(!recheck || recheckResources === 0 && recheckOrphans === 0 && !holdsSupersededResources(recheck.state))) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but now has ${recheckResources} resource(s) and ${recheckOrphans} rollback-orphaned resource(s) — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12648
- await ctx.stateBackend.deleteState(stackName, regionForState);
12649
- result.stateDeleted = true;
12650
- logger.info(`${green("✓")} State deleted`);
12651
- await Promise.all([recordRetainedForReadoption(ctx.stateBackend, stackName, regionForState, [], logger).then(() => purgeStateHistoryIfOptedIn(ctx, stackName, regionForState)), releaseRegistryMarkerAfterDestroy(ctx, stackName, regionForState, logger)]);
12652
- } finally {
12653
- await emptyLock.release({ failureMessage: "Failed to release lock after empty-state cleanup" });
12987
+ renderer.removeTask(logicalId);
12988
+ for (const guard of deleteIndeterminateGuards(deleteResult)) {
12989
+ result.guardIndeterminateCount++;
12990
+ guardIndeterminateTargets.add(logicalId);
12991
+ recordDestroyEvent(ctx.eventRecorder, {
12992
+ eventType: "RESOURCE_GUARD_INDETERMINATE",
12993
+ stackName,
12994
+ operation: "DELETE",
12995
+ logicalId,
12996
+ resourceType: resource.resourceType,
12997
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12998
+ ...resource.physicalId && { physicalId: resource.physicalId },
12999
+ guard: guard.guard,
13000
+ reason: guard.reason
13001
+ });
12654
13002
  }
12655
- result.skippedEmpty = true;
12656
- return result;
12657
- }
12658
- const needsStrongRefCheck = !!(state.outputs && Object.keys(state.outputs).length > 0);
12659
- if (needsStrongRefCheck) {
12660
- const consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12661
- if (consumers.length > 0) throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12662
- }
12663
- logger.info(`\nResources to be deleted (${resourceCount}):`);
12664
- for (const [logicalId, resource] of Object.entries(state.resources)) logger.info(` - ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12665
- if (supersededCount > 0) {
12666
- logger.info(safeMsg`\nOld resources a replacement left to delete (${supersededCount}):`);
12667
- for (const entry of supersededResourcesOf(state)) logger.info(safeMsg` - ${entry.logicalId} (${entry.state.resourceType}), superseded`);
12668
- }
12669
- const protectedCount = ctx.removeProtection ? countProtectedResources(state) + countProtectedJournaledOrphans(journaledOrphans, state.region) : 0;
12670
- let binding;
12671
- const stackNoEchoValues = () => {
12672
- if (binding === void 0) {
12673
- let timer;
12674
- const capped = new Promise((resolve) => {
12675
- timer = setTimeout(() => {
12676
- logger.warn(safeMsg`The stack's NoEcho values were not bound within ${NOECHO_PRINTING_BIND_CAP_MS / 1e3}s, ` + "so a resource name taken from one may print unmasked where state holds it in plaintext (state written before schema v11).");
12677
- resolve(void 0);
12678
- }, NOECHO_PRINTING_BIND_CAP_MS);
12679
- timer.unref?.();
13003
+ if (deleteResult?.outcome === "skipped") {
13004
+ const skipReason = deleteSkipReason(deleteResult) ?? "no reason reported by the provider";
13005
+ logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
13006
+ result.skippedCount++;
13007
+ skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13008
+ recordDestroyEvent(ctx.eventRecorder, {
13009
+ eventType: "RESOURCE_SKIPPED",
13010
+ stackName,
13011
+ operation: "DELETE",
13012
+ logicalId,
13013
+ resourceType: resource.resourceType,
13014
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13015
+ ...resource.physicalId && { physicalId: resource.physicalId },
13016
+ reason: skipReason,
13017
+ durationMs: Date.now() - resourceStartedAt
12680
13018
  });
12681
- binding = {
12682
- bound: Promise.resolve().then(() => ctx.noEchoReresolver?.printingNoEchoValues()).catch(() => void 0).finally(() => clearTimeout(timer)),
12683
- capped
12684
- };
13019
+ return;
12685
13020
  }
12686
- return Promise.race([binding.bound, binding.capped]);
12687
- };
12688
- const orphansAtDestroy = state.orphans ?? [];
12689
- if (orphansAtDestroy.length > 0) {
12690
- logger.info(`\n${orphansAtDestroy.length} resource(s) are still in AWS from an earlier failed deploy. cdkd left them there because their DeletionPolicy is Retain (CDK's RemovalPolicy.RETAIN), and has been tracking them so a later deploy of this stack could adopt them back instead of colliding with their names.`);
12691
- logger.info("Destroying this stack deletes that record. The resources stay in AWS, may continue to incur charges, and cdkd will no longer know about them:");
12692
- const orphanListing = orphanRecordsPrintingBag(orphansAtDestroy, await stackNoEchoValues());
12693
- for (const entry of orphansAtDestroy) withPrintingSecrets(orphanListing, () => logger.info(` - ${displaySafe(entry.logicalId)} (${displaySafe(entry.state.resourceType)}) ${displaySafe(entry.state.physicalId)}`));
12694
- }
12695
- if (journaledOrphans.count > 0) {
12696
- logger.info(`\n${journaledOrphans.count} resource(s) were created by a failed deploy and are recorded only in the rollback journal. Each is deleted first as its DeletionPolicy directs (Retain keeps it in AWS, Snapshot takes the final snapshot), unless state or a later deploy may own it, which is warned about instead:`);
12697
- const listing = journaledOrphanPrintingBag(journaledOrphans.segments.flatMap(({ ops }) => ops), state.resources, await stackNoEchoValues());
12698
- withPrintingSecrets(listing, () => {
12699
- for (const line of journaledOrphanLines(journaledOrphans, logger)) logger.info(line);
13021
+ const leftInAws = childLeftInAws > 0 ? deleteLeftInPlace(deleteResult) ?? `${childLeftInAws} resource(s) a failed deploy created were left in AWS` : void 0;
13022
+ const deletedLine = leftInAws !== void 0 ? formatResourceLine("skipped", logicalId, resource.resourceType, `deleted (${leftInAws})`) : formatResourceLine("deleted", logicalId, resource.resourceType);
13023
+ logger.info(` ${deletedLine}`);
13024
+ result.skippedCount += childLeftInAws;
13025
+ result.journaledOrphanSkips += childLeftInAws;
13026
+ result.deletedCount++;
13027
+ recordDestroyEvent(ctx.eventRecorder, {
13028
+ eventType: "RESOURCE_SUCCEEDED",
13029
+ stackName,
13030
+ operation: "DELETE",
13031
+ logicalId,
13032
+ resourceType: resource.resourceType,
13033
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13034
+ ...resource.physicalId && { physicalId: resource.physicalId },
13035
+ durationMs: Date.now() - resourceStartedAt
12700
13036
  });
12701
- }
12702
- if (!ctx.skipConfirmation) {
12703
- if (process.stdin.isTTY !== true) throw new CdkdError(`The destroy confirmation prompt for stack ${displayStackName(stackName)} cannot run in a non-interactive environment. Pass --yes / -y to confirm the destroy (cdkd destroy also accepts -f / --force), or run the command from a real terminal.`, "NON_INTERACTIVE_CONFIRM");
12704
- const rl = readline$1.createInterface({
12705
- input: process.stdin,
12706
- output: process.stdout
13037
+ if (leftInAws !== void 0) recordDestroyEvent(ctx.eventRecorder, {
13038
+ eventType: "RESOURCE_SKIPPED",
13039
+ stackName,
13040
+ operation: "DELETE",
13041
+ logicalId,
13042
+ resourceType: resource.resourceType,
13043
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13044
+ reason: leftInAws,
13045
+ durationMs: Date.now() - resourceStartedAt
12707
13046
  });
12708
- const journaledClause = journaledOrphans.count > 0 ? ` and ${journaledOrphans.count} recorded only in its rollback journal` : "";
12709
- const prompt = ctx.removeProtection ? `\nAbout to destroy ${resourceCount} resources${journaledClause} from stack ${displayStackName(stackName)}, REMOVING DELETION PROTECTION on ${protectedCount} of them. Continue? (y/N): ` : `\nAre you sure you want to destroy stack ${displayStackName(stackName)} and delete all ${resourceCount} resources${journaledClause}? (Y/n): `;
12710
- const answer = await rl.question(prompt);
12711
- rl.close();
12712
- const trimmed = answer.trim().toLowerCase();
12713
- if (ctx.removeProtection) {
12714
- if (trimmed !== "y" && trimmed !== "yes") {
12715
- logger.info("Destroy cancelled");
12716
- result.cancelled = true;
12717
- return result;
12718
- }
12719
- } else if (trimmed === "n" || trimmed === "no") {
12720
- logger.info("Destroy cancelled");
12721
- result.cancelled = true;
12722
- return result;
13047
+ delete remainingResources[logicalId];
13048
+ persistStateAfterDelete(logicalId);
13049
+ } catch (error) {
13050
+ renderer.removeTask(logicalId);
13051
+ const msg = describeAwsFailure(error).detail;
13052
+ if (!isInterruptedWaitError(error) && !isFinalSnapshotError(error) && !isMarkedNonRetryable(error) && !isWaitAbandonedError(error) && !isMarkedNotGone(error) && (msg.includes("does not exist") || msg.includes("not found") || msg.includes("No policy found") || msg.includes("NoSuchEntity") || msg.includes("NotFoundException"))) {
13053
+ logger.debug(` ${displaySafe(logicalId)} already deleted, removing from state`);
13054
+ result.deletedCount++;
13055
+ recordDestroyEvent(ctx.eventRecorder, {
13056
+ eventType: "RESOURCE_SUCCEEDED",
13057
+ stackName,
13058
+ operation: "DELETE",
13059
+ logicalId,
13060
+ resourceType: resource.resourceType,
13061
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13062
+ ...resource.physicalId && { physicalId: resource.physicalId },
13063
+ durationMs: Date.now() - resourceStartedAt
13064
+ });
13065
+ delete remainingResources[logicalId];
13066
+ persistStateAfterDelete(logicalId);
13067
+ } else if (error instanceof ResourceTimeoutError) {
13068
+ const wrapped = new ProvisioningError(error.message, resource.resourceType, logicalId, resource.physicalId, error);
13069
+ logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, wrapped.message);
13070
+ result.errorCount++;
13071
+ failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13072
+ blockDependenciesOf(logicalId);
13073
+ recordDestroyEvent(ctx.eventRecorder, {
13074
+ eventType: "RESOURCE_FAILED",
13075
+ stackName,
13076
+ operation: "DELETE",
13077
+ logicalId,
13078
+ resourceType: resource.resourceType,
13079
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13080
+ durationMs: Date.now() - resourceStartedAt,
13081
+ error: extractDeploymentEventError(wrapped)
13082
+ });
13083
+ } else {
13084
+ logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, safeStringify(error));
13085
+ result.errorCount++;
13086
+ failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13087
+ blockDependenciesOf(logicalId);
13088
+ recordDestroyEvent(ctx.eventRecorder, {
13089
+ eventType: "RESOURCE_FAILED",
13090
+ stackName,
13091
+ operation: "DELETE",
13092
+ logicalId,
13093
+ resourceType: resource.resourceType,
13094
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13095
+ durationMs: Date.now() - resourceStartedAt,
13096
+ error: extractDeploymentEventError(error)
13097
+ });
12723
13098
  }
13099
+ } finally {
13100
+ renderer.removeTask(logicalId);
12724
13101
  }
12725
- const stackRegion = state.region;
12726
- let destroyProviderRegistry = ctx.providerRegistry;
12727
- let destroyAwsClients;
12728
- let regionSwitched = false;
12729
- const restoreBaseRegionAndClients = () => {
12730
- if (!regionSwitched) return;
12731
- regionSwitched = false;
12732
- destroyAwsClients = void 0;
12733
- process.env["AWS_REGION"] = ctx.baseRegion;
12734
- process.env["AWS_DEFAULT_REGION"] = ctx.baseRegion;
12735
- setAwsClients(ctx.baseAwsClients);
12736
- };
12737
- if (stackScope !== void 0 && stackRegion) {
12738
- logger.info(`Stack region: ${displaySafe(stackRegion, { asciiOnly: true })}`);
12739
- process.env["AWS_REGION"] = stackRegion;
12740
- process.env["AWS_DEFAULT_REGION"] = stackRegion;
12741
- regionSwitched = true;
12742
- try {
12743
- destroyAwsClients = stackScope.clients;
12744
- setAwsClients(destroyAwsClients);
12745
- destroyProviderRegistry = stackScope.registry;
12746
- registerAllProviders(destroyProviderRegistry, providerClasses);
12747
- destroyProviderRegistry.setCustomResourceResponseBucket(ctx.stateBucket);
12748
- if (ctx.allowUnsupportedTypes?.length) destroyProviderRegistry.allowUnsupportedTypes(ctx.allowUnsupportedTypes);
12749
- } catch (setupError) {
12750
- restoreBaseRegionAndClients();
12751
- throw setupError;
13102
+ }
13103
+
13104
+ // src/cli/commands/destroy-runner/under-lock.ts
13105
+ async function destroyStackUnderLock({ stackName, state, ctx, logger, result, regionForState, refusalRecovery, stackLockBase, journaledOrphans, needsStrongRefCheck, stackNoEchoValues, destroyProviderRegistry, destroyAwsClients, restoreBaseRegionAndClients }) {
13106
+ const retainedForReadoption = [];
13107
+ let retainedEarlier;
13108
+ const guardIndeterminateTargets = /* @__PURE__ */ new Set();
13109
+ const startRetainedEarlierRead = () => {
13110
+ if (retainedEarlier === void 0) {
13111
+ retainedEarlier = Promise.resolve().then(() => ctx.stateBackend.loadRetainedRecord(stackName, regionForState));
13112
+ retainedEarlier.catch(() => void 0);
12752
13113
  }
12753
- }
13114
+ };
12754
13115
  const renderer = getLiveRenderer();
12755
13116
  let statePreserved = false;
12756
13117
  let heldTail;
@@ -12769,61 +13130,22 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12769
13130
  },
12770
13131
  onAcquireFailure: restoreBaseRegionAndClients
12771
13132
  });
12772
- try {
12773
- const [current, marker] = await Promise.all([ctx.stateBackend.getState(stackName, regionForState), readRefactorMarker(ctx.stateBackend)]);
12774
- if (current === null || !holdsSameResourcesAs(state, current.state)) throw new CdkdError(safeMsg`cdkd destroy refused stack ${stackName} (${regionForState}): its state ` + "changed after it was read (another command wrote it while this one waited for confirmation), so nothing was deleted. Re-run cdkd destroy.", "STATE_CHANGED");
12775
- if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12776
- args: accountArgs(refusalRecovery),
12777
- clause: withheldAccountClause(refusalRecovery, "the command below prints")
12778
- }, {
12779
- command: ctx.stateDestroy === true ? "cdkd state destroy" : "cdkd destroy",
12780
- stackRegion: regionForState
12781
- });
12782
- refusePendingMovesOut(current.state, stackName, regionForState, "cdkd destroy");
12783
- refuseRefactorMarker(marker, stackName, regionForState, "cdkd destroy");
12784
- } catch (error) {
12785
- await lock.release({ failureMessage: "Failed to release lock after a state re-check refusal" });
12786
- restoreBaseRegionAndClients();
12787
- throw error;
12788
- }
12789
- if (needsStrongRefCheck) {
12790
- const releaseThenUnregister = async () => {
12791
- await lock.release({ failureMessage: "Failed to release lock after strong-ref refusal/failure" });
12792
- restoreBaseRegionAndClients();
12793
- };
12794
- let consumers;
12795
- try {
12796
- consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12797
- } catch (error) {
12798
- await releaseThenUnregister();
12799
- throw error;
12800
- }
12801
- if (consumers.length > 0) {
12802
- await releaseThenUnregister();
12803
- throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12804
- }
12805
- }
13133
+ await recheckUnderLock({
13134
+ ctx,
13135
+ stackName,
13136
+ state,
13137
+ regionForState,
13138
+ refusalRecovery,
13139
+ lock,
13140
+ restoreBaseRegionAndClients,
13141
+ needsStrongRefCheck
13142
+ });
12806
13143
  const remainingResources = { ...state.resources };
12807
13144
  let remainingSuperseded = state.supersededResources;
12808
- const stateTargetFor = (logicalId, resourceType) => resourceType === NESTED_STACK_TYPE ? `${stackName}~${logicalId}` : stackName;
13145
+ const stateTargetFor = (logicalId, resourceType) => resourceType === "AWS::CloudFormation::Stack" ? `${stackName}~${logicalId}` : stackName;
12809
13146
  const skippedStateTargets = /* @__PURE__ */ new Set();
12810
13147
  const failedStateTargets = /* @__PURE__ */ new Set();
12811
- const hintCommand = (command, t) => pasteableCommand(command, [
12812
- {
12813
- value: t,
12814
- hole: "stack",
12815
- opts: { plainIdent: true }
12816
- },
12817
- {
12818
- flag: "--stack-region",
12819
- value: regionForState,
12820
- hole: "region",
12821
- opts: { plainIdent: true }
12822
- },
12823
- ...accountArgs(refusalRecovery)
12824
- ]);
12825
- const hintFor = (command, targets, label) => [...new Set(targets.map((t) => `\n${label}: ${hintCommand(command, t).command}`))].join("");
12826
- const hintHolesClause = (targets) => (targets.every((t) => hintCommand("cdkd state show", t).withheld.every((w) => w.hole !== "stack" && w.hole !== "region")) ? "" : " A target that is not a plain identifier is printed as a quoted '<stack>' or '<region>' placeholder; list the records as stored with 'cdkd state list --long'.") + (targets.length === 0 ? "" : ((clause) => clause === "" ? "" : ` ${clause}`)(withheldAccountClause(refusalRecovery, "the command lines below print").trimEnd()));
13148
+ const { hintFor, hintHolesClause } = makeSummaryHints(regionForState, refusalRecovery);
12827
13149
  let secretPrincipalRegions;
12828
13150
  let secretPrincipalRegionsIncomplete = false;
12829
13151
  const buildDestroySnapshot = () => {
@@ -12860,10 +13182,14 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12860
13182
  if (secretPrincipalRegionsIncomplete && Object.values(state.resources ?? {}).some((r) => holdsUnprovenSecretPrincipalRecord(r))) logger.warn(safeMsg`${stackName}: this nested child is destroyed without its parent stack, so the regions its parent reads from are unknown: a secret-derived principal record whose reference has no recorded region is skipped. To resolve it, destroy it through its parent stack (the top-level stack that holds it).`);
12861
13183
  renderer.start();
12862
13184
  stackNoEchoValues();
12863
- const journaledUnderLock = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12864
- if (journaledUnderLock.unreadable === true && journaledOrphans.unreadable !== true) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was readable when this run started and cannot be read now (see the warning above). Nothing was deleted; re-run the destroy once it can be read.`);
12865
- refuseNewPendingRequests(journaledUnderLock, stackName, regionForState);
12866
- if (!sameJournaledOrphans(journaledUnderLock, journaledOrphans)) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) recorded ${journaledOrphans.count} resource(s) a failed deploy created when this run started and ${journaledUnderLock.count} now, not the same ones — another cdkd process wrote to it. Nothing was deleted; re-run the destroy to act on the current journal.`);
13185
+ const journaledUnderLock = await reReadJournaledOrphansUnderLock({
13186
+ ctx,
13187
+ stackName,
13188
+ regionForState,
13189
+ state,
13190
+ journaledOrphans,
13191
+ logger
13192
+ });
12867
13193
  const noEchoValues = await stackNoEchoValues();
12868
13194
  if (journaledUnderLock.count > 0) {
12869
13195
  const orphanOutcome = await deleteJournaledOrphans(journaledUnderLock, { ...state.resources }, stackName, stackInstanceIdOf(state, displayStackName(stackName)), {
@@ -12895,83 +13221,44 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12895
13221
  logger.warn(safeMsg`Failed to strip the deleted journal entries (a re-run repeats their deletes): ${describeAwsFailure(stripError).detail}`);
12896
13222
  }
12897
13223
  }
12898
- logger.info("Building dependency graph...");
12899
- const template = {
12900
- AWSTemplateFormatVersion: "2010-09-09",
12901
- Resources: {}
12902
- };
12903
- for (const [logicalId, resource] of Object.entries(state.resources)) template.Resources[logicalId] = {
12904
- Type: resource.resourceType,
12905
- Properties: resource.properties || {},
12906
- ...resource.dependencies && resource.dependencies.length > 0 && { DependsOn: resource.dependencies }
12907
- };
12908
- const blockingResources = { ...template.Resources };
12909
- const typeToLogicalIds = /* @__PURE__ */ new Map();
12910
- for (const [logicalId, resource] of Object.entries(state.resources)) {
12911
- const ids = typeToLogicalIds.get(resource.resourceType) ?? [];
12912
- ids.push(logicalId);
12913
- typeToLogicalIds.set(resource.resourceType, ids);
12914
- }
12915
- for (const [logicalId, resource] of Object.entries(state.resources)) {
12916
- const mustDeleteAfter = IMPLICIT_DELETE_DEPENDENCIES[resource.resourceType];
12917
- if (!mustDeleteAfter) continue;
12918
- for (const depType of mustDeleteAfter) {
12919
- const depIds = typeToLogicalIds.get(depType);
12920
- if (!depIds) continue;
12921
- for (const depId of depIds) {
12922
- const existing = template.Resources[depId]?.DependsOn ?? [];
12923
- const depsArray = Array.isArray(existing) ? existing : [existing];
12924
- if (!depsArray.includes(logicalId)) {
12925
- template.Resources[depId] = {
12926
- ...template.Resources[depId],
12927
- DependsOn: [...depsArray, logicalId]
12928
- };
12929
- logger.debug(`Implicit delete dependency: ${displaySafe(depId)} (${displaySafe(depType)}) must be deleted before ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12930
- }
12931
- }
12932
- }
12933
- }
12934
- for (const { before, after } of computeImplicitDeleteEdges(state.resources)) {
12935
- const blocking = blockingResources[before]?.DependsOn ?? [];
12936
- const blockingArray = Array.isArray(blocking) ? blocking : [blocking];
12937
- if (!blockingArray.includes(after)) blockingResources[before] = {
12938
- ...blockingResources[before],
12939
- DependsOn: [...blockingArray, after]
12940
- };
12941
- const existing = template.Resources[before]?.DependsOn ?? [];
12942
- const depsArray = Array.isArray(existing) ? existing : [existing];
12943
- if (!depsArray.includes(after)) {
12944
- template.Resources[before] = {
12945
- ...template.Resources[before],
12946
- DependsOn: [...depsArray, after]
12947
- };
12948
- logger.debug(`Implicit delete dependency: ${displaySafe(before)} (${displaySafe(state.resources[before]?.resourceType)}) must be deleted before ${displaySafe(after)} (${displaySafe(state.resources[after]?.resourceType)})`);
12949
- }
12950
- }
12951
- const dagBuilder = new DagBuilder();
12952
- const graph = dagBuilder.buildGraph(template);
12953
- const blockingGraph = dagBuilder.buildGraph({
12954
- ...template,
12955
- Resources: blockingResources
12956
- });
12957
- const executionLevels = dagBuilder.getExecutionLevels(graph);
12958
- logger.debug(`Dependency graph: ${executionLevels.length} level(s)`);
13224
+ const { dagBuilder, blockingGraph, executionLevels } = buildDeleteGraph(state, logger);
12959
13225
  const blockedBy = /* @__PURE__ */ new Map();
12960
13226
  const blockedIds = [];
12961
13227
  const blockDependenciesOf = (logicalId) => {
12962
13228
  for (const dependency of dagBuilder.getAllDependencies(blockingGraph, logicalId)) if (!blockedBy.has(dependency)) blockedBy.set(dependency, logicalId);
12963
13229
  };
12964
- const reresolver = ctx.noEchoReresolver;
12965
- const judgedBagOf = secretNamePrintingBags(state.resources, reresolver === void 0 ? noEchoValues : namingSecretsWithRecordedNoEcho(noEchoValues, (logicalId) => {
12966
- try {
12967
- return reresolver.recordedNoEchoValuesFor(logicalId, Object.hasOwn(state.resources, logicalId) ? state.resources[logicalId] : void 0);
12968
- } catch (error) {
12969
- logger.debug(safeMsg`Could not read ${logicalId}'s stored NoEcho values for its printing bag (${error instanceof Error ? error.name : typeof error}).`);
12970
- return;
12971
- }
12972
- }));
12973
- const namingScope = nameScopeOf(stackName, stackInstanceIdOf(state, displayStackName(stackName)), state);
12974
- const printingBagOf = (logicalId) => withStackScope(namingScope, () => judgedBagOf(logicalId));
13230
+ const printingBagOf = makePrintingBagOf({
13231
+ ctx,
13232
+ state,
13233
+ noEchoValues,
13234
+ stackName,
13235
+ logger
13236
+ });
13237
+ const resourceFrame = {
13238
+ lock,
13239
+ state,
13240
+ ctx,
13241
+ stackName,
13242
+ logger,
13243
+ result,
13244
+ renderer,
13245
+ blockedBy,
13246
+ blockedIds,
13247
+ blockDependenciesOf,
13248
+ retainedForReadoption,
13249
+ startRetainedEarlierRead,
13250
+ skippedStateTargets,
13251
+ failedStateTargets,
13252
+ stateTargetFor,
13253
+ guardIndeterminateTargets,
13254
+ remainingResources,
13255
+ persistStateAfterDelete,
13256
+ printingBagOf,
13257
+ destroyProviderRegistry,
13258
+ destroyAwsClients,
13259
+ secretPrincipalRegions,
13260
+ secretPrincipalRegionsIncomplete
13261
+ };
12975
13262
  for (let levelIndex = executionLevels.length - 1; levelIndex >= 0; levelIndex--) {
12976
13263
  if (lock.interrupted) {
12977
13264
  logger.debug("Interrupted (draining) — not scheduling further deletion levels");
@@ -12981,270 +13268,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12981
13268
  if (!level) continue;
12982
13269
  logger.debug(`Deletion level ${executionLevels.length - levelIndex}/${executionLevels.length} (${level.length} resources)`);
12983
13270
  const stackRegion = state.region ?? ctx.baseRegion;
12984
- const deletePromises = level.map((logicalId) => withPrintingSecrets(printingBagOf(logicalId), async () => {
12985
- if (lock.interrupted) return;
12986
- const resource = state.resources[logicalId];
12987
- if (!resource) {
12988
- logger.warn(`Resource ${displaySafe(logicalId)} not found in state, skipping`);
12989
- return;
12990
- }
12991
- const blocker = blockedBy.get(logicalId);
12992
- if (blocker !== void 0) {
12993
- const blockReason = `${blocker} depends on it and its delete failed`;
12994
- logger.info(safeMsg` ${formatResourceLine("skipped", logicalId, resource.resourceType, `not deleted (${blockReason})`)}`);
12995
- result.blockedCount++;
12996
- blockedIds.push(logicalId);
12997
- recordDestroyEvent(ctx.eventRecorder, {
12998
- eventType: "RESOURCE_SKIPPED",
12999
- stackName,
13000
- operation: "DELETE",
13001
- logicalId,
13002
- resourceType: resource.resourceType,
13003
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13004
- ...resource.physicalId && { physicalId: resource.physicalId },
13005
- reason: blockReason
13006
- });
13007
- return;
13008
- }
13009
- if (shouldRetainResource(resource.deletionPolicy)) {
13010
- logger.info(` ⊘ ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) retained — DeletionPolicy: ${displaySafe(resource.deletionPolicy)}`);
13011
- result.retainedCount++;
13012
- if (keptForRetainedRecord(resource)) {
13013
- retainedForReadoption.push({
13014
- logicalId,
13015
- resourceType: resource.resourceType,
13016
- physicalId: resource.physicalId
13017
- });
13018
- if (retainedEarlier === void 0) {
13019
- retainedEarlier = Promise.resolve().then(() => ctx.stateBackend.loadRetainedRecord(stackName, regionForState));
13020
- retainedEarlier.catch(() => void 0);
13021
- }
13022
- }
13023
- recordDestroyEvent(ctx.eventRecorder, {
13024
- eventType: "RESOURCE_RETAINED",
13025
- stackName,
13026
- operation: "DELETE",
13027
- logicalId,
13028
- resourceType: resource.resourceType,
13029
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
13030
- });
13031
- return;
13032
- }
13033
- if (resource.resourceType !== NESTED_STACK_TYPE && (typeof resource.physicalId !== "string" || resource.physicalId.trim() === "")) {
13034
- const skipReason = "state record has no physical id";
13035
- logger.warn(`Resource ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has no non-empty string 'physicalId' in its state record, so cdkd cannot address it in AWS and did not try to delete it. Repairing the record in state.json and re-running helps; the record is kept.`);
13036
- logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
13037
- result.skippedCount++;
13038
- skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13039
- recordDestroyEvent(ctx.eventRecorder, {
13040
- eventType: "RESOURCE_SKIPPED",
13041
- stackName,
13042
- operation: "DELETE",
13043
- logicalId,
13044
- resourceType: resource.resourceType,
13045
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13046
- reason: skipReason
13047
- });
13048
- return;
13049
- }
13050
- const baseLabel = `Deleting ${logicalId} (${resource.resourceType})`;
13051
- renderer.addTask(logicalId, baseLabel);
13052
- const resourceStartedAt = Date.now();
13053
- recordDestroyEvent(ctx.eventRecorder, {
13054
- eventType: "RESOURCE_STARTED",
13055
- stackName,
13056
- operation: "DELETE",
13057
- logicalId,
13058
- resourceType: resource.resourceType,
13059
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
13060
- });
13061
- try {
13062
- let finalSnapshotIdentifier;
13063
- const policy = effectiveDeletionPolicy(resource.resourceType, resource.deletionPolicy, resource.properties);
13064
- if (policy === "Snapshot" && ctx.skipFinalSnapshot !== true) {
13065
- if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType) && resource.provisionedBy !== "cc-api") finalSnapshotIdentifier = buildFinalSnapshotIdentifier(resource.physicalId, resource.resourceType);
13066
- else if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType)) throw ccRoutedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
13067
- else if (PRE_DELETE_SNAPSHOT_TYPES.has(resource.resourceType)) await createPreDeleteFinalSnapshot(resource.resourceType, resource.physicalId, logicalId, destroyAwsClients ?? ctx.baseAwsClients, maskedSnapshotLogger(logger, createUnionSecretMasker([printingBagOf(logicalId)])));
13068
- else throw unsupportedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
13069
- }
13070
- const provider = destroyProviderRegistry.getProviderFor({
13071
- resourceType: resource.resourceType,
13072
- provisionedBy: resource.provisionedBy
13073
- }).provider;
13074
- const providerMinTimeoutMs = provider.getMinResourceTimeoutMs?.() ?? 0;
13075
- const warnAfterMs = ctx.resourceWarnAfterByType?.[resource.resourceType] ?? ctx.resourceWarnAfterMs ?? 3e5;
13076
- const globalTimeoutMs = ctx.resourceTimeoutMs ?? 18e5;
13077
- const slowTypeMinTimeoutMs = slowCcOperationTimeoutMs(resource.resourceType, "DELETE");
13078
- const timeoutMs = ctx.resourceTimeoutByType?.[resource.resourceType] ?? Math.max(providerMinTimeoutMs, slowTypeMinTimeoutMs, globalTimeoutMs);
13079
- let deleteResult;
13080
- let childLeftInAws = 0;
13081
- const recordedRegions = secretPrincipalRegions !== void 0 ? recordedReferenceRegions(resource) : void 0;
13082
- const secretPrincipalOptIn = secretPrincipalRegions !== void 0 ? {
13083
- importedProducerRegions: secretPrincipalRegions,
13084
- ...secretPrincipalRegionsIncomplete && { producerRegionsIncomplete: true },
13085
- retryMemo: { detached: /* @__PURE__ */ new Set() },
13086
- ...recordedRegions !== void 0 && { recordedRegions }
13087
- } : void 0;
13088
- await withResourceDeadline(async () => {
13089
- const maxAttempts = provider.disableOuterRetry ? 0 : 3;
13090
- const noEchoDeleteValues = readsNoEchoDeleteValues(resource.resourceType) ? await ctx.noEchoReresolver?.valuesFor(logicalId, resource) : void 0;
13091
- let lastDeleteError;
13092
- for (let attempt = 0; attempt <= maxAttempts; attempt++) try {
13093
- const { value: outcome, unaddressed } = await runDeleteAttempt(attempt >= maxAttempts, () => collectNestedChildUnaddressed(() => withStackRecords(destroyStackRecordsView(state.resources), () => provider.delete(logicalId, resource.physicalId, resource.resourceType, resource.properties, {
13094
- ...state.region !== void 0 && { expectedRegion: state.region },
13095
- ...ctx.removeProtection === true && { removeProtection: true },
13096
- ...finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier },
13097
- deletionPolicy: policy ?? "Delete",
13098
- ...ctx.skipFinalSnapshot === true && { skipFinalSnapshot: true },
13099
- ...secretPrincipalOptIn !== void 0 && { resolveSecretDerivedPrincipals: secretPrincipalOptIn },
13100
- recordedAttributes: resource.attributes,
13101
- recordedNoEchoLeaves: resource.noEchoLeaves,
13102
- ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
13103
- ...ctx.noEchoReresolver !== void 0 && { noEchoReresolver: ctx.noEchoReresolver },
13104
- ...ctx.stackDestroy === true && { stackDestroy: true },
13105
- maskSecrets: createUnionSecretMasker([printingBagOf(logicalId)])
13106
- }))));
13107
- deleteResult = outcome ?? void 0;
13108
- childLeftInAws = unaddressed?.deleteSkipped ?? 0;
13109
- lastDeleteError = null;
13110
- break;
13111
- } catch (retryError) {
13112
- lastDeleteError = retryError;
13113
- const classify = retryClassificationText(retryError);
13114
- if (!(!isMarkedNonRetryable(retryError) && (isRetryableTransientError(retryError, classify) || classify.includes("Too Many Requests"))) || attempt >= maxAttempts) break;
13115
- const delay = 5e3 * Math.pow(2, attempt);
13116
- logger.debug(` ⏳ Retrying delete ${displaySafe(logicalId)} in ${delay / 1e3}s (attempt ${attempt + 1}/${maxAttempts})`);
13117
- await new Promise((resolve) => setTimeout(resolve, delay));
13118
- }
13119
- if (lastDeleteError) throw lastDeleteError;
13120
- }, {
13121
- warnAfterMs,
13122
- timeoutMs,
13123
- onWarn: (elapsedMs) => {
13124
- const minutes = Math.max(1, Math.round(elapsedMs / 6e4));
13125
- renderer.updateTaskLabel(logicalId, `${baseLabel} [taking longer than expected, ${minutes}m+]`);
13126
- renderer.printAbove(() => {
13127
- logger.warn(`${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has been deleting for ${minutes}m — still waiting`);
13128
- });
13129
- },
13130
- onTimeout: (elapsedMs) => new ResourceTimeoutError(logicalId, resource.resourceType, stackRegion, elapsedMs, "DELETE", timeoutMs)
13131
- });
13132
- renderer.removeTask(logicalId);
13133
- for (const guard of deleteIndeterminateGuards(deleteResult)) {
13134
- result.guardIndeterminateCount++;
13135
- guardIndeterminateTargets.add(logicalId);
13136
- recordDestroyEvent(ctx.eventRecorder, {
13137
- eventType: "RESOURCE_GUARD_INDETERMINATE",
13138
- stackName,
13139
- operation: "DELETE",
13140
- logicalId,
13141
- resourceType: resource.resourceType,
13142
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13143
- ...resource.physicalId && { physicalId: resource.physicalId },
13144
- guard: guard.guard,
13145
- reason: guard.reason
13146
- });
13147
- }
13148
- if (deleteResult?.outcome === "skipped") {
13149
- const skipReason = deleteSkipReason(deleteResult) ?? "no reason reported by the provider";
13150
- logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
13151
- result.skippedCount++;
13152
- skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13153
- recordDestroyEvent(ctx.eventRecorder, {
13154
- eventType: "RESOURCE_SKIPPED",
13155
- stackName,
13156
- operation: "DELETE",
13157
- logicalId,
13158
- resourceType: resource.resourceType,
13159
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13160
- ...resource.physicalId && { physicalId: resource.physicalId },
13161
- reason: skipReason,
13162
- durationMs: Date.now() - resourceStartedAt
13163
- });
13164
- return;
13165
- }
13166
- const leftInAws = childLeftInAws > 0 ? deleteLeftInPlace(deleteResult) ?? `${childLeftInAws} resource(s) a failed deploy created were left in AWS` : void 0;
13167
- const deletedLine = leftInAws !== void 0 ? formatResourceLine("skipped", logicalId, resource.resourceType, `deleted (${leftInAws})`) : formatResourceLine("deleted", logicalId, resource.resourceType);
13168
- logger.info(` ${deletedLine}`);
13169
- result.skippedCount += childLeftInAws;
13170
- result.journaledOrphanSkips += childLeftInAws;
13171
- result.deletedCount++;
13172
- recordDestroyEvent(ctx.eventRecorder, {
13173
- eventType: "RESOURCE_SUCCEEDED",
13174
- stackName,
13175
- operation: "DELETE",
13176
- logicalId,
13177
- resourceType: resource.resourceType,
13178
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13179
- ...resource.physicalId && { physicalId: resource.physicalId },
13180
- durationMs: Date.now() - resourceStartedAt
13181
- });
13182
- if (leftInAws !== void 0) recordDestroyEvent(ctx.eventRecorder, {
13183
- eventType: "RESOURCE_SKIPPED",
13184
- stackName,
13185
- operation: "DELETE",
13186
- logicalId,
13187
- resourceType: resource.resourceType,
13188
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13189
- reason: leftInAws,
13190
- durationMs: Date.now() - resourceStartedAt
13191
- });
13192
- delete remainingResources[logicalId];
13193
- persistStateAfterDelete(logicalId);
13194
- } catch (error) {
13195
- renderer.removeTask(logicalId);
13196
- const msg = describeAwsFailure(error).detail;
13197
- if (!isInterruptedWaitError(error) && !isFinalSnapshotError(error) && !isMarkedNonRetryable(error) && !isWaitAbandonedError(error) && !isMarkedNotGone(error) && (msg.includes("does not exist") || msg.includes("not found") || msg.includes("No policy found") || msg.includes("NoSuchEntity") || msg.includes("NotFoundException"))) {
13198
- logger.debug(` ${displaySafe(logicalId)} already deleted, removing from state`);
13199
- result.deletedCount++;
13200
- recordDestroyEvent(ctx.eventRecorder, {
13201
- eventType: "RESOURCE_SUCCEEDED",
13202
- stackName,
13203
- operation: "DELETE",
13204
- logicalId,
13205
- resourceType: resource.resourceType,
13206
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13207
- ...resource.physicalId && { physicalId: resource.physicalId },
13208
- durationMs: Date.now() - resourceStartedAt
13209
- });
13210
- delete remainingResources[logicalId];
13211
- persistStateAfterDelete(logicalId);
13212
- } else if (error instanceof ResourceTimeoutError) {
13213
- const wrapped = new ProvisioningError(error.message, resource.resourceType, logicalId, resource.physicalId, error);
13214
- logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, wrapped.message);
13215
- result.errorCount++;
13216
- failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13217
- blockDependenciesOf(logicalId);
13218
- recordDestroyEvent(ctx.eventRecorder, {
13219
- eventType: "RESOURCE_FAILED",
13220
- stackName,
13221
- operation: "DELETE",
13222
- logicalId,
13223
- resourceType: resource.resourceType,
13224
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13225
- durationMs: Date.now() - resourceStartedAt,
13226
- error: extractDeploymentEventError(wrapped)
13227
- });
13228
- } else {
13229
- logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, safeStringify(error));
13230
- result.errorCount++;
13231
- failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13232
- blockDependenciesOf(logicalId);
13233
- recordDestroyEvent(ctx.eventRecorder, {
13234
- eventType: "RESOURCE_FAILED",
13235
- stackName,
13236
- operation: "DELETE",
13237
- logicalId,
13238
- resourceType: resource.resourceType,
13239
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13240
- durationMs: Date.now() - resourceStartedAt,
13241
- error: extractDeploymentEventError(error)
13242
- });
13243
- }
13244
- } finally {
13245
- renderer.removeTask(logicalId);
13246
- }
13247
- }));
13271
+ const deletePromises = level.map((logicalId) => withPrintingSecrets(printingBagOf(logicalId), () => deleteStackResource(resourceFrame, logicalId, stackRegion)));
13248
13272
  await Promise.all(deletePromises);
13249
13273
  }
13250
13274
  for (const entry of supersededResourcesOf(state)) {
@@ -13339,38 +13363,19 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13339
13363
  else logger.warn(`${result.skippedCount - result.journaledOrphanSkips} resource(s) skipped — cdkd did not confirm they were deleted, so they may still exist in AWS. State preserved (the records are kept so the resources stay traceable).`);
13340
13364
  if (result.blockedCount > 0) logger.warn(safeMsg`${result.blockedCount} resource(s) not deleted because the delete of a resource that ` + "depends on them failed, as CloudFormation leaves them: " + safeMsg`${blockedIds.map((id) => plainOrDescribed(id, "logical id")).join(", ")}. ` + "Their records are kept: once the resource blocking them is deleted, a re-run of 'cdkd destroy' / 'cdkd state destroy' deletes them.");
13341
13365
  }
13342
- const retainedSuffix = result.retainedCount > 0 ? `, ${result.retainedCount} retained` : "";
13343
- const skippedSuffix = (result.skippedCount > 0 ? `, ${yellow(result.skippedCount)} skipped` : "") + (result.blockedCount > 0 ? `, ${yellow(result.blockedCount)} blocked` : "");
13344
- const guardSuffix = result.guardIndeterminateCount > 0 ? `, ${yellow(result.guardIndeterminateCount)} unverified` : "";
13345
- if (result.guardIndeterminateCount > 0) {
13346
- const eventsCommand = pasteableCommand("cdkd events", [{
13347
- value: stackName,
13348
- hole: "stack",
13349
- opts: { plainIdent: true }
13350
- }]);
13351
- const durablePointer = ctx.eventRecorder === void 0 ? "This summary is the only record: this run wrote no deployment events, because it destroyed a nested-stack child, which threads no event recorder." : "The RESOURCE_GUARD_INDETERMINATE entries name the check and the reason and survive the run." + withheldTargetClause(eventsCommand, "stack", "cdkd events", "This stack's name") + `\nRead them with: ${eventsCommand.command}`;
13352
- logger.warn(`\n${yellow("⚠")} ${result.guardIndeterminateCount} pre-flight safety check(s) could NOT be completed during this destroy and cdkd proceeded anyway: ${[...guardIndeterminateTargets].map((t) => plainOrDescribed(t, "logical id")).join(", ")}. A check can be suppressed by DENYING the permission it needs, so treat this as unconfirmed rather than benign. ${durablePointer}`);
13353
- }
13354
- if (result.journaledOrphanSkips > 0) logger.warn(safeMsg`${result.journaledOrphanSkips} resource(s) a failed deploy created were left in AWS (each named in a ` + "warning above, which says what to do with it). This stack no longer records them.");
13355
- if (!preserveState) {
13356
- const leftInAws = result.journaledOrphanSkips > 0;
13357
- logger.info(`\n${leftInAws ? yellow("⚠") : green("✓")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} ${leftInAws ? "destroyed, with resources left in AWS" : "destroyed"}`)} (${green(result.deletedCount)} deleted${retainedSuffix}${leftInAws ? skippedSuffix : ""}${guardSuffix}, ${result.errorCount} errors)`);
13358
- } else if (result.interrupted && result.errorCount === 0) logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} destroy interrupted`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to finish.`);
13359
- else if (result.errorCount === 0) {
13360
- const targets = [...skippedStateTargets];
13361
- const showHint = hintFor("cdkd state show", targets, "Inspect it with");
13362
- const orphanHint = hintFor("cdkd state orphan", targets, "Drop the record with");
13363
- logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). cdkd did not confirm the skipped resource(s) were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` + hintHolesClause(targets) + showHint + orphanHint);
13364
- } else {
13365
- const failedTargets = failedStateTargets.size > 0 ? [...failedStateTargets] : [stackName];
13366
- const orphanHint = journaledOrphanFailures > 0 ? "" : hintFor("cdkd state orphan", failedTargets, "Drop the record with");
13367
- const skippedTargets = [...skippedStateTargets];
13368
- const skippedClause = skippedTargets.length > 0 ? ` Separately, ${result.skippedCount} resource(s) were SKIPPED — cdkd did not confirm they were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` : "";
13369
- const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
13370
- const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
13371
- const dedupedCommands = (lines) => [...new Set(lines.split("\n").filter((l) => l !== ""))].map((l) => `\n${l}`).join("");
13372
- logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${red(result.errorCount)} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to clean up. ` + (journaledOrphanFailures > 0 ? `${journaledOrphanFailures} of the failures are resources a failed deploy created that only the rollback journal records: re-run the destroy to retry them. Do not drop this stack's state record — that also deletes the journal, their only record.` : "If the same resource keeps failing, dropping the state record is the last resort: it removes the record without deleting AWS resources.") + skippedClause + hintHolesClause([...orphanHint === "" ? [] : failedTargets, ...skippedTargets]) + dedupedCommands(orphanHint + skippedCommands));
13373
- }
13366
+ printDestroySummary({
13367
+ result,
13368
+ ctx,
13369
+ stackName,
13370
+ logger,
13371
+ preserveState,
13372
+ guardIndeterminateTargets,
13373
+ skippedStateTargets,
13374
+ failedStateTargets,
13375
+ hintFor,
13376
+ hintHolesClause,
13377
+ journaledOrphanFailures
13378
+ });
13374
13379
  } finally {
13375
13380
  try {
13376
13381
  await lock.release({
@@ -13397,29 +13402,191 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13397
13402
  }
13398
13403
  return result;
13399
13404
  }
13400
- async function scanActiveConsumers(producerStack, producerRegion, ctx) {
13401
- const refs = await ctx.stateBackend.listStacks();
13402
- return (await Promise.all(refs.map(async (ref) => {
13403
- const region = ref.region ?? ctx.baseRegion;
13404
- if (ref.stackName === producerStack && region === producerRegion) return null;
13405
+
13406
+ // src/cli/commands/destroy-runner/run.ts
13407
+ async function runDestroyForStack(stackName, state, ctx) {
13408
+ const stackRegion = state.region;
13409
+ if (!stackRegion || stackRegion === ctx.baseRegion) return destroyStackInRegion(stackName, state, ctx, void 0);
13410
+ const scopeClients = new AwsClients({
13411
+ region: stackRegion,
13412
+ ...ctx.profile && { profile: ctx.profile }
13413
+ });
13414
+ try {
13415
+ const awsScope = {
13416
+ region: stackRegion,
13417
+ clients: scopeClients
13418
+ };
13419
+ const nestedContext = getCurrentNestedStackContext();
13420
+ return await runInStackAwsScope(awsScope, () => {
13421
+ const registry = new ProviderRegistry();
13422
+ const destroyInScope = () => destroyStackInRegion(stackName, state, ctx, {
13423
+ clients: scopeClients,
13424
+ registry
13425
+ });
13426
+ return nestedContext === void 0 ? destroyInScope() : withNestedStackContext({
13427
+ ...nestedContext,
13428
+ providerRegistry: registry,
13429
+ awsClients: scopeClients
13430
+ }, destroyInScope);
13431
+ });
13432
+ } finally {
13405
13433
  try {
13406
- const imports = (await ctx.stateBackend.getState(ref.stackName, region))?.state.imports;
13407
- if (!imports || imports.length === 0) return null;
13408
- const matches = imports.filter((entry) => entry.sourceStack === producerStack && canonicalizeRegion(entry.sourceRegion) === canonicalizeRegion(producerRegion));
13409
- if (matches.length === 0) return null;
13410
- return matches.map((entry) => ({
13411
- consumerStack: ref.stackName,
13412
- consumerRegion: region,
13413
- exportName: entry.exportName
13414
- }));
13415
- } catch {
13416
- return null;
13434
+ scopeClients.destroy();
13435
+ } catch (destroyError) {
13436
+ getLogger().debug(`Failed to destroy region-scoped AWS clients: ${describeAwsFailure(destroyError).detail}`);
13417
13437
  }
13418
- }))).filter((r) => r !== null).flat();
13438
+ }
13419
13439
  }
13420
- function refuseNewPendingRequests(read, stackName, region) {
13421
- if ((read.pendingRequests ?? 0) === 0) return;
13422
- throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(region, { asciiOnly: true })}) now records a Cloud Control CREATE a failed deploy stopped waiting for — another cdkd process wrote to it. Nothing was deleted; re-run the destroy, which checks how that CREATE ended first.`);
13440
+ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13441
+ const providerClasses = await loadProviderClasses();
13442
+ const logger = getLogger();
13443
+ const result = {
13444
+ stackName,
13445
+ cancelled: false,
13446
+ skippedEmpty: false,
13447
+ deletedCount: 0,
13448
+ retainedCount: 0,
13449
+ skippedCount: 0,
13450
+ guardIndeterminateCount: 0,
13451
+ journaledOrphanSkips: 0,
13452
+ stateDeleted: false,
13453
+ blockedCount: 0,
13454
+ errorCount: 0,
13455
+ interrupted: false
13456
+ };
13457
+ const regionForState = state.region ?? ctx.baseRegion;
13458
+ const crossPrefixScan = ctx.crossPrefixCheck?.cache.full(stackName, regionForState);
13459
+ const refusalRecovery = {
13460
+ profile: ctx.profile,
13461
+ stateBucket: ctx.stateBucket,
13462
+ statePrefix: ctx.statePrefix
13463
+ };
13464
+ const stackLockBase = {
13465
+ lockManager: ctx.lockManager,
13466
+ stackName,
13467
+ region: regionForState,
13468
+ operation: "destroy",
13469
+ recovery: refusalRecovery
13470
+ };
13471
+ const journaledOrphans = await refuseMalformedRecordAndLoadJournaledOrphans({
13472
+ state,
13473
+ stackName,
13474
+ regionForState,
13475
+ refusalRecovery,
13476
+ ctx,
13477
+ logger,
13478
+ stackLockBase
13479
+ });
13480
+ const resourceCount = Object.keys(state.resources).length;
13481
+ const orphanCount = (state.orphans ?? []).length;
13482
+ const supersededCount = supersededResourcesOf(state).length;
13483
+ refuseMalformedOutputsForDestroy(state, stackName, regionForState, refusalRecovery);
13484
+ if (crossPrefixScan) applyCrossPrefixScan(await crossPrefixScan, {
13485
+ stackName,
13486
+ region: regionForState,
13487
+ bucket: ctx.stateBucket,
13488
+ recovery: {
13489
+ profile: ctx.profile,
13490
+ stateBucket: ctx.stateBucket
13491
+ }
13492
+ }, "destroy", (message) => logger.warn(message), (message) => logger.info(message));
13493
+ if (resourceCount === 0 && orphanCount === 0 && !holdsSupersededResources(state) && journaledOrphans.count === 0) return destroyEmptyStack({
13494
+ stackName,
13495
+ ctx,
13496
+ logger,
13497
+ stackLockBase,
13498
+ regionForState,
13499
+ refusalRecovery,
13500
+ journaledOrphans,
13501
+ result
13502
+ });
13503
+ const needsStrongRefCheck = !!(state.outputs && Object.keys(state.outputs).length > 0);
13504
+ if (needsStrongRefCheck) {
13505
+ const consumers = await scanActiveConsumers(stackName, regionForState, ctx);
13506
+ if (consumers.length > 0) throw new StackHasActiveImportsError(stackName, regionForState, consumers);
13507
+ }
13508
+ logger.info(`\nResources to be deleted (${resourceCount}):`);
13509
+ for (const [logicalId, resource] of Object.entries(state.resources)) logger.info(` - ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
13510
+ if (supersededCount > 0) {
13511
+ logger.info(safeMsg`\nOld resources a replacement left to delete (${supersededCount}):`);
13512
+ for (const entry of supersededResourcesOf(state)) logger.info(safeMsg` - ${entry.logicalId} (${entry.state.resourceType}), superseded`);
13513
+ }
13514
+ const protectedCount = ctx.removeProtection ? countProtectedResources(state) + countProtectedJournaledOrphans(journaledOrphans, state.region) : 0;
13515
+ let binding;
13516
+ const stackNoEchoValues = () => {
13517
+ if (binding === void 0) {
13518
+ let timer;
13519
+ const capped = new Promise((resolve) => {
13520
+ timer = setTimeout(() => {
13521
+ logger.warn(safeMsg`The stack's NoEcho values were not bound within ${NOECHO_PRINTING_BIND_CAP_MS / 1e3}s, ` + "so a resource name taken from one may print unmasked where state holds it in plaintext (state written before schema v11).");
13522
+ resolve(void 0);
13523
+ }, NOECHO_PRINTING_BIND_CAP_MS);
13524
+ timer.unref?.();
13525
+ });
13526
+ binding = {
13527
+ bound: Promise.resolve().then(() => ctx.noEchoReresolver?.printingNoEchoValues()).catch(() => void 0).finally(() => clearTimeout(timer)),
13528
+ capped
13529
+ };
13530
+ }
13531
+ return Promise.race([binding.bound, binding.capped]);
13532
+ };
13533
+ const cancelled = await announceOrphansAndConfirm({
13534
+ state,
13535
+ logger,
13536
+ stackNoEchoValues,
13537
+ journaledOrphans,
13538
+ ctx,
13539
+ stackName,
13540
+ resourceCount,
13541
+ protectedCount,
13542
+ result
13543
+ });
13544
+ if (cancelled !== void 0) return cancelled;
13545
+ const stackRegion = state.region;
13546
+ let destroyProviderRegistry = ctx.providerRegistry;
13547
+ let destroyAwsClients;
13548
+ let regionSwitched = false;
13549
+ const restoreBaseRegionAndClients = () => {
13550
+ if (!regionSwitched) return;
13551
+ regionSwitched = false;
13552
+ destroyAwsClients = void 0;
13553
+ process.env["AWS_REGION"] = ctx.baseRegion;
13554
+ process.env["AWS_DEFAULT_REGION"] = ctx.baseRegion;
13555
+ setAwsClients(ctx.baseAwsClients);
13556
+ };
13557
+ if (stackScope !== void 0 && stackRegion) {
13558
+ logger.info(`Stack region: ${displaySafe(stackRegion, { asciiOnly: true })}`);
13559
+ process.env["AWS_REGION"] = stackRegion;
13560
+ process.env["AWS_DEFAULT_REGION"] = stackRegion;
13561
+ regionSwitched = true;
13562
+ try {
13563
+ destroyAwsClients = stackScope.clients;
13564
+ setAwsClients(destroyAwsClients);
13565
+ destroyProviderRegistry = stackScope.registry;
13566
+ registerAllProviders(destroyProviderRegistry, providerClasses);
13567
+ destroyProviderRegistry.setCustomResourceResponseBucket(ctx.stateBucket);
13568
+ if (ctx.allowUnsupportedTypes?.length) destroyProviderRegistry.allowUnsupportedTypes(ctx.allowUnsupportedTypes);
13569
+ } catch (setupError) {
13570
+ restoreBaseRegionAndClients();
13571
+ throw setupError;
13572
+ }
13573
+ }
13574
+ return destroyStackUnderLock({
13575
+ stackName,
13576
+ state,
13577
+ ctx,
13578
+ logger,
13579
+ result,
13580
+ regionForState,
13581
+ refusalRecovery,
13582
+ stackLockBase,
13583
+ journaledOrphans,
13584
+ needsStrongRefCheck,
13585
+ stackNoEchoValues,
13586
+ destroyProviderRegistry,
13587
+ destroyAwsClients,
13588
+ restoreBaseRegionAndClients
13589
+ });
13423
13590
  }
13424
13591
 
13425
13592
  // src/cli/commands/destroy-skip-message.ts
@@ -20382,7 +20549,10 @@ const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain iden
20382
20549
  const STACK_REGION_DESCRIBED_NOTE = " (The stack name or region is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
20383
20550
  function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20384
20551
  if (skipFinalSnapshot) return "DeletionPolicy Snapshot — NO final snapshot (--skip-final-snapshot)";
20385
- if (refusesFinalSnapshot(resourceType, effectiveProvisionedBy)) return "DeletionPolicy Snapshot — cdkd cannot snapshot this resource; the rollback will REFUSE it (re-run with --skip-final-snapshot to delete without one)";
20552
+ if (refusesFinalSnapshot(resourceType, effectiveProvisionedBy)) {
20553
+ if (resourceType === "AWS::RDS::DBInstance") return "DeletionPolicy Snapshot — cdkd cannot snapshot this resource; the rollback will REFUSE it unless AWS reports a read replica or cluster member, deleted without one as in CloudFormation (re-run with --skip-final-snapshot to delete without one)";
20554
+ return "DeletionPolicy Snapshot — cdkd cannot snapshot this resource; the rollback will REFUSE it (re-run with --skip-final-snapshot to delete without one)";
20555
+ }
20386
20556
  return "DeletionPolicy Snapshot — final snapshot, then delete";
20387
20557
  }
20388
20558
  function safe(value) {
@@ -32791,4 +32961,4 @@ function collectVerbFlags(program) {
32791
32961
  }
32792
32962
 
32793
32963
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
32794
- //# sourceMappingURL=program-Be87SvBg.js.map
32964
+ //# sourceMappingURL=program-DaGdaozO.js.map