@cdkd/cli 0.334.0 → 0.334.2

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 (27) hide show
  1. package/dist/{asg-provider-1ln_ANde.js → asg-provider-DTZ_iFWa.js} +2 -2
  2. package/dist/{asg-provider-1ln_ANde.js.map → asg-provider-DTZ_iFWa.js.map} +1 -1
  3. package/dist/cli.js +13 -7
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{db-instance-modify-retry-BCMjrw0H.js → db-instance-modify-retry-zm23duXt.js} +3 -3
  6. package/dist/{db-instance-modify-retry-BCMjrw0H.js.map → db-instance-modify-retry-zm23duXt.js.map} +1 -1
  7. package/dist/{deploy-engine-DIK2cLmn.js → deploy-engine-Dq_RyFZd.js} +9337 -8674
  8. package/dist/deploy-engine-Dq_RyFZd.js.map +1 -0
  9. package/dist/{iam-role-provider-I4_WshA4.js → iam-role-provider-DwAhjMfG.js} +2 -2
  10. package/dist/{iam-role-provider-I4_WshA4.js.map → iam-role-provider-DwAhjMfG.js.map} +1 -1
  11. package/dist/index.d.ts +54 -96
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{neptune-provider-D4YDyGKt.js → neptune-provider-BFDPuF1_.js} +17 -9
  15. package/dist/{neptune-provider-D4YDyGKt.js.map → neptune-provider-BFDPuF1_.js.map} +1 -1
  16. package/dist/{program-Dipucz4X.js → program-Be87SvBg.js} +999 -720
  17. package/dist/program-Be87SvBg.js.map +1 -0
  18. package/dist/{provider-classes-BBtEm3us.js → provider-classes-D0isRHVc.js} +21 -10
  19. package/dist/{provider-classes-BBtEm3us.js.map → provider-classes-D0isRHVc.js.map} +1 -1
  20. package/dist/{rds-provider-BOcleXHf.js → rds-provider-CYwGhhxE.js} +16 -5
  21. package/dist/rds-provider-CYwGhhxE.js.map +1 -0
  22. package/dist/{version-CXL6Ontw.js → version-CagOv0Ke.js} +2 -2
  23. package/dist/{version-CXL6Ontw.js.map → version-CagOv0Ke.js.map} +1 -1
  24. package/package.json +2 -2
  25. package/dist/deploy-engine-DIK2cLmn.js.map +0 -1
  26. package/dist/program-Dipucz4X.js.map +0 -1
  27. package/dist/rds-provider-BOcleXHf.js.map +0 -1
@@ -2,8 +2,9 @@ import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefault
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
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";
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 stackInstanceIdOf, $n as nameGenerationCarriedFrom, $r as addSuperseded, $s as malformedOutputsWarning, $t as deleteJournaledOrphans, $u as runDockerForeground, Ad as AssemblyReader, Ai as isFinalSnapshotError, Al as recordPhysicalNameCopy, An as equalModuloMarkedMask, Ao as unsettledItemsField, Ar as formatDestructiveChange, As as refuseMalformedResourceEntriesForImport, At as isSecretBearingReferenceString, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bi as ledgerForStack, Bl as wholeStringLeavesOf, Bn as replacementNeverSwapped, Bo as renderStatefulReason, Br as proposeRenames, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as NESTED_PENDING_PARENT_REASON, Bu as describeDockerExecFailure, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as secretNamedRecordNeedles, Cl as pathCrossesDottedKey, Cn as replayFailedOperations, Co as carriesFetchableDynamicReference, Cr as isExportAliasCollision, Cs as malformedLocalResourcesWarning, Ct as conditionInputsFrom, Cu as createAssetRedirectResolver, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as PRE_DELETE_SNAPSHOT_TYPES, Dn as settleUnsettledPrevious, Do as withSharedDrainBudget, Dr as maskingRetryLogger, Ds as refuseMalformedResourceEntries, Du as ensureAssetStorage, Ed as PARTITION_TABLE, Ei as ATOMIC_FINAL_SNAPSHOT_TYPES, El as inheritNestedStackParameterAssociations, En as recordAfterRollbackUpdate, Eo as keepsSecretReferenceToken, Er as DEFAULT_RESOURCE_WARN_AFTER_MS, Es as refuseMalformedResourceAttributesForOrphan, Eu as AssetModeResolver, Fa as DiffCalculator, Fd as utf8ByteLength, Fl as recordMaskOnlyValue, Fn as isReplacementOrphan, Fo as findReplacedReadersOfRecreateTargets, Fr as withMovedTo, Fs as malformedDriftResourcePropertiesWarning, Ft as planOrphanAdoption, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gi as DeploymentEventsStore, Gl as S3StateBackend, Gr as withStackRecords, Gs as malformedOrphansWarning, Gt as nestedChildStackName$1, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as withCreateTokenLedger, Hl as isSingleDynamicReferenceToken, Hn as seedsDeleteFirstGuard, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as displacedPhysicalIdShown, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Il as recordMaskOnlyValuesIn, In as planFailedOps, Io as shownType, Ir as isPairableType, Is as malformedResourcePropertiesWarning, It as pendingRequestCount, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as CrossPrefixScanCache, Jr as cyan, Js as repairMalformedOrphansForReadOnly, Jt as revertedNestedRowIds, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Ki as extractDeploymentEventError, Kl as rebuildClientForBucketRegion, Kn as inheritProducerRegions, Ko as coerceCfnBoolean, Ks as refuseMalformedOrphans, Kt as recordDisplacedSkips, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as secretSegmentsOfState, Ll as recordNoEchoAttributeValues, Ln as planRollback, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as looselyEqual, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as resolvePendingCloudControlRequests, Lu as buildDockerImage, Md as processStackMessages, Mi as unsupportedFinalSnapshotError, Ml as splitGetAttStringForm, Mn as undeclaredEmptyObservedKeys, Mo as unsettledPropertiesOf, Mr as hintSidesOf, Ms as refuseMalformedResourceEntriesForOrphan, Mt as mergeNoChangeOutputs, Mu as parseBootstrapMarker, Nd as describeJsonParseFailure, Ni as createPreDeleteFinalSnapshot, Nl as carriesSecretMask, Nn as demoteSupersededOrphans, No as withUnsettledProperties, Nr as movedToHint, Ns as repairMalformedResourceEntriesForReadOnly, Nt as makeCanonicalizePropertiesFn, Nu as readBootstrapMarkerBody, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as ccRoutedFinalSnapshotError, Ol as physicalNameCopiesOf, On as withUnprovenUnsettled, Oo as INTRINSIC_KEYS, Or as constructPathOf$1, Os as refuseMalformedResourceEntriesForDeploy, Ot as withResourceDeadline, Ou as buildDenyExternalAccessPolicy, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as buildFinalSnapshotIdentifier, Pl as provenPublicValue, Pn as isJournaledOrphan, Po as withoutUnsettledProperties, Pr as rollbackOrphanIds, Ps as unreadableResourceEntries, Pt as makeSiblingClaimReader, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as isNotImplemented, Qn as updatePartialReason, Qr as yellow, Qs as malformedOutputsRefusalMessage, Qt as withNestedStackContext, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Ri as withSecretPhysicalIdsMaskedInState, Rl as recordNoEchoParameterFreshValue, Rn as recheckFailedPlan, Ro as isStatefulRecreateTargetForReplace, Rr as mappingPairs, Rs as refuseMalformedResourcePropertiesForDrift, Rt as keptForRetainedRecord, Ru as resolveDockerContextDirectory, S as setResolvedResourceTimeouts, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Sl as isUncertifiedBaselineMaskPosition, Sn as refusePendingMovesOut, So as isImpossibleEmptyStoredAttribute, Sr as collectPublishedOutputNames, Ss as malformedLocalResourceEntriesWarning, St as conditionFingerprint, Su as buildAssetRedirectMap, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as storedSecretNameNeedles, Tl as identityKeyFor, Tn as removeProtectionTypeList, To as carriesDynamicReference, Tr as DEFAULT_RESOURCE_TIMEOUT_MS, Ts as malformedScrubResourceEntriesRefusalMessage, Tt as readRecordedConditionVerdicts, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ul as LockManager, Un as orphanNeedsIdentity, Ur as destroyStackRecordsView, Us as hasReadableOrphans, Ut as dropSettledNestedJournals, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as resolveReplacementOldType, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as displacedOpClause, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wi as DeploymentEventsReader, Wl as isLockInfoExpired, Wn as findNestedStackTypeChanges, Ws as malformedOrphansRefusalMessage, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as crossPrefixDeniedWarning, Xr as green, Xs as malformedExportSourceWarning, Xt as collectNestedChildUnaddressed, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as applyCrossPrefixScan, Yr as gray, Ys as malformedExportNamesWarning, Yt as withNestedRevertRun, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as isAccessDenied, Zn as updatePartialMessage, Zr as red, Zs as malformedLocalOutputsWarning, Zt as getCurrentNestedStackContext, Zu as formatDockerLoginError, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as maskEventTextWithBoundBags, _l as scrubResourceRecord, _n as sameMove, _o as keepHeldTokenProvenance, _r as exportNameNoEchoParameters, _s as refuseMalformedOrphansForOrphan, _t as findNestedTemplateTreeDefect, _u as timePhase, a as isProtectionValueActive, aa as ProviderRegistry, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as supersededHeldByOtherTypeWarning, al as hasMaskableValues, an as makeForeignHolderScan, ar as withNameGenerationReached, as as withRetry, au as hasReadableExportSet, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as secretNamePrintingBag, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as pendingMovesOutOf, bo as recordedReferenceRegions, br as noEchoParameterValueSeed, bs as unreadableOrphanRecords, bt as renderNestedTemplateTreeDefect, bu as stringifyValue, ca as wouldReturnToSdkProvider, cc as malformedStateRefusalMessage, cd as resolveApp, ci as withoutSuperseded, cl as printingCorpusOf, co as coerceParameterTypedValue, cr as reachableDivergentParameters, cs as declaresNoEcho, cu as importableOutputKeys, da as customResourceResponseExpirationWarning, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as noEchoExactEchoLeavesOf, dl as shareLogOnlyValues, do as AWS_NO_VALUE, dr as displayTextOrWithheld, ds as malformedOrphanRecordsRefusalMessage, dt as crossStackOutputProvenanceSource, du as orphansAfterRollback, ed as runDockerStreaming, ei as deleteSupersededEntry, el as redactForState, en as dropFailedCommands, eo as classifyReplaySecretRegion, er as nameGenerationHighWaterOf, eu as withStackInstanceIdWithheld, fa as TemplateNoEchoReresolver, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as noEchoParameterNamesOf, fl as unionOfSecretBags, fn as readRefactorMarker, fo as cfnRefValueFromPhysicalId, fr as exportAliasCollisionScrubWarning, fs as malformedOrphanRecordsWarning, ft as inheritedProvenanceForChildDiff, fu as orphansCarriedFrom, ga as withPrintingSecrets, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as journaledOrphanPrintingBag, gl as maskSecretsInText, gn as refuseRefactorMarker, gr as carriedExportAliasExposure, gs as refuseMalformedOrphanRecordsForDestroy, gt as childTemplateLoader, gu as renderPhaseTimings, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as completedReplayEntries, hl as maskSecretsInError, hn as refactorMarkerRefusalMessage, ho as refStateLookupFromResource, hr as secretSafeKeyDisplay, hs as refuseMalformedOrphanRecords, ht as serviceTokenBlockingReason, hu as PhaseClock, i as PROTECTION_PROPERTY_BY_TYPE, ia as CC_BROKEN_REASON, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as supersededAfterRollback, il as createUnionSecretMasker, in as loadJournaledOrphans, ir as retiredNameGenerationsLeaving, is as describeTypeWithThrottleRetry, iu as exportNamesCarriedFrom, jd as StageLoadError, ji as refusesFinalSnapshot, jl as recordNestedStackParameterExpressions, jn as equalModuloMask, jo as unsettledItemsOf, jr as findRefactorHints, js as refuseMalformedResourceEntriesForImportSave, jt as keptWholeReasonText, ju as getBootstrapMarkerKey, kd as refuseFailedLookups, ki as effectiveDeletionPolicy, kn as calculateResourceDrift, kr as findDestructiveChanges, ks as refuseMalformedResourceEntriesForDestroy, kt as diffSecurity, ku as assertAssetBucketRegion, la as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as noEchoAttributeNamesOf, ll as recordLogOnlyParameterValue, lo as isUnboundTemplateParameter, lr as resourcesNamingDeclaredParameter, ls as deployRefusesOrphanRowsReason, lt as IMPLICIT_DELETE_DEPENDENCIES, lu as importableOutputs, ma as isCustomResourceType$1, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as createReadOnlyAttributeHealerFactory, ml as errorCauseChain, mn as refactorMarkerMovesOf, mo as lacksRecordedTableArn, mr as secretBearingStateKeyWarning, ms as previewableOrphanRecords, mt as findServiceTokenRefusals, mu as stackInstanceIdCarriedFrom, n as recordedProtectionEvidence, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as isSupersededResourceRecord, nn as isHandledOrphan, no as regionLessSecretName, nr as retiredAfterRollback, ns as prefetchCreateOnlyPropertyPaths, nu as acceptedCreateOnlyDropsOf, o as perType, oa as ccBrokenReason, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as supersededHolderOf, ol as literalSplitDelimitersOf, on as sameJournaledOrphans, or as computeParameterTaint, os as parameterInputsFor, ou as hasReasonlessBaselineRefusal, pa as readsNoEchoDeleteValues, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as withAttemptedItemsMasked, pl as createSecretMasker, pn as readRefactorMarkerOnce, po as isStalePlaceholderArnAttribute, pr as secretBearing, ps as malformedOrphanRowsKeptWarning, pt as deferredServiceTokenWarning, pu as shouldRetainResource, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as CrossPrefixReadError, qr as bold, qs as refuseMalformedOrphansForDestroy, qu as partitionSensitiveEnv, r as recordedProtectionNote, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as removeSuperseded, rl as carryLogOnlyValues, rn as journaledOrphanLines, rr as retiredNameGenerationsAfter, rs as templateResourceTypes, ru as describeRegionValueKind, s as readProtection, sa as isCustomResource, sc as malformedResourcesWarning, sd as loadCdkJson, si as supersededResourcesOf, sl as logOnlyValueCount, sn as formatResourceLine, sr as namesAnyDeclaredParameter, su as hasUnverifiableParameterRefusal, t as DeployEngine, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as holdsSupersededResources, tn as dropFailedHint, to as producerRegionsFromState, tr as nameScopeOf, tu as splitImportedOps, ua as applyCustomResourceResponseExpiration, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as noEchoComparisonForTemplate, ul as recordLogOnlyValue, uo as parameterTypeMayLoseSecretIdentity, ur as WITHHELD_NAME_DISPLAY, us as isReadableOrphanRecord, ut as computeImplicitDeleteEdges, uu as isReadableBag, va as CloudControlProvider, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as namingSecretsWithRecordedNoEcho, vl as withPhysicalNameCopies, vn as updateRefactorMarker, vr as exportNameSecretExposure, vs as repairMalformedOrphanRecordsForReadOnly, vt as isAbsoluteAssetPath, vu as AssetPublisher, wa as deleteSkipReason, wd as decodeListingKey, wi as stateSecretNameNeedles, wl as spelledKeysOf, wn as replayRollback, wo as isNamelessDynamicReferenceError, wr as bindingSkippedOutputs, ws as malformedResourceEntriesWarning, wt as parentSuppliedValues, wu as loadPublishableAssetManifest, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as secretNamePrintingBags, xl as dynamicReferenceTokens, xn as pendingMovesRefusalMessage, xo as getAccountInfo, xr as collectDeclaredOutputNames, xs as isReadableResourceEntry, xt as templateIdentity, xu as WorkGraph, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yi as orphanRecordsPrintingBag, yn as hasPendingMovesOut, yo as recordedOutputReferenceRegions, yr as isWholeDynamicReferenceValue, ys as unpreviewableOrphanRecords, yt as listNestedTemplateRows, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zl as recordProvenPublicExpression, zn as recordUnderIdIsNotOwn, zo as isStatefulRecreateTargetSync, zr as parseMappingFile, zs as refuseMalformedResourcePropertiesForExport, zt as recordRetainedForReadoption, zu as describeDockerCapturedOutput } from "./deploy-engine-DIK2cLmn.js";
6
- import { t as getCdkdVersion } from "./version-CXL6Ontw.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";
7
+ import { t as cdkdCacheHome } from "./cli.js";
7
8
  import { randomBytes, randomUUID } from "node:crypto";
8
9
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
9
10
  import { GetRoleCommand, GetUserCommand } from "@aws-sdk/client-iam";
@@ -14,7 +15,7 @@ import { GetSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-sec
14
15
  import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
15
16
  import { DescribeLogStreamsCommand, ResourceNotFoundException as ResourceNotFoundException$1 } from "@aws-sdk/client-cloudwatch-logs";
16
17
  import * as fs from "node:fs";
17
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
18
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, promises, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
18
19
  import * as path from "node:path";
19
20
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
20
21
  import { execFile, spawn } from "node:child_process";
@@ -1851,7 +1852,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
1851
1852
  // src/provisioning/register-providers.ts
1852
1853
  let providerClasses;
1853
1854
  function loadProviderClasses() {
1854
- providerClasses ??= import("./provider-classes-BBtEm3us.js");
1855
+ providerClasses ??= import("./provider-classes-D0isRHVc.js");
1855
1856
  return providerClasses;
1856
1857
  }
1857
1858
  function registerAllProviders(registry, classes) {
@@ -13429,7 +13430,7 @@ function skippedDestroyMessage(totalSkipped, totalOrphanSkips, rerunCommand) {
13429
13430
  return `Destroy skipped ${recordSkips} entr${recordSkips === 1 ? "y" : "ies"} whose delete cdkd did not confirm, so the underlying resources may still exist in AWS. A skipped nested stack counts as ONE entry and may cover several of its own resources — the per-stack summaries above give the exact breakdown. State preserved (the records are kept). The per-resource 'skipped (...)' lines and their warnings name each cause and whether repairing the record in state.json helps: where it does, repair it and re-run '${rerunCommand}'; otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand and drop the records with 'cdkd state orphan <stack> --stack-region <region>'.` + (totalOrphanSkips > 0 ? ` Separately, ${orphanSentence}` : "");
13430
13431
  }
13431
13432
 
13432
- // src/cli/commands/destroy.ts
13433
+ // src/cli/commands/destroy/helpers.ts
13433
13434
  function orderConsumersBeforeProducers(stackNames, consumerToProducers) {
13434
13435
  const pendingConsumers = /* @__PURE__ */ new Map();
13435
13436
  for (const name of stackNames) pendingConsumers.set(name, /* @__PURE__ */ new Set());
@@ -13466,6 +13467,147 @@ async function purgeEventsAfterDestroy(reader, stackName, region, opts, logger)
13466
13467
  return null;
13467
13468
  }
13468
13469
  }
13470
+
13471
+ // src/cli/commands/destroy/select-targets.ts
13472
+ async function selectDestroyTargets(stackArgs, options, stateBackend, logger) {
13473
+ const appCmd = options.app || resolveApp();
13474
+ let appStacks = [];
13475
+ let synthScanStacks = [];
13476
+ let synthesized = false;
13477
+ let synthError;
13478
+ if (appCmd) try {
13479
+ const synthesizer = new Synthesizer();
13480
+ const context = parseContextOptions(options.context);
13481
+ const result = await synthesizer.synthesize({
13482
+ app: appCmd,
13483
+ output: options.output || "cdk.out",
13484
+ ...Object.keys(context).length > 0 && { context },
13485
+ deferMacroExpansion: true,
13486
+ failedLookupsCheckedByCaller: true
13487
+ });
13488
+ appStacks = result.stacks.map((s) => ({
13489
+ stackName: s.stackName,
13490
+ displayName: s.displayName,
13491
+ ...s.stagePath !== void 0 && { stagePath: s.stagePath },
13492
+ ...s.region && { region: s.region },
13493
+ ...s.account && { account: s.account },
13494
+ ...s.terminationProtection !== void 0 && { terminationProtection: s.terminationProtection },
13495
+ template: s.template,
13496
+ ...s.nestedTemplates !== void 0 && { nestedTemplates: s.nestedTemplates }
13497
+ }));
13498
+ synthScanStacks = result.stacks.map((s) => ({
13499
+ stackName: s.stackName,
13500
+ template: s.template
13501
+ }));
13502
+ synthesized = true;
13503
+ } catch (error) {
13504
+ if (error instanceof StageLoadError) {
13505
+ const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: cdkd state destroy ${commandHole("stack")}.`);
13506
+ if (typeof error.stack === "string") {
13507
+ const headerLines = `${error.name}: ${error.message}`.split("\n").length;
13508
+ const frames = error.stack.split("\n").slice(headerLines).join("\n");
13509
+ if (frames.length > 0) named.stack = `${named.name}: ${named.message}\n${frames}`;
13510
+ }
13511
+ throw named;
13512
+ }
13513
+ synthError = error instanceof Error ? error : new Error(safeStringify(error));
13514
+ logger.debug("Could not synthesize app, falling back to state-based stack list");
13515
+ }
13516
+ const stackPatterns = stackArgs.length > 0 ? stackArgs : options.stack ? [options.stack] : [];
13517
+ const wildcardPatterns = stackPatterns.filter((p) => p.includes("*") || p.includes("?"));
13518
+ if (appStacks.length === 0 && (options.all || wildcardPatterns.length > 0)) {
13519
+ const selector = options.all ? "--all" : wildcardPatterns.map((p) => displaySafe(p)).join(", ");
13520
+ if (synthesized) throw new Error(`${selector} selects among the stacks this app synthesizes, and it synthesized none; refusing to fall back to every stack in state.`);
13521
+ const hole = commandHole("stack");
13522
+ throw new CdkdError(`${selector} selects among the stacks this app synthesizes, and ` + (synthError ? "the app could not be synthesized" : "no app is configured") + "; refusing to fall back to every stack in state, which spans every app sharing this state bucket. " + (synthError ? "Fix the app so it synthesizes" : "Configure the app with --app or cdk.json") + `, or name each stack exactly: cdkd destroy ${hole}, or cdkd state destroy ${hole}, which needs no app.`, "DESTROY_NO_APP_SCOPE", synthError);
13523
+ }
13524
+ if (options.all && appStacks.length > 0) {
13525
+ const app = partitionTopLevel(appStacks);
13526
+ if (app.topLevel.length === 0) throw new Error(renderAllNoTopLevelStacks(app.inStages));
13527
+ }
13528
+ const allStateRefs = await stateBackend.listStacks();
13529
+ let candidateStacks;
13530
+ if (appStacks.length > 0) {
13531
+ const stateNames = new Set(allStateRefs.map((r) => r.stackName));
13532
+ candidateStacks = appStacks.filter((s) => stateNames.has(s.stackName));
13533
+ } else if (stackArgs.length > 0 || options.stack) {
13534
+ const seen = /* @__PURE__ */ new Set();
13535
+ candidateStacks = [];
13536
+ for (const ref of allStateRefs) {
13537
+ if (seen.has(ref.stackName)) continue;
13538
+ seen.add(ref.stackName);
13539
+ candidateStacks.push({ stackName: ref.stackName });
13540
+ }
13541
+ } else throw new CdkdError("Could not determine which stacks belong to this app. Specify stack names explicitly, or ensure --app / cdk.json is configured.", "DESTROY_NO_STACK_SELECTED", synthError);
13542
+ const appStackSet = new Set(appStacks);
13543
+ const toTarget = (s) => ({
13544
+ stackName: s.stackName,
13545
+ synth: appStackSet.has(s) ? s : void 0
13546
+ });
13547
+ let targets;
13548
+ const namesAppStack = /* @__PURE__ */ new Set();
13549
+ if (options.all) {
13550
+ const { topLevel, inStages } = partitionTopLevel(candidateStacks);
13551
+ if (inStages.length > 0) logger.warn(renderAllLeftOutStageStacks(inStages));
13552
+ targets = topLevel.map(toTarget);
13553
+ } else if (stackPatterns.length > 0) {
13554
+ const selectFrom = appStacks.length > 0 ? appStacks : candidateStacks;
13555
+ const inState = new Set(candidateStacks.map((s) => s.stackName));
13556
+ targets = matchStacks(selectFrom, stackPatterns, { dedupe: "identity" }).filter((s) => inState.has(s.stackName)).map(toTarget);
13557
+ if (appStacks.length > 0) {
13558
+ const gone = stacksNoLongerSelected(candidateStacks, stackPatterns, new Set(targets.map((t) => t.stackName)));
13559
+ if (gone.stacks.length > 0) logger.warn(renderStacksNoLongerSelected(gone.patterns, gone.stacks));
13560
+ }
13561
+ const stateNames = new Set(allStateRefs.map((r) => r.stackName));
13562
+ const unmatched = unmatchedPatterns(selectFrom, stackPatterns, (s) => inState.has(s.stackName));
13563
+ if (appStacks.length > 0) {
13564
+ for (const p of stackPatterns) if (appStacks.some((s) => stackMatchesPattern(s, p))) namesAppStack.add(p);
13565
+ }
13566
+ const inStateOnly = unmatched.filter((p) => stateNames.has(p) && !namesAppStack.has(p));
13567
+ const absent = unmatched.filter((p) => !inStateOnly.includes(p));
13568
+ if (absent.length > 0) logger.warn(renderUnmatchedPatternsWarning(absent, "in state"));
13569
+ if (targets.length > 0 && inStateOnly.length > 0) logger.warn(renderNotInAppWarning(inStateOnly));
13570
+ } else if (candidateStacks.length === 1) targets = candidateStacks.map(toTarget);
13571
+ else if (candidateStacks.length === 0) {
13572
+ logger.info("No stacks found in state");
13573
+ return;
13574
+ } else throw new Error(`Multiple stacks found: ${candidateStacks.map(describeStack).join(", ")}. Specify stack name(s) or use --all (top-level stacks; '**' for every stack)`);
13575
+ return {
13576
+ appStacks,
13577
+ synthScanStacks,
13578
+ stackPatterns,
13579
+ allStateRefs,
13580
+ targets,
13581
+ namesAppStack
13582
+ };
13583
+ }
13584
+ async function orderDestroyTargets(targets, appStacks, synthScanStacks, regionForStack, logger) {
13585
+ const uniqueNames = [...new Set(targets.map((t) => t.stackName))];
13586
+ if (synthScanStacks.length > 0 && uniqueNames.length > 1) {
13587
+ const inSet = new Set(uniqueNames);
13588
+ const inferred = inferCrossStackStackDeps(synthScanStacks.filter((s) => inSet.has(s.stackName)));
13589
+ targets = orderConsumersBeforeProducers(uniqueNames, inferred).flatMap((name) => targets.filter((t) => t.stackName === name));
13590
+ }
13591
+ const sharedAppNames = new Set(appStacks.map((s) => s.stackName).filter((name, i, names) => names.indexOf(name) !== i));
13592
+ const strictRegion = /* @__PURE__ */ new Map();
13593
+ for (const target of targets) {
13594
+ if (!sharedAppNames.has(target.stackName) || target.synth === void 0) continue;
13595
+ strictRegion.set(target, target.synth.region ?? await regionForStack(target.stackName));
13596
+ }
13597
+ const strictBySynth = new Map(targets.flatMap((t) => t.synth !== void 0 && strictRegion.has(t) ? [[t.synth, strictRegion.get(t)]] : []));
13598
+ const strictNames = new Set([...strictBySynth.keys()].map((s) => s.stackName));
13599
+ refuseStackNameRegionCollisions(appStacks.filter((s) => strictBySynth.has(s) || strictNames.has(s.stackName) && s.region !== void 0), (s) => strictBySynth.get(s) ?? s.region, new Set(strictBySynth.keys()));
13600
+ const describeTarget = (t) => t.synth !== void 0 && strictRegion.has(t) ? `${describeStack(t.synth)} in ${displaySafe(strictRegion.get(t))}` : displaySafe(t.stackName);
13601
+ logger.info(`Found ${targets.length} stack(s) to destroy: ${targets.map(describeTarget).join(", ")}`);
13602
+ return {
13603
+ targets,
13604
+ uniqueNames,
13605
+ strictRegion,
13606
+ describeTarget
13607
+ };
13608
+ }
13609
+
13610
+ // src/cli/commands/destroy/command.ts
13469
13611
  async function destroyCommand(stackArgs, options) {
13470
13612
  const providerClasses = await loadProviderClasses();
13471
13613
  const logger = getLogger();
@@ -13552,114 +13694,16 @@ async function destroyCommand(stackArgs, options) {
13552
13694
  registerAllProviders(providerRegistry, providerClasses);
13553
13695
  providerRegistry.setCustomResourceResponseBucket(stateBucket);
13554
13696
  if (options.allowUnsupportedTypes?.length) providerRegistry.allowUnsupportedTypes(options.allowUnsupportedTypes);
13555
- const appCmd = options.app || resolveApp();
13556
- let appStacks = [];
13557
- let synthScanStacks = [];
13558
- let synthesized = false;
13559
- let synthError;
13560
- if (appCmd) try {
13561
- const synthesizer = new Synthesizer();
13562
- const context = parseContextOptions(options.context);
13563
- const result = await synthesizer.synthesize({
13564
- app: appCmd,
13565
- output: options.output || "cdk.out",
13566
- ...Object.keys(context).length > 0 && { context },
13567
- deferMacroExpansion: true,
13568
- failedLookupsCheckedByCaller: true
13569
- });
13570
- appStacks = result.stacks.map((s) => ({
13571
- stackName: s.stackName,
13572
- displayName: s.displayName,
13573
- ...s.stagePath !== void 0 && { stagePath: s.stagePath },
13574
- ...s.region && { region: s.region },
13575
- ...s.account && { account: s.account },
13576
- ...s.terminationProtection !== void 0 && { terminationProtection: s.terminationProtection },
13577
- template: s.template,
13578
- ...s.nestedTemplates !== void 0 && { nestedTemplates: s.nestedTemplates }
13579
- }));
13580
- synthScanStacks = result.stacks.map((s) => ({
13581
- stackName: s.stackName,
13582
- template: s.template
13583
- }));
13584
- synthesized = true;
13585
- } catch (error) {
13586
- if (error instanceof StageLoadError) {
13587
- const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: cdkd state destroy ${commandHole("stack")}.`);
13588
- if (typeof error.stack === "string") {
13589
- const headerLines = `${error.name}: ${error.message}`.split("\n").length;
13590
- const frames = error.stack.split("\n").slice(headerLines).join("\n");
13591
- if (frames.length > 0) named.stack = `${named.name}: ${named.message}\n${frames}`;
13592
- }
13593
- throw named;
13594
- }
13595
- synthError = error instanceof Error ? error : new Error(safeStringify(error));
13596
- logger.debug("Could not synthesize app, falling back to state-based stack list");
13597
- }
13598
- const stackPatterns = stackArgs.length > 0 ? stackArgs : options.stack ? [options.stack] : [];
13599
- const wildcardPatterns = stackPatterns.filter((p) => p.includes("*") || p.includes("?"));
13600
- if (appStacks.length === 0 && (options.all || wildcardPatterns.length > 0)) {
13601
- const selector = options.all ? "--all" : wildcardPatterns.map((p) => displaySafe(p)).join(", ");
13602
- if (synthesized) throw new Error(`${selector} selects among the stacks this app synthesizes, and it synthesized none; refusing to fall back to every stack in state.`);
13603
- const hole = commandHole("stack");
13604
- throw new CdkdError(`${selector} selects among the stacks this app synthesizes, and ` + (synthError ? "the app could not be synthesized" : "no app is configured") + "; refusing to fall back to every stack in state, which spans every app sharing this state bucket. " + (synthError ? "Fix the app so it synthesizes" : "Configure the app with --app or cdk.json") + `, or name each stack exactly: cdkd destroy ${hole}, or cdkd state destroy ${hole}, which needs no app.`, "DESTROY_NO_APP_SCOPE", synthError);
13605
- }
13606
- if (options.all && appStacks.length > 0) {
13607
- const app = partitionTopLevel(appStacks);
13608
- if (app.topLevel.length === 0) throw new Error(renderAllNoTopLevelStacks(app.inStages));
13609
- }
13610
- const allStateRefs = await stateBackend.listStacks();
13611
- let candidateStacks;
13612
- if (appStacks.length > 0) {
13613
- const stateNames = new Set(allStateRefs.map((r) => r.stackName));
13614
- candidateStacks = appStacks.filter((s) => stateNames.has(s.stackName));
13615
- } else if (stackArgs.length > 0 || options.stack) {
13616
- const seen = /* @__PURE__ */ new Set();
13617
- candidateStacks = [];
13618
- for (const ref of allStateRefs) {
13619
- if (seen.has(ref.stackName)) continue;
13620
- seen.add(ref.stackName);
13621
- candidateStacks.push({ stackName: ref.stackName });
13622
- }
13623
- } else throw new CdkdError("Could not determine which stacks belong to this app. Specify stack names explicitly, or ensure --app / cdk.json is configured.", "DESTROY_NO_STACK_SELECTED", synthError);
13697
+ const selection = await selectDestroyTargets(stackArgs, options, stateBackend, logger);
13698
+ if (selection === void 0) return;
13699
+ const { appStacks, synthScanStacks, stackPatterns, allStateRefs, namesAppStack } = selection;
13700
+ let targets = selection.targets;
13624
13701
  let totalErrors = 0;
13625
13702
  let totalSkipped = 0;
13626
13703
  let totalOrphanSkips = 0;
13627
13704
  let interrupted = false;
13628
13705
  const runInterrupted = () => interrupted || interruptWatch.interrupted();
13629
13706
  let stoppedEarly = false;
13630
- const appStackSet = new Set(appStacks);
13631
- const toTarget = (s) => ({
13632
- stackName: s.stackName,
13633
- synth: appStackSet.has(s) ? s : void 0
13634
- });
13635
- let targets;
13636
- const namesAppStack = /* @__PURE__ */ new Set();
13637
- if (options.all) {
13638
- const { topLevel, inStages } = partitionTopLevel(candidateStacks);
13639
- if (inStages.length > 0) logger.warn(renderAllLeftOutStageStacks(inStages));
13640
- targets = topLevel.map(toTarget);
13641
- } else if (stackPatterns.length > 0) {
13642
- const selectFrom = appStacks.length > 0 ? appStacks : candidateStacks;
13643
- const inState = new Set(candidateStacks.map((s) => s.stackName));
13644
- targets = matchStacks(selectFrom, stackPatterns, { dedupe: "identity" }).filter((s) => inState.has(s.stackName)).map(toTarget);
13645
- if (appStacks.length > 0) {
13646
- const gone = stacksNoLongerSelected(candidateStacks, stackPatterns, new Set(targets.map((t) => t.stackName)));
13647
- if (gone.stacks.length > 0) logger.warn(renderStacksNoLongerSelected(gone.patterns, gone.stacks));
13648
- }
13649
- const stateNames = new Set(allStateRefs.map((r) => r.stackName));
13650
- const unmatched = unmatchedPatterns(selectFrom, stackPatterns, (s) => inState.has(s.stackName));
13651
- if (appStacks.length > 0) {
13652
- for (const p of stackPatterns) if (appStacks.some((s) => stackMatchesPattern(s, p))) namesAppStack.add(p);
13653
- }
13654
- const inStateOnly = unmatched.filter((p) => stateNames.has(p) && !namesAppStack.has(p));
13655
- const absent = unmatched.filter((p) => !inStateOnly.includes(p));
13656
- if (absent.length > 0) logger.warn(renderUnmatchedPatternsWarning(absent, "in state"));
13657
- if (targets.length > 0 && inStateOnly.length > 0) logger.warn(renderNotInAppWarning(inStateOnly));
13658
- } else if (candidateStacks.length === 1) targets = candidateStacks.map(toTarget);
13659
- else if (candidateStacks.length === 0) {
13660
- logger.info("No stacks found in state");
13661
- return;
13662
- } else throw new Error(`Multiple stacks found: ${candidateStacks.map(describeStack).join(", ")}. Specify stack name(s) or use --all (top-level stacks; '**' for every stack)`);
13663
13707
  if (targets.length === 0) {
13664
13708
  if (stackPatterns.length > 0) {
13665
13709
  const allStateNamesSet = new Set(allStateRefs.map((r) => r.stackName));
@@ -13682,22 +13726,9 @@ async function destroyCommand(stackArgs, options) {
13682
13726
  logger.info("No matching stacks found in state");
13683
13727
  return;
13684
13728
  }
13685
- const uniqueNames = [...new Set(targets.map((t) => t.stackName))];
13686
- if (synthScanStacks.length > 0 && uniqueNames.length > 1) {
13687
- const inSet = new Set(uniqueNames);
13688
- targets = orderConsumersBeforeProducers(uniqueNames, inferCrossStackStackDeps(synthScanStacks.filter((s) => inSet.has(s.stackName)))).flatMap((name) => targets.filter((t) => t.stackName === name));
13689
- }
13690
- const sharedAppNames = new Set(appStacks.map((s) => s.stackName).filter((name, i, names) => names.indexOf(name) !== i));
13691
- const strictRegion = /* @__PURE__ */ new Map();
13692
- for (const target of targets) {
13693
- if (!sharedAppNames.has(target.stackName) || target.synth === void 0) continue;
13694
- strictRegion.set(target, target.synth.region ?? await regionForStack(target.stackName));
13695
- }
13696
- const strictBySynth = new Map(targets.flatMap((t) => t.synth !== void 0 && strictRegion.has(t) ? [[t.synth, strictRegion.get(t)]] : []));
13697
- const strictNames = new Set([...strictBySynth.keys()].map((s) => s.stackName));
13698
- refuseStackNameRegionCollisions(appStacks.filter((s) => strictBySynth.has(s) || strictNames.has(s.stackName) && s.region !== void 0), (s) => strictBySynth.get(s) ?? s.region, new Set(strictBySynth.keys()));
13699
- const describeTarget = (t) => t.synth !== void 0 && strictRegion.has(t) ? `${describeStack(t.synth)} in ${displaySafe(strictRegion.get(t))}` : displaySafe(t.stackName);
13700
- logger.info(`Found ${targets.length} stack(s) to destroy: ${targets.map(describeTarget).join(", ")}`);
13729
+ const ordering = await orderDestroyTargets(targets, appStacks, synthScanStacks, regionForStack, logger);
13730
+ targets = ordering.targets;
13731
+ const { uniqueNames, strictRegion, describeTarget } = ordering;
13701
13732
  const accountId = "unknown";
13702
13733
  const stateRefsByName = /* @__PURE__ */ new Map();
13703
13734
  for (const ref of allStateRefs) {
@@ -13920,6 +13951,8 @@ async function destroyCommand(stackArgs, options) {
13920
13951
  stateBackendForCleanup?.destroyClient();
13921
13952
  }
13922
13953
  }
13954
+
13955
+ // src/cli/commands/destroy.ts
13923
13956
  function createDestroyCommand() {
13924
13957
  const cmd = new Command("destroy").description("Destroy all resources in the stack").argument("[stacks...]", "Stack name(s) to destroy. Accepts CDK display paths (e.g. 'MyStage/Api') with wildcards ('MyStage/*', '**'), or exact physical CloudFormation names (e.g. 'MyStage-Api').").option("--all", "Destroy every top-level stack (top-level only; Stage stacks: '**')", false).option("--purge-events", `After a clean destroy, also delete the stack's deployment-event history, purging every earlier version under the stack's deployments/ prefix on a versioned state bucket too unless a warning says otherwise. By default events survive destroy as post-mortem context. Skipped when the destroy fails or is interrupted (those events aid the retry). Equivalent for an already-destroyed stack: cdkd events prune ${commandHole("stack")} --all.`, false).action(withErrorHandling(destroyCommand));
13925
13958
  [
@@ -13936,140 +13969,6 @@ function createDestroyCommand() {
13936
13969
  return cmd;
13937
13970
  }
13938
13971
 
13939
- // src/cli/commands/rollback-drop-failed.ts
13940
- function refuseDropFailedConflicts(options) {
13941
- const conflicting = [
13942
- ...(options.orphan ?? []).length > 0 ? ["--orphan"] : [],
13943
- ...options.revertFailed === true ? ["--revert-failed"] : [],
13944
- ...options.skipFinalSnapshot === true ? ["--skip-final-snapshot"] : []
13945
- ];
13946
- if (conflicting.length === 0) return;
13947
- throw new CdkdError(`--drop-failed cannot be combined with ${conflicting.join(", ")}: it replays nothing, it only removes one entry from the rollback journal. Run the rollback and the drop as separate commands.`, "ROLLBACK_DROP_FAILED_CONFLICT");
13948
- }
13949
- function selectDropTarget(segments, logicalId, stackShown) {
13950
- const named = logicalIdShown(logicalId);
13951
- const droppable = [];
13952
- let otherFailed = 0;
13953
- let completed = 0;
13954
- const droppableIds = /* @__PURE__ */ new Set();
13955
- segments.forEach((segment, index) => {
13956
- const failed = segment.failedOperations ?? [];
13957
- const replay = segment.reason === "nested-pending-parent" ? [] : splitImportedOps(failed, segment).replay;
13958
- for (const op of replay) if (isDroppable(op)) droppableIds.add(op.logicalId);
13959
- for (const op of failed) {
13960
- if (op.logicalId !== logicalId) continue;
13961
- if (replay.includes(op) && isDroppable(op)) droppable.push({
13962
- segment,
13963
- segmentNumber: index + 1,
13964
- op,
13965
- companions: replay.filter((c) => c.changeType === "UPDATE" && replacementNeverSwapped(c, [op]))
13966
- });
13967
- else otherFailed++;
13968
- }
13969
- completed += segment.operations.filter((op) => op.logicalId === logicalId).length;
13970
- });
13971
- if (droppable.length === 1) return droppable[0];
13972
- if (droppable.length > 1) throw new CdkdError(`The rollback journal of ${stackShown} holds ${droppable.length} entries for ${named} that --drop-failed could drop (segments ${droppable.map((d) => d.segmentNumber).join(", ")}), and it drops exactly one, so it does not choose. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
13973
- if (otherFailed > 0) throw new CdkdError(`The rollback journal of ${stackShown} holds no entry for ${named} that --drop-failed can drop: it drops only a failed CREATE whose resource cdkd proved it made, journaled as its only record, the entry cdkd destroy and cdkd deploy keep retrying. ${named}'s failed operation(s) are of another kind, or one a newer journal entry may own; neither blocks either command. Nothing was changed.`, "ROLLBACK_DROP_FAILED_NOT_ORPHAN");
13974
- if (completed > 0) throw new CdkdError(`${named} is a completed operation in the rollback journal of ${stackShown}, not a failed one; --drop-failed drops failed operations only. Nothing was changed. To leave a completed operation out of a rollback, pass --orphan with its logical id.`, "ROLLBACK_DROP_FAILED_COMPLETED");
13975
- const ids = [...droppableIds].map(logicalIdShown);
13976
- throw new CdkdError(`The rollback journal of ${stackShown} has no entry for ${named}. Nothing was changed. ` + (ids.length === 0 ? "It holds no entry --drop-failed can drop." : `Entries --drop-failed can drop: ${ids.join(", ")}.`), "ROLLBACK_DROP_FAILED_UNKNOWN");
13977
- }
13978
- function isDroppable(op) {
13979
- return isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true || op.changeType === "CREATE" && op.pendingCloudControlRequest !== void 0;
13980
- }
13981
- const POLICY_TARGETS = {
13982
- "AWS::SQS::QueuePolicy": "Queues",
13983
- "AWS::SNS::TopicPolicy": "Topics"
13984
- };
13985
- function dropTargetLines(target, segmentCount, logger) {
13986
- const { op } = target;
13987
- const lines = [` - ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) ${op.pendingCloudControlRequest !== void 0 ? "an abandoned Cloud Control request" : displacedPhysicalIdShown(op, logger) ?? "a physical id"} [failed CREATE, segment ${target.segmentNumber}/${segmentCount}]`];
13988
- const targetsKey = Object.hasOwn(POLICY_TARGETS, op.resourceType) ? POLICY_TARGETS[op.resourceType] : void 0;
13989
- const targets = targetsKey === void 0 ? void 0 : op.attemptedProperties?.[targetsKey];
13990
- if (Array.isArray(targets) && targets.length > 0) {
13991
- lines.push(` ${targetsKey} it was attached to:`);
13992
- for (const t of targets) lines.push(` - ${typeof t === "string" && t !== "" ? displacedPhysicalIdShown(op, logger, t) ?? "a value" : "a value that is not a string"}`);
13993
- }
13994
- if (target.companions.length > 0) lines.push(` (with the failed replacement UPDATE recorded beside it, which names no resource of its own)`);
13995
- return lines;
13996
- }
13997
- async function confirmDrop(question) {
13998
- return confirmOrRefuse(question, {
13999
- suffix: " (y/N): ",
14000
- refusal: "The cdkd rollback --drop-failed confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the drop, or run the command from a real terminal."
14001
- });
14002
- }
14003
- async function dropFailedJournalEntry(args) {
14004
- const { stateBackend, lockManager, stackName, region, logicalId, logger } = args;
14005
- const stackShown = `stack ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
14006
- let interrupted = false;
14007
- const sigintHandler = () => {
14008
- process.stderr.write("\nInterrupted — the rollback journal is not changed.\n");
14009
- interrupted = true;
14010
- };
14011
- process.on("SIGINT", sigintHandler);
14012
- const unforwardSigterm = forwardSigtermToSigint();
14013
- try {
14014
- await lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
14015
- } catch (error) {
14016
- process.removeListener("SIGINT", sigintHandler);
14017
- unforwardSigterm();
14018
- throw error;
14019
- }
14020
- try {
14021
- const journal = await stateBackend.loadRollbackJournal(stackName, region);
14022
- if (!journal || journal.segments.length === 0) throw new CdkdError(`${stackShown.charAt(0).toUpperCase()}${stackShown.slice(1)} has no rollback journal; nothing to drop.`, "ROLLBACK_DROP_FAILED_NO_JOURNAL");
14023
- let stateData;
14024
- try {
14025
- stateData = await stateBackend.getState(stackName, region);
14026
- } catch (err) {
14027
- throw new CdkdError(`Could not read the state record of ${stackShown} (${err instanceof Error ? err.name : "an error"}), which the drop needs to mask the entry. Nothing was changed; re-run once it can be read.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
14028
- }
14029
- const resources = stateData ? stateData.state.resources : {};
14030
- if (!isReadableBag(resources)) throw new CdkdError(`The state record of ${stackShown} holds resources that cannot be read, which the drop needs to mask the entry. Nothing was changed.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
14031
- const stateResources = resources;
14032
- const judged = structuredClone(journal.segments);
14033
- demoteSupersededOrphans(judged);
14034
- const target = selectDropTarget(judged, logicalId, stackShown);
14035
- const drop = [target.op, ...target.companions].map((op) => ({
14036
- segment: target.segment,
14037
- op
14038
- }));
14039
- if (journal.segments.reduce((n, segment) => n + (segment.failedOperations ?? []).filter((op) => isHandledOrphan(drop, segment, op)).length, 0) !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} holds another entry identical to ${logicalIdShown(logicalId)}'s, so dropping it by its identity would drop more than one. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
14040
- const printing = journaledOrphanPrintingBag(judged.flatMap((segment) => segment.failedOperations ?? []), stateResources);
14041
- withPrintingSecrets(printing, () => {
14042
- logger.info(safeMsg`\nDrop one entry from the rollback journal of ${stackShown}:`);
14043
- for (const line of dropTargetLines(target, journal.segments.length, logger)) logger.info(line);
14044
- logger.info("\nThis removes only the journal entry, which is cdkd's last record of that resource. Nothing is deleted in AWS: check the resource above by hand, and delete it yourself if it should not stay. cdkd destroy and cdkd deploy then no longer act on it.\n");
14045
- });
14046
- const stopIfInterrupted = () => {
14047
- if (!interrupted) return;
14048
- throw new CdkdError("Interrupted before the rollback journal was changed; nothing was dropped.", "ROLLBACK_DROP_FAILED_INTERRUPTED");
14049
- };
14050
- stopIfInterrupted();
14051
- if (!args.skipConfirmation) {
14052
- if (!await (args.confirm ?? confirmDrop)("Drop this entry from the rollback journal?")) {
14053
- logger.info("Drop cancelled; the rollback journal is not changed.");
14054
- return;
14055
- }
14056
- }
14057
- stopIfInterrupted();
14058
- const removed = await stateBackend.dropRollbackJournalFailedOperations(stackName, region, (op, segment) => isHandledOrphan(drop, segment, op));
14059
- if (removed !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} was rewritten with ${removed} entr${removed === 1 ? "y" : "ies"} removed where ${drop.length} ${drop.length === 1 ? "was" : "were"} expected: it changed under the stack lock. Inspect the stack's rollback-journal.json (next to its state.json).`, "ROLLBACK_DROP_FAILED_CHANGED");
14060
- logger.info(safeMsg`Dropped ${logicalIdShown(logicalId)}'s entry from the rollback journal of ${stackShown}. ` + "Nothing was deleted in AWS; every other entry is kept.");
14061
- } finally {
14062
- try {
14063
- await lockManager.releaseLock(stackName, region).catch((err) => {
14064
- logger.warn(safeMsg`Failed to release the lock of ${stackShown}: ${err instanceof Error ? err.name : "an error"}`);
14065
- });
14066
- } finally {
14067
- process.removeListener("SIGINT", sigintHandler);
14068
- unforwardSigterm();
14069
- }
14070
- }
14071
- }
14072
-
14073
13972
  // src/cli/commands/state-migrate.ts
14074
13973
  async function stateMigrateCommand(options) {
14075
13974
  const logger = getLogger();
@@ -20300,27 +20199,7 @@ function createStateCommand() {
20300
20199
  return cmd;
20301
20200
  }
20302
20201
 
20303
- // src/cli/commands/rollback.ts
20304
- function rerunRollback(stackName) {
20305
- const rerun = pasteableCommand("cdkd rollback", [{
20306
- value: stackName,
20307
- hole: "stack",
20308
- opts: { plainIdent: true }
20309
- }]);
20310
- return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
20311
- }
20312
- function backendErrorText(error, stackName, region) {
20313
- if (!isPasteableIdent(stackName) || !isPasteableIdent(region)) return "its error text names a stack or region that is not a plain identifier, so it is not shown";
20314
- return displaySafe(describeAwsFailure(error).detail);
20315
- }
20316
- function stackRegionShown(stackName, region) {
20317
- return `${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
20318
- }
20319
- function stackRegionIsPlain(stackName, region) {
20320
- return isPasteableIdent(stackName) && isPasteableIdent(region);
20321
- }
20322
- const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
20323
- 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'.)";
20202
+ // src/cli/commands/rollback/options.ts
20324
20203
  function stackRegionOption() {
20325
20204
  return new Option("--stack-region <region>", "Region of the target stack when the same name has state in multiple regions").argParser(parseStackRegion);
20326
20205
  }
@@ -20345,29 +20224,175 @@ async function findJournalCandidates(backend, prefix) {
20345
20224
  }
20346
20225
  return refs;
20347
20226
  }
20348
- function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20349
- if (skipFinalSnapshot) return "DeletionPolicy Snapshot — NO final snapshot (--skip-final-snapshot)";
20350
- 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)";
20351
- return "DeletionPolicy Snapshot — final snapshot, then delete";
20352
- }
20353
- function safe(value) {
20354
- return displayIdent(value);
20355
- }
20356
- function safeStack(value) {
20357
- return displayIdent(value, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
20358
- }
20359
- function safeRoleArn(value) {
20360
- return displayIdent(value, { maxCodePoints: 613 });
20227
+
20228
+ // src/cli/commands/rollback-drop-failed.ts
20229
+ function refuseDropFailedConflicts(options) {
20230
+ const conflicting = [
20231
+ ...(options.orphan ?? []).length > 0 ? ["--orphan"] : [],
20232
+ ...options.revertFailed === true ? ["--revert-failed"] : [],
20233
+ ...options.skipFinalSnapshot === true ? ["--skip-final-snapshot"] : []
20234
+ ];
20235
+ if (conflicting.length === 0) return;
20236
+ throw new CdkdError(`--drop-failed cannot be combined with ${conflicting.join(", ")}: it replays nothing, it only removes one entry from the rollback journal. Run the rollback and the drop as separate commands.`, "ROLLBACK_DROP_FAILED_CONFLICT");
20361
20237
  }
20362
- function refuseDivergentRecordRegionForRollback(state, stackName, keyRegion, divergentBodyRegion, provenOrphans) {
20363
- if (divergentBodyRegion === void 0) return;
20364
- const resourceCount = isReadableBag(state.resources) ? Object.keys(state.resources).length : void 0;
20365
- if (resourceCount === 0 && provenOrphans === 0) return;
20366
- const lists = resourceCount === void 0 ? "its resources map cannot be read" : resourceCount > 0 ? `it still lists ${resourceCount} resource${resourceCount === 1 ? "" : "s"}` : `its journal holds ${provenOrphans} failed create${provenOrphans === 1 ? "" : "s"} whose resource the rollback would delete`;
20367
- throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. Re-run with --verbose to see what the record's region field holds, repair that field to match the key it is stored under, and run the rollback again.`, STATE_REGION_DIVERGED));
20238
+ function selectDropTarget(segments, logicalId, stackShown) {
20239
+ const named = logicalIdShown(logicalId);
20240
+ const droppable = [];
20241
+ let otherFailed = 0;
20242
+ let completed = 0;
20243
+ const droppableIds = /* @__PURE__ */ new Set();
20244
+ segments.forEach((segment, index) => {
20245
+ const failed = segment.failedOperations ?? [];
20246
+ const replay = segment.reason === "nested-pending-parent" ? [] : splitImportedOps(failed, segment).replay;
20247
+ for (const op of replay) if (isDroppable(op)) droppableIds.add(op.logicalId);
20248
+ for (const op of failed) {
20249
+ if (op.logicalId !== logicalId) continue;
20250
+ if (replay.includes(op) && isDroppable(op)) droppable.push({
20251
+ segment,
20252
+ segmentNumber: index + 1,
20253
+ op,
20254
+ companions: replay.filter((c) => c.changeType === "UPDATE" && replacementNeverSwapped(c, [op]))
20255
+ });
20256
+ else otherFailed++;
20257
+ }
20258
+ completed += segment.operations.filter((op) => op.logicalId === logicalId).length;
20259
+ });
20260
+ if (droppable.length === 1) return droppable[0];
20261
+ if (droppable.length > 1) throw new CdkdError(`The rollback journal of ${stackShown} holds ${droppable.length} entries for ${named} that --drop-failed could drop (segments ${droppable.map((d) => d.segmentNumber).join(", ")}), and it drops exactly one, so it does not choose. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
20262
+ if (otherFailed > 0) throw new CdkdError(`The rollback journal of ${stackShown} holds no entry for ${named} that --drop-failed can drop: it drops only a failed CREATE whose resource cdkd proved it made, journaled as its only record, the entry cdkd destroy and cdkd deploy keep retrying. ${named}'s failed operation(s) are of another kind, or one a newer journal entry may own; neither blocks either command. Nothing was changed.`, "ROLLBACK_DROP_FAILED_NOT_ORPHAN");
20263
+ if (completed > 0) throw new CdkdError(`${named} is a completed operation in the rollback journal of ${stackShown}, not a failed one; --drop-failed drops failed operations only. Nothing was changed. To leave a completed operation out of a rollback, pass --orphan with its logical id.`, "ROLLBACK_DROP_FAILED_COMPLETED");
20264
+ const ids = [...droppableIds].map(logicalIdShown);
20265
+ throw new CdkdError(`The rollback journal of ${stackShown} has no entry for ${named}. Nothing was changed. ` + (ids.length === 0 ? "It holds no entry --drop-failed can drop." : `Entries --drop-failed can drop: ${ids.join(", ")}.`), "ROLLBACK_DROP_FAILED_UNKNOWN");
20368
20266
  }
20369
- function divergedDuringRollbackMessage(divergentBodyRegion) {
20370
- return `the state record was rewritten during this rollback, and the rewrite carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the region of its key, so cdkd did not write over it`;
20267
+ function isDroppable(op) {
20268
+ return isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true || op.changeType === "CREATE" && op.pendingCloudControlRequest !== void 0;
20269
+ }
20270
+ const POLICY_TARGETS = {
20271
+ "AWS::SQS::QueuePolicy": "Queues",
20272
+ "AWS::SNS::TopicPolicy": "Topics"
20273
+ };
20274
+ function dropTargetLines(target, segmentCount, logger) {
20275
+ const { op } = target;
20276
+ const lines = [` - ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) ${op.pendingCloudControlRequest !== void 0 ? "an abandoned Cloud Control request" : displacedPhysicalIdShown(op, logger) ?? "a physical id"} [failed CREATE, segment ${target.segmentNumber}/${segmentCount}]`];
20277
+ const targetsKey = Object.hasOwn(POLICY_TARGETS, op.resourceType) ? POLICY_TARGETS[op.resourceType] : void 0;
20278
+ const targets = targetsKey === void 0 ? void 0 : op.attemptedProperties?.[targetsKey];
20279
+ if (Array.isArray(targets) && targets.length > 0) {
20280
+ lines.push(` ${targetsKey} it was attached to:`);
20281
+ for (const t of targets) lines.push(` - ${typeof t === "string" && t !== "" ? displacedPhysicalIdShown(op, logger, t) ?? "a value" : "a value that is not a string"}`);
20282
+ }
20283
+ if (target.companions.length > 0) lines.push(` (with the failed replacement UPDATE recorded beside it, which names no resource of its own)`);
20284
+ return lines;
20285
+ }
20286
+ async function confirmDrop(question) {
20287
+ return confirmOrRefuse(question, {
20288
+ suffix: " (y/N): ",
20289
+ refusal: "The cdkd rollback --drop-failed confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the drop, or run the command from a real terminal."
20290
+ });
20291
+ }
20292
+ async function dropFailedJournalEntry(args) {
20293
+ const { stateBackend, lockManager, stackName, region, logicalId, logger } = args;
20294
+ const stackShown = `stack ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
20295
+ let interrupted = false;
20296
+ const sigintHandler = () => {
20297
+ process.stderr.write("\nInterrupted — the rollback journal is not changed.\n");
20298
+ interrupted = true;
20299
+ };
20300
+ process.on("SIGINT", sigintHandler);
20301
+ const unforwardSigterm = forwardSigtermToSigint();
20302
+ try {
20303
+ await lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
20304
+ } catch (error) {
20305
+ process.removeListener("SIGINT", sigintHandler);
20306
+ unforwardSigterm();
20307
+ throw error;
20308
+ }
20309
+ try {
20310
+ const journal = await stateBackend.loadRollbackJournal(stackName, region);
20311
+ if (!journal || journal.segments.length === 0) throw new CdkdError(`${stackShown.charAt(0).toUpperCase()}${stackShown.slice(1)} has no rollback journal; nothing to drop.`, "ROLLBACK_DROP_FAILED_NO_JOURNAL");
20312
+ let stateData;
20313
+ try {
20314
+ stateData = await stateBackend.getState(stackName, region);
20315
+ } catch (err) {
20316
+ throw new CdkdError(`Could not read the state record of ${stackShown} (${err instanceof Error ? err.name : "an error"}), which the drop needs to mask the entry. Nothing was changed; re-run once it can be read.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
20317
+ }
20318
+ const resources = stateData ? stateData.state.resources : {};
20319
+ if (!isReadableBag(resources)) throw new CdkdError(`The state record of ${stackShown} holds resources that cannot be read, which the drop needs to mask the entry. Nothing was changed.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
20320
+ const stateResources = resources;
20321
+ const judged = structuredClone(journal.segments);
20322
+ demoteSupersededOrphans(judged);
20323
+ const target = selectDropTarget(judged, logicalId, stackShown);
20324
+ const drop = [target.op, ...target.companions].map((op) => ({
20325
+ segment: target.segment,
20326
+ op
20327
+ }));
20328
+ if (journal.segments.reduce((n, segment) => n + (segment.failedOperations ?? []).filter((op) => isHandledOrphan(drop, segment, op)).length, 0) !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} holds another entry identical to ${logicalIdShown(logicalId)}'s, so dropping it by its identity would drop more than one. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
20329
+ const printing = journaledOrphanPrintingBag(judged.flatMap((segment) => segment.failedOperations ?? []), stateResources);
20330
+ withPrintingSecrets(printing, () => {
20331
+ logger.info(safeMsg`\nDrop one entry from the rollback journal of ${stackShown}:`);
20332
+ for (const line of dropTargetLines(target, journal.segments.length, logger)) logger.info(line);
20333
+ logger.info("\nThis removes only the journal entry, which is cdkd's last record of that resource. Nothing is deleted in AWS: check the resource above by hand, and delete it yourself if it should not stay. cdkd destroy and cdkd deploy then no longer act on it.\n");
20334
+ });
20335
+ const stopIfInterrupted = () => {
20336
+ if (!interrupted) return;
20337
+ throw new CdkdError("Interrupted before the rollback journal was changed; nothing was dropped.", "ROLLBACK_DROP_FAILED_INTERRUPTED");
20338
+ };
20339
+ stopIfInterrupted();
20340
+ if (!args.skipConfirmation) {
20341
+ if (!await (args.confirm ?? confirmDrop)("Drop this entry from the rollback journal?")) {
20342
+ logger.info("Drop cancelled; the rollback journal is not changed.");
20343
+ return;
20344
+ }
20345
+ }
20346
+ stopIfInterrupted();
20347
+ const removed = await stateBackend.dropRollbackJournalFailedOperations(stackName, region, (op, segment) => isHandledOrphan(drop, segment, op));
20348
+ if (removed !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} was rewritten with ${removed} entr${removed === 1 ? "y" : "ies"} removed where ${drop.length} ${drop.length === 1 ? "was" : "were"} expected: it changed under the stack lock. Inspect the stack's rollback-journal.json (next to its state.json).`, "ROLLBACK_DROP_FAILED_CHANGED");
20349
+ logger.info(safeMsg`Dropped ${logicalIdShown(logicalId)}'s entry from the rollback journal of ${stackShown}. ` + "Nothing was deleted in AWS; every other entry is kept.");
20350
+ } finally {
20351
+ try {
20352
+ await lockManager.releaseLock(stackName, region).catch((err) => {
20353
+ logger.warn(safeMsg`Failed to release the lock of ${stackShown}: ${err instanceof Error ? err.name : "an error"}`);
20354
+ });
20355
+ } finally {
20356
+ process.removeListener("SIGINT", sigintHandler);
20357
+ unforwardSigterm();
20358
+ }
20359
+ }
20360
+ }
20361
+
20362
+ // src/cli/commands/rollback/render.ts
20363
+ function rerunRollback(stackName) {
20364
+ const rerun = pasteableCommand("cdkd rollback", [{
20365
+ value: stackName,
20366
+ hole: "stack",
20367
+ opts: { plainIdent: true }
20368
+ }]);
20369
+ return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
20370
+ }
20371
+ function backendErrorText(error, stackName, region) {
20372
+ if (!isPasteableIdent(stackName) || !isPasteableIdent(region)) return "its error text names a stack or region that is not a plain identifier, so it is not shown";
20373
+ return displaySafe(describeAwsFailure(error).detail);
20374
+ }
20375
+ function stackRegionShown(stackName, region) {
20376
+ return `${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
20377
+ }
20378
+ function stackRegionIsPlain(stackName, region) {
20379
+ return isPasteableIdent(stackName) && isPasteableIdent(region);
20380
+ }
20381
+ const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
20382
+ 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
+ function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20384
+ 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)";
20386
+ return "DeletionPolicy Snapshot — final snapshot, then delete";
20387
+ }
20388
+ function safe(value) {
20389
+ return displayIdent(value);
20390
+ }
20391
+ function safeStack(value) {
20392
+ return displayIdent(value, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
20393
+ }
20394
+ function safeRoleArn(value) {
20395
+ return displayIdent(value, { maxCodePoints: 613 });
20371
20396
  }
20372
20397
  function replacementTypes(op) {
20373
20398
  const routing = resolveReplacementOldType(op);
@@ -20427,6 +20452,453 @@ async function confirm(question) {
20427
20452
  refusal: "The cdkd rollback confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the rollback, or run the command from a real terminal."
20428
20453
  });
20429
20454
  }
20455
+
20456
+ // src/cli/commands/rollback/guards.ts
20457
+ function refuseDivergentRecordRegionForRollback(state, stackName, keyRegion, divergentBodyRegion, provenOrphans) {
20458
+ if (divergentBodyRegion === void 0) return;
20459
+ const resourceCount = isReadableBag(state.resources) ? Object.keys(state.resources).length : void 0;
20460
+ if (resourceCount === 0 && provenOrphans === 0) return;
20461
+ const lists = resourceCount === void 0 ? "its resources map cannot be read" : resourceCount > 0 ? `it still lists ${resourceCount} resource${resourceCount === 1 ? "" : "s"}` : `its journal holds ${provenOrphans} failed create${provenOrphans === 1 ? "" : "s"} whose resource the rollback would delete`;
20462
+ throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. Re-run with --verbose to see what the record's region field holds, repair that field to match the key it is stored under, and run the rollback again.`, STATE_REGION_DIVERGED));
20463
+ }
20464
+ function divergedDuringRollbackMessage(divergentBodyRegion) {
20465
+ return `the state record was rewritten during this rollback, and the rewrite carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the region of its key, so cdkd did not write over it`;
20466
+ }
20467
+ async function judgeNestedPendingRecords(setup, stackName, region, segments) {
20468
+ const pending = segments.filter((s) => s.reason === NESTED_PENDING_PARENT_REASON);
20469
+ if (pending.length === 0) return 0;
20470
+ const lastCut = stackName.lastIndexOf("~");
20471
+ const parent = lastCut > 0 ? stackName.slice(0, lastCut) : void 0;
20472
+ const topLevel = stackName.split("~")[0];
20473
+ const refuse = (detail) => {
20474
+ throw new Error(`The rollback journal of nested stack ${safeStack(stackName)} (${safe(region)}) holds the record of a nested deploy that ${detail} Roll back the top-level stack ${safeStack(topLevel)} instead, or re-deploy it, which clears the record.`);
20475
+ };
20476
+ if (parent === void 0) return pending.length;
20477
+ let parentJournal;
20478
+ try {
20479
+ parentJournal = await setup.stateBackend.loadRollbackJournal(parent, region);
20480
+ } catch (error) {
20481
+ return refuse(`cannot be judged: the journal of its parent ${safeStack(parent)} could not be read (${backendErrorText(error, parent, region)}), so the record may still be needed.`);
20482
+ }
20483
+ const parentRuns = new Set((parentJournal?.segments ?? []).flatMap((s) => s.runId !== void 0 ? [s.runId] : []));
20484
+ if (pending.some((s) => s.runId !== void 0 && parentRuns.has(s.runId))) refuse(`its parent has not settled, which only a rollback of the top-level stack may replay.`);
20485
+ let lock;
20486
+ try {
20487
+ lock = await setup.lockManager.getLockInfo(topLevel, region);
20488
+ } catch (error) {
20489
+ return refuse(`cannot be judged: the lock of the top-level stack could not be read (${backendErrorText(error, topLevel, region)}).`);
20490
+ }
20491
+ if (lock && !isLockInfoExpired(lock)) refuse("may belong to a deploy still running: the top-level stack is locked. Retry once it is free.");
20492
+ return pending.length;
20493
+ }
20494
+
20495
+ // src/cli/commands/rollback/preview.ts
20496
+ async function printRollbackPlanSegments(ctx) {
20497
+ const { journal, logger, options, inSegmentScope, planStateView, providerRegistry, region, setup, stackName, orphanLogicalIds } = ctx;
20498
+ for (let s = journal.segments.length - 1; s >= 0; s--) {
20499
+ const segment = journal.segments[s];
20500
+ logger.info(`\n Segment ${s + 1}/${journal.segments.length} (${safe(segment.reason)}${segment.runId ? `, run ${safe(segment.runId)}` : ""}):`);
20501
+ const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
20502
+ const completedOps = splitImportedOps(segment.operations, segment, orphanLogicalIds);
20503
+ for (const op of [...failedOps.imported, ...completedOps.imported]) logger.info(importedOpLabel(op));
20504
+ for (const op of [...failedOps.displaced, ...completedOps.displaced]) logger.info(displacedOpLabel(op, segment));
20505
+ const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
20506
+ if (failedOps.replay.length > 0) {
20507
+ if (failedToReplay.length > 0) {
20508
+ const failedPlan = await inSegmentScope(segment, () => recheckFailedPlan(planFailedOps(failedToReplay, planStateView), planStateView, {
20509
+ providerRegistry,
20510
+ region,
20511
+ logger
20512
+ }));
20513
+ for (const item of failedPlan) {
20514
+ logger.info(failedActionLabel(item, options.skipFinalSnapshot === true));
20515
+ if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
20516
+ }
20517
+ applyFailedPlanToPreview(failedPlan, planStateView, options.skipFinalSnapshot === true);
20518
+ }
20519
+ for (const fop of failedOps.replay.filter((op) => !failedToReplay.includes(op))) logger.info(` - (left as-is) ${logicalIdShown(fop.logicalId)} (${resourceTypeShown(fop.resourceType)}) — its ${plainOrDescribed(fop.changeType, "change type")} FAILED mid-deploy; pass --revert-failed to attempt reverting it`);
20520
+ }
20521
+ const plan = planRollback(completedOps.replay, planStateView, orphanLogicalIds);
20522
+ for (const item of plan) {
20523
+ logger.info(actionLabel(item, options.skipFinalSnapshot === true));
20524
+ if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
20525
+ }
20526
+ applyPlanToPreview(plan, planStateView, options.skipFinalSnapshot === true);
20527
+ }
20528
+ }
20529
+ async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
20530
+ const plain = isPasteableIdent(childStackName);
20531
+ const shown = plain ? `nested stack ${childStackName}` : "a nested stack whose name is not a plain identifier";
20532
+ const withPointer = (lines) => plain ? lines : [...lines, ` ${NESTED_NAME_DESCRIBED_NOTE}`];
20533
+ if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
20534
+ try {
20535
+ const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
20536
+ const segments = (journal?.segments ?? []).filter((s) => s.runId === runId);
20537
+ if (!childState || segments.length === 0) return withPointer([` (${shown}: no journal record for this run — its revert will FAIL and the segment is kept)`]);
20538
+ const view = { ...childState.state.resources };
20539
+ const lines = [` ${shown} replays its own journal:`];
20540
+ for (let s = segments.length - 1; s >= 0; s--) {
20541
+ const childOps = splitImportedOps(segments[s].operations, segments[s]);
20542
+ for (const op of childOps.imported) lines.push(` ${importedOpLabel(op)}`);
20543
+ for (const op of childOps.displaced) lines.push(` ${displacedOpLabel(op, segments[s])}`);
20544
+ const childPlan = planRollback(childOps.replay, view, /* @__PURE__ */ new Set());
20545
+ for (const item of childPlan) lines.push(` ${actionLabel(item, skipFinalSnapshot)}`);
20546
+ applyPlanToPreview(childPlan, view, skipFinalSnapshot);
20547
+ }
20548
+ if (lines.length === 1) lines.push(" (nothing to undo)");
20549
+ return withPointer(lines);
20550
+ } catch (error) {
20551
+ return withPointer([` (${shown}: could not preview its revert: ${backendErrorText(error, childStackName, region)})`]);
20552
+ }
20553
+ }
20554
+ function planItemWillBeRefused(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20555
+ if (skipFinalSnapshot) return false;
20556
+ return refusesFinalSnapshot(resourceType, effectiveProvisionedBy);
20557
+ }
20558
+ function applyPlanToPreview(plan, previewState, skipFinalSnapshot) {
20559
+ for (const item of plan) {
20560
+ const { op, action } = item;
20561
+ switch (action) {
20562
+ case "delete-with-final-snapshot":
20563
+ if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
20564
+ if (op.changeType === "CREATE") delete previewState[op.logicalId];
20565
+ break;
20566
+ case "delete":
20567
+ case "orphan-retain":
20568
+ case "orphan-flag":
20569
+ if (op.changeType === "CREATE") delete previewState[op.logicalId];
20570
+ break;
20571
+ case "revert":
20572
+ case "reverse-replacement":
20573
+ case "reverse-replacement-readopt": if (op.previousState) previewState[op.logicalId] = op.previousState;
20574
+ }
20575
+ }
20576
+ }
20577
+ function applyFailedPlanToPreview(plan, previewState, skipFinalSnapshot) {
20578
+ for (const item of plan) {
20579
+ const { op, action } = item;
20580
+ switch (action) {
20581
+ case "delete-failed-create-with-final-snapshot":
20582
+ if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
20583
+ if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
20584
+ break;
20585
+ case "delete-failed-create":
20586
+ case "orphan-failed-create-retain":
20587
+ if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
20588
+ break;
20589
+ case "revert-failed-update": if (op.previousState) previewState[op.logicalId] = op.previousState;
20590
+ }
20591
+ }
20592
+ }
20593
+
20594
+ // src/cli/commands/rollback/replay.ts
20595
+ async function runRollbackReplay(ctx) {
20596
+ const { providerClasses, setup, options, logger, stackName, region, crossPrefixScan, finalSnapshotClients, skipConfirmation } = ctx;
20597
+ const providerRegistry = new ProviderRegistry();
20598
+ registerAllProviders(providerRegistry, providerClasses);
20599
+ providerRegistry.setCustomResourceResponseBucket(setup.bucket);
20600
+ let interrupted = false;
20601
+ let declinedDivergentRewrite = false;
20602
+ let declinedDivergentReason = "";
20603
+ const sigintHandler = () => {
20604
+ process.stderr.write("\nInterrupted — stopping rollback after the current operation...\n");
20605
+ interrupted = true;
20606
+ };
20607
+ process.on("SIGINT", sigintHandler);
20608
+ const unforwardSigterm = forwardSigtermToSigint();
20609
+ try {
20610
+ await setup.lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
20611
+ } catch (error) {
20612
+ process.removeListener("SIGINT", sigintHandler);
20613
+ unforwardSigterm();
20614
+ throw error;
20615
+ }
20616
+ try {
20617
+ const stateData = await setup.stateBackend.getState(stackName, region);
20618
+ const stackInstanceId = stackInstanceIdOf(stateData?.state, displayStackName(stackName));
20619
+ let journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
20620
+ if (await resolvePendingCloudControlRequests({
20621
+ journal: setup.stateBackend,
20622
+ loaded: journal,
20623
+ reader: () => providerRegistry.getCloudControlProvider(),
20624
+ stackName,
20625
+ region,
20626
+ command: "rollback",
20627
+ logger,
20628
+ stateResources: stateData?.state.resources,
20629
+ stackInstanceId: stateData === null ? () => setup.stateBackend.readStackInstanceSibling(stackName, region) : stackInstanceId
20630
+ })) journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
20631
+ const orphanedPending = journal ? await judgeNestedPendingRecords(setup, stackName, region, journal.segments) : 0;
20632
+ if (journal && orphanedPending > 0) journal = {
20633
+ ...journal,
20634
+ segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
20635
+ };
20636
+ if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.`);
20637
+ applyCrossPrefixScan(await crossPrefixScan, {
20638
+ stackName,
20639
+ region,
20640
+ bucket: setup.bucket,
20641
+ recovery: {
20642
+ profile: options.profile,
20643
+ stateBucket: setup.bucket
20644
+ }
20645
+ }, "rollback", (message) => logger.warn(message), (message) => logger.info(message));
20646
+ if (!stateData) throw new Error(`Rollback journal exists for ${safeStack(stackName)} (${safe(region)}) but its state.json is missing (keys: ${safe(setup.prefix)}/${safeStack(stackName)}/${safe(region)}/state.json and .../rollback-journal.json). State appears corrupted — inspect the bucket manually.`);
20647
+ demoteSupersededOrphans(journal.segments, Array.isArray(stateData.state.orphans) ? stateData.state.orphans : []);
20648
+ if (!options.revertFailed) for (const segment of journal.segments) {
20649
+ const failedRows = splitImportedOps(segment.failedOperations ?? [], segment).replay;
20650
+ for (const logicalId of revertedNestedRowIds(failedRows)) {
20651
+ const child = nestedChildStackName$1(stackName, logicalId);
20652
+ if (((await setup.stateBackend.loadRollbackJournal(child, region).catch(() => null))?.segments ?? []).some((s) => s.runId === segment.runId && s.reason !== "nested-pending-parent" && splitImportedOps(s.operations, s).replay.length > 0)) throw new Error(`Nested stack ${plainOrDescribed(child, "nested stack name")} failed during a deploy this journal records, and its own journal still holds that deploy's completed operations. Re-run with --revert-failed so they are reverted in order with the parent's.`);
20653
+ }
20654
+ }
20655
+ const baseState = stateData.state;
20656
+ const refusalRecovery = {
20657
+ profile: options.profile,
20658
+ stateBucket: setup.bucket,
20659
+ statePrefix: options.statePrefix
20660
+ };
20661
+ refuseMalformedState(baseState, stackName, region, refusalRecovery);
20662
+ refuseMalformedOrphans(baseState, stackName, region, refusalRecovery);
20663
+ refuseMalformedOrphanRecords(baseState, stackName, region, refusalRecovery);
20664
+ refuseDivergentRecordRegionForRollback(baseState, stackName, region, stateData.divergentBodyRegion, journal.segments.flatMap((seg) => seg.failedOperations ?? []).filter((op) => op.physicalIdRecoveredFromError === true).length);
20665
+ const stateResources = { ...baseState.resources };
20666
+ const mintedOrphans = [];
20667
+ const rolledBackCreates = [];
20668
+ const supersededHost = {};
20669
+ const orphanLogicalIds = new Set(options.orphan ?? []);
20670
+ const newestSegment = journal.segments[journal.segments.length - 1];
20671
+ if (newestSegment?.roleArn && !options.roleArn) {
20672
+ const roleArnIsPlain = isIamRoleArn(newestSegment.roleArn) && safeRoleArn(newestSegment.roleArn) === newestSegment.roleArn;
20673
+ logger.info((roleArnIsPlain ? `Note: the failed deploy ran with --role-arn ${safeRoleArn(newestSegment.roleArn)}; ` : "Note: the failed deploy ran with --role-arn and a role ARN that is not a plain identifier (read it from the rollback journal); ") + `this rollback is running with ambient credentials (pass --role-arn to match).`);
20674
+ }
20675
+ let fallbackSkipPrefix;
20676
+ const legacySkipPrefix = () => fallbackSkipPrefix ??= resolveSkipPrefix({ quiet: true });
20677
+ const legacySegments = journal.segments.filter((s) => s.skipPrefix === void 0).length;
20678
+ if (legacySegments > 0) logger.warn(safeMsg`${legacySegments} of ${journal.segments.length} rollback journal segment(s) ` + "were recorded by a cdkd that did not record the user-supplied-name prefix setting; replaying them with the stack-name prefix " + (legacySkipPrefix() ? "SKIPPED" : "KEPT") + " on user-supplied physical names (CDKD_PREFIX_USER_SUPPLIED_NAMES / context.cdkd.prefixUserSuppliedNames in ./cdk.json / the default). If the failed deploy ran with --prefix-user-supplied-names, re-run with CDKD_PREFIX_USER_SUPPLIED_NAMES=true instead.");
20679
+ const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
20680
+ const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
20681
+ logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
20682
+ if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
20683
+ if (orphanedPending > 0) logger.info(safeMsg`\n Discard ${orphanedPending} record(s) of nested deploys whose parent run no longer ` + `has a journal to replay them (nothing else would ever replay them).`);
20684
+ const planStateView = { ...stateResources };
20685
+ await printRollbackPlanSegments({
20686
+ journal,
20687
+ logger,
20688
+ options,
20689
+ inSegmentScope,
20690
+ planStateView,
20691
+ providerRegistry,
20692
+ region,
20693
+ setup,
20694
+ stackName,
20695
+ orphanLogicalIds
20696
+ });
20697
+ logger.info("");
20698
+ if (!skipConfirmation) {
20699
+ if (!await confirm(`Roll back ${stackRegionShown(stackName, region)}` + (options.removeProtection === true ? ", TURNING DELETION PROTECTION OFF on the resources it deletes from this stack and the nested stacks it reverts?" : "?"))) {
20700
+ logger.info("Rollback cancelled");
20701
+ return;
20702
+ }
20703
+ }
20704
+ if (orphanedPending > 0) {
20705
+ const discarded = await setup.stateBackend.dropRollbackJournalSegments(stackName, region, (s) => s.reason === NESTED_PENDING_PARENT_REASON);
20706
+ logger.info(safeMsg`Discarded ${discarded} record(s) of nested deploys whose parent run no longer has a ` + `journal to replay them.`);
20707
+ }
20708
+ const eventRecorder = startRunRecorder({
20709
+ backend: setup.stateBackend,
20710
+ stackName,
20711
+ region,
20712
+ command: "rollback"
20713
+ });
20714
+ const ctx = {
20715
+ providerRegistry,
20716
+ region,
20717
+ logger: logger.child("rollback"),
20718
+ recordEvent: (e) => eventRecorder.record(maskEventTextWithBoundBags(e)),
20719
+ finalSnapshotClients,
20720
+ skipFinalSnapshot: options.skipFinalSnapshot === true,
20721
+ ...options.removeProtection === true && { removeProtection: true },
20722
+ foreignHolder: makeForeignHolderScan(setup.stateBackend)({
20723
+ stackName,
20724
+ region
20725
+ }),
20726
+ importedProducerRegions: producerRegionsFromState(baseState),
20727
+ ...(stackName.includes("~") || baseState.parentStack !== void 0) && { producerRegionsIncomplete: true }
20728
+ };
20729
+ let currentEtag = stateData.etag;
20730
+ const saveState = async () => {
20731
+ if (declinedDivergentRewrite) return;
20732
+ const { skippedOutputs: _droppedByRollback, ...carriedState } = baseState;
20733
+ const next = () => ({
20734
+ ...carriedState,
20735
+ ...stackInstanceIdCarriedFrom(baseState),
20736
+ ...supersededAfterRollback(baseState, supersededHost),
20737
+ version: 15,
20738
+ region,
20739
+ resources: { ...stateResources },
20740
+ ...orphansAfterRollback(baseState, mintedOrphans),
20741
+ ...retiredAfterRollback(baseState, mintedOrphans, rolledBackCreates),
20742
+ lastModified: Date.now()
20743
+ });
20744
+ try {
20745
+ currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
20746
+ } catch {
20747
+ try {
20748
+ const fresh = await setup.stateBackend.getState(stackName, region);
20749
+ if (fresh?.divergentBodyRegion !== void 0) {
20750
+ declinedDivergentRewrite = true;
20751
+ declinedDivergentReason = divergedDuringRollbackMessage(fresh.divergentBodyRegion);
20752
+ throw new Error(declinedDivergentReason);
20753
+ }
20754
+ currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
20755
+ } catch (retryError) {
20756
+ if (declinedDivergentRewrite) {
20757
+ logger.warn(`Did not persist state after a rollback operation: ${declinedDivergentReason}. The resource was reverted in AWS. Repair the record's region field to match the key it is stored under, then run the rollback again to reconcile state.`);
20758
+ return;
20759
+ }
20760
+ logger.warn(`Failed to persist state after a rollback operation: ${backendErrorText(retryError, stackName, region)}. The resource was reverted in AWS; re-run the rollback to reconcile state.` + rerunRollback(stackName));
20761
+ }
20762
+ }
20763
+ };
20764
+ const oldestInitialDeploy = journal.segments[0]?.initialDeploy === true;
20765
+ let totalFailures = 0;
20766
+ let totalWarnings = 0;
20767
+ const failedOrphanIds = [];
20768
+ const inlinePolicyWriters = new RollbackInlinePolicyWriters();
20769
+ const failedOpsPrinting = journaledOrphanPrintingBag(journal.segments.flatMap((s) => s.failedOperations ?? []), stateResources);
20770
+ try {
20771
+ while (journal.segments.length > 0) {
20772
+ if (interrupted) break;
20773
+ const segment = journal.segments[journal.segments.length - 1];
20774
+ const completedSplit = splitImportedOps(segment.operations, segment, orphanLogicalIds);
20775
+ const completedOps = completedSplit.replay;
20776
+ const displaced = [...completedSplit.displaced, ...splitImportedOps(segment.failedOperations ?? [], segment).displaced];
20777
+ for (const op of displaced) logger.warn(displacedOpLabel(op, segment).trim());
20778
+ recordDisplacedSkips(ctx.recordEvent, stackName, displaced);
20779
+ let nestedRun;
20780
+ const result = await withNestedStackContext({
20781
+ stateBackend: setup.stateBackend,
20782
+ lockManager: setup.lockManager,
20783
+ providerRegistry,
20784
+ parentStackName: stackName,
20785
+ parentRegion: region,
20786
+ accountId: "unknown",
20787
+ awsClients: finalSnapshotClients,
20788
+ stateBucket: setup.bucket,
20789
+ exportIndexStore: setup.exportIndexStore,
20790
+ destroyOptions: {
20791
+ ...options.profile && { profile: options.profile },
20792
+ statePrefix: options.statePrefix,
20793
+ ...options.skipFinalSnapshot === true && { skipFinalSnapshot: true },
20794
+ ...options.removeProtection === true && { removeProtection: true }
20795
+ }
20796
+ }, () => withNestedRevertRun(segment.runId, (run) => {
20797
+ nestedRun = run;
20798
+ return inSegmentScope(segment, async () => {
20799
+ let failedOpFailures = 0;
20800
+ let failedOpWarnings = 0;
20801
+ const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
20802
+ const failedForGuard = segment.failedOperations ?? [];
20803
+ const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
20804
+ if (failedToReplay.length > 0) {
20805
+ const failedResult = await withPrintingSecrets(failedOpsPrinting, () => withPrintingSecrets(journaledOrphanPrintingBag(failedToReplay, stateResources), () => replayFailedOperations(failedToReplay, stateResources, stackName, ctx, {
20806
+ afterOp: saveState,
20807
+ isInterrupted: () => interrupted,
20808
+ emitEnvelope: completedOps.length === 0,
20809
+ onOrphan: (record) => mintedOrphans.push(record),
20810
+ onRolledBackCreate: (create) => rolledBackCreates.push(create),
20811
+ inlinePolicyWriters
20812
+ })));
20813
+ failedOpFailures = failedResult.failures;
20814
+ failedOpWarnings = failedResult.warnings;
20815
+ for (const op of failedResult.remainingFailedOps) if (isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true) failedOrphanIds.push(op.logicalId);
20816
+ const remaining = [
20817
+ ...failedOps.imported,
20818
+ ...failedOps.displaced,
20819
+ ...failedOps.replay.filter((op) => !failedToReplay.includes(op)),
20820
+ ...failedResult.remainingFailedOps,
20821
+ ...completedOps.length > 0 ? failedToReplay.filter((op) => seedsDeleteFirstGuard(op) && !failedResult.remainingFailedOps.includes(op)) : []
20822
+ ];
20823
+ if (!declinedDivergentRewrite && remaining.length !== (segment.failedOperations ?? []).length) try {
20824
+ await setup.stateBackend.setRollbackJournalFailedOperations(stackName, region, remaining);
20825
+ if (remaining.length === 0) delete segment.failedOperations;
20826
+ else segment.failedOperations = remaining;
20827
+ } catch (stripError) {
20828
+ logger.warn(safeMsg`Failed to strip replayed failed-ops from the journal: ${backendErrorText(stripError, stackName, region)}`);
20829
+ }
20830
+ if (failedResult.interrupted) return {
20831
+ failures: failedOpFailures,
20832
+ warnings: failedOpWarnings,
20833
+ interrupted: true
20834
+ };
20835
+ }
20836
+ const replayResult = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(completedOps), stateResources), () => replayRollback(completedOps, stateResources, stackName, ctx, {
20837
+ orphanLogicalIds,
20838
+ afterOp: saveState,
20839
+ isInterrupted: () => interrupted,
20840
+ onOrphan: (record) => mintedOrphans.push(record),
20841
+ onRolledBackCreate: (create) => rolledBackCreates.push(create),
20842
+ inlinePolicyWriters,
20843
+ failedOperations: failedForGuard,
20844
+ onSuperseded: (entry) => addSuperseded(supersededHost, entry),
20845
+ onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
20846
+ }));
20847
+ return {
20848
+ failures: replayResult.failures + failedOpFailures,
20849
+ warnings: replayResult.warnings + failedOpWarnings,
20850
+ interrupted: replayResult.interrupted
20851
+ };
20852
+ });
20853
+ }));
20854
+ totalFailures += result.failures;
20855
+ totalWarnings += result.warnings + (nestedRun?.warnings ?? 0) + displaced.length;
20856
+ if (declinedDivergentRewrite) break;
20857
+ if (result.interrupted) {
20858
+ interrupted = true;
20859
+ break;
20860
+ }
20861
+ if (result.failures > 0) break;
20862
+ await setup.stateBackend.popRollbackJournalSegment(stackName, region);
20863
+ journal.segments.pop();
20864
+ await dropSettledNestedJournals({
20865
+ stateBackend: setup.stateBackend,
20866
+ lockManager: setup.lockManager,
20867
+ parentStackName: stackName,
20868
+ region,
20869
+ settled: nestedRun?.settled ?? /* @__PURE__ */ new Map(),
20870
+ runId: segment.runId,
20871
+ logger
20872
+ });
20873
+ }
20874
+ } finally {
20875
+ await eventRecorder.finalize(totalFailures > 0 || interrupted || declinedDivergentRewrite ? "FAILED" : "SUCCEEDED");
20876
+ }
20877
+ const survivingOrphans = orphansAfterRollback(baseState, mintedOrphans).orphans ?? [];
20878
+ if (journal.segments.length === 0 && oldestInitialDeploy && Object.keys(stateResources).length === 0 && survivingOrphans.length === 0 && !holdsSupersededResources(baseState)) {
20879
+ await setup.stateBackend.deleteState(stackName, region);
20880
+ await recordRetainedForReadoption(setup.stateBackend, stackName, region, [], logger);
20881
+ await releaseRegistryMarkerQuietly(setup.stateBackend, stackName, region, logger);
20882
+ logger.info(`State for ${stackRegionShown(stackName, region)} removed (stack fully rolled back).`);
20883
+ }
20884
+ if (declinedDivergentRewrite) throw new PartialFailureError(`Rollback stopped: ${declinedDivergentReason}.` + (totalFailures > 0 ? ` ${totalFailures} operation(s) also failed.` : "") + " Journal preserved (this segment, any older ones, and their failed operations) — re-run the rollback once the record's region field matches its key.");
20885
+ if (interrupted) throw new PartialFailureError(`Rollback interrupted. Journal preserved — re-run the rollback to finish.` + rerunRollback(stackName));
20886
+ if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved — re-run the rollback to retry.` + dropFailedHint(stackName, region, failedOrphanIds) + rerunRollback(stackName));
20887
+ if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
20888
+ logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
20889
+ } finally {
20890
+ try {
20891
+ await setup.lockManager.releaseLock(stackName, region).catch((err) => {
20892
+ logger.warn(`Failed to release lock for ${quotedOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}): ${backendErrorText(err, stackName, region)}`);
20893
+ });
20894
+ } finally {
20895
+ process.removeListener("SIGINT", sigintHandler);
20896
+ unforwardSigterm();
20897
+ }
20898
+ }
20899
+ }
20900
+
20901
+ // src/cli/commands/rollback/command.ts
20430
20902
  async function rollbackCommand(stackArg, options) {
20431
20903
  const providerClasses = await loadProviderClasses();
20432
20904
  const logger = getLogger();
@@ -20485,328 +20957,17 @@ async function rollbackCommand(stackArg, options) {
20485
20957
  });
20486
20958
  setAwsClients(stackAwsClients);
20487
20959
  const finalSnapshotClients = stackAwsClients;
20488
- await runWithStackAwsClients(stackAwsClients, async () => {
20489
- const providerRegistry = new ProviderRegistry();
20490
- registerAllProviders(providerRegistry, providerClasses);
20491
- providerRegistry.setCustomResourceResponseBucket(setup.bucket);
20492
- let interrupted = false;
20493
- let declinedDivergentRewrite = false;
20494
- let declinedDivergentReason = "";
20495
- const sigintHandler = () => {
20496
- process.stderr.write("\nInterrupted — stopping rollback after the current operation...\n");
20497
- interrupted = true;
20498
- };
20499
- process.on("SIGINT", sigintHandler);
20500
- const unforwardSigterm = forwardSigtermToSigint();
20501
- try {
20502
- await setup.lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
20503
- } catch (error) {
20504
- process.removeListener("SIGINT", sigintHandler);
20505
- unforwardSigterm();
20506
- throw error;
20507
- }
20508
- try {
20509
- const stateData = await setup.stateBackend.getState(stackName, region);
20510
- const stackInstanceId = stackInstanceIdOf(stateData?.state, displayStackName(stackName));
20511
- let journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
20512
- if (await resolvePendingCloudControlRequests({
20513
- journal: setup.stateBackend,
20514
- loaded: journal,
20515
- reader: () => providerRegistry.getCloudControlProvider(),
20516
- stackName,
20517
- region,
20518
- command: "rollback",
20519
- logger,
20520
- stateResources: stateData?.state.resources,
20521
- stackInstanceId: stateData === null ? () => setup.stateBackend.readStackInstanceSibling(stackName, region) : stackInstanceId
20522
- })) journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
20523
- const orphanedPending = journal ? await judgeNestedPendingRecords(setup, stackName, region, journal.segments) : 0;
20524
- if (journal && orphanedPending > 0) journal = {
20525
- ...journal,
20526
- segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
20527
- };
20528
- if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.`);
20529
- applyCrossPrefixScan(await crossPrefixScan, {
20530
- stackName,
20531
- region,
20532
- bucket: setup.bucket,
20533
- recovery: {
20534
- profile: options.profile,
20535
- stateBucket: setup.bucket
20536
- }
20537
- }, "rollback", (message) => logger.warn(message), (message) => logger.info(message));
20538
- if (!stateData) throw new Error(`Rollback journal exists for ${safeStack(stackName)} (${safe(region)}) but its state.json is missing (keys: ${safe(setup.prefix)}/${safeStack(stackName)}/${safe(region)}/state.json and .../rollback-journal.json). State appears corrupted — inspect the bucket manually.`);
20539
- demoteSupersededOrphans(journal.segments, Array.isArray(stateData.state.orphans) ? stateData.state.orphans : []);
20540
- if (!options.revertFailed) for (const segment of journal.segments) {
20541
- const failedRows = splitImportedOps(segment.failedOperations ?? [], segment).replay;
20542
- for (const logicalId of revertedNestedRowIds(failedRows)) {
20543
- const child = nestedChildStackName$1(stackName, logicalId);
20544
- if (((await setup.stateBackend.loadRollbackJournal(child, region).catch(() => null))?.segments ?? []).some((s) => s.runId === segment.runId && s.reason !== "nested-pending-parent" && splitImportedOps(s.operations, s).replay.length > 0)) throw new Error(`Nested stack ${plainOrDescribed(child, "nested stack name")} failed during a deploy this journal records, and its own journal still holds that deploy's completed operations. Re-run with --revert-failed so they are reverted in order with the parent's.`);
20545
- }
20546
- }
20547
- const baseState = stateData.state;
20548
- const refusalRecovery = {
20549
- profile: options.profile,
20550
- stateBucket: setup.bucket,
20551
- statePrefix: options.statePrefix
20552
- };
20553
- refuseMalformedState(baseState, stackName, region, refusalRecovery);
20554
- refuseMalformedOrphans(baseState, stackName, region, refusalRecovery);
20555
- refuseMalformedOrphanRecords(baseState, stackName, region, refusalRecovery);
20556
- refuseDivergentRecordRegionForRollback(baseState, stackName, region, stateData.divergentBodyRegion, journal.segments.flatMap((seg) => seg.failedOperations ?? []).filter((op) => op.physicalIdRecoveredFromError === true).length);
20557
- const stateResources = { ...baseState.resources };
20558
- const mintedOrphans = [];
20559
- const rolledBackCreates = [];
20560
- const supersededHost = {};
20561
- const orphanLogicalIds = new Set(options.orphan ?? []);
20562
- const newestSegment = journal.segments[journal.segments.length - 1];
20563
- if (newestSegment?.roleArn && !options.roleArn) {
20564
- const roleArnIsPlain = isIamRoleArn(newestSegment.roleArn) && safeRoleArn(newestSegment.roleArn) === newestSegment.roleArn;
20565
- logger.info((roleArnIsPlain ? `Note: the failed deploy ran with --role-arn ${safeRoleArn(newestSegment.roleArn)}; ` : "Note: the failed deploy ran with --role-arn and a role ARN that is not a plain identifier (read it from the rollback journal); ") + `this rollback is running with ambient credentials (pass --role-arn to match).`);
20566
- }
20567
- let fallbackSkipPrefix;
20568
- const legacySkipPrefix = () => fallbackSkipPrefix ??= resolveSkipPrefix({ quiet: true });
20569
- const legacySegments = journal.segments.filter((s) => s.skipPrefix === void 0).length;
20570
- if (legacySegments > 0) logger.warn(safeMsg`${legacySegments} of ${journal.segments.length} rollback journal segment(s) ` + "were recorded by a cdkd that did not record the user-supplied-name prefix setting; replaying them with the stack-name prefix " + (legacySkipPrefix() ? "SKIPPED" : "KEPT") + " on user-supplied physical names (CDKD_PREFIX_USER_SUPPLIED_NAMES / context.cdkd.prefixUserSuppliedNames in ./cdk.json / the default). If the failed deploy ran with --prefix-user-supplied-names, re-run with CDKD_PREFIX_USER_SUPPLIED_NAMES=true instead.");
20571
- const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
20572
- const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
20573
- logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
20574
- if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
20575
- if (orphanedPending > 0) logger.info(safeMsg`\n Discard ${orphanedPending} record(s) of nested deploys whose parent run no longer ` + `has a journal to replay them (nothing else would ever replay them).`);
20576
- const planStateView = { ...stateResources };
20577
- for (let s = journal.segments.length - 1; s >= 0; s--) {
20578
- const segment = journal.segments[s];
20579
- logger.info(`\n Segment ${s + 1}/${journal.segments.length} (${safe(segment.reason)}${segment.runId ? `, run ${safe(segment.runId)}` : ""}):`);
20580
- const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
20581
- const completedOps = splitImportedOps(segment.operations, segment, orphanLogicalIds);
20582
- for (const op of [...failedOps.imported, ...completedOps.imported]) logger.info(importedOpLabel(op));
20583
- for (const op of [...failedOps.displaced, ...completedOps.displaced]) logger.info(displacedOpLabel(op, segment));
20584
- const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
20585
- if (failedOps.replay.length > 0) {
20586
- if (failedToReplay.length > 0) {
20587
- const failedPlan = await inSegmentScope(segment, () => recheckFailedPlan(planFailedOps(failedToReplay, planStateView), planStateView, {
20588
- providerRegistry,
20589
- region,
20590
- logger
20591
- }));
20592
- for (const item of failedPlan) {
20593
- logger.info(failedActionLabel(item, options.skipFinalSnapshot === true));
20594
- if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
20595
- }
20596
- applyFailedPlanToPreview(failedPlan, planStateView, options.skipFinalSnapshot === true);
20597
- }
20598
- for (const fop of failedOps.replay.filter((op) => !failedToReplay.includes(op))) logger.info(` - (left as-is) ${logicalIdShown(fop.logicalId)} (${resourceTypeShown(fop.resourceType)}) — its ${plainOrDescribed(fop.changeType, "change type")} FAILED mid-deploy; pass --revert-failed to attempt reverting it`);
20599
- }
20600
- const plan = planRollback(completedOps.replay, planStateView, orphanLogicalIds);
20601
- for (const item of plan) {
20602
- logger.info(actionLabel(item, options.skipFinalSnapshot === true));
20603
- if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
20604
- }
20605
- applyPlanToPreview(plan, planStateView, options.skipFinalSnapshot === true);
20606
- }
20607
- logger.info("");
20608
- if (!skipConfirmation) {
20609
- if (!await confirm(`Roll back ${stackRegionShown(stackName, region)}` + (options.removeProtection === true ? ", TURNING DELETION PROTECTION OFF on the resources it deletes from this stack and the nested stacks it reverts?" : "?"))) {
20610
- logger.info("Rollback cancelled");
20611
- return;
20612
- }
20613
- }
20614
- if (orphanedPending > 0) {
20615
- const discarded = await setup.stateBackend.dropRollbackJournalSegments(stackName, region, (s) => s.reason === NESTED_PENDING_PARENT_REASON);
20616
- logger.info(safeMsg`Discarded ${discarded} record(s) of nested deploys whose parent run no longer has a ` + `journal to replay them.`);
20617
- }
20618
- const eventRecorder = startRunRecorder({
20619
- backend: setup.stateBackend,
20620
- stackName,
20621
- region,
20622
- command: "rollback"
20623
- });
20624
- const ctx = {
20625
- providerRegistry,
20626
- region,
20627
- logger: logger.child("rollback"),
20628
- recordEvent: (e) => eventRecorder.record(maskEventTextWithBoundBags(e)),
20629
- finalSnapshotClients,
20630
- skipFinalSnapshot: options.skipFinalSnapshot === true,
20631
- ...options.removeProtection === true && { removeProtection: true },
20632
- foreignHolder: makeForeignHolderScan(setup.stateBackend)({
20633
- stackName,
20634
- region
20635
- }),
20636
- importedProducerRegions: producerRegionsFromState(baseState),
20637
- ...(stackName.includes("~") || baseState.parentStack !== void 0) && { producerRegionsIncomplete: true }
20638
- };
20639
- let currentEtag = stateData.etag;
20640
- const saveState = async () => {
20641
- if (declinedDivergentRewrite) return;
20642
- const { skippedOutputs: _droppedByRollback, ...carriedState } = baseState;
20643
- const next = () => ({
20644
- ...carriedState,
20645
- ...stackInstanceIdCarriedFrom(baseState),
20646
- ...supersededAfterRollback(baseState, supersededHost),
20647
- version: 15,
20648
- region,
20649
- resources: { ...stateResources },
20650
- ...orphansAfterRollback(baseState, mintedOrphans),
20651
- ...retiredAfterRollback(baseState, mintedOrphans, rolledBackCreates),
20652
- lastModified: Date.now()
20653
- });
20654
- try {
20655
- currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
20656
- } catch {
20657
- try {
20658
- const fresh = await setup.stateBackend.getState(stackName, region);
20659
- if (fresh?.divergentBodyRegion !== void 0) {
20660
- declinedDivergentRewrite = true;
20661
- declinedDivergentReason = divergedDuringRollbackMessage(fresh.divergentBodyRegion);
20662
- throw new Error(declinedDivergentReason);
20663
- }
20664
- currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
20665
- } catch (retryError) {
20666
- if (declinedDivergentRewrite) {
20667
- logger.warn(`Did not persist state after a rollback operation: ${declinedDivergentReason}. The resource was reverted in AWS. Repair the record's region field to match the key it is stored under, then run the rollback again to reconcile state.`);
20668
- return;
20669
- }
20670
- logger.warn(`Failed to persist state after a rollback operation: ${backendErrorText(retryError, stackName, region)}. The resource was reverted in AWS; re-run the rollback to reconcile state.` + rerunRollback(stackName));
20671
- }
20672
- }
20673
- };
20674
- const oldestInitialDeploy = journal.segments[0]?.initialDeploy === true;
20675
- let totalFailures = 0;
20676
- let totalWarnings = 0;
20677
- const failedOrphanIds = [];
20678
- const inlinePolicyWriters = new RollbackInlinePolicyWriters();
20679
- const failedOpsPrinting = journaledOrphanPrintingBag(journal.segments.flatMap((s) => s.failedOperations ?? []), stateResources);
20680
- try {
20681
- while (journal.segments.length > 0) {
20682
- if (interrupted) break;
20683
- const segment = journal.segments[journal.segments.length - 1];
20684
- const completedSplit = splitImportedOps(segment.operations, segment, orphanLogicalIds);
20685
- const completedOps = completedSplit.replay;
20686
- const displaced = [...completedSplit.displaced, ...splitImportedOps(segment.failedOperations ?? [], segment).displaced];
20687
- for (const op of displaced) logger.warn(displacedOpLabel(op, segment).trim());
20688
- recordDisplacedSkips(ctx.recordEvent, stackName, displaced);
20689
- let nestedRun;
20690
- const result = await withNestedStackContext({
20691
- stateBackend: setup.stateBackend,
20692
- lockManager: setup.lockManager,
20693
- providerRegistry,
20694
- parentStackName: stackName,
20695
- parentRegion: region,
20696
- accountId: "unknown",
20697
- awsClients: finalSnapshotClients,
20698
- stateBucket: setup.bucket,
20699
- exportIndexStore: setup.exportIndexStore,
20700
- destroyOptions: {
20701
- ...options.profile && { profile: options.profile },
20702
- statePrefix: options.statePrefix,
20703
- ...options.skipFinalSnapshot === true && { skipFinalSnapshot: true },
20704
- ...options.removeProtection === true && { removeProtection: true }
20705
- }
20706
- }, () => withNestedRevertRun(segment.runId, (run) => {
20707
- nestedRun = run;
20708
- return inSegmentScope(segment, async () => {
20709
- let failedOpFailures = 0;
20710
- let failedOpWarnings = 0;
20711
- const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
20712
- const failedForGuard = segment.failedOperations ?? [];
20713
- const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
20714
- if (failedToReplay.length > 0) {
20715
- const failedResult = await withPrintingSecrets(failedOpsPrinting, () => withPrintingSecrets(journaledOrphanPrintingBag(failedToReplay, stateResources), () => replayFailedOperations(failedToReplay, stateResources, stackName, ctx, {
20716
- afterOp: saveState,
20717
- isInterrupted: () => interrupted,
20718
- emitEnvelope: completedOps.length === 0,
20719
- onOrphan: (record) => mintedOrphans.push(record),
20720
- onRolledBackCreate: (create) => rolledBackCreates.push(create),
20721
- inlinePolicyWriters
20722
- })));
20723
- failedOpFailures = failedResult.failures;
20724
- failedOpWarnings = failedResult.warnings;
20725
- for (const op of failedResult.remainingFailedOps) if (isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true) failedOrphanIds.push(op.logicalId);
20726
- const remaining = [
20727
- ...failedOps.imported,
20728
- ...failedOps.displaced,
20729
- ...failedOps.replay.filter((op) => !failedToReplay.includes(op)),
20730
- ...failedResult.remainingFailedOps,
20731
- ...completedOps.length > 0 ? failedToReplay.filter((op) => seedsDeleteFirstGuard(op) && !failedResult.remainingFailedOps.includes(op)) : []
20732
- ];
20733
- if (!declinedDivergentRewrite && remaining.length !== (segment.failedOperations ?? []).length) try {
20734
- await setup.stateBackend.setRollbackJournalFailedOperations(stackName, region, remaining);
20735
- if (remaining.length === 0) delete segment.failedOperations;
20736
- else segment.failedOperations = remaining;
20737
- } catch (stripError) {
20738
- logger.warn(safeMsg`Failed to strip replayed failed-ops from the journal: ${backendErrorText(stripError, stackName, region)}`);
20739
- }
20740
- if (failedResult.interrupted) return {
20741
- failures: failedOpFailures,
20742
- warnings: failedOpWarnings,
20743
- interrupted: true
20744
- };
20745
- }
20746
- const replayResult = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(completedOps), stateResources), () => replayRollback(completedOps, stateResources, stackName, ctx, {
20747
- orphanLogicalIds,
20748
- afterOp: saveState,
20749
- isInterrupted: () => interrupted,
20750
- onOrphan: (record) => mintedOrphans.push(record),
20751
- onRolledBackCreate: (create) => rolledBackCreates.push(create),
20752
- inlinePolicyWriters,
20753
- failedOperations: failedForGuard,
20754
- onSuperseded: (entry) => addSuperseded(supersededHost, entry),
20755
- onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
20756
- }));
20757
- return {
20758
- failures: replayResult.failures + failedOpFailures,
20759
- warnings: replayResult.warnings + failedOpWarnings,
20760
- interrupted: replayResult.interrupted
20761
- };
20762
- });
20763
- }));
20764
- totalFailures += result.failures;
20765
- totalWarnings += result.warnings + (nestedRun?.warnings ?? 0) + displaced.length;
20766
- if (declinedDivergentRewrite) break;
20767
- if (result.interrupted) {
20768
- interrupted = true;
20769
- break;
20770
- }
20771
- if (result.failures > 0) break;
20772
- await setup.stateBackend.popRollbackJournalSegment(stackName, region);
20773
- journal.segments.pop();
20774
- await dropSettledNestedJournals({
20775
- stateBackend: setup.stateBackend,
20776
- lockManager: setup.lockManager,
20777
- parentStackName: stackName,
20778
- region,
20779
- settled: nestedRun?.settled ?? /* @__PURE__ */ new Map(),
20780
- runId: segment.runId,
20781
- logger
20782
- });
20783
- }
20784
- } finally {
20785
- await eventRecorder.finalize(totalFailures > 0 || interrupted || declinedDivergentRewrite ? "FAILED" : "SUCCEEDED");
20786
- }
20787
- const survivingOrphans = orphansAfterRollback(baseState, mintedOrphans).orphans ?? [];
20788
- if (journal.segments.length === 0 && oldestInitialDeploy && Object.keys(stateResources).length === 0 && survivingOrphans.length === 0 && !holdsSupersededResources(baseState)) {
20789
- await setup.stateBackend.deleteState(stackName, region);
20790
- await recordRetainedForReadoption(setup.stateBackend, stackName, region, [], logger);
20791
- await releaseRegistryMarkerQuietly(setup.stateBackend, stackName, region, logger);
20792
- logger.info(`State for ${stackRegionShown(stackName, region)} removed (stack fully rolled back).`);
20793
- }
20794
- if (declinedDivergentRewrite) throw new PartialFailureError(`Rollback stopped: ${declinedDivergentReason}.` + (totalFailures > 0 ? ` ${totalFailures} operation(s) also failed.` : "") + " Journal preserved (this segment, any older ones, and their failed operations) — re-run the rollback once the record's region field matches its key.");
20795
- if (interrupted) throw new PartialFailureError(`Rollback interrupted. Journal preserved — re-run the rollback to finish.` + rerunRollback(stackName));
20796
- if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved — re-run the rollback to retry.` + dropFailedHint(stackName, region, failedOrphanIds) + rerunRollback(stackName));
20797
- if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
20798
- logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
20799
- } finally {
20800
- try {
20801
- await setup.lockManager.releaseLock(stackName, region).catch((err) => {
20802
- logger.warn(`Failed to release lock for ${quotedOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}): ${backendErrorText(err, stackName, region)}`);
20803
- });
20804
- } finally {
20805
- process.removeListener("SIGINT", sigintHandler);
20806
- unforwardSigterm();
20807
- }
20808
- }
20809
- });
20960
+ await runWithStackAwsClients(stackAwsClients, () => runRollbackReplay({
20961
+ providerClasses,
20962
+ setup,
20963
+ options,
20964
+ logger,
20965
+ stackName,
20966
+ region,
20967
+ crossPrefixScan,
20968
+ finalSnapshotClients,
20969
+ skipConfirmation
20970
+ }));
20810
20971
  } finally {
20811
20972
  if (stackAwsClients) {
20812
20973
  setAwsClients(setup.awsClients);
@@ -20815,97 +20976,8 @@ async function rollbackCommand(stackArg, options) {
20815
20976
  setup.dispose();
20816
20977
  }
20817
20978
  }
20818
- async function judgeNestedPendingRecords(setup, stackName, region, segments) {
20819
- const pending = segments.filter((s) => s.reason === NESTED_PENDING_PARENT_REASON);
20820
- if (pending.length === 0) return 0;
20821
- const lastCut = stackName.lastIndexOf("~");
20822
- const parent = lastCut > 0 ? stackName.slice(0, lastCut) : void 0;
20823
- const topLevel = stackName.split("~")[0];
20824
- const refuse = (detail) => {
20825
- throw new Error(`The rollback journal of nested stack ${safeStack(stackName)} (${safe(region)}) holds the record of a nested deploy that ${detail} Roll back the top-level stack ${safeStack(topLevel)} instead, or re-deploy it, which clears the record.`);
20826
- };
20827
- if (parent === void 0) return pending.length;
20828
- let parentJournal;
20829
- try {
20830
- parentJournal = await setup.stateBackend.loadRollbackJournal(parent, region);
20831
- } catch (error) {
20832
- return refuse(`cannot be judged: the journal of its parent ${safeStack(parent)} could not be read (${backendErrorText(error, parent, region)}), so the record may still be needed.`);
20833
- }
20834
- const parentRuns = new Set((parentJournal?.segments ?? []).flatMap((s) => s.runId !== void 0 ? [s.runId] : []));
20835
- if (pending.some((s) => s.runId !== void 0 && parentRuns.has(s.runId))) refuse(`its parent has not settled, which only a rollback of the top-level stack may replay.`);
20836
- let lock;
20837
- try {
20838
- lock = await setup.lockManager.getLockInfo(topLevel, region);
20839
- } catch (error) {
20840
- return refuse(`cannot be judged: the lock of the top-level stack could not be read (${backendErrorText(error, topLevel, region)}).`);
20841
- }
20842
- if (lock && !isLockInfoExpired(lock)) refuse("may belong to a deploy still running: the top-level stack is locked. Retry once it is free.");
20843
- return pending.length;
20844
- }
20845
- async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
20846
- const plain = isPasteableIdent(childStackName);
20847
- const shown = plain ? `nested stack ${childStackName}` : "a nested stack whose name is not a plain identifier";
20848
- const withPointer = (lines) => plain ? lines : [...lines, ` ${NESTED_NAME_DESCRIBED_NOTE}`];
20849
- if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
20850
- try {
20851
- const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
20852
- const segments = (journal?.segments ?? []).filter((s) => s.runId === runId);
20853
- if (!childState || segments.length === 0) return withPointer([` (${shown}: no journal record for this run — its revert will FAIL and the segment is kept)`]);
20854
- const view = { ...childState.state.resources };
20855
- const lines = [` ${shown} replays its own journal:`];
20856
- for (let s = segments.length - 1; s >= 0; s--) {
20857
- const childOps = splitImportedOps(segments[s].operations, segments[s]);
20858
- for (const op of childOps.imported) lines.push(` ${importedOpLabel(op)}`);
20859
- for (const op of childOps.displaced) lines.push(` ${displacedOpLabel(op, segments[s])}`);
20860
- const childPlan = planRollback(childOps.replay, view, /* @__PURE__ */ new Set());
20861
- for (const item of childPlan) lines.push(` ${actionLabel(item, skipFinalSnapshot)}`);
20862
- applyPlanToPreview(childPlan, view, skipFinalSnapshot);
20863
- }
20864
- if (lines.length === 1) lines.push(" (nothing to undo)");
20865
- return withPointer(lines);
20866
- } catch (error) {
20867
- return withPointer([` (${shown}: could not preview its revert: ${backendErrorText(error, childStackName, region)})`]);
20868
- }
20869
- }
20870
- function planItemWillBeRefused(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20871
- if (skipFinalSnapshot) return false;
20872
- return refusesFinalSnapshot(resourceType, effectiveProvisionedBy);
20873
- }
20874
- function applyPlanToPreview(plan, previewState, skipFinalSnapshot) {
20875
- for (const item of plan) {
20876
- const { op, action } = item;
20877
- switch (action) {
20878
- case "delete-with-final-snapshot":
20879
- if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
20880
- if (op.changeType === "CREATE") delete previewState[op.logicalId];
20881
- break;
20882
- case "delete":
20883
- case "orphan-retain":
20884
- case "orphan-flag":
20885
- if (op.changeType === "CREATE") delete previewState[op.logicalId];
20886
- break;
20887
- case "revert":
20888
- case "reverse-replacement":
20889
- case "reverse-replacement-readopt": if (op.previousState) previewState[op.logicalId] = op.previousState;
20890
- }
20891
- }
20892
- }
20893
- function applyFailedPlanToPreview(plan, previewState, skipFinalSnapshot) {
20894
- for (const item of plan) {
20895
- const { op, action } = item;
20896
- switch (action) {
20897
- case "delete-failed-create-with-final-snapshot":
20898
- if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
20899
- if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
20900
- break;
20901
- case "delete-failed-create":
20902
- case "orphan-failed-create-retain":
20903
- if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
20904
- break;
20905
- case "revert-failed-update": if (op.previousState) previewState[op.logicalId] = op.previousState;
20906
- }
20907
- }
20908
- }
20979
+
20980
+ // src/cli/commands/rollback.ts
20909
20981
  function createRollbackCommand() {
20910
20982
  const cmd = new Command("rollback").description("Revert a stack to its pre-deploy state after a failed --no-rollback / interrupted deploy or a partially-failed automatic rollback (state-driven, no synth needed).").argument("[stack]", "Stack name to roll back (defaults to the single journaled stack)").addOption(new Option("--force", "Skip the confirmation prompt").default(false)).addOption(new Option("--orphan <logicalId>", "Skip the given resource during replay (repeatable). Mirrors cdk rollback --orphan.").argParser((value, previous) => [...previous ?? [], value])).addOption(new Option("--revert-failed", "Also attempt to revert the resource whose operation FAILED mid-deploy. Off by default: the remote state of the failed resource is unknown, so force-applying its previous state is opt-in.").default(false)).addOption(new Option("--drop-failed <logicalId>", "Remove ONE journaled failed CREATE (a resource cdkd proved it made, journaled as its only record) from the rollback journal, after checking that resource by hand. Replays nothing and deletes nothing in AWS; every other entry is kept.")).addOption(skipFinalSnapshotOption).addOption(new Option("--remove-protection", `Turn deletion protection off before this stack's rollback deletes a resource the failed deploy left: one its state records from a completed CREATE, or one a failed CREATE left behind (a journaled orphan, or under --revert-failed the failed CREATE itself) when cdkd can prove it is that resource and no other stack holds it. A nested stack it deletes cascades the flag to that child's resources, and a nested stack it reverts carries it into that child's revert. Covers ${removeProtectionTypeList()}.`).default(false)).addOption(stackRegionOption()).addHelpText("after", [
20911
20983
  "",
@@ -25424,6 +25496,7 @@ const SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
25424
25496
 
25425
25497
  // src/local/rie-client.ts
25426
25498
  const INVOKE_PATH = "/2015-03-31/functions/function/invocations";
25499
+ const NOT_AN_RIE_STATUS = /* @__PURE__ */ new Set([404, 405]);
25427
25500
  async function waitForRieReady(host, port, timeoutMs = 5e3) {
25428
25501
  const deadline = Date.now() + timeoutMs;
25429
25502
  let lastError;
@@ -25484,6 +25557,7 @@ async function invokeRie(host, port, event, timeoutMs) {
25484
25557
  clearTimeout(timer);
25485
25558
  }
25486
25559
  const raw = await response.text();
25560
+ if (NOT_AN_RIE_STATUS.has(response.status)) throw new Error(`The container answered the invoke at ${url} with HTTP ${response.status}, which the Lambda Runtime Interface Emulator never sends for that path: something else is listening on the container's port 8080 (the function's own server?). Check the container logs.`);
25487
25561
  let payload = raw;
25488
25562
  try {
25489
25563
  payload = JSON.parse(raw);
@@ -25579,11 +25653,11 @@ function createContainerPool(specs, options) {
25579
25653
  } else containerId = await removedIfDisposedOnFailure(name, runDetached({
25580
25654
  image: spec.image,
25581
25655
  mounts: [],
25582
- ...spec.profileCredentialsFile && { extraMounts: [{
25656
+ extraMounts: [...spec.rieMount ? [spec.rieMount] : [], ...spec.profileCredentialsFile ? [{
25583
25657
  hostPath: spec.profileCredentialsFile.hostPath,
25584
25658
  containerPath: spec.profileCredentialsFile.containerPath,
25585
25659
  readOnly: true
25586
- }] },
25660
+ }] : []],
25587
25661
  env: spec.env,
25588
25662
  ...spec.sensitiveEnvKeys !== void 0 && { sensitiveEnvKeys: spec.sensitiveEnvKeys },
25589
25663
  cmd: spec.command,
@@ -27023,6 +27097,192 @@ async function verifyImageInLocalCache(imageUri) {
27023
27097
  }
27024
27098
  }
27025
27099
 
27100
+ // src/local/rie-mount.ts
27101
+ const RIE_CONTAINER_PATH = "/var/rapid/aws-lambda-rie";
27102
+ const RIE_SOURCE_IMAGE = "public.ecr.aws/lambda/provided:al2023";
27103
+ const RIE_SOURCE_PATH = "/usr/local/bin/aws-lambda-rie";
27104
+ const RIE_BASENAME = "aws-lambda-rie";
27105
+ const ELF_MACHINE_BY_PLATFORM = {
27106
+ "linux/amd64": 62,
27107
+ "linux/arm64": 183
27108
+ };
27109
+ function rieCacheDirectory(env = process.env) {
27110
+ const root = cdkdCacheHome(env);
27111
+ return root === void 0 ? void 0 : join(root, "lambda-rie");
27112
+ }
27113
+ const inFlight = /* @__PURE__ */ new Map();
27114
+ const warnedNoBinary = /* @__PURE__ */ new Set();
27115
+ async function resolveRieWrap(input) {
27116
+ const logger = getLogger().child("rie");
27117
+ let program;
27118
+ try {
27119
+ const own = nonEmpty(input.entryPoint) && nonEmpty(input.command) ? {
27120
+ entrypoint: [],
27121
+ cmd: []
27122
+ } : await inspectImageEntrypointCmd(input.image);
27123
+ const entryPoint = nonEmpty(input.entryPoint) ? [...input.entryPoint] : own.entrypoint;
27124
+ const cmd = nonEmpty(input.command) ? [...input.command] : own.cmd;
27125
+ program = [...entryPoint, ...cmd];
27126
+ } catch (err) {
27127
+ logger.warn(safeMsg`Could not read the ENTRYPOINT / CMD of image ${input.image} (${messageOf(err)}), so no Lambda Runtime Interface Emulator is mounted into it; it runs as built.`);
27128
+ return;
27129
+ }
27130
+ const ownRie = program.find(isRieExecutable);
27131
+ if (ownRie !== void 0) {
27132
+ logger.debug(safeMsg`Image ${input.image} already starts ${ownRie}; not mounting another RIE`);
27133
+ return;
27134
+ }
27135
+ let hostPath;
27136
+ try {
27137
+ hostPath = await ensureRieBinary(input.platform, input.skipPull === true);
27138
+ } catch (err) {
27139
+ if (!warnedNoBinary.has(input.platform)) {
27140
+ warnedNoBinary.add(input.platform);
27141
+ logger.warn(safeMsg`Could not mount the Lambda Runtime Interface Emulator into container-image functions (${messageOf(err)}). ` + "They run as built, so only images that ship their own emulator (the AWS Lambda base images do) can be invoked.");
27142
+ } else logger.debug(safeMsg`RIE mount skipped for ${input.image}: ${messageOf(err)}`);
27143
+ return;
27144
+ }
27145
+ return {
27146
+ mount: {
27147
+ hostPath,
27148
+ containerPath: RIE_CONTAINER_PATH,
27149
+ readOnly: true
27150
+ },
27151
+ entryPoint: [RIE_CONTAINER_PATH],
27152
+ cmd: program
27153
+ };
27154
+ }
27155
+ function isRieExecutable(path) {
27156
+ return basename(path).startsWith(RIE_BASENAME);
27157
+ }
27158
+ function messageOf(err) {
27159
+ return err instanceof Error ? err.message : String(err);
27160
+ }
27161
+ function nonEmpty(v) {
27162
+ return v !== void 0 && v.length > 0;
27163
+ }
27164
+ async function inspectImageEntrypointCmd(image) {
27165
+ const args = [
27166
+ "image",
27167
+ "inspect",
27168
+ "--format",
27169
+ "{{json .Config}}",
27170
+ image
27171
+ ];
27172
+ let stdout;
27173
+ try {
27174
+ ({stdout} = await runDockerStreaming(args, { streamLive: false }));
27175
+ } catch (err) {
27176
+ throw new Error(`docker image inspect failed: ${describeDockerFailure(err, args)}`);
27177
+ }
27178
+ const config = JSON.parse(stdout.trim());
27179
+ return {
27180
+ entrypoint: stringArray(config?.Entrypoint),
27181
+ cmd: stringArray(config?.Cmd)
27182
+ };
27183
+ }
27184
+ function stringArray(v) {
27185
+ return Array.isArray(v) && v.every((s) => typeof s === "string") ? v : [];
27186
+ }
27187
+ async function ensureRieBinary(platform, skipPull) {
27188
+ const machine = ELF_MACHINE_BY_PLATFORM[platform];
27189
+ if (machine === void 0) throw new Error(`unsupported platform '${platform}'`);
27190
+ const root = rieCacheDirectory();
27191
+ if (root === void 0) throw new Error("no cache directory (HOME is not set)");
27192
+ const target = join(root, platform.replace("/", "-"), RIE_BASENAME);
27193
+ let run = inFlight.get(target);
27194
+ if (run === void 0) {
27195
+ run = (async () => {
27196
+ if (await isRegularFile(target) && await isElfFor(target, machine)) return target;
27197
+ await extractRie(platform, target, machine, skipPull);
27198
+ return target;
27199
+ })();
27200
+ inFlight.set(target, run);
27201
+ run.catch(() => inFlight.delete(target));
27202
+ }
27203
+ return run;
27204
+ }
27205
+ async function isRegularFile(path) {
27206
+ try {
27207
+ return (await promises.lstat(path)).isFile();
27208
+ } catch {
27209
+ return false;
27210
+ }
27211
+ }
27212
+ async function isElfFor(path, machine) {
27213
+ let handle;
27214
+ try {
27215
+ handle = await promises.open(path, "r");
27216
+ const header = Buffer.alloc(20);
27217
+ const { bytesRead } = await handle.read(header, 0, 20, 0);
27218
+ return bytesRead === 20 && header.readUInt32BE(0) === 2135247942 && header.readUInt16LE(18) === machine;
27219
+ } catch {
27220
+ return false;
27221
+ } finally {
27222
+ await handle?.close().catch(() => void 0);
27223
+ }
27224
+ }
27225
+ async function extractRie(platform, target, machine, skipPull) {
27226
+ getLogger().child("rie").info(skipPull ? safeMsg`Copying the Lambda Runtime Interface Emulator for ${platform} out of the local ${RIE_SOURCE_IMAGE} image (one time)...` : safeMsg`Fetching the Lambda Runtime Interface Emulator for ${platform} from ${RIE_SOURCE_IMAGE} (one time)...`);
27227
+ const dir = join(target, "..");
27228
+ await promises.mkdir(dir, {
27229
+ recursive: true,
27230
+ mode: 448
27231
+ });
27232
+ if (!skipPull) {
27233
+ const pullArgs = [
27234
+ "pull",
27235
+ "--platform",
27236
+ platform,
27237
+ RIE_SOURCE_IMAGE
27238
+ ];
27239
+ try {
27240
+ await runDockerStreaming(pullArgs, { streamLive: false });
27241
+ } catch (err) {
27242
+ throw new Error(`docker pull failed: ${describeDockerFailure(err, pullArgs)}`);
27243
+ }
27244
+ }
27245
+ const createArgs = [
27246
+ "create",
27247
+ ...skipPull ? ["--pull", "never"] : [],
27248
+ "--platform",
27249
+ platform,
27250
+ RIE_SOURCE_IMAGE
27251
+ ];
27252
+ let containerId;
27253
+ try {
27254
+ containerId = (await runDockerStreaming(createArgs, { streamLive: false })).stdout.trim();
27255
+ } catch (err) {
27256
+ throw new Error(`docker create failed: ${describeDockerFailure(err, createArgs)}`);
27257
+ }
27258
+ const tmp = join(dir, `.${RIE_BASENAME}.${process.pid}.${randomBytes(4).toString("hex")}`);
27259
+ try {
27260
+ const cpArgs = [
27261
+ "cp",
27262
+ `${containerId}:${RIE_SOURCE_PATH}`,
27263
+ tmp
27264
+ ];
27265
+ try {
27266
+ await runDockerStreaming(cpArgs, { streamLive: false });
27267
+ } catch (err) {
27268
+ throw new Error(`docker cp failed: ${describeDockerFailure(err, cpArgs)}`);
27269
+ }
27270
+ if (!await isRegularFile(tmp) || !await isElfFor(tmp, machine)) throw new Error(`the copied ${RIE_SOURCE_PATH} is not a ${platform} executable`);
27271
+ await promises.chmod(tmp, 493);
27272
+ await promises.rename(tmp, target);
27273
+ } finally {
27274
+ await promises.rm(tmp, {
27275
+ force: true,
27276
+ recursive: true
27277
+ }).catch(() => void 0);
27278
+ await runDockerStreaming([
27279
+ "rm",
27280
+ "-f",
27281
+ containerId
27282
+ ], { streamLive: false }).catch(() => void 0);
27283
+ }
27284
+ }
27285
+
27026
27286
  // src/local/lambda-resolver/types.ts
27027
27287
  var LocalInvokeResolutionError = class LocalInvokeResolutionError extends Error {
27028
27288
  constructor(message) {
@@ -27684,13 +27944,24 @@ async function buildContainerSpec(args) {
27684
27944
  containerPath: profileCredsFile.containerPath
27685
27945
  } }
27686
27946
  };
27947
+ const rie = await resolveRieWrap({
27948
+ image: imageRef,
27949
+ platform,
27950
+ entryPoint: lambda.imageConfig.entryPoint,
27951
+ command: lambda.imageConfig.command,
27952
+ skipPull
27953
+ });
27687
27954
  return {
27688
27955
  kind: "image",
27689
27956
  lambda,
27690
27957
  image: imageRef,
27691
27958
  platform,
27692
- command: lambda.imageConfig.command ?? [],
27693
- ...lambda.imageConfig.entryPoint !== void 0 && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
27959
+ command: rie ? rie.cmd : lambda.imageConfig.command ?? [],
27960
+ ...rie && {
27961
+ entryPoint: rie.entryPoint,
27962
+ rieMount: rie.mount
27963
+ },
27964
+ ...!rie && lambda.imageConfig.entryPoint !== void 0 && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
27694
27965
  ...lambda.imageConfig.workingDirectory !== void 0 && { workingDir: lambda.imageConfig.workingDirectory },
27695
27966
  env: dockerEnv,
27696
27967
  ...sensitiveEnvKeys !== void 0 && { sensitiveEnvKeys },
@@ -32386,13 +32657,21 @@ async function resolveContainerImagePlan(lambda, options) {
32386
32657
  });
32387
32658
  }
32388
32659
  const tmpfs = resolveTmpfsForLambda(lambda);
32660
+ const rie = await resolveRieWrap({
32661
+ image: imageRef,
32662
+ platform,
32663
+ entryPoint: lambda.imageConfig.entryPoint,
32664
+ command: lambda.imageConfig.command,
32665
+ skipPull: options.pull === false
32666
+ });
32389
32667
  return {
32390
32668
  image: imageRef,
32391
32669
  mounts: [],
32392
- extraMounts: [],
32393
- cmd: lambda.imageConfig.command ?? [],
32670
+ extraMounts: rie ? [rie.mount] : [],
32671
+ cmd: rie ? rie.cmd : lambda.imageConfig.command ?? [],
32394
32672
  platform,
32395
- ...lambda.imageConfig.entryPoint && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
32673
+ ...rie && { entryPoint: rie.entryPoint },
32674
+ ...!rie && lambda.imageConfig.entryPoint && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
32396
32675
  ...lambda.imageConfig.workingDirectory !== void 0 && { workingDir: lambda.imageConfig.workingDirectory },
32397
32676
  ...tmpfs !== void 0 && { tmpfs }
32398
32677
  };
@@ -32512,4 +32791,4 @@ function collectVerbFlags(program) {
32512
32791
  }
32513
32792
 
32514
32793
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
32515
- //# sourceMappingURL=program-Dipucz4X.js.map
32794
+ //# sourceMappingURL=program-Be87SvBg.js.map