@cdkd/cli 0.348.0 → 0.349.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/{asg-provider-r1ojkIvF.js → asg-provider-Dvy_jqxt.js} +2 -2
  2. package/dist/{asg-provider-r1ojkIvF.js.map → asg-provider-Dvy_jqxt.js.map} +1 -1
  3. package/dist/aws-partition-DA0r2sr-.js +58 -0
  4. package/dist/aws-partition-DA0r2sr-.js.map +1 -0
  5. package/dist/cli.js +2 -2
  6. package/dist/custom-resource-runtime-Dwnnj7bg.js +1104 -0
  7. package/dist/custom-resource-runtime-Dwnnj7bg.js.map +1 -0
  8. package/dist/{db-instance-modify-retry-BaSXzEMy.js → db-instance-modify-retry-pFWx2ED5.js} +2 -2
  9. package/dist/{db-instance-modify-retry-BaSXzEMy.js.map → db-instance-modify-retry-pFWx2ED5.js.map} +1 -1
  10. package/dist/delete-started-Co5Gt1jH.js +169 -0
  11. package/dist/delete-started-Co5Gt1jH.js.map +1 -0
  12. package/dist/{deploy-engine-2XoVAu4C.js → deploy-engine-DeYSJno7.js} +652 -12015
  13. package/dist/deploy-engine-DeYSJno7.js.map +1 -0
  14. package/dist/diff-calculator-CRkRB1Dg.js +4959 -0
  15. package/dist/diff-calculator-CRkRB1Dg.js.map +1 -0
  16. package/dist/ec2-termination-protection-BM1Zt3Fn.js +1277 -0
  17. package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +1 -0
  18. package/dist/{ecr-uri-C1_heDAt.js → ecr-uri-C3_6QVgR.js} +2 -2
  19. package/dist/{ecr-uri-C1_heDAt.js.map → ecr-uri-C3_6QVgR.js.map} +1 -1
  20. package/dist/expected-bucket-owner-CGoY_YS8.js +88 -0
  21. package/dist/expected-bucket-owner-CGoY_YS8.js.map +1 -0
  22. package/dist/{iam-role-provider-BnLtoKcW.js → iam-role-provider-BaN9MMWs.js} +3 -2
  23. package/dist/iam-role-provider-BaN9MMWs.js.map +1 -0
  24. package/dist/image-plan-D4I8-FhR.js +1940 -0
  25. package/dist/image-plan-D4I8-FhR.js.map +1 -0
  26. package/dist/index.d.ts +3 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +3 -2
  29. package/dist/{neptune-provider-lzti8HIF.js → neptune-provider-BYgFNrtZ.js} +3 -3
  30. package/dist/{neptune-provider-lzti8HIF.js.map → neptune-provider-BYgFNrtZ.js.map} +1 -1
  31. package/dist/{program-DSlYCm_d.js → program-BBGm88gl.js} +629 -1858
  32. package/dist/program-BBGm88gl.js.map +1 -0
  33. package/dist/{provider-classes-RMTfwJPz.js → provider-classes-CRCHL04N.js} +33 -17
  34. package/dist/provider-classes-CRCHL04N.js.map +1 -0
  35. package/dist/{rds-provider-COq1pW0G.js → rds-provider-DKZjtd50.js} +62 -40
  36. package/dist/rds-provider-DKZjtd50.js.map +1 -0
  37. package/dist/{read-replica-sjvqi8Of.js → read-replica-C5e4xpYi.js} +2 -2
  38. package/dist/{read-replica-sjvqi8Of.js.map → read-replica-C5e4xpYi.js.map} +1 -1
  39. package/dist/replacement-rules-01_01yDU.js +4937 -0
  40. package/dist/replacement-rules-01_01yDU.js.map +1 -0
  41. package/dist/resource-deadline-TfDpwRQ_.js +423 -0
  42. package/dist/resource-deadline-TfDpwRQ_.js.map +1 -0
  43. package/dist/{version-DXmr3_M4.js → version-DamSnfI_.js} +2 -2
  44. package/dist/{version-DXmr3_M4.js.map → version-DamSnfI_.js.map} +1 -1
  45. package/package.json +3 -2
  46. package/dist/deploy-engine-2XoVAu4C.js.map +0 -1
  47. package/dist/iam-role-provider-BnLtoKcW.js.map +0 -1
  48. package/dist/program-DSlYCm_d.js.map +0 -1
  49. package/dist/provider-classes-RMTfwJPz.js.map +0 -1
  50. package/dist/rds-provider-COq1pW0G.js.map +0 -1
@@ -1,11 +1,19 @@
1
- import { t as getCdkdVersion } from "./version-DXmr3_M4.js";
2
- import { $ as withStackScope, B as generateResourceName, E as coerceCfnBoolean, I as PATTERN_B_NAME_OPTIONS, L as PATTERN_B_NAME_PROPERTIES, Q as withSkipPrefix, R as PATTERN_B_RESOURCE_TYPES, S as explicitNamePropertyFor, X as isNameGeneration, _t as truncateCodePoints, a as reserveStdoutForPayload, at as asIsMessage, ct as displayIdent, dt as isPasteableIdent, gt as terminalSafe, ht as stringifyJsonPayload, i as releaseStdoutForPayload, it as UNRENDERABLE, lt as displaySafe, m as verboseAwareText, mt as safeMsg, n as getLogger, nt as SECRET_REF_MAX_CODE_POINTS, ot as cutMarker, p as safeStringify, pt as plainIdentOr, r as isStdoutReservedForPayload, rt as STACK_REF_MAX_CODE_POINTS, s as runStackBuffered, st as displayAwsMessage, tt as SAFE_MSG_ALTERED_CHAR, u as describeAwsFailure, ut as displayStackName, y as getLiveRenderer, z as derivesPatternBName } from "./logger-DmQRya0S.js";
3
- import { $a as poisonRenderedSpellingsCollidingIn, $d as setChildProcessAwsEnv, $i as isFinalSnapshotError, $l as describeRegionValueKind, $n as updatePartialMessage, $o as MULTI_REGION_RECREATE_BLOCKED_TYPES, $r as DEFAULT_RESOURCE_TIMEOUT_MS, $s as refuseMalformedOrphansForDestroy, $t as NESTED_PENDING_PARENT_REASON, $u as warnFinchArgvExposure, A as PROTECTION_PROPERTY_BY_TYPE, Ad as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ai as withAttemptedItemsMasked, Al as identityKeyFor, An as rollbackOrphanIds, Ao as lacksRecordedTableArn, Ar as retiredNameGenerationsLeaving, As as malformedResourceEntriesWarning, Au as rewriteTemplateAssetReferences, Bd as describeJsonParseFailure, Bi as secretNamedRecordNeedles, Bl as recordMaskOnlyValue, Bn as propertiesChangedReason, Bo as isNamelessDynamicReferenceError, Br as exportAliasCollisionScrubWarning, Bs as unreadableResourceEntries, Bt as refactorMarkerRefusalMessage, Bu as validateContainerRepoName, C as refusePendingMovesOut, Ca as TemplateNoEchoReresolver, Cc as STATE_RESOURCES_MALFORMED, Cd as warnDeprecatedNoPrefixCliFlag, Ci as green, Cl as withPhysicalNameCopies, Cn as DeploymentEventsStore, Cr as removeProtectionTypeList, Cs as refuseMalformedOrphansForOrphan, Cu as AssetPublisher, D as diffSecurity, Da as withPrintingSecrets, Dc as hasReadableResources, Dd as MIGRATE_TMP_PREFIX, Di as noEchoComparisonForTemplate, Dl as isUncertifiedBaselineMaskPosition, Dn as findRefactorHints, Do as AWS_NO_VALUE, Dr as nameScopeOf, Ds as isReadableResourceEntry, Du as buildAssetRedirectMap, E as serviceTokenBlockingReason, Ec as hasReadableOutputs, Ed as CFN_TEMPLATE_URL_LIMIT, Ei as noEchoAttributeNamesOf, El as dynamicReferenceTokens, En as formatDestructiveChange, Eo as parameterTypeMayLoseSecretIdentity, Er as nameGenerationHighWaterOf, Es as unreadableOrphanRecords, Eu as WorkGraph, Fa as UNSPECIFIED_SKIP_REASON, Fd as derivePartitionAndUrlSuffix, Fi as namingSecretsWithRecordedNoEcho, Fl as recordPhysicalNameCopy, Fn as differingRemedy, Fo as recordedOutputReferenceRegions, Fr as namesAnyDeclaredParameter, Fs as refuseMalformedResourceEntriesForDestroy, Ft as keptForRetainedRecord, Fu as isCrossRegionRedirect, Gc as isMarkedCoordinate, Gd as hasPlainPrototype, Gl as wholeStringLeavesOf, Gn as DELETED_RESOURCE_REMEDY, Gr as exportNameNoEchoParameters, Gs as refuseMalformedResourcePropertiesForExport, Gu as describeDockerExecFailure, Hc as DagBuilder, Hd as utf8ByteLength, Hi as storedSecretNameNeedles, Hl as recordNoEchoAttributeValues, Hn as referencedLogicalIds, Ho as keepsSecretReferenceToken, Hr as secretBearingStateKeyWarning, Hs as malformedResourcePropertiesWarning, Ht as sameMove, Hu as buildDockerImage, Ia as deleteIndeterminateGuards, Id as refuseFailedLookups, Ii as orphanRecordsPrintingBag, Il as recordNestedStackParameterExpressions, In as isPairableType, Io as recordedReferenceRegions, Ir as reachableDivergentParameters, Is as refuseMalformedResourceEntriesForImport, It as recordRetainedForReadoption, Iu as getBootstrapMarkerKey, Ja as isWaitAbandonedError, Jc as maskWholeValue, Jd as absoluteAssemblyPathEscape, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jl as LockManager, Jn as withUnprovenUnsettled, Jo as unsettledPropertiesOf, Jr as noEchoParameterValueSeed, Js as UNREADABLE_ORPHANS_CONTAINER_ROW, Ju as redactedDockerCause, Kc as maskAtCoordinates, Kd as nullPrototypeRecord, Ki as secretSegmentsOfState, Kl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Kn as recordAfterRollbackUpdate, Ko as unsettledItemsField, Kr as exportNameSecretExposure, Ks as refuseMalformedResourcePropertiesForOrphan, Kt as formatResourceLine, Ku as describeDockerFailure, La as deleteLeftInPlace, Ld as AssemblyReader, Li as secretNamePrintingBag, Ll as splitGetAttStringForm, Ln as looselyEqual, Lo as getAccountInfo, Lr as resourcesNamingDeclaredParameter, Ls as refuseMalformedResourceEntriesForImportSave, Lt as readRefactorMarker, Lu as parseBootstrapMarker, M as perType, Ma as setResolvedResourceTimeouts, Md as expectedOwnerParam, Mi as completedReplayEntries, Mn as changedReferenceInDiff, Ms as refuseMalformedResourceAttributesForOrphan, Mt as withResourceDeadline, Mu as ensureAssetStorage, N as readProtection, Na as slowCcOperationTimeoutMs, Nc as NO_CC_HANDLERS_REASON, Nd as PARTITION_TABLE, Ni as journaledOrphanPrintingBag, Nl as physicalNameCopiesOf, Nn as changedReferencePath, No as keepHeldTokenProvenance, Nr as inheritProducerRegions, Ns as refuseMalformedResourceEntries, Nt as IMPLICIT_DELETE_DEPENDENCIES, Nu as buildDenyExternalAccessPolicy, O as recordedProtectionEvidence, Oc as findActionableSdkUnwired, Od as findLargeInlineResources, Oi as noEchoExactEchoLeavesOf, Ol as spelledKeysOf, On as hintSidesOf, Oo as cfnRefValueFromPhysicalId, Or as retiredAfterRollback, Os as malformedLocalResourceEntriesWarning, Ou as createAssetRedirectResolver, Pa as RollbackInlinePolicyWriters, Pc as hasNoCloudControlHandlers, Pd as canonicalizeRegion, Pi as maskEventTextWithBoundBags, Pn as changedReferenceReason, Pr as computeParameterTaint, Ps as refuseMalformedResourceEntriesForDeploy, Pt as computeImplicitDeleteEdges, Pu as assertAssetBucketRegion, Qa as isAlwaysLiveAttribute, Qc as noEchoOutputsComparison, Qd as resolveAssemblyPath, Qi as effectiveDeletionPolicy, Ql as acceptedCreateOnlyDropsOf, Qn as undeclaredEmptyObservedKeys, Qo as shownType, Qr as bindingSkippedOutputs, Qs as refuseMalformedOrphans, Qt as resolvePendingCloudControlRequests, Qu as partitionSensitiveEnv, Ra as deleteSkipReason, Rd as StageLoadError, Ri as secretNamePrintingBags, Rl as carriesSecretMask, Rn as mappingPairs, Ro as isImpossibleEmptyStoredAttribute, Rr as WITHHELD_NAME_DISPLAY, Rs as refuseMalformedResourceEntriesForOrphan, Rt as readRefactorMarkerOnce, Ru as readBootstrapMarkerBody, S as pendingMovesRefusalMessage, Sa as customResourceResponseExpirationWarning, Sc as withheldAccountClause, Sd as stateBucketExistenceConfirmed, Si as gray, Sl as scrubResourceRecord, Sn as DeploymentEventsReader, Sr as segmentCleanupOptions, Ss as refuseMalformedOrphanRecordsForDestroy, Su as withStackInstanceIdWithheld, T as findServiceTokenRefusals, Ta as isCustomResourceType$1, Tc as displayLogicalId, Td as CFN_TEMPLATE_BODY_LIMIT, Ti as yellow, Tl as DYNAMIC_REFERENCE_TOKEN_SCAN, Tn as findDestructiveChanges, To as isUnboundTemplateParameter, Tr as nameGenerationCarriedFrom, Ts as unpreviewableOrphanRecords, Tu as stringifyValue, Uc as TemplateParser, Ud as defineOwnKey, Ui as extractDeploymentEventError, Ul as recordNoEchoParameterFreshValue, Un as replayFailedOperations, Uo as withSharedDrainBudget, Ur as secretSafeKeyDisplay, Us as refuseMalformedResourcePropertiesForDestroy, Ut as updateRefactorMarker, Uu as resolveDockerContextDirectory, Vd as parseFailureDebugDetail, Vi as stateSecretNameNeedles, Vl as recordMaskOnlyValuesIn, Vn as proposeRenames, Vo as carriesDynamicReference, Vr as secretBearing, Vs as malformedDriftResourcePropertiesWarning, Vt as refuseRefactorMarker, Vu as BOOTSTRAP_MARKER_PREFIX, Wc as canonicalCoordinates, Wd as hasOwnKey, Wl as recordProvenPublicExpression, Wn as replayRollback, Wo as INTRINSIC_KEYS, Wr as carriedExportAliasExposure, Ws as refuseMalformedResourcePropertiesForDrift, Wu as describeDockerCapturedOutput, Xa as IntrinsicFunctionResolver, Xc as noEchoCoordinatesOf, Xd as displayAssemblyPath, Xi as ccRoutedFinalSnapshotError, Xl as S3StateBackend, Xn as equalModuloMarkedMask, Xo as withoutUnsettledProperties, Xr as collectPublishedOutputNames, Xs as malformedOrphansRefusalMessage, Xu as dockerSpawnEnvWithSensitive, Ya as DiffCalculator, Yc as maskedLeafCoordinatesOf, Yd as describeFileReadFailure, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yl as isLockInfoExpired, Yn as calculateResourceDrift, Yo as withUnsettledProperties, Yr as collectDeclaredOutputNames, Ys as hasReadableOrphans, Yu as redactDockerArgvValues, Za as isSelectOutOfBounds, Zc as noEchoLeavesOf, Zd as renderAssemblyPathEscape, Zi as ccRoutedInstanceTakesNoSnapshot, Zl as splitImportedOps, Zn as equalModuloMask, Zo as findReplacedReadersOfRecreateTargets, Zr as isExportAliasCollision, Zs as malformedOrphansWarning, Zt as pendingRequestCount, Zu as finchSecretArgvRefusal, _ as listNestedTemplateRows, _a as ccBrokenReason, _c as refuseMalformedResourcesForExport, _d as resolveSkipPrefix, _l as unionOfSecretBags, _n as loadJournaledOrphans, _o as producerRegionsFromState, _r as findNestedStackTypeChanges, _s as malformedOrphanRecordsRefusalMessage, _u as applyCrossPrefixScan, a as scanActiveConsumers, ac as malformedOutputsWarning, ad as runDockerStreaming, ai as withStackRecords, al as redactForState, an as recordDisplacedSkips, ao as applyRoleArnIfSet, au as orphansAfterRollback, b as hasPendingMovesOut, ba as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, bc as JSON_LISTING_HOLE_VALUE, bd as resolveStateBucketWithSource, bi as bold, bl as maskSecretsInError, bn as makeSiblingClaimReader, bs as previewableOrphanRecords, bu as isNotImplemented, c as inheritedProvenanceForChildDiff, cc as refuseMalformedOutputsForDestroy, cd as getDockerImageBySourceHash, ci as holdsSupersededResources, cl as carryLogOnlyValues, cn as withNestedRevertRun, co as explicitRoleArnOrThrow, cr as demoteSupersededOrphans, cs as prefetchCreateOnlyPropertyPaths, cu as stackInstanceIdCarriedFrom, d as conditionInputsFrom, dc as refuseDivergentRecordRegionForDestroy, dd as getDefaultStateBucketName, di as supersededHeldByOtherTypeWarning, dl as literalSplitDelimitersOf, dn as withNestedStackContext, do as AWS_CREDENTIAL_ENV_KEYS, dr as planFailedOps, ds as withRetry, du as PhaseClock, ea as refusesFinalSnapshot, ec as repairMalformedOrphansForReadOnly, ed as isDockerClientEnvKey, ef as injectAwsRegion, ei as DEFAULT_RESOURCE_WARN_AFTER_MS, el as readsNoEchoSource, en as displacedOpClause, eo as stackIdTailOf, er as updatePartialReason, es as isStatefulRecreateTargetForReplace, eu as exportNamesCarriedFrom, f as parentSuppliedValues, fc as malformedRenderedContainersWarning, fd as getLegacyStateBucketName, fi as supersededHolderOf, fl as logOnlyValueCount, fn as deleteJournaledOrphans, fo as applyCallerIdentityCredentials, fr as recheckFailedPlan, fs as parameterInputsFor, fu as renderPhaseTimings, g as isAbsoluteAssetPath, ga as ProviderRegistry, gc as refuseMalformedResourcesForDestroy, gd as resolveCaptureObservedState, gl as shareLogOnlyValues, gn as journaledOrphanLines, go as classifyReplaySecretRegion, gr as withPreviousPolicies, gs as isReadableOrphanRecord, gu as CrossPrefixScanCache, h as findNestedTemplateTreeDefect, ha as CC_BROKEN_REASON, hc as refuseMalformedResourcesForDeploy, hd as resolveAutoAssetStorage, hl as recordLogOnlyValue, hn as isHandledOrphan, ho as classifyRecordedSecretRegion, hr as resolveReplacementOldType, hs as deployRefusesOrphanRowsReason, hu as CrossPrefixReadError, i as mergeNoChangeOutputs, ic as malformedOutputsRefusalMessage, id as runDockerForeground, in as nestedChildStackName$1, io as refuseUnreadableCdkCrossAccountRefs, ir as withCreateTokenLedger, iu as isReadableBag, j as isProtectionValueActive, jc as unwrittenCreateOnlyReplacement, jd as decodeListingKey, ji as createReadOnlyAttributeHealerFactory, jl as inheritNestedStackParameterAssociations, jn as withMovedTo, jo as refStateLookupFromResource, jr as withNameGenerationReached, js as malformedScrubResourceEntriesRefusalMessage, ju as AssetModeResolver, k as recordedProtectionNote, ka as CloudControlProvider, kc as findHandledUnwrittenCreateOnly, kd as uploadCfnTemplate, ki as noEchoParameterNamesOf, kl as pathCrossesDottedKey, kn as movedToHint, ko as isStalePlaceholderArnAttribute, kr as retiredNameGenerationsAfter, ks as malformedLocalResourcesWarning, ku as loadPublishableAssetManifest, l as makeCanonicalizePropertiesFn, lc as repairMalformedOutputsForReadOnly, ld as Synthesizer, li as isSupersededResourceRecord, ll as createUnionSecretMasker, ln as collectNestedChildUnaddressed, lo as isIamRoleArn, lr as isJournaledOrphan, ls as templateResourceTypes, lu as hasReasonlessBaselineRefusal, m as childTemplateLoader, mc as malformedStateRefusalMessage, md as resolveApp, mi as withoutSuperseded, ml as recordLogOnlyParameterValue, mn as dropFailedHint, mo as envCredentialsAreAssumedRole, mr as replacementNeverSwapped, ms as declaresNoEcho, mu as rebuildClientForBucketRegion, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as malformedExportSourceWarning, nd as formatDockerLoginError, nl as valueAtCoordinate, nn as dropSettledNestedJournals, no as resolveDynamicReferences, nr as ledgerForStack, ns as renderStatefulReason, nu as importableOutputKeys, o as inRunStackKey, od as abortInFlightMultipartUploads, oo as assertFlagRoleArn, or as planRollback, ou as orphansCarriedFrom, p as readRecordedConditionVerdicts, pc as malformedResourcesWarning, pd as loadCdkJson, pi as supersededResourcesOf, pl as printingCorpusOf, pn as dropFailedCommands, po as callerEnvCredentials, pr as recordUnderIdIsNotOwn, pu as timePhase, qc as maskReadbackAtCoordinates, qd as ownValue, qi as withSecretPhysicalIdsMaskedInState, ql as isSingleDynamicReferenceToken, qn as settleUnsettledPrevious, qo as unsettledItemsOf, qr as isWholeDynamicReferenceValue, qs as repairMalformedResourcePropertiesForReadOnly, qu as redactedCause, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as malformedLocalOutputsWarning, rd as getDockerCmd, rf as resolveBucketRegion, ri as destroyStackRecordsView, rl as liveMatchesUnresolvedTokenFrame, ro as producerLookupOver, ru as importableOutputs, s as crossStackOutputProvenanceSource, sc as refuseMalformedOutputs, sd as AssetManifestLoader, si as deleteSupersededEntry, sn as revertedNestedRowIds, so as assertSendableRoleArn, sr as seedsDeleteFirstGuard, su as shouldRetainResource, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as malformedExportNamesWarning, td as isMalformedEnvKey, tf as injectedAwsRegionValue, ti as maskingRetryLogger, tl as recordedNoEchoValuesOf, tn as displacedPhysicalIdShown, ts as isStatefulRecreateTargetSync, tu as hasReadableExportSet, u as conditionFingerprint, uc as STATE_REGION_DIVERGED, ud as synthesisStatusMessage, ui as supersededAfterRollback, ul as hasMaskableValues, un as getCurrentNestedStackContext, uo as sendableAssumeRoleCommand, ur as isReplacementOrphan, us as describeTypeWithThrottleRetry, uu as hasUnverifiableParameterRefusal, v as renderNestedTemplateTreeDefect, va as isCustomResource, vc as refuseMalformedState, vd as resolveStateBucketWithDefault, vl as createSecretMasker, vn as sameJournaledOrphans, vo as regionLessSecretName, vs as malformedOrphanRecordsWarning, vu as crossPrefixDeniedWarning, w as deferredServiceTokenWarning, wa as readsNoEchoDeleteValues, wc as UNREADABLE_RESOURCES_MAP_ROW, wd as ssmResolvedValueType, wi as red, wn as constructPathOf$1, wo as coerceParameterTypedValue, wr as orphanNeedsIdentity, ws as repairMalformedOrphanRecordsForReadOnly, wu as isSensitiveAttributeName, x as pendingMovesOutOf, xa as applyCustomResourceResponseExpiration, xc as accountArgs, xd as resolveUseCdkBootstrapAssets, xi as cyan, xl as maskSecretsInText, xn as planOrphanAdoption, xs as refuseMalformedOrphanRecords, xu as stackInstanceIdOf, y as templateIdentity, ya as wouldReturnToSdkProvider, yc as repairMalformedResourcesForReadOnly, yd as resolveStateBucketWithDefaultAndSource, yl as errorCauseChain, yn as makeForeignHolderScan, ys as malformedOrphanRowsKeptWarning, yu as isAccessDenied, zd as processStackMessages, zl as provenPublicValue, zn as parseMappingFile, zo as carriesFetchableDynamicReference, zr as displayTextOrWithheld, zs as repairMalformedResourceEntriesForReadOnly, zt as refactorMarkerMovesOf, zu as validateAssetBucketName } from "./deploy-engine-2XoVAu4C.js";
4
- import { A as stripControlChars, B as retryClassificationText, Ct as withheldTargetClause, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, St as shellQuote, Tt as setPasteableVerbFlags, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, _t as pasteableCommand, a as normalizeAwsError, at as ProvisioningError, bt as quotedOrDescribed, ct as SynthesisError, et as CdkdError, ft as SHELL_ACTIVE_WHY, g as PartialFailureError, gt as isInertUnquoted, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, mt as commandHole, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError, ut as TIMEOUT_FLAG_RESOURCE_TYPE, v as StackHasActiveImportsError, wt as setPasteableRunFlags, xt as shellBoundedDisplay, y as StackTerminationProtectionError, yt as plainOrDescribed, z as isTransientServerError } from "./ambient-client-defaults-7acjxfyN.js";
1
+ import { t as getCdkdVersion } from "./version-DamSnfI_.js";
2
+ import { $ as renderUnmatchedPatternsWarning, $t as parseContextOptions, A as followContainerLogs, At as rawCliRegion, B as resolveRuntimeCodeMountPath, Bt as writeProfileCredentialsFile, C as waitForRieReady, Ct as warnAwsEmulatorStateSourceHint, Dt as foldRegionOption, E as SENSITIVE_ENV_KEYS, Et as exportInferredRegionForSdk, F as removeContainer, Ft as resolveEffectiveRegion, G as partitionTopLevel, Gt as contextOptions, H as resolveRuntimeImage, Ht as appOptions, It as stackRegionResolver, J as renderAllNoTopLevelStacks, Jt as destroyOptions, K as refuseStackNameRegionCollisions, Kt as deployOptions, L as runDetached, Lt as stateWithRegion, M as killAndDrainContainerLogs, Mt as reconcileMarkerRegionWithLegacyDefault, N as pickFreePort, Nt as regionNeedsReconciliation, O as ensureDockerAvailable, Ot as legacyStateBucketFallbackRegion, P as pullImage, Pt as regionShown, Q as renderStacksNoLongerSelected, Qt as noLocalCustomResourcesOption, Rt as withOtherIndexRemoval, S as invokeRie, St as taskRoleAssumedInRealAws, T as DockerRunnerError, Tt as adoptDeprecatedRegionFlag, U as describeStack, Ut as applyWaitFlagEnv, V as resolveRuntimeFileExtension, Vt as annotationMessageOptions, W as matchStacks, Wt as commonOptions, X as renderNoStackMatch, Xt as guardStackRegionOptions, Y as renderAmbiguousTargetStack, Yt as exclusivelyOption, Z as renderNotInAppWarning, Zt as noCfnFallbackOption, _ as copyLayerTreeLastWins, _n as listAllLockKeys, _t as prepareLocalLoopbackForwarder, a as materializeLayerFromArn, an as warnIfDeprecatedRegion, at as buildCdkPathIndex, b as probeHostGatewaySupport, bt as resolveContainerRegion, cn as parseAssumeRoleToken, ct as stackForConstructPath, d as resolveAssetCodeDirectory, dn as resourceTimeoutOptions, dt as assertAwsEmulatorValue, en as parseStackRegion, et as selectTargetStack, f as derivePseudoParametersFromRegion$1, fn as validateResourceTimeouts, ft as attachLocalLoopbackForwarder, g as buildContainerImage$1, gn as describeStateKey, gt as mixedModeEmulatorOverride, h as architectureToPlatform, hn as STATE_KEY_MAX_CODE_POINTS, ht as mixedModeActive, i as resolveInlineCodeFilePath, in as useCdkBootstrapAssetsOption, it as unmatchedPatterns, jt as reconcileExportIndexRegion, k as flushStdio, kt as namedCliRegion, l as resolveLambdaLayers, ln as allowUnsupportedTypesOption, lt as stackForPathFormTarget, m as tryResolveImageFnJoin, mn as STATE_FILE_SUFFIX, mt as localAwsEmulatorCredentials, n as resolveTmpfsForLambda, nn as stackOptions, nt as stacksForDependency, o as resolveLambdaTarget, on as effectiveAssumeRoleArn, ot as readCdkPathOrUndefined, p as substituteImagePlaceholders, pn as LOCK_FILE_SUFFIX, pt as getActiveWorkloadAwsWiring$1, q as renderAllLeftOutStageStacks, qt as deprecatedRegionOption, r as resolveZipImagePlan, rn as stateOptions, rt as stacksNoLongerSelected, s as extractEphemeralStorageMb, sn as normalizeStartApiAssumeRole, st as resolveCdkPathToLogicalIds, t as resolveLocalBuildPlan$1, tn as skipFinalSnapshotOption, tt as stackMatchesPattern, u as assetPathDirs, un as parseDuration, ut as activateLocalAwsAndRoleArn, v as layerAssetDirectory, vn as listAllStateKeys, vt as profileCredentialsForWorkload, w as CONTAINER_LOG_DRAIN_TIMEOUT_MS, wt as workloadGetsEmulatorKeysOnly, x as resolveHostGatewayExtraHosts, xt as setContainerRegion, y as HOST_GATEWAY_MIN_VERSION, yn as parseStateKey, yt as realAwsException, z as streamLogs, zt as strandedProfileCredentialsNotice } from "./image-plan-D4I8-FhR.js";
5
3
  import { $t as forceQuitRecoveryClause, Dt as logicalIdShown, H as assertRegionMatch, M as VALUE_NOT_SHOWN, Qt as buildLockContentionMessage, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, bt as interruptWatchListenerCount, dn as setPasteableAwsCaBundle, en as formatLockExpiry, fn as setPasteableAwsProfile, kt as resourceTypeShown, ln as producerCoordinateKey, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mt as isAwsCliLiteral, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, p as IAM_PRINCIPAL_NAME, pn as withPasteableAwsProfile, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, un as producerRecordKey, vt as beginCommandInterruptScope, xt as isInterruptedWaitError, y as readRecordedPrincipals, yt as endCommandInterruptScope, z as remedyLogicalId } from "./update-removal-D-FspP88.js";
4
+ import { A as stripControlChars, B as retryClassificationText, Ct as withheldTargetClause, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, St as shellQuote, Tt as setPasteableVerbFlags, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, _t as pasteableCommand, a as normalizeAwsError, at as ProvisioningError, bt as quotedOrDescribed, ct as SynthesisError, et as CdkdError, ft as SHELL_ACTIVE_WHY, g as PartialFailureError, gt as isInertUnquoted, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, mt as commandHole, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError, v as StackHasActiveImportsError, wt as setPasteableRunFlags, xt as shellBoundedDisplay, y as StackTerminationProtectionError, yt as plainOrDescribed, z as isTransientServerError } from "./ambient-client-defaults-7acjxfyN.js";
6
5
  import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefaults, o as setAwsClients, s as resolveS3ClientDefaults, t as AwsClients, u as setS3ClientDefaultsDebugLog } from "./aws-clients-DOkPjjAW.js";
7
- import { a as getAssumedRoleCredentials, c as setAssumedRoleCredentials, h as formatAuthority, l as setAwsEndpointOverrideSource, m as runInStackAwsScope, n as awsClientDefaults, o as getPreAssumeEnvCredentials, r as awsEndpointOverrideActive, s as runWithRealAws } from "./aws-client-defaults-DAebi99J.js";
8
- import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-C1_heDAt.js";
6
+ import { $ as withStackScope, B as generateResourceName, E as coerceCfnBoolean, I as PATTERN_B_NAME_OPTIONS, L as PATTERN_B_NAME_PROPERTIES, Q as withSkipPrefix, R as PATTERN_B_RESOURCE_TYPES, S as explicitNamePropertyFor, X as isNameGeneration, _t as truncateCodePoints, a as reserveStdoutForPayload, at as asIsMessage, ct as displayIdent, dt as isPasteableIdent, gt as terminalSafe, ht as stringifyJsonPayload, i as releaseStdoutForPayload, it as UNRENDERABLE, lt as displaySafe, m as verboseAwareText, mt as safeMsg, n as getLogger, nt as SECRET_REF_MAX_CODE_POINTS, ot as cutMarker, p as safeStringify, pt as plainIdentOr, r as isStdoutReservedForPayload, rt as STACK_REF_MAX_CODE_POINTS, s as runStackBuffered, st as displayAwsMessage, tt as SAFE_MSG_ALTERED_CHAR, u as describeAwsFailure, ut as displayStackName, y as getLiveRenderer, z as derivesPatternBName } from "./logger-DmQRya0S.js";
7
+ import { a as getAssumedRoleCredentials, c as setAssumedRoleCredentials, h as formatAuthority, l as setAwsEndpointOverrideSource, m as runInStackAwsScope, n as awsClientDefaults, r as awsEndpointOverrideActive, s as runWithRealAws } from "./aws-client-defaults-DAebi99J.js";
8
+ import { A as loadCdkJson, B as warnDeprecatedNoPrefixCliFlag, C as runDockerForeground, D as synthesisStatusMessage, E as Synthesizer, F as resolveStateBucketWithDefault, G as uploadCfnTemplate, H as CFN_TEMPLATE_URL_LIMIT, I as resolveStateBucketWithDefaultAndSource, J as AssemblyReader, K as refuseFailedLookups, L as resolveStateBucketWithSource, M as resolveAutoAssetStorage, N as resolveCaptureObservedState, O as getDefaultStateBucketName, P as resolveSkipPrefix, R as resolveUseCdkBootstrapAssets, S as getDockerCmd, T as abortInFlightMultipartUploads, U as MIGRATE_TMP_PREFIX, V as CFN_TEMPLATE_BODY_LIMIT, W as findLargeInlineResources, X as processStackMessages, Y as StageLoadError, Z as setChildProcessAwsEnv, _ as partitionSensitiveEnv, a as AssetPublisher, b as isMalformedEnvKey, c as resolveDockerContextDirectory, d as describeDockerFailure, f as redactedCause, g as finchSecretArgvRefusal, h as dockerSpawnEnvWithSensitive, i as isLockInfoExpired, j as resolveApp, k as getLegacyStateBucketName, m as redactDockerArgvValues, n as DagBuilder, o as WorkGraph, p as redactedDockerCause, r as LockManager, s as buildDockerImage, t as DiffCalculator, u as describeDockerExecFailure, v as warnFinchArgvExposure, w as runDockerStreaming, x as formatDockerLoginError, y as isDockerClientEnvKey, z as stateBucketExistenceConfirmed } from "./diff-calculator-CRkRB1Dg.js";
9
+ import { $a as applyCallerIdentityCredentials, $c as loadPublishableAssetManifest, $i as isFinalSnapshotError, $n as withUnprovenUnsettled, $r as noEchoParameterValueSeed, $s as malformedOutputsWarning, $t as displacedOpClause, A as recordedProtectionEvidence, Aa as UNSPECIFIED_SKIP_REASON, Ac as hasNoCloudControlHandlers, Ai as withAttemptedItemsMasked, Al as nullPrototypeRecord, An as findDestructiveChanges, Ao as isImpossibleEmptyStoredAttribute, Ar as nameGenerationCarriedFrom, As as refuseMalformedResourceEntriesForImportSave, Ba as stackIdTailOf, Bc as applyCrossPrefixScan, Bi as secretNamedRecordNeedles, Bl as resolveBucketRegion, Bn as differingRemedy, Br as namesAnyDeclaredParameter, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as refuseRefactorMarker, C as refusePendingMovesOut, Ca as withPrintingSecrets, Cc as findHandledUnwrittenCreateOnly, Ci as green, Cl as ssmResolvedValueType, Cn as NOECHO_MAC_KEY_ALIAS, Cs as malformedResourceEntriesWarning, D as findServiceTokenRefusals, Di as noEchoComparisonForTemplate, Dl as defineOwnKey, Dn as noEchoMacVerdict, Dr as segmentCleanupOptions, Ds as refuseMalformedResourceEntriesForDeploy, E as deferredServiceTokenWarning, Ei as noEchoAttributeNamesOf, El as decodeListingKey, En as noEchoMacParametersOf, Eo as recordedReferenceRegions, Es as refuseMalformedResourceEntries, F as readProtection, Fa as isWaitAbandonedError, Fc as hasReasonlessBaselineRefusal, Fi as namingSecretsWithRecordedNoEcho, Fl as displayAssemblyPath, Fn as rollbackOrphanIds, Fo as withSharedDrainBudget, Fr as retiredNameGenerationsLeaving, Fs as malformedResourcePropertiesWarning, Ft as recordRetainedForReadoption, Ga as applyRoleArnIfSet, Gc as withStackInstanceIdWithheld, Gn as propertiesChangedReason, Go as MULTI_REGION_RECREATE_BLOCKED_TYPES, Gr as exportAliasCollisionScrubWarning, Gs as malformedOrphansWarning, Gt as formatResourceLine, Ha as resolveDynamicReferences, Hc as isAccessDenied, Hi as storedSecretNameNeedles, Hn as looselyEqual, Ho as findReplacedReadersOfRecreateTargets, Hr as resourcesNamingDeclaredParameter, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as updateRefactorMarker, Ia as IntrinsicFunctionResolver, Ic as hasUnverifiableParameterRefusal, Ii as orphanRecordsPrintingBag, In as withMovedTo, Ir as withNameGenerationReached, It as readRefactorMarker, Ja as explicitRoleArnOrThrow, Jc as buildAssetRedirectMap, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jn as replayFailedOperations, Jo as renderStatefulReason, Jr as secretSafeKeyDisplay, Js as repairMalformedOrphansForReadOnly, Ka as assertFlagRoleArn, Kc as isSensitiveAttributeName, Ki as secretSegmentsOfState, Kn as proposeRenames, Ko as isStatefulRecreateTargetForReplace, Kr as secretBearing, Ks as refuseMalformedOrphans, La as isSelectOutOfBounds, Lc as rebuildClientForBucketRegion, Li as secretNamePrintingBag, Ll as renderAssemblyPathEscape, Ln as changedReferenceInDiff, Lo as INTRINSIC_KEYS, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as readRefactorMarkerOnce, M as PROTECTION_PROPERTY_BY_TYPE, Ma as deleteLeftInPlace, Mc as S3StateBackend, Mi as completedReplayEntries, Mn as findRefactorHints, Mo as isNamelessDynamicReferenceError, Mr as nameScopeOf, Ms as repairMalformedResourceEntriesForReadOnly, Mt as IMPLICIT_DELETE_DEPENDENCIES, N as isProtectionValueActive, Na as deleteSkipReason, Nc as splitImportedOps, Ni as journaledOrphanPrintingBag, Nn as hintSidesOf, No as carriesDynamicReference, Nr as retiredAfterRollback, Ns as unreadableResourceEntries, Nt as computeImplicitDeleteEdges, O as serviceTokenBlockingReason, Oa as setResolvedResourceTimeouts, Oi as noEchoExactEchoLeavesOf, Ol as hasOwnKey, On as noEchoValueMacsOf, Or as removeProtectionTypeList, Os as refuseMalformedResourceEntriesForDestroy, P as perType, Pi as maskEventTextWithBoundBags, Pl as describeFileReadFailure, Pn as movedToHint, Po as keepsSecretReferenceToken, Pr as retiredNameGenerationsAfter, Ps as malformedDriftResourcePropertiesWarning, Pt as keptForRetainedRecord, Qa as AWS_CREDENTIAL_ENV_KEYS, Qi as effectiveDeletionPolicy, Qn as settleUnsettledPrevious, Qr as isWholeDynamicReferenceValue, Qs as malformedOutputsRefusalMessage, Qt as NESTED_PENDING_PARENT_REASON, Ra as isAlwaysLiveAttribute, Rc as CrossPrefixReadError, Ri as secretNamePrintingBags, Rl as resolveAssemblyPath, Rn as changedReferencePath, Rr as inheritProducerRegions, Rs as refuseMalformedResourcePropertiesForDrift, Rt as refactorMarkerMovesOf, S as pendingMovesRefusalMessage, Sc as findActionableSdkUnwired, Si as gray, Sn as DeploymentEventsStore, So as keepHeldTokenProvenance, Sr as findNestedStackTypeChanges, Ss as malformedLocalResourcesWarning, T as readsOnlyNoEchoParameters, Ta as CloudControlProvider, Tc as unwrittenCreateOnlyReplacement, Ti as yellow, Tn as noEchoMacBinding, Ts as refuseMalformedResourceAttributesForOrphan, Ua as producerLookupOver, Uc as isNotImplemented, Ui as extractDeploymentEventError, Un as mappingPairs, Ur as WITHHELD_NAME_DISPLAY, Us as hasReadableOrphans, Vc as crossPrefixDeniedWarning, Vi as stateSecretNameNeedles, Vn as isPairableType, Vr as reachableDivergentParameters, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as sameMove, Wa as refuseUnreadableCdkCrossAccountRefs, Wc as stackInstanceIdOf, Wn as parseMappingFile, Wo as shownType, Wr as displayTextOrWithheld, Ws as malformedOrphansRefusalMessage, Xa as parseIamRoleArn, Xi as ccRoutedFinalSnapshotError, Xn as DELETED_RESOURCE_REMEDY, Xr as exportNameNoEchoParameters, Xs as malformedExportSourceWarning, Xt as pendingRequestCount, Ya as isIamRoleArn, Yc as createAssetRedirectResolver, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yn as replayRollback, Yr as carriedExportAliasExposure, Ys as malformedExportNamesWarning, Za as sendableAssumeRoleCommand, Zi as ccRoutedInstanceTakesNoSnapshot, Zn as recordAfterRollbackUpdate, Zr as exportNameSecretExposure, Zs as malformedLocalOutputsWarning, Zt as resolvePendingCloudControlRequests, _ as listNestedTemplateRows, _a as customResourceResponseExpirationWarning, _c as STATE_RESOURCES_MALFORMED, _i as supersededHolderOf, _n as sameJournaledOrphans, _o as lacksRecordedTableArn, _r as recheckFailedPlan, _s as repairMalformedOrphanRecordsForReadOnly, a as scanActiveConsumers, aa as ProviderRegistry, ac as refuseDivergentRecordRegionForDestroy, ai as DEFAULT_RESOURCE_WARN_AFTER_MS, al as buildDenyExternalAccessPolicy, ao as regionLessSecretName, ar as updatePartialReason, b as hasPendingMovesOut, ba as readsNoEchoDeleteValues, bc as hasReadableOutputs, bi as bold, bn as planOrphanAdoption, br as resolveReplacementOldType, bs as isReadableResourceEntry, c as inheritedProvenanceForChildDiff, ca as wouldReturnToSdkProvider, cc as malformedStateRefusalMessage, ci as destroyStackRecordsView, cl as getBootstrapMarkerKey, cn as collectNestedChildUnaddressed, cs as deployRefusesOrphanRowsReason, d as conditionInputsFrom, dc as refuseMalformedResourcesForExport, dl as validateAssetBucketName, dn as deleteJournaledOrphans, do as coerceParameterTypedValue, dr as planRollback, ds as malformedOrphanRecordsWarning, ea as refusesFinalSnapshot, ei as collectDeclaredOutputNames, en as displacedPhysicalIdShown, eo as callerEnvCredentials, er as calculateResourceDrift, f as parentSuppliedValues, fc as refuseMalformedState, fi as deleteSupersededEntry, fl as validateContainerRepoName, fn as dropFailedCommands, fo as isUnboundTemplateParameter, fr as seedsDeleteFirstGuard, fs as malformedOrphanRowsKeptWarning, g as isAbsoluteAssetPath, ga as applyCustomResourceResponseExpiration, gc as withheldAccountClause, gi as supersededHeldByOtherTypeWarning, gn as loadJournaledOrphans, go as isStalePlaceholderArnAttribute, gr as planFailedOps, gs as refuseMalformedOrphansForOrphan, h as findNestedTemplateTreeDefect, ha as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, hc as accountArgs, hi as supersededAfterRollback, hl as getDockerImageBySourceHash, hn as journaledOrphanLines, ho as cfnRefValueFromPhysicalId, hr as isReplacementOrphan, hs as refuseMalformedOrphanRecordsForDestroy, i as mergeNoChangeOutputs, ia as CC_BROKEN_REASON, ic as STATE_REGION_DIVERGED, ii as DEFAULT_RESOURCE_TIMEOUT_MS, il as ensureAssetStorage, in as recordDisplacedSkips, io as producerRegionsFromState, ir as updatePartialMessage, is as parameterInputsFor, j as recordedProtectionNote, ja as deleteIndeterminateGuards, jc as TemplateParser, ji as createReadOnlyAttributeHealerFactory, jl as ownValue, jn as formatDestructiveChange, jo as carriesFetchableDynamicReference, jr as nameGenerationHighWaterOf, js as refuseMalformedResourceEntriesForOrphan, k as diffSecurity, ka as RollbackInlinePolicyWriters, kc as NO_CC_HANDLERS_REASON, ki as noEchoParameterNamesOf, kl as hasPlainPrototype, kn as constructPathOf$1, ko as getAccountInfo, kr as orphanNeedsIdentity, ks as refuseMalformedResourceEntriesForImport, l as makeCanonicalizePropertiesFn, lc as refuseMalformedResourcesForDeploy, ll as parseBootstrapMarker, ln as getCurrentNestedStackContext, lr as withCreateTokenLedger, ls as isReadableOrphanRecord, m as childTemplateLoader, ma as withCustomResourceStack, mc as JSON_LISTING_HOLE_VALUE, mi as isSupersededResourceRecord, ml as AssetManifestLoader, mn as isHandledOrphan, mo as AWS_NO_VALUE, mr as isJournaledOrphan, ms as refuseMalformedOrphanRecords, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as refuseMalformedOutputsForDestroy, ni as isExportAliasCollision, nl as rewriteTemplateAssetReferences, no as classifyRecordedSecretRegion, nr as equalModuloMask, ns as maskedPropertyFingerprintsOf, o as inRunStackKey, oa as ccBrokenReason, oc as malformedRenderedContainersWarning, oi as maskingRetryLogger, ol as assertAssetBucketRegion, on as revertedNestedRowIds, os as declaresNoEcho, p as readRecordedConditionVerdicts, pa as setLocalCustomResourceRuntimeEnabled, pc as repairMalformedResourcesForReadOnly, pi as holdsSupersededResources, pl as BOOTSTRAP_MARKER_PREFIX, pn as dropFailedHint, po as parameterTypeMayLoseSecretIdentity, pr as demoteSupersededOrphans, ps as previewableOrphanRecords, qa as assertSendableRoleArn, qi as withSecretPhysicalIdsMaskedInState, qn as referencedLogicalIds, qo as isStatefulRecreateTargetSync, qr as secretBearingStateKeyWarning, qs as refuseMalformedOrphansForDestroy, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as repairMalformedOutputsForReadOnly, ri as bindingSkippedOutputs, rl as AssetModeResolver, rn as nestedChildStackName$1, ro as classifyReplaySecretRegion, rr as undeclaredEmptyObservedKeys, s as crossStackOutputProvenanceSource, sa as isCustomResource, sc as malformedResourcesWarning, sl as isCrossRegionRedirect, sn as withNestedRevertRun, sr as ledgerForStack, ss as maskedPropertyFingerprint, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as refuseMalformedOutputs, ti as collectPublishedOutputNames, tn as dropSettledNestedJournals, to as envCredentialsAreAssumedRole, tr as equalModuloMarkedMask, u as conditionFingerprint, uc as refuseMalformedResourcesForDestroy, ui as withStackRecords, ul as readBootstrapMarkerBody, un as withNestedStackContext, us as malformedOrphanRecordsRefusalMessage, v as renderNestedTemplateTreeDefect, vc as UNREADABLE_RESOURCES_MAP_ROW, vi as supersededResourcesOf, vn as makeForeignHolderScan, vo as refStateLookupFromResource, vr as recordUnderIdIsNotOwn, vs as unpreviewableOrphanRecords, w as macWriteOnlyKeys, wi as red, wl as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, wn as createNoEchoValueMacs, wo as recordedOutputReferenceRegions, ws as malformedScrubResourceEntriesRefusalMessage, x as pendingMovesOutOf, xa as isCustomResourceType$1, xc as hasReadableResources, xi as cyan, xn as DeploymentEventsReader, xr as withPreviousPolicies, xs as malformedLocalResourceEntriesWarning, y as templateIdentity, ya as TemplateNoEchoReresolver, yc as displayLogicalId, yi as withoutSuperseded, yn as makeSiblingClaimReader, yr as replacementNeverSwapped, ys as unreadableOrphanRecords, za as poisonRenderedSpellingsCollidingIn, zc as CrossPrefixScanCache, zn as changedReferenceReason, zr as computeParameterTaint, zs as refuseMalformedResourcePropertiesForExport, zt as refactorMarkerRefusalMessage } from "./deploy-engine-DeYSJno7.js";
10
+ import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix, t as PARTITION_TABLE } from "./aws-partition-DA0r2sr-.js";
11
+ import { A as parseFailureDebugDetail, E as timePhase, M as utf8ByteLength, O as describeJsonParseFailure, T as renderPhaseTimings, d as getCreateOnlyPropertyPaths, g as describeTypeWithThrottleRetry, m as templateResourceTypes, p as prefetchCreateOnlyPropertyPaths, x as PhaseClock, y as withRetry } from "./ec2-termination-protection-BM1Zt3Fn.js";
12
+ import { t as expectedOwnerParam } from "./expected-bucket-owner-CGoY_YS8.js";
13
+ import { a as acceptedCreateOnlyDropsOf, c as hasReadableExportSet, d as isReadableBag, f as orphansAfterRollback, g as stackInstanceIdCarriedFrom, i as slowCcOperationTimeoutMs, l as importableOutputKeys, m as shouldRetainResource, o as describeRegionValueKind, p as orphansCarriedFrom, s as exportNamesCarriedFrom, u as importableOutputs } from "./delete-started-Co5Gt1jH.js";
14
+ import { An as recordProvenPublicExpression, Cn as provenPublicValue, D as recordedNoEchoValuesOf, Dn as recordMaskOnlyValuesIn, En as recordMaskOnlyValue, Fn as isSingleDynamicReferenceToken, Ft as spelledKeysOf, It as pathCrossesDottedKey, Mt as DYNAMIC_REFERENCE_TOKEN_SCAN, Nn as WHOLE_DYNAMIC_REFERENCE_PATTERN, Nt as dynamicReferenceTokens, On as recordNoEchoAttributeValues, Ot as scrubResourceRecord, Pt as isUncertifiedBaselineMaskPosition, Rt as identityKeyFor, T as readsNoEchoSource, W as redactForState, _t as maskSecretsInText, an as physicalNameCopiesOf, at as literalSplitDelimitersOf, b as noEchoOutputsComparison, cn as recordNestedStackParameterExpressions, ct as recordLogOnlyParameterValue, dn as splitGetAttStringForm, dt as shareLogOnlyValues, et as carryLogOnlyValues, f as isMarkedCoordinate, fn as carriesSecretMask, ft as unionOfSecretBags, g as maskedLeafCoordinatesOf, gt as maskSecretsInError, h as maskWholeValue, it as hasMaskableValues, j as liveMatchesUnresolvedTokenFrame, jn as wholeStringLeavesOf, k as valueAtCoordinate, kn as recordNoEchoParameterFreshValue, kt as withPhysicalNameCopies, m as maskReadbackAtCoordinates, mt as errorCauseChain, nt as createUnionSecretMasker, ot as logOnlyValueCount, p as maskAtCoordinates, pt as createSecretMasker, qt as inheritNestedStackParameterAssociations, sn as recordPhysicalNameCopy, st as printingCorpusOf, u as canonicalCoordinates, ut as recordLogOnlyValue, v as noEchoCoordinatesOf, y as noEchoLeavesOf } from "./replacement-rules-01_01yDU.js";
15
+ import { D as withoutUnsettledProperties, E as withUnsettledProperties, S as unsettledItemsOf, i as withResourceDeadline, w as unsettledPropertiesOf, x as unsettledItemsField } from "./resource-deadline-TfDpwRQ_.js";
16
+ import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-C3_6QVgR.js";
9
17
  import { t as cdkdCacheHome } from "./cli.js";
10
18
  import { randomBytes, randomUUID } from "node:crypto";
11
19
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
@@ -17,497 +25,24 @@ import { GetSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-sec
17
25
  import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
18
26
  import { DescribeLogStreamsCommand, ResourceNotFoundException as ResourceNotFoundException$1 } from "@aws-sdk/client-cloudwatch-logs";
19
27
  import * as fs from "node:fs";
20
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, promises, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
28
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, promises, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
21
29
  import * as path from "node:path";
22
30
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
23
- import { execFile, spawn } from "node:child_process";
31
+ import { execFile } from "node:child_process";
24
32
  import { devNull, tmpdir } from "node:os";
33
+ import { CreateAliasCommand, CreateKeyCommand, DescribeKeyCommand, KMSClient, ScheduleKeyDeletionCommand } from "@aws-sdk/client-kms";
25
34
  import { BatchDeleteImageCommand, DeleteRepositoryCommand, DescribeImagesCommand as DescribeImagesCommand$1, ECRClient, GetAuthorizationTokenCommand } from "@aws-sdk/client-ecr";
26
- import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, HOST_GATEWAY_MIN_VERSION, LocalInvokeBuildError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, activateWorkloadAwsWiring, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, architectureToPlatform, attachAuthorizers, attachLoopbackForwarder, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildContainerImage, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, derivePseudoParametersFromRegion, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, dockerRegistryEnv, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, ensureForwarderImage, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getActiveWorkloadAwsWiring as getActiveWorkloadAwsWiring$1, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, isRealAwsSentinel, keysNotFromTemplate, keysOverriddenBy, loopbackForwarderPlan, materializeLayerFromArn, mcpInvokeOnce, noImplicitEcrPullArgs, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, probeHostGatewaySupport, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, recordAssumedRole, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveHostGatewayExtraHosts, resolveImageOverrides, resolveRuntimeCodeMountPath, resolveRuntimeFileExtension, resolveRuntimeImage, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, substituteImagePlaceholders, takeAwsEmulatorStateSourceHint, tryResolveImageFnJoin, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
35
+ import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, attachAuthorizers, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, dockerRegistryEnv, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, keysNotFromTemplate, keysOverriddenBy, loopbackForwarderPlan, mcpInvokeOnce, noImplicitEcrPullArgs, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveImageOverrides, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
27
36
  import { isDeepStrictEqual, promisify } from "node:util";
28
37
  import graphlib from "graphlib";
29
38
  import { Command, InvalidArgumentError, Option } from "commander";
30
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
31
39
  import * as readline$1 from "node:readline/promises";
32
40
  import readline from "node:readline/promises";
33
41
  import { Document, Pair, Scalar, YAMLError, YAMLMap, YAMLSeq, isScalar, parse, parseDocument, stringify, visit } from "yaml";
34
42
  import { emitKeypressEvents } from "node:readline";
35
43
  import { createLocalStartAgentCoreCommand, createLocalStartCloudFrontCommand, createLocalStartMicrovmCommand, createLocalStartWebFunctionCommand, createLocalStateProvider, getEmbedConfig, isCfnFlagPresent, listTargets, rejectExplicitCfnStackWithMultipleStacks, resolveCfnFallbackRegion, setEmbedConfig, substituteAgainstState, substituteAgainstStateAsync, substituteEnvVarsFromState, substituteEnvVarsFromStateAsync } from "cdk-local";
36
- import { createServer } from "node:net";
37
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
38
44
  import { WebSocketServer } from "ws";
39
45
 
40
- // src/cli/commands/state-file-keys.ts
41
- const STATE_FILE_SUFFIX = "/state.json";
42
- const LEGACY_SEGMENTS_UNDER_PREFIX = 1;
43
- const LOCK_FILE_SUFFIX = "/lock.json";
44
- const REGION_SEGMENT = /^(?:[a-z]{2}|eusc)(-[a-z]+)+-\d+$/;
45
- async function listAllStateKeys(stateBackend) {
46
- return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(STATE_FILE_SUFFIX));
47
- }
48
- async function listAllLockKeys(stateBackend) {
49
- return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(LOCK_FILE_SUFFIX));
50
- }
51
- function parseStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
52
- const body = key.slice(0, -suffix.length);
53
- const prefix = knownPrefix?.replace(/\/+$/, "");
54
- if (prefix !== void 0 && prefix !== "" && key.startsWith(`${prefix}/`)) {
55
- const rest = body.slice(prefix.length + 1).split("/");
56
- if (rest.length === LEGACY_SEGMENTS_UNDER_PREFIX && rest[0]) return { stack: rest[0] };
57
- }
58
- const segments = body.split("/");
59
- const last = segments[segments.length - 1] ?? key;
60
- const secondLast = segments[segments.length - 2];
61
- if (secondLast !== void 0 && secondLast !== "" && REGION_SEGMENT.test(last)) return {
62
- stack: secondLast,
63
- region: last
64
- };
65
- return { stack: last };
66
- }
67
- function describeStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
68
- const { stack, region } = parseStateKey(key, suffix, knownPrefix);
69
- const name = displayIdent(stack, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
70
- return region === void 0 ? name : `${name} (${displayIdent(region)})`;
71
- }
72
- const STATE_KEY_MAX_CODE_POINTS = STACK_REF_MAX_CODE_POINTS + 64;
73
-
74
- // src/cli/options/resource-timeout.ts
75
- function parseDuration(value) {
76
- if (typeof value !== "string" || value.length === 0) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
77
- const match = /^(\d+(?:\.\d+)?)([smh])$/.exec(value.trim());
78
- if (!match) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
79
- const num = Number(match[1]);
80
- if (!Number.isFinite(num) || num <= 0) throw new Error(`Invalid duration "${value}": must be greater than zero`);
81
- const unit = match[2];
82
- return Math.round(num * (unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5));
83
- }
84
- const RESOURCE_TYPE_REGEX = TIMEOUT_FLAG_RESOURCE_TYPE;
85
- function parseResourceTimeoutToken(flagName) {
86
- return (raw, previous) => {
87
- const acc = previous ?? { perTypeMs: {} };
88
- if (!acc.perTypeMs) acc.perTypeMs = {};
89
- const eqIndex = raw.indexOf("=");
90
- if (eqIndex === -1) {
91
- acc.globalMs = parseDuration(raw);
92
- return acc;
93
- }
94
- const typePart = raw.substring(0, eqIndex).trim();
95
- const durationPart = raw.substring(eqIndex + 1).trim();
96
- if (!RESOURCE_TYPE_REGEX.test(typePart)) throw new Error(`Invalid ${flagName} value "${raw}": left-hand side must be a CloudFormation resource type like AWS::Service::Resource (got "${typePart}")`);
97
- if (durationPart.length === 0) throw new Error(`Invalid ${flagName} value "${raw}": missing duration after '=' (e.g. ${typePart}=1h)`);
98
- let ms;
99
- try {
100
- ms = parseDuration(durationPart);
101
- } catch (err) {
102
- const inner = describeAwsFailure(err).detail;
103
- throw new Error(`Invalid ${flagName} value "${raw}": ${inner}`);
104
- }
105
- acc.perTypeMs[typePart] = ms;
106
- return acc;
107
- };
108
- }
109
- const resourceTimeoutOptions = [new Option("--resource-warn-after <duration_or_type=duration>", "Warn when a single resource operation exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 5m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=10m) for a per-type override.").default(void 0, "5m").argParser(parseResourceTimeoutToken("--resource-warn-after")), new Option("--resource-timeout <duration_or_type=duration>", "Abort a single resource operation that exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 30m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=1h) for a per-type override. Custom-Resource-heavy stacks may need to raise this above the default 30m (the Custom Resource provider's polling cap is 1h). When this is shorter than the 5m --resource-warn-after default, --resource-warn-after is auto-lowered to min(5m, 0.5*timeout) and a warning is logged so the user can override explicitly.").default(void 0, "30m").argParser(parseResourceTimeoutToken("--resource-timeout"))];
110
- function formatMs(ms) {
111
- if (ms % 36e5 === 0) return `${ms / 36e5}h`;
112
- if (ms % 6e4 === 0) return `${ms / 6e4}m`;
113
- return `${Math.round(ms / 1e3)}s`;
114
- }
115
- function autoLoweredWarnMs(timeoutMs) {
116
- return Math.max(1, Math.min(DEFAULT_RESOURCE_WARN_AFTER_MS, Math.floor(timeoutMs / 2)));
117
- }
118
- function validateResourceTimeouts(opts) {
119
- const timeout = opts.resourceTimeout;
120
- const globalWarn = opts.resourceWarnAfter?.globalMs;
121
- const globalTimeout = timeout?.globalMs;
122
- if (typeof globalWarn === "number" && typeof globalTimeout === "number") {
123
- if (globalWarn >= globalTimeout) throw new Error(`--resource-warn-after (${globalWarn}ms) must be less than --resource-timeout (${globalTimeout}ms)`);
124
- } else if (typeof globalTimeout === "number") {
125
- if (3e5 >= globalTimeout) {
126
- const lowered = autoLoweredWarnMs(globalTimeout);
127
- ensureWarnAfter(opts).globalMs = lowered;
128
- getLogger().warn(`--resource-warn-after defaulted to ${formatMs(lowered)} because --resource-timeout ${formatMs(globalTimeout)} is shorter than the ${formatMs(DEFAULT_RESOURCE_WARN_AFTER_MS)} default. Pass --resource-warn-after ${commandHole("duration")} explicitly to override.`);
129
- }
130
- } else if (typeof globalWarn === "number" && globalWarn >= 18e5) throw new Error(`--resource-warn-after (${formatMs(globalWarn)}) must be less than --resource-timeout (default ${formatMs(DEFAULT_RESOURCE_TIMEOUT_MS)}). Pass --resource-timeout ${commandHole("duration")} alongside it to raise the deadline.`);
131
- const warnPerType = opts.resourceWarnAfter?.perTypeMs ?? {};
132
- const timeoutPerType = timeout?.perTypeMs ?? {};
133
- const types = /* @__PURE__ */ new Set([...Object.keys(warnPerType), ...Object.keys(timeoutPerType)]);
134
- for (const t of types) {
135
- const explicitPerTypeWarn = warnPerType[t];
136
- const explicitPerTypeTimeout = timeoutPerType[t];
137
- const effectiveGlobalWarn = opts.resourceWarnAfter?.globalMs;
138
- const effectiveWarn = explicitPerTypeWarn ?? effectiveGlobalWarn ?? 3e5;
139
- const effectiveTimeout = explicitPerTypeTimeout ?? globalTimeout ?? 18e5;
140
- if (effectiveWarn < effectiveTimeout) continue;
141
- if (explicitPerTypeWarn !== void 0 && explicitPerTypeTimeout !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(explicitPerTypeTimeout)})`);
142
- if (explicitPerTypeWarn !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(effectiveTimeout)}). Pass --resource-timeout ${t}=${commandHole("duration")} alongside it to raise the deadline.`);
143
- const lowered = autoLoweredWarnMs(effectiveTimeout);
144
- ensureWarnAfter(opts).perTypeMs[t] = lowered;
145
- getLogger().warn(`--resource-warn-after for ${t} defaulted to ${formatMs(lowered)} because --resource-timeout for ${t} (${formatMs(effectiveTimeout)}) is shorter than the inherited ${formatMs(effectiveWarn)} warn. Pass --resource-warn-after ${t}=${commandHole("duration")} explicitly to override.`);
146
- }
147
- }
148
- function ensureWarnAfter(opts) {
149
- if (!opts.resourceWarnAfter) opts.resourceWarnAfter = { perTypeMs: {} };
150
- if (!opts.resourceWarnAfter.perTypeMs) opts.resourceWarnAfter.perTypeMs = {};
151
- return opts.resourceWarnAfter;
152
- }
153
-
154
- // src/cli/options/provisioning-route.ts
155
- const RESOURCE_TYPE_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+$/;
156
- function parseAllowUnsupportedTypesToken(value, previous) {
157
- const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
158
- for (const token of parsed) if (!RESOURCE_TYPE_FORMAT.test(token)) throw new Error(`Invalid --allow-unsupported-types value "${token}": expected a CloudFormation resource type like AWS::Service::Type or Custom::Foo.`);
159
- return [...previous ?? [], ...parsed];
160
- }
161
- const allowUnsupportedTypesOption = new Option("--allow-unsupported-types <types>", "Comma-separated resource types to attempt via Cloud Control even though cdkd reports them unsupported (AWS NON_PROVISIONABLE). Escape hatch — Cloud Control will likely still fail. Example: --allow-unsupported-types AWS::Foo::Bar,AWS::Baz::Qux").argParser(parseAllowUnsupportedTypesToken);
162
- const RESOURCE_PROPERTY_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+:[A-Z][A-Za-z0-9]*$/;
163
- function parseRouteEntries(value, previous, flag) {
164
- const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
165
- for (const token of parsed) {
166
- if (!RESOURCE_PROPERTY_FORMAT.test(token)) throw new Error(`Invalid ${flag} value "${token}": expected <ResourceType>:<PropertyName> with PascalCase on both halves (e.g. AWS::ApiGatewayV2::Api:Body).`);
167
- if (token.startsWith("Custom::")) throw new Error(`Invalid ${flag} value "${token}": Custom:: resources are routed through cfn-response and have no SDK-unwired properties at cdkd, so the flag would have no effect. Use --allow-unsupported-types for type-level escape hatches instead.`);
168
- }
169
- return [...previous ?? [], ...parsed];
170
- }
171
- function parsePreferSdkRouteToken(value, previous) {
172
- return parseRouteEntries(value, previous, "--prefer-sdk-route");
173
- }
174
- let deprecatedAliasWarned = false;
175
- function parseAllowUnsupportedPropertiesToken(value, previous) {
176
- if (!deprecatedAliasWarned) {
177
- deprecatedAliasWarned = true;
178
- process.stderr.write("--allow-unsupported-properties is deprecated and will be removed in the first minor release after 2026-12-01; use --prefer-sdk-route, which takes the same <ResourceType>:<PropertyName> tokens and does the same thing. The old name reads as the opposite of its behaviour: it does not make the property reach AWS, it keeps the resource on the SDK provider and accepts that the value is NOT written.\n");
179
- }
180
- return parseRouteEntries(value, previous, "--allow-unsupported-properties");
181
- }
182
- const preferSdkRouteOption = new Option("--prefer-sdk-route <entries>", "Comma-separated <ResourceType>:<PropertyName> tokens to keep on the SDK provider instead of auto-routing the resource to Cloud Control. The named values are then NOT written to AWS — the deployed resource is missing the field. Ignored for a resource that routes to Cloud Control for another reason (a sibling unwired property, or a sticky cc-api state record), where the values are written after all. Example: --prefer-sdk-route AWS::ApiGatewayV2::Api:Body").argParser(parsePreferSdkRouteToken);
183
- const allowUnsupportedPropertiesOption = new Option("--allow-unsupported-properties <entries>", "Deprecated alias for --prefer-sdk-route.").argParser(parseAllowUnsupportedPropertiesToken).hideHelp();
184
- const LOGICAL_ID_FORMAT = /^[A-Za-z][A-Za-z0-9]{0,254}$/;
185
- function parseRecreateViaCcApiToken(value, previous) {
186
- const token = value.trim();
187
- if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-cc-api flag per resource — repeat the flag for additional targets.`);
188
- return [...previous ?? [], token];
189
- }
190
- const recreateViaCcApiOption = new Option("--recreate-via-cc-api <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via Cloud Control API in this deploy, so a top-level CFn property the SDK provider does not write reaches AWS via CC. Repeatable — pass the flag once per resource. Per-resource opt-in (no bulk / no per-stack shortcut) so the destroy-and-recreate cost is acknowledged for each target. Stateful resource types (RDS, DynamoDB, S3, EFS, ...) refuse unless --force-stateful-recreation is ALSO passed (two-flag protection). Cannot be combined with --prefer-sdk-route on the same resource type and property. Refused, with no bypass, for a type Cloud Control cannot create (NON_PROVISIONABLE).").argParser(parseRecreateViaCcApiToken);
191
- function parseRecreateViaSdkProviderToken(value, previous) {
192
- const token = value.trim();
193
- if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-sdk-provider value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-sdk-provider flag per resource — repeat the flag for additional targets.`);
194
- return [...previous ?? [], token];
195
- }
196
- function parsePinCcApiToken(value, previous) {
197
- const token = value.trim();
198
- if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --pin-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --pin-cc-api flag per resource — repeat the flag for additional targets.`);
199
- return [...previous ?? [], token];
200
- }
201
- const pinCcApiOption = new Option("--pin-cc-api <logicalId>", "Keep the named resource (by CloudFormation logical id) on the Cloud Control route in this deploy, declining the automatic return to the SDK Provider that a type-level sdk-coverage exemption would otherwise apply to a resource recorded as provisionedBy: cc-api. Repeatable — pass the flag once per resource. Has no effect on a resource already on the SDK path, and does not override an exemption admitted because Cloud Control cannot manage the type.").argParser(parsePinCcApiToken);
202
- const recreateViaSdkProviderOption = new Option("--recreate-via-sdk-provider <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via cdkd's SDK Provider in this deploy, so a resource currently sticky on provisionedBy: cc-api flips back to provisionedBy: sdk. Used after a release adds SDK coverage for a type the user originally needed CC for (e.g. Lambda LoggingConfig). Repeatable — pass the flag once per resource. Per-resource opt-in. Stateful resource types refuse unless --force-stateful-recreation is ALSO passed.").argParser(parseRecreateViaSdkProviderToken);
203
-
204
- // src/cli/options/assume-role.ts
205
- function parseAssumeRoleToken(raw, previous) {
206
- const acc = previous ?? { perLambda: nullPrototypeRecord() };
207
- if (!acc.perLambda) acc.perLambda = nullPrototypeRecord();
208
- const shownRaw = quotedArgv(raw, 613);
209
- const eqIndex = raw.trim().startsWith("arn:") ? -1 : raw.indexOf("=");
210
- if (eqIndex === -1) {
211
- const bare = raw.trim();
212
- if (!isIamRoleArn(bare)) throw new Error(`Invalid --assume-role value ${shownRaw}: expected an IAM role ARN like arn:aws:iam::123456789012:role/MyRole, or LogicalId='<arn>'.`);
213
- acc.globalArn = bare;
214
- return acc;
215
- }
216
- const logicalId = raw.substring(0, eqIndex).trim();
217
- const arn = raw.substring(eqIndex + 1).trim();
218
- if (!/^[A-Za-z][A-Za-z0-9]*$/.test(logicalId)) throw new Error(`Invalid --assume-role value ${shownRaw}: left-hand side ${quotedArgv(logicalId)} must be a CloudFormation logical ID (alphanumeric, leading letter).`);
219
- if (!isIamRoleArn(arn)) throw new Error(`Invalid --assume-role value ${shownRaw}: right-hand side ${quotedArgv(arn, 613)} must be an IAM role ARN like arn:aws:iam::123456789012:role/MyRole.`);
220
- acc.perLambda[logicalId] = arn;
221
- return acc;
222
- }
223
- function quotedArgv(value, maxCodePoints) {
224
- const shown = displayIdent(value, maxCodePoints === void 0 ? void 0 : { maxCodePoints });
225
- return !/\s/.test(value) && shown === value ? `"${value}"` : shellBoundedDisplay(shown);
226
- }
227
- function normalizeStartApiAssumeRole(raw, autoResolve) {
228
- if (raw === void 0) return autoResolve ? {
229
- perLambda: nullPrototypeRecord(),
230
- bareAutoResolve: true
231
- } : void 0;
232
- if (autoResolve && raw.globalArn) throw new Error(`--assume-role-auto auto-resolves EACH routed Lambda's own execution role, but --assume-role ${quotedArgv(raw.globalArn, 613)} also names a single global default. These are mutually exclusive on the global slot. Either drop the global ARN to keep --assume-role-auto for every Lambda, or drop --assume-role-auto to keep the global default. Per-Lambda overrides (--assume-role '<LogicalId>'='<arn>') are compatible with either side.`);
233
- if (autoResolve) raw.bareAutoResolve = true;
234
- return raw;
235
- }
236
- function effectiveAssumeRoleArn(logicalId, opt) {
237
- if (!opt) return void 0;
238
- const perLambda = opt.perLambda;
239
- if (perLambda && Object.hasOwn(perLambda, logicalId)) return perLambda[logicalId];
240
- return opt.globalArn;
241
- }
242
-
243
- // src/cli/options.ts
244
- function parseContextOptions(contextArgs) {
245
- const context = nullPrototypeRecord();
246
- if (contextArgs) for (const arg of contextArgs) {
247
- const eqIndex = arg.indexOf("=");
248
- if (eqIndex > 0) context[arg.substring(0, eqIndex)] = arg.substring(eqIndex + 1);
249
- }
250
- return context;
251
- }
252
- const commonOptions = [
253
- new Option("--verbose", "Enable verbose logging").default(false),
254
- new Option("--profile <profile>", "AWS profile"),
255
- new Option("--role-arn <arn>", "IAM role ARN to assume for AWS API calls (env: CDKD_ROLE_ARN); the role needs the actions for the resource types you deploy plus the bookkeeping actions cdkd itself issues, because cdkd makes raw service API calls and does not route through CloudFormation, so CDK CLI deploy-roles will NOT work. Combines with --profile: the profile supplies the base credentials the role is assumed FROM, and the role is what every later AWS call runs as"),
256
- new Option("-y, --yes", "Automatically answer interactive prompts with the recommended response (e.g. confirm destroy)").default(false)
257
- ];
258
- const deprecatedRegionOption = new Option("--region <region>", "[deprecated] Prefer AWS_REGION or your AWS profile; --region is still honored but will be removed in a future release").hideHelp();
259
- function warnIfDeprecatedRegion(options) {
260
- if (options.region !== void 0) process.stderr.write("Warning: --region is deprecated and will be removed in a future release. It is still honored for now (it overrides AWS_REGION / your AWS profile), but prefer the AWS_REGION environment variable or your AWS profile to choose the region.\n");
261
- }
262
- const appOptions = [new Option("-a, --app <command>", "CDK app command (e.g., \"node app.ts\") or path to a pre-synthesized cloud assembly directory. Falls back to cdk.json or CDKD_APP env"), new Option("--output <path>", "Output directory for synthesis").default("cdk.out")];
263
- const stateOptions = [new Option("--state-bucket <bucket>", "S3 bucket for state storage. Falls back to CDKD_STATE_BUCKET env or cdk.json"), new Option("--state-prefix <prefix>", "S3 key prefix for state files").default(DEFAULT_STATE_PREFIX).argParser(parseStatePrefix)];
264
- function parseStatePrefix(value) {
265
- if (value.includes("<") || value.includes(">")) throw new InvalidArgumentError("a state prefix cannot contain '<' or '>': that is a placeholder cdkd printed in a suggested command for a value it could not show. Replace it with your actual prefix.");
266
- return value;
267
- }
268
- const stackOptions = [new Option("--stack <name>", "Stack name to operate on")];
269
- function parseStackRegion(value) {
270
- if (value.trim() === "") throw new InvalidArgumentError(`expected a region name (e.g. us-east-1), got ${value === "" ? "an empty value" : "whitespace only"}. Omit the flag entirely to operate on every region a stack has state in.`);
271
- return value;
272
- }
273
- function guardStackRegionOptions(cmd) {
274
- for (const option of cmd.options) if (option.long === "--stack-region" && option.parseArg === void 0) option.argParser(parseStackRegion);
275
- for (const sub of cmd.commands) guardStackRegionOptions(sub);
276
- }
277
- const noWaitOption = new Option("--no-wait", "Skip waiting for async resources to stabilize (RDS, ElastiCache, NAT Gateway, EC2 Instance, ELBv2 LoadBalancer, Lambda MicroVM Image, ECS Service steady state)");
278
- const fullWaitOption = new Option("--full-wait", "Also wait for stabilizations cdkd skips by default, matching CloudFormation (CloudFront Distribution Deployed, RDS Multi-AZ DB cluster storage optimization; raise --resource-timeout AWS::RDS::DBCluster for a long one)");
279
- function validateWaitFlags(opts) {
280
- if (opts.wait === false && opts.fullWait === true) throw new Error("--no-wait and --full-wait cannot be combined: --no-wait skips stabilization waits, --full-wait adds them. Pick one.");
281
- }
282
- function applyWaitFlagEnv(opts) {
283
- validateWaitFlags(opts);
284
- process.env["CDKD_WAIT_FLAGS_AVAILABLE"] = "true";
285
- if (opts.wait === false) process.env["CDKD_NO_WAIT"] = "true";
286
- if (opts.fullWait === true) process.env["CDKD_FULL_WAIT"] = "true";
287
- }
288
- const aggressiveVpcParallelOption = new Option("--no-aggressive-vpc-parallel", "Disable the default relaxation of CDK-injected VPC route DependsOn (on by default; opt out to keep the strict CDK ordering)");
289
- const forceStatefulRecreationOption = new Option("--force-stateful-recreation", "Confirm a data-losing destroy + recreate of a stateful resource. Required whenever a replacement target is a stateful type on the --recreate-via-cc-api / --recreate-via-sdk-provider pre-flight, with --replace, AND on the paths a plain deploy reaches with no flag: a template immutable-property change, and an in-place update the provisioning layer rejects. Stateful types are databases, filesystems, KMS keys, table / vector storage, source repositories, and more; https://cdkd.dev/cli-deploy-safety/ carries the full list. S3 buckets and log groups are the conditional cases: at pre-flight, a non-empty bucket, or a log group with retention, with log streams, or whose emptiness the probe could not settle; mid-deploy, ANY bucket or log group, because the emptiness probe cannot run there. The two probes differ on failure — the bucket fails open, the log group closed. Destroy + recreate loses ALL data in the resource — no automatic data migration. Full opt-in for CI use: --recreate-via-cc-api '<id>' --force-stateful-recreation --yes.").default(false);
290
- const replaceOption = new Option("--replace", "Replace (DELETE + CREATE) a resource whose in-place update is rejected because an immutable property changed and AWS exposes no update API for it (e.g. Lambda LayerVersion content, EFS AccessPoint, ECS TaskDefinition, ApiGatewayV2 immutable fields). Without this flag such a change fails the deploy. Stateful types (RDS / DynamoDB / EFS / any S3 bucket / any Logs log group / etc.) ALSO require --force-stateful-recreation since the replacement is a data-losing DELETE + CREATE — mid-deploy neither emptiness probe can run, so both conditional types count as stateful there.").default(false);
291
- const useCdkBootstrapAssetsOption = new Option("--use-cdk-bootstrap-assets", "Publish assets to the CDK bootstrap bucket/repo named by the asset manifest verbatim, skipping the cdkd asset-storage redirection even when this region is opted in via 'cdkd bootstrap'. For apps deployed via both CloudFormation and cdkd during a migration window. Per-app pin: cdk.json context.cdkd.useCdkBootstrapAssets. Also suppresses the legacy-mode 'cdk gc' notice.").default(false);
292
- const strictGetattOption = new Option("--strict-getatt", "Fail the deploy on ANY Fn::GetAtt that falls back to the physical ID because cdkd cannot construct the attribute (default: warn and use the physical ID, hard-failing only when the fallback is knowably wrong — an *Arn attribute with a non-ARN value or a *Url attribute with a non-http(s) value). Also fails the deploy when a stack Output cannot be resolved (default: warn and store no value).").default(false);
293
- const allowUnaddressedOption = new Option("--allow-unaddressed", "Exit 0 even when the deploy left a resource unaddressed — a DELETE the provider could not issue, or a replacement whose old resource survives untracked (default: exit 2, matching cdkd destroy). The summary rows and warnings are printed either way; only the exit code changes.").default(false);
294
- const noCfnFallbackOption = new Option("--no-cfn-fallback", "Do not fall back to CloudFormation (ListExports / stack outputs) when an Fn::ImportValue / Fn::GetStackOutput reference is not found in cdkd state (default: fall back, so producers still managed by CloudFormation can be referenced)");
295
- const annotationMessageOptions = [new Option("--strict", "Do not proceed with stacks carrying warning annotations").default(false), new Option("--ignore-errors", "Ignore error annotations from stack synthesis, which will likely produce an invalid deployment").default(false)];
296
- function exclusivelyOption(command) {
297
- return new Option("-e, --exclusively", command === "deploy" ? "Only deploy requested stacks, do not include dependencies" : "Only destroy requested stacks, do not include the stacks that depend on them").default(false);
298
- }
299
- const deployOptions = [
300
- new Option("--concurrency <number>", "Maximum concurrent resource operations").default(20).argParser((value) => parseInt(value, 10)),
301
- new Option("--stack-concurrency <number>", "Maximum concurrent stack deployments").default(4).argParser((value) => parseInt(value, 10)),
302
- new Option("--asset-publish-concurrency <number>", "Maximum concurrent asset publish operations (S3 uploads + ECR push)").default(8).argParser((value) => parseInt(value, 10)),
303
- new Option("--image-build-concurrency <number>", "Maximum concurrent Docker image builds").default(4).argParser((value) => parseInt(value, 10)),
304
- new Option("--dry-run", "Show changes without applying").default(false),
305
- new Option("--skip-assets", "Skip asset publishing").default(false),
306
- new Option("--no-rollback", "Skip rollback on deployment failure"),
307
- new Option("--no-auto-asset-storage", "Do not auto-create cdkd-owned asset storage (asset bucket + container-asset ECR repo + marker) on the first deploy into a region not yet opted in via 'cdkd bootstrap'. Deploys into such regions stay in legacy mode (CDK bootstrap destinations). Per-app opt-out: cdk.json context.cdkd.autoAssetStorage: false."),
308
- new Option("--no-capture-observed-state", "Skip capturing AWS-current properties after each create/update (adds a fire-and-forget readCurrentState per resource so cdkd drift can compare against the real deploy-time AWS snapshot instead of the template). On by default. Disable when deploy speed matters more than rich drift detection — falls back to comparing against template properties (the pre-v3 behavior)."),
309
- new Option("--prefix-user-supplied-names", "Opt in to LEGACY behavior: prepend the stack name to physical names the user explicitly supplied in their CDK code (e.g. `new iam.Role(this, \"X\", { roleName: \"my-role\" })` → AWS resource named `MyStack-my-role` instead of `my-role`). Since v0.94.0 the default is to NOT prefix user-supplied names — this flag restores the pre-v0.94.0 behavior on Pattern B providers (IAM Role / User / Group / InstanceProfile / ManagedPolicy / ELBv2 LoadBalancer / TargetGroup). Enable via this flag, CDKD_PREFIX_USER_SUPPLIED_NAMES=true, or cdk.json context.cdkd.prefixUserSuppliedNames=true. Applies to `cdkd deploy` only.").default(false),
310
- noWaitOption,
311
- fullWaitOption,
312
- aggressiveVpcParallelOption,
313
- exclusivelyOption("deploy"),
314
- allowUnsupportedTypesOption,
315
- preferSdkRouteOption,
316
- allowUnsupportedPropertiesOption,
317
- recreateViaCcApiOption,
318
- recreateViaSdkProviderOption,
319
- pinCcApiOption,
320
- forceStatefulRecreationOption,
321
- replaceOption,
322
- useCdkBootstrapAssetsOption,
323
- strictGetattOption,
324
- noCfnFallbackOption,
325
- allowUnaddressedOption,
326
- ...resourceTimeoutOptions
327
- ];
328
- const contextOptions = [new Option("-c, --context <key=value...>", "Set context values (can be specified multiple times)")];
329
- const destroyOptions = [
330
- new Option("-f, --force", "Do not ask for confirmation before destroying the stacks").default(false),
331
- new Option("--remove-protection", `Bypass deletion protection on protected resources by flipping the per-resource protection flag off in-place before delete. Covers stack-level terminationProtection (CDK property) and resource-level protection on ${removeProtectionTypeList()}.`).default(false),
332
- allowUnsupportedTypesOption
333
- ];
334
- const skipFinalSnapshotOption = new Option("--skip-final-snapshot", "Delete resources whose DeletionPolicy (or, on replacements, UpdateReplacePolicy) is 'Snapshot' — including an RDS DB cluster or standalone DB instance with no DeletionPolicy, whose CloudFormation default is 'Snapshot' — WITHOUT creating the final snapshot the policy promises (DATA LOSS — explicit opt-out of CloudFormation parity). By default cdkd creates the final snapshot for every CloudFormation-supported type (RDS DBInstance / DBCluster, Neptune / DocDB clusters, ElastiCache CacheCluster / ReplicationGroup, Redshift Cluster, EC2 Volume) and refuses the delete when it cannot — e.g. a resource managed via the Cloud Control API route, whose delete has no final-snapshot parameter. On 'cdkd rollback' the flag governs the rolled-back CREATE's DeletionPolicy; a reverse-replacement delete of the NEW resource keeps its own bounded UpdateReplacePolicy behavior and is unaffected.").default(false);
335
-
336
- // src/local/local-role-arn.ts
337
- async function applyRoleArnForLocal(opts) {
338
- if (getActiveWorkloadAwsWiring()?.mixed) await runWithRealAws(() => applyRoleArnIfSet(opts));
339
- else await applyRoleArnIfSet(opts);
340
- const role = getAssumedRoleCredentials();
341
- if (role === void 0) return;
342
- recordAssumedRole(getPreAssumeEnvCredentials(), {
343
- accessKeyId: role.accessKeyId,
344
- secretAccessKey: role.secretAccessKey,
345
- sessionToken: role.sessionToken
346
- });
347
- }
348
-
349
- // src/cli/commands/local-profile-credentials-file.ts
350
- const CONTAINER_AWS_CREDENTIALS_PATH = "/cdkd-aws/credentials";
351
- async function writeProfileCredentialsFile(profileName, creds, opts) {
352
- if (profileName === "") throw new Error("writeProfileCredentialsFile: profile name must not be empty.");
353
- if (/[\r\n[\]]/.test(profileName)) throw new Error(`writeProfileCredentialsFile: profile name ${displayIdent(profileName)} contains a forbidden character (any of CR, LF, '[', ']' would corrupt the INI file or the docker -e env var).`);
354
- const dir = await mkdtemp(path.join(tmpdir(), "cdkd-profile-creds-"));
355
- const hostPath = path.join(dir, "credentials");
356
- opts?.onDirCreated?.(hostPath);
357
- const lines = [
358
- `[${profileName}]`,
359
- `aws_access_key_id = ${creds.accessKeyId}`,
360
- `aws_secret_access_key = ${creds.secretAccessKey}`
361
- ];
362
- if (creds.sessionToken) lines.push(`aws_session_token = ${creds.sessionToken}`);
363
- try {
364
- await writeFile(hostPath, lines.join("\n") + "\n", { mode: 384 });
365
- } catch (err) {
366
- let removed = true;
367
- await rm(dir, {
368
- recursive: true,
369
- force: true
370
- }).catch(() => {
371
- removed = false;
372
- });
373
- if (removed) try {
374
- opts?.onDirRemoved?.(hostPath);
375
- } catch {}
376
- throw err;
377
- }
378
- return {
379
- hostPath,
380
- containerPath: CONTAINER_AWS_CREDENTIALS_PATH,
381
- profileName,
382
- dispose: async () => {
383
- await rm(dir, {
384
- recursive: true,
385
- force: true
386
- });
387
- }
388
- };
389
- }
390
- function strandedProfileCredentialsNotice(hostPath) {
391
- if (hostPath === void 0) return void 0;
392
- return `The AWS credentials file mounted into the containers is NOT removed: delete ${displayIdent(hostPath)} once you tear them down.`;
393
- }
394
-
395
- // src/local/local-aws-wiring.ts
396
- async function activateLocalAwsWiring(options) {
397
- assertAwsEmulatorValue(options.awsEmulator);
398
- try {
399
- await activateWorkloadAwsWiring({
400
- awsEmulator: options.awsEmulator,
401
- caBundle: options.caBundle,
402
- profile: options.profile,
403
- pull: options.pull,
404
- envVars: options.envVars
405
- });
406
- } catch (err) {
407
- const cause = err instanceof Error && err.cause instanceof Error ? err.cause : void 0;
408
- throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_WIRING_FAILED", cause);
409
- }
410
- }
411
- async function activateLocalAwsAndRoleArn(options) {
412
- await activateLocalAwsWiring(options);
413
- await applyRoleArnForLocal({
414
- roleArn: options.roleArn,
415
- region: options.region
416
- });
417
- }
418
- function assertAwsEmulatorValue(flag) {
419
- const value = resolveAwsEmulatorOption(flag);
420
- if (typeof value !== "string") return;
421
- const where = `--aws-emulator (or ${awsEmulatorEnvName()})`;
422
- let u;
423
- try {
424
- u = new URL(value);
425
- } catch {
426
- u = void 0;
427
- }
428
- if (u === void 0 ? /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(value) || /[?#]/.test(value) : u.username !== "" || u.password !== "" || u.search !== "" || u.hash !== "") throw new CdkdError(`${where} must be a bare scheme://host:port URL; the value carries a user name, password, query or fragment, which is not shown here. Remove it.`, "LOCAL_AWS_WIRING_FAILED");
429
- if (u === void 0 || u.protocol !== "https:" && u.protocol !== "http:") throw new CdkdError(`${where} takes an http(s) URL such as https://127.0.0.1:9297, and the value given is not one. The URL is OPTIONAL, so a value right after the flag is taken as the URL: put --aws-emulator after the target, or write --aws-emulator=<url>.`, "LOCAL_AWS_WIRING_FAILED");
430
- }
431
- async function applyLocalAwsWiring(wiring, env, extraMounts, takenContainerPaths) {
432
- const defaults = wiring.mode === "forward" && !env["AWS_ACCESS_KEY_ID"] ? await resolveHostDefaultCredentials() : void 0;
433
- const wiredEnv = applyWorkloadAwsWiringToEnv(env, wiring, defaults);
434
- const emulatorOnly = workloadGetsEmulatorKeysOnly(env, wiring);
435
- const mounts = extraMounts.filter((m) => !emulatorOnly || m.containerPath !== "/cdkd-aws/credentials");
436
- const taken = /* @__PURE__ */ new Set([...takenContainerPaths, ...mounts.map((m) => m.containerPath)]);
437
- for (const m of wiring.mounts) if (!taken.has(m.containerPath)) mounts.push({
438
- ...m,
439
- readOnly: true
440
- });
441
- return {
442
- env: wiredEnv,
443
- extraMounts: mounts
444
- };
445
- }
446
- function loopbackPortsFor(wiring, env, network) {
447
- if (network !== "host") return effectiveLoopbackPorts(env, wiring);
448
- const mixed = wiring.mixed;
449
- if (mixed && effectiveLoopbackPorts(env, wiring).includes(mixed.resignPort)) throw new CdkdError("A run with \"real-aws\" exceptions (AWS Emulator mixed mode) cannot use the host network: its re-signing sidecar listens on the workload's own loopback. Drop the \"real-aws\" exceptions or the host network.", "LOCAL_AWS_EMULATOR_FORWARDER_FAILED");
450
- return [];
451
- }
452
- async function prepareLocalLoopbackForwarder(wiring) {
453
- try {
454
- await ensureForwarderImage(wiring.skipPull === true);
455
- } catch (err) {
456
- if (wiring.mode === "emulator" || wiring.mixed) throw new CdkdError(`--aws-emulator: the loopback forwarder image could not be pulled: ${err.message}`, "LOCAL_AWS_EMULATOR_FORWARDER_PULL_FAILED");
457
- }
458
- }
459
- async function attachLocalLoopbackForwarder(containerId, ports) {
460
- const wiring = getActiveWorkloadAwsWiring$1();
461
- if (!wiring) return;
462
- try {
463
- await (ports === void 0 ? attachLoopbackForwarder(containerId, wiring) : attachLoopbackForwarder(containerId, wiring, ports));
464
- } catch (err) {
465
- throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_EMULATOR_FORWARDER_FAILED", err instanceof Error ? err : void 0);
466
- }
467
- }
468
- async function profileCredentialsForWorkload(profile, resolve) {
469
- if (!profile || localAwsEmulatorActive()) return void 0;
470
- return resolve(profile);
471
- }
472
- function setContainerRegion(env, region) {
473
- if (!region) return;
474
- const folded = canonicalizeRegion(region);
475
- env["AWS_REGION"] = folded;
476
- env["AWS_DEFAULT_REGION"] = folded;
477
- }
478
- function localAwsEmulatorActive() {
479
- return getActiveWorkloadAwsWiring$1()?.mode === "emulator";
480
- }
481
- function localAwsEmulatorCredentials() {
482
- const wiring = getActiveWorkloadAwsWiring$1();
483
- return wiring?.mode === "emulator" ? wiring.emulatorCredentials : void 0;
484
- }
485
- function workloadGetsEmulatorKeysOnly(env, wiring) {
486
- if (!wiring) return false;
487
- if (wiring.mode === "emulator") return true;
488
- if (!wiring.mixed) return false;
489
- return !Object.entries(env).some(([k, v]) => k !== "AWS_ENDPOINT_URL" && isRealAwsSentinel(k, v));
490
- }
491
- function taskRoleAssumedInRealAws(env, wiring) {
492
- if (wiring?.mode === "emulator") return false;
493
- if (!wiring?.mixed) return true;
494
- return isRealAwsSentinel("AWS_ENDPOINT_URL_STS", env["AWS_ENDPOINT_URL_STS"]);
495
- }
496
- function mixedModeActive() {
497
- return getActiveWorkloadAwsWiring$1()?.mixed !== void 0;
498
- }
499
- function realAwsException(service, workload) {
500
- return mixedModeActive() && !isAwsServiceRoutedToEmulator(service, workload);
501
- }
502
- function mixedModeEmulatorOverride() {
503
- return getAwsEndpointOverride() ?? getActiveWorkloadAwsWiring$1()?.mixed?.emulatorClientOverride;
504
- }
505
- function warnAwsEmulatorStateSourceHint(dropped, stateSourceGiven) {
506
- if (dropped === 0 || stateSourceGiven) return;
507
- const hint = takeAwsEmulatorStateSourceHint();
508
- if (hint !== void 0) getLogger().warn(hint);
509
- }
510
-
511
46
  // src/cli/aws-emulator-activation.ts
512
47
  async function activateAwsEmulatorForCommand(flag) {
513
48
  try {
@@ -690,231 +225,6 @@ function defaultProfileRegion(ini) {
690
225
  }
691
226
  }
692
227
 
693
- // src/cli/region-options.ts
694
- function foldRegionOption(options) {
695
- if (options.region !== void 0) options.region = canonicalizeRegion(options.region);
696
- for (const key of ["AWS_REGION", "AWS_DEFAULT_REGION"]) {
697
- const value = process.env[key];
698
- if (value) process.env[key] = canonicalizeRegion(value);
699
- }
700
- }
701
- function namedCliRegion(optionRegion) {
702
- return canonicalizeRegion(optionRegion || process.env["AWS_REGION"]) || void 0;
703
- }
704
- function rawCliRegion(optionRegion) {
705
- return optionRegion || process.env["AWS_REGION"] || void 0;
706
- }
707
- async function resolveEffectiveRegion(options) {
708
- const flag = canonicalizeRegion(options.region);
709
- if (flag) return {
710
- region: flag,
711
- source: "flag"
712
- };
713
- const awsRegion = canonicalizeRegion(process.env["AWS_REGION"]);
714
- if (awsRegion && awsRegion === injectedAwsRegionValue()) return {
715
- region: awsRegion,
716
- source: "default-env"
717
- };
718
- if (awsRegion) return {
719
- region: awsRegion,
720
- source: "env"
721
- };
722
- const defaultRegionEnv = canonicalizeRegion(process.env["AWS_DEFAULT_REGION"]);
723
- if (defaultRegionEnv) return {
724
- region: defaultRegionEnv,
725
- source: "default-env"
726
- };
727
- const fromProfile = canonicalizeRegion(await resolveSdkDefaultRegion(options.profile));
728
- if (fromProfile) return {
729
- region: fromProfile,
730
- source: "profile"
731
- };
732
- return {
733
- region: LEGACY_DEFAULT_REGION,
734
- source: "default"
735
- };
736
- }
737
- function exportInferredRegionForSdk(effective) {
738
- if (effective.source !== "default-env") return;
739
- injectAwsRegion(effective.region);
740
- }
741
- const LEGACY_DEFAULT_REGION = "us-east-1";
742
- async function resolveSdkDefaultRegion(profile) {
743
- const { STSClient } = await import("@aws-sdk/client-sts");
744
- let client;
745
- try {
746
- client = new STSClient({
747
- ...awsClientDefaults({ profile }),
748
- ...profile && { profile }
749
- });
750
- return await client.config.region() || void 0;
751
- } catch {
752
- return;
753
- } finally {
754
- client?.destroy?.();
755
- }
756
- }
757
- function ownedByLegacyDefault(probe) {
758
- return { stateExists: (stackName, region) => probe.stateExistsOwnedBy(stackName, region, LEGACY_DEFAULT_REGION) };
759
- }
760
- async function placeStack(effective, stackName, probe) {
761
- const [inResolved, inLegacy] = await Promise.all([probe.stateExists(stackName, effective.region), probe.stateExists(stackName, LEGACY_DEFAULT_REGION)]);
762
- if (inResolved && inLegacy) return "both";
763
- if (inResolved) return "resolved";
764
- return inLegacy ? "legacy" : "none";
765
- }
766
- function bothRegionsMessage(effective, stackName) {
767
- return `Stack ${quoteStackName(stackName)} has state in both ${LEGACY_DEFAULT_REGION} and ${displayIdent(effective.region)} (which ${inferredFrom(effective)} resolves). Continuing to use ${LEGACY_DEFAULT_REGION}, as a command with no region named did before. Set AWS_REGION=${displayIdent(effective.region)} to work on the ${displayIdent(effective.region)} one, or AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`;
768
- }
769
- function inferredFrom(effective) {
770
- return effective.source === "default-env" ? "AWS_DEFAULT_REGION" : "your AWS profile";
771
- }
772
- function holdMessage(effective, stackName) {
773
- return `Stack ${quoteStackName(stackName)} has existing state in ${LEGACY_DEFAULT_REGION}, but ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing stack is not duplicated. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message, or AWS_REGION=${displayIdent(effective.region)} to work in ${displayIdent(effective.region)} instead (where this stack has no state).`;
774
- }
775
- function quoteStackName(stackName) {
776
- return displayIdent(stackName) === stackName ? `'${stackName}'` : "a stack whose name is not a plain identifier";
777
- }
778
- function stackRegionResolver(input) {
779
- const { effective, logger } = input;
780
- const probe = ownedByLegacyDefault(input.probe);
781
- const placements = /* @__PURE__ */ new Map();
782
- const place = (stackName) => {
783
- let placement = placements.get(stackName);
784
- if (placement === void 0) {
785
- placement = placeStack(effective, stackName, probe);
786
- placement.catch(() => placements.delete(stackName));
787
- placements.set(stackName, placement);
788
- }
789
- return placement;
790
- };
791
- const answers = /* @__PURE__ */ new Map();
792
- const answer = async (stackName) => {
793
- const placement = await place(stackName);
794
- if (placement === "legacy" || placement === "both") {
795
- logger.info(placement === "both" ? bothRegionsMessage(effective, stackName) : holdMessage(effective, stackName));
796
- return LEGACY_DEFAULT_REGION;
797
- }
798
- if (placement === "resolved") return effective.region;
799
- const others = (input.siblings ?? []).filter((name) => name !== stackName);
800
- const siblingPlacements = await Promise.all(others.map(place));
801
- if (siblingPlacements.some((p) => p === "legacy" || p === "both") && !siblingPlacements.includes("resolved")) {
802
- logger.info(`Stack ${quoteStackName(stackName)} has no state yet, and the other stacks of this app that have state all stay in ${LEGACY_DEFAULT_REGION}, while ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Using ${LEGACY_DEFAULT_REGION} for it too, so the app stays in one region. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`);
803
- return LEGACY_DEFAULT_REGION;
804
- }
805
- return effective.region;
806
- };
807
- return (stackName, pinned) => {
808
- if (pinned) return Promise.resolve(pinned);
809
- if (!regionNeedsReconciliation(effective)) return Promise.resolve(effective.region);
810
- let result = answers.get(stackName);
811
- if (result === void 0) {
812
- result = answer(stackName);
813
- result.catch(() => answers.delete(stackName));
814
- answers.set(stackName, result);
815
- }
816
- return result;
817
- };
818
- }
819
- function stateWithRegion(state, region) {
820
- return state.region ? state : {
821
- ...state,
822
- region
823
- };
824
- }
825
- function legacyStateBucketFallbackRegion(effective) {
826
- return regionNeedsReconciliation(effective) ? LEGACY_DEFAULT_REGION : void 0;
827
- }
828
- async function reconcileExportIndexRegion(input) {
829
- const { effective, probe, statePrefix, logger } = input;
830
- if (!regionNeedsReconciliation(effective)) return effective.region;
831
- const indexKey = (region) => `${statePrefix}/_index/${region}/exports.json`;
832
- try {
833
- if (!await probe.rawObjectExists(indexKey("us-east-1"))) return effective.region;
834
- } catch (error) {
835
- logger.warn(safeMsg`[region] could not probe the exports index (${error.name ?? "error"}); using ${effective.region}.`);
836
- return effective.region;
837
- }
838
- logger.debug(safeMsg`[region] exports index exists in ${LEGACY_DEFAULT_REGION}; using it rather than ${effective.region} (inferred).`);
839
- return LEGACY_DEFAULT_REGION;
840
- }
841
- function withOtherIndexRemoval(runStore, input) {
842
- const { effective, runIndexRegion, statePrefix, probe, createStore, logger } = input;
843
- const other = runIndexRegion === "us-east-1" ? effective.region : LEGACY_DEFAULT_REGION;
844
- if (!regionNeedsReconciliation(effective) || other === runIndexRegion) return runStore;
845
- let otherStore;
846
- const removeFromOther = async (stackName, region) => {
847
- try {
848
- otherStore ??= probe.rawObjectExists(`${statePrefix}/_index/${other}/exports.json`).then((exists) => exists ? createStore(other) : void 0);
849
- await (await otherStore)?.removeStackIfPresent(stackName, region);
850
- } catch (error) {
851
- otherStore = void 0;
852
- logger.warn(safeMsg`Could not remove ${stackName}'s entries from the ${other} exports index (${error.name ?? "error"}); a later Fn::ImportValue may read a stale value from it.`);
853
- }
854
- };
855
- return new Proxy(runStore, { get(target, prop, receiver) {
856
- if (prop === "removeStack") return async (stackName, region) => {
857
- await target.removeStack(stackName, region);
858
- await removeFromOther(stackName, region);
859
- };
860
- const value = Reflect.get(target, prop, receiver);
861
- return typeof value === "function" ? value.bind(target) : value;
862
- } });
863
- }
864
- async function reconcileMarkerRegionWithLegacyDefault(input) {
865
- const { effective, probe, markerKeyFor, logger } = input;
866
- if (!regionNeedsReconciliation(effective)) return effective.region;
867
- const markerExists = async (region) => {
868
- try {
869
- return await probe.getRawObject(markerKeyFor(region)) !== null;
870
- } catch (error) {
871
- if (error.name !== "NoSuchBucket") throw error;
872
- logger.debug(`[region] no state bucket yet, so no bootstrap marker for ${region} (first bootstrap).`);
873
- return false;
874
- }
875
- };
876
- if (await markerExists(effective.region)) {
877
- logger.debug(`[region] asset storage exists in ${effective.region} (from your AWS profile); using it.`);
878
- return effective.region;
879
- }
880
- if (!await markerExists("us-east-1")) return effective.region;
881
- logger.info(`cdkd asset storage exists in ${LEGACY_DEFAULT_REGION}, but your AWS profile resolves ${effective.region}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing storage is not orphaned. Pass '--region ${effective.region}' to target your profile's region, or '--region ${LEGACY_DEFAULT_REGION}' to silence this message.`);
882
- return LEGACY_DEFAULT_REGION;
883
- }
884
- function regionNeedsReconciliation(effective) {
885
- if (effective.source === "flag" || effective.source === "env") return false;
886
- return effective.region !== LEGACY_DEFAULT_REGION;
887
- }
888
- function adoptDeprecatedRegionFlag(cmd) {
889
- const registered = cmd.options;
890
- const inherited = registered.findIndex((option) => option.long === "--region");
891
- if (inherited !== -1) {
892
- registered.splice(inherited, 1);
893
- const emitter = cmd;
894
- emitter.removeAllListeners("option:region");
895
- emitter.removeAllListeners("optionEnv:region");
896
- if (cmd.getOptionValueSource("region") === "default") {
897
- const internals = cmd;
898
- delete internals._optionValues["region"];
899
- delete internals._optionValueSources["region"];
900
- }
901
- }
902
- cmd.addOption(deprecatedRegionOption);
903
- cmd.hook("preAction", (_thisCommand, actionCommand) => {
904
- const options = actionCommand.opts();
905
- warnIfDeprecatedRegion(options);
906
- if (options.stackRegion !== void 0) {
907
- options.rawStackRegion = options.stackRegion;
908
- options.stackRegion = canonicalizeRegion(options.stackRegion);
909
- }
910
- foldRegionOption(options);
911
- });
912
- return cmd;
913
- }
914
- function regionShown(region) {
915
- return displayIdent(region) === region ? plainOrDescribed(region, "region") : "a region that is not a plain identifier";
916
- }
917
-
918
228
  // src/cli/commands/bootstrap-destroy.ts
919
229
  async function promptBootstrapDestroyConfirm(input) {
920
230
  const logger = getLogger();
@@ -1266,6 +576,117 @@ async function configureStateBucket(args) {
1266
576
  else report(safeMsg`✓ Lifecycle rule ${CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID} already present (left unchanged)`);
1267
577
  }
1268
578
 
579
+ // src/cli/commands/bootstrap-noecho-mac-key.ts
580
+ function errorName(error) {
581
+ const raw = error?.name;
582
+ return typeof raw === "string" && /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(raw) ? raw : "Error";
583
+ }
584
+ const NOECHO_MAC_KEY_ADMIN_ACTIONS = [
585
+ "kms:DescribeKey",
586
+ "kms:GetKeyPolicy",
587
+ "kms:PutKeyPolicy",
588
+ "kms:ListResourceTags",
589
+ "kms:ListGrants",
590
+ "kms:RevokeGrant",
591
+ "kms:CreateAlias",
592
+ "kms:UpdateAlias",
593
+ "kms:DeleteAlias",
594
+ "kms:EnableKey",
595
+ "kms:DisableKey",
596
+ "kms:UpdateKeyDescription",
597
+ "kms:TagResource",
598
+ "kms:UntagResource",
599
+ "kms:ScheduleKeyDeletion",
600
+ "kms:CancelKeyDeletion"
601
+ ];
602
+ function noEchoMacKeyPolicy(partition, accountId) {
603
+ const root = { AWS: `arn:${partition}:iam::${accountId}:root` };
604
+ return JSON.stringify({
605
+ Version: "2012-10-17",
606
+ Statement: [{
607
+ Sid: "KeyAdministration",
608
+ Effect: "Allow",
609
+ Principal: root,
610
+ Action: [...NOECHO_MAC_KEY_ADMIN_ACTIONS],
611
+ Resource: "*"
612
+ }, {
613
+ Sid: "GenerateMacThroughIam",
614
+ Effect: "Allow",
615
+ Principal: root,
616
+ Action: "kms:GenerateMac",
617
+ Resource: "*"
618
+ }]
619
+ });
620
+ }
621
+ function partitionOfArn$1(arn) {
622
+ const partition = arn?.split(":")[1];
623
+ return partition !== void 0 && /^aws(-[a-z]+)*$/.test(partition) ? partition : "aws";
624
+ }
625
+ async function ensureNoEchoMacKey(args) {
626
+ const { kms, region, accountId, partition, report, warn } = args;
627
+ if (awsEndpointOverrideActive()) {
628
+ report(`Skipping the NoEcho value MAC key (${NOECHO_MAC_KEY_ALIAS}): AWS Emulator target`);
629
+ return "skipped";
630
+ }
631
+ const failed = (step, error) => {
632
+ warn(`Could not set up the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} in ${region} (${errorName(error)} from ${step}). Deploys keep working: a write-only property a NoEcho parameter feeds is re-sent on every deploy. Re-run 'cdkd bootstrap' with kms:CreateKey, kms:PutKeyPolicy, kms:CreateAlias and kms:DescribeKey to create it.`);
633
+ return "failed";
634
+ };
635
+ try {
636
+ const meta = (await kms.send(new DescribeKeyCommand({ KeyId: NOECHO_MAC_KEY_ALIAS }))).KeyMetadata;
637
+ if (meta?.KeySpec === "HMAC_256" && meta.KeyUsage === "GENERATE_VERIFY_MAC" && meta.KeyState === "Enabled") {
638
+ report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
639
+ return "exists";
640
+ }
641
+ warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key (${meta?.KeySpec ?? "unknown spec"}, ${meta?.KeyState ?? "unknown state"}), so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
642
+ return "failed";
643
+ } catch (error) {
644
+ if (errorName(error) !== "NotFoundException") return failed("kms:DescribeKey", error);
645
+ }
646
+ let keyId;
647
+ try {
648
+ keyId = (await kms.send(new CreateKeyCommand({
649
+ KeySpec: "HMAC_256",
650
+ KeyUsage: "GENERATE_VERIFY_MAC",
651
+ Policy: noEchoMacKeyPolicy(partition, accountId),
652
+ Description: "cdkd: MACs of NoEcho parameter values, so a deploy re-sends a write-only property only when its value changed",
653
+ Tags: [{
654
+ TagKey: "cdkd:purpose",
655
+ TagValue: "noecho-value-mac"
656
+ }]
657
+ }))).KeyMetadata?.KeyId;
658
+ if (keyId === void 0) return failed("kms:CreateKey", /* @__PURE__ */ new Error("no key id"));
659
+ } catch (error) {
660
+ return failed("kms:CreateKey", error);
661
+ }
662
+ try {
663
+ await kms.send(new CreateAliasCommand({
664
+ AliasName: NOECHO_MAC_KEY_ALIAS,
665
+ TargetKeyId: keyId
666
+ }));
667
+ } catch (error) {
668
+ const name = errorName(error);
669
+ await kms.send(new ScheduleKeyDeletionCommand({
670
+ KeyId: keyId,
671
+ PendingWindowInDays: 7
672
+ })).catch((retireError) => warn(`Could not schedule the deletion of the unused KMS key ${keyId} in ${region} (${errorName(retireError)}); schedule it by hand: aws kms schedule-key-deletion --key-id ${keyId} --pending-window-in-days 7 --region ${region}`));
673
+ if (name !== "AlreadyExistsException") return failed("kms:CreateAlias", error);
674
+ try {
675
+ const won = (await kms.send(new DescribeKeyCommand({ KeyId: NOECHO_MAC_KEY_ALIAS }))).KeyMetadata;
676
+ if (won?.KeySpec === "HMAC_256" && won.KeyUsage === "GENERATE_VERIFY_MAC" && won.KeyState === "Enabled") {
677
+ report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
678
+ return "exists";
679
+ }
680
+ } catch (describeError) {
681
+ return failed("kms:DescribeKey", describeError);
682
+ }
683
+ warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key, so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
684
+ return "failed";
685
+ }
686
+ report(`Created the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS}`);
687
+ return "created";
688
+ }
689
+
1269
690
  // src/cli/commands/bootstrap.ts
1270
691
  async function bootstrapCommand(options) {
1271
692
  const logger = getLogger();
@@ -1287,12 +708,17 @@ async function bootstrapCommand(options) {
1287
708
  let s3Client = awsClients.s3;
1288
709
  let bucketName;
1289
710
  let accountId;
711
+ let partition;
1290
712
  if (options.stateBucket) {
1291
713
  bucketName = options.stateBucket;
1292
- accountId = (await awsClients.sts.send(new GetCallerIdentityCommand({}))).Account;
714
+ const identity = await awsClients.sts.send(new GetCallerIdentityCommand({}));
715
+ accountId = identity.Account;
716
+ partition = partitionOfArn$1(identity.Arn);
1293
717
  } else {
1294
718
  logger.info("No --state-bucket specified, resolving default bucket name...");
1295
- accountId = (await awsClients.sts.send(new GetCallerIdentityCommand({}))).Account;
719
+ const identity = await awsClients.sts.send(new GetCallerIdentityCommand({}));
720
+ accountId = identity.Account;
721
+ partition = partitionOfArn$1(identity.Arn);
1296
722
  bucketName = getDefaultStateBucketName(accountId);
1297
723
  logger.info(`Using default state bucket: ${bucketName}`);
1298
724
  }
@@ -1356,6 +782,24 @@ async function bootstrapCommand(options) {
1356
782
  operation: "HeadBucket"
1357
783
  });
1358
784
  }
785
+ const kmsClient = new KMSClient({
786
+ ...awsClientDefaults({ profile: options.profile }),
787
+ region,
788
+ ...options.profile && { profile: options.profile }
789
+ });
790
+ let noEchoMacKey;
791
+ try {
792
+ noEchoMacKey = await ensureNoEchoMacKey({
793
+ kms: kmsClient,
794
+ region,
795
+ accountId,
796
+ partition,
797
+ report: (message) => logger.info(message),
798
+ warn: (message) => logger.warn(message)
799
+ });
800
+ } finally {
801
+ kmsClient.destroy();
802
+ }
1359
803
  let skipStateBucketConfig = false;
1360
804
  if (bucketExists) {
1361
805
  if (!options.force) {
@@ -1417,6 +861,7 @@ async function bootstrapCommand(options) {
1417
861
  logger.info(`Asset bucket: ${assetStorage.assetBucket}`);
1418
862
  logger.info(`Container-asset repository: ${assetStorage.containerRepo}`);
1419
863
  }
864
+ if (noEchoMacKey === "created" || noEchoMacKey === "exists") logger.info(`NoEcho value MAC key: ${NOECHO_MAC_KEY_ALIAS}`);
1420
865
  logger.info(`Region: ${region}`);
1421
866
  if (assetStorage) logger.info(`\ncdkd asset storage is now ON for region ${region}: deploys in this region publish assets to the cdkd-owned bucket/repo (out of 'cdk gc' reach) instead of the CDK bootstrap storage. The first deploy of each existing stack with assets will show a one-time UPDATE re-pointing asset references — content is identical, no replacement.`);
1422
867
  logger.info("\nYou can now use cdkd deploy with:");
@@ -1428,7 +873,7 @@ async function bootstrapCommand(options) {
1428
873
  }
1429
874
  }
1430
875
  function createBootstrapCommand() {
1431
- const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead.").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION, AWS_DEFAULT_REGION, the profile's region, else us-east-1; an inferred region keeps existing us-east-1 asset storage)")).action(withErrorHandling(async (options) => {
876
+ const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead. Also creates the region's HMAC KMS key that lets deploys tell whether a NoEcho parameter value changed (alias/cdkd-noecho-mac).").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION, AWS_DEFAULT_REGION, the profile's region, else us-east-1; an inferred region keeps existing us-east-1 asset storage)")).action(withErrorHandling(async (options) => {
1432
877
  if (options.destroy) {
1433
878
  if (options.assetBucket !== void 0 || options.containerRepo !== void 0) throw new CdkdError("--asset-bucket / --container-repo cannot be combined with --destroy. The teardown reads the region's asset storage names from the bootstrap marker.", "INVALID_OPTIONS");
1434
879
  if (!options.assets) throw new CdkdError("--no-assets cannot be combined with --destroy. The teardown scope is the asset storage itself; use --include-state-bucket to also delete the state bucket.", "INVALID_OPTIONS");
@@ -1454,248 +899,6 @@ function createBootstrapCommand() {
1454
899
  return cmd;
1455
900
  }
1456
901
 
1457
- // src/utils/glob-match.ts
1458
- function globMatches(pattern, subject) {
1459
- const segments = pattern.split("*");
1460
- if (segments.length === 1) return pattern === subject;
1461
- const head = segments[0];
1462
- const tail = segments[segments.length - 1];
1463
- if (subject.length < head.length + tail.length) return false;
1464
- if (!subject.startsWith(head) || !subject.endsWith(tail)) return false;
1465
- const end = subject.length - tail.length;
1466
- let cursor = head.length;
1467
- for (let i = 1; i < segments.length - 1; i++) {
1468
- const segment = segments[i];
1469
- if (segment === "") continue;
1470
- const at = subject.indexOf(segment, cursor);
1471
- if (at === -1 || at + segment.length > end) return false;
1472
- cursor = at + segment.length;
1473
- }
1474
- return true;
1475
- }
1476
- function pathGlobMatches(pattern, subject) {
1477
- const p = pattern.split("/");
1478
- const s = subject.split("/");
1479
- let can = s.map(() => false).concat(true);
1480
- for (let i = p.length - 1; i >= 0; i--) {
1481
- const next = new Array(s.length + 1).fill(false);
1482
- if (p[i] === "**") for (let j = s.length; j >= 0; j--) next[j] = can[j] || j < s.length && next[j + 1];
1483
- else for (let j = 0; j < s.length; j++) next[j] = can[j + 1] && globMatches(p[i], s[j]);
1484
- can = next;
1485
- }
1486
- return can[0];
1487
- }
1488
-
1489
- // src/cli/cdk-path.ts
1490
- function readCdkPath(resource) {
1491
- const meta = resource.Metadata;
1492
- if (!meta) return "";
1493
- const v = meta["aws:cdk:path"];
1494
- return typeof v === "string" ? v : "";
1495
- }
1496
- function readCdkPathOrUndefined(resource) {
1497
- const path = readCdkPath(resource);
1498
- return path === "" ? void 0 : path;
1499
- }
1500
- function buildCdkPathIndex(template) {
1501
- const index = /* @__PURE__ */ new Map();
1502
- for (const [logicalId, resource] of Object.entries(template.Resources)) {
1503
- if (resource.Type === "AWS::CDK::Metadata") continue;
1504
- const path = readCdkPath(resource);
1505
- if (path) index.set(path, logicalId);
1506
- }
1507
- return index;
1508
- }
1509
- function resolveCdkPathToLogicalIds(input, index) {
1510
- const seen = /* @__PURE__ */ new Map();
1511
- const prefix = `${input}/`;
1512
- for (const [path, logicalId] of index) if (path === input || path.startsWith(prefix)) {
1513
- if (!seen.has(logicalId)) seen.set(logicalId, path);
1514
- }
1515
- return [...seen.entries()].map(([logicalId, cdkPath]) => ({
1516
- logicalId,
1517
- cdkPath
1518
- }));
1519
- }
1520
- function stackForConstructPath(path, stacks) {
1521
- let best;
1522
- let bestRank = -1;
1523
- for (const s of stacks) {
1524
- const names = [[s.displayName, 1], [s.stackName, 0]];
1525
- for (const [name, preference] of names) {
1526
- if (typeof name !== "string" || name.length === 0) continue;
1527
- if (!path.startsWith(`${name}/`)) continue;
1528
- const rank = name.length * 2 + preference;
1529
- if (rank > bestRank) {
1530
- best = s;
1531
- bestRank = rank;
1532
- }
1533
- }
1534
- }
1535
- return best;
1536
- }
1537
- function stackForPathFormTarget(parsed, target, stacks) {
1538
- if (!parsed.isPath || parsed.pathOrId !== target) return void 0;
1539
- return stackForConstructPath(parsed.pathOrId, stacks);
1540
- }
1541
-
1542
- // src/cli/stack-matcher.ts
1543
- function matchStacks(stacks, patterns, options = {}) {
1544
- if (patterns.length === 0) return [];
1545
- const selected = /* @__PURE__ */ new Set();
1546
- for (const pattern of patterns) for (const stack of stacksForPattern(stacks, pattern)) selected.add(stack);
1547
- if (options.dedupe === "identity") return stacks.filter((s) => selected.has(s));
1548
- const seen = /* @__PURE__ */ new Set();
1549
- return stacks.filter((s) => selected.has(s) && !seen.has(s.stackName) && seen.add(s.stackName));
1550
- }
1551
- function stackNameRegionCollisions(stacks, regionOf, selected = new Set(stacks)) {
1552
- const byNameRegion = /* @__PURE__ */ new Map();
1553
- for (const stack of stacks) {
1554
- const key = injectiveKey(stack.stackName, regionOf(stack) ?? "");
1555
- const group = byNameRegion.get(key);
1556
- if (group) group.push(stack);
1557
- else byNameRegion.set(key, [stack]);
1558
- }
1559
- const sameAccountPossible = (a, b) => a.account === void 0 || b.account === void 0 || a.account === b.account;
1560
- const groups = [];
1561
- for (const group of byNameRegion.values()) {
1562
- const chosen = group.filter((s) => selected.has(s));
1563
- if (chosen.length === 0) continue;
1564
- const colliding = group.filter((s) => selected.has(s) || chosen.some((c) => sameAccountPossible(c, s)));
1565
- if (colliding.length > 1) groups.push(colliding);
1566
- }
1567
- return groups;
1568
- }
1569
- function stacksForDependency(depName, dependent, pool) {
1570
- if (depName === dependent.stackName) return [];
1571
- const candidates = pool.filter((s) => s.stackName === depName);
1572
- if (candidates.length <= 1) return candidates;
1573
- const sameStage = candidates.filter((s) => s.stagePath === dependent.stagePath);
1574
- const inStage = sameStage.length > 0 ? sameStage : candidates;
1575
- if (inStage.length === 1) return inStage;
1576
- const sameRegion = inStage.filter((s) => s.region === dependent.region);
1577
- return sameRegion.length > 0 ? sameRegion : inStage;
1578
- }
1579
- function renderStackNameRegionCollision(groups, regionOf) {
1580
- const ident = (v) => displayIdent(v, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
1581
- return `Selected stacks address the same CloudFormation stack: ${groups.map((group) => {
1582
- const region = regionOf(group[0]);
1583
- const where = region === void 0 ? "and neither sets env.region, so they deploy to the same region" : `in region ${ident(region)}`;
1584
- const accounts = [...new Set(group.flatMap((s) => s.account ? [s.account] : []))];
1585
- const accountNote = accounts.length > 1 ? ` (their accounts ${accounts.map(ident).join(", ")} differ, but one run deploys every selected stack under its own account)` : "";
1586
- return `${group.map(describeStack).join(", ")} share the physical stack name ${ident(group[0].stackName)} ${where}${accountNote}`;
1587
- }).join("; ")}. Give each a distinct stackName or env.region, or select only one of them by its CDK path.` + (groups.some((g) => g.some((s) => s.region === void 0 && regionOf(s) !== void 0)) ? " A stack without env.region takes the run's region: pin that Stage's region, or set AWS_REGION to another region for this run." : "");
1588
- }
1589
- function refuseStackNameRegionCollisions(stacks, regionOf, selected) {
1590
- const groups = stackNameRegionCollisions(stacks, regionOf, selected);
1591
- if (groups.length > 0) throw new CdkdError(renderStackNameRegionCollision(groups, (s) => regionOf(s)), "STACK_NAME_REGION_COLLISION");
1592
- }
1593
- function selectTargetStack(parsed, target, stacks) {
1594
- if (parsed.stackPattern === null) return stacks.length === 1 ? {
1595
- kind: "found",
1596
- stack: stacks[0]
1597
- } : { kind: "no-prefix" };
1598
- const byPrefix = stackForPathFormTarget(parsed, target, stacks);
1599
- if (byPrefix) {
1600
- if (stackForPathFormTarget(parsed, target, [...stacks].reverse()) === byPrefix) return {
1601
- kind: "found",
1602
- stack: byPrefix
1603
- };
1604
- return {
1605
- kind: "ambiguous",
1606
- pattern: byPrefix.stackName,
1607
- matched: stacks.filter((s) => s.stackName === byPrefix.stackName)
1608
- };
1609
- }
1610
- const matched = matchStacks([...stacks], [parsed.stackPattern], { dedupe: "identity" });
1611
- if (matched.length === 1) return {
1612
- kind: "found",
1613
- stack: matched[0]
1614
- };
1615
- if (matched.length === 0) return {
1616
- kind: "not-found",
1617
- pattern: parsed.stackPattern
1618
- };
1619
- return {
1620
- kind: "ambiguous",
1621
- pattern: parsed.stackPattern,
1622
- matched
1623
- };
1624
- }
1625
- function renderAmbiguousTargetStack(pattern, matched) {
1626
- const sharedName = matched.length > 1 && matched.every((s) => s.stackName === pattern);
1627
- const example = matched.find((s) => s.displayName && s.displayName !== s.stackName)?.displayName;
1628
- const hint = example !== void 0 && displayIdent(example, { maxCodePoints: 1152 }) === example ? ` (e.g. '${example}/<construct path>')` : "";
1629
- return `Stack pattern ${renderPatternList([pattern])} matched ${matched.length} stacks: ${matched.map(describeStack).join(", ")}` + (sharedName ? ", which share that physical stack name" : "") + (example !== void 0 ? `. Name one stack by its CDK path, shown in parentheses${hint}.` : ". Use a more specific pattern.");
1630
- }
1631
- function stacksForPattern(stacks, pattern) {
1632
- const byId = stacks.filter((s) => pathGlobMatches(pattern, s.displayName ?? s.stackName));
1633
- return byId.length > 0 ? byId : stacks.filter((s) => s.stackName === pattern);
1634
- }
1635
- function describeStack(stack) {
1636
- const name = displayIdent(stack.stackName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
1637
- if (stack.displayName && stack.displayName !== stack.stackName) return `${name} (${displayIdent(stack.displayName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS })})`;
1638
- return name;
1639
- }
1640
- function renderNoStackMatch(patterns, available) {
1641
- return patterns.length > 0 ? `No stacks matching ${patterns.join(", ")} found in assembly. ` + (available.length > 0 ? `Available: ${available.map(describeStack).join(", ")}` : "The assembly has no stacks") : "No stacks found in assembly";
1642
- }
1643
- function unmatchedPatterns(stacks, patterns, isPresent = () => true) {
1644
- return [...new Set(patterns)].filter((p) => !stacksForPattern(stacks, p).some(isPresent));
1645
- }
1646
- function renderUnmatchedPatternsWarning(unmatched, where) {
1647
- const verb = unmatched.length === 1 ? "was" : "were";
1648
- return `${renderPatternList(unmatched)} matched no stack ${where} and ${verb} skipped.`;
1649
- }
1650
- function renderNotInAppWarning(names) {
1651
- const one = names.length === 1;
1652
- return `${renderPatternList(names)} ${one ? "is" : "are"} in state but ${one ? "is not a stack" : "are not stacks"} of this app and ${one ? "was" : "were"} skipped. A nested stack is destroyed with its parent; another app's stack, with that app or by name through cdkd state destroy.`;
1653
- }
1654
- function renderPatternList(patterns) {
1655
- return patterns.map((p) => displayIdent(p, {
1656
- maxCodePoints: STACK_REF_MAX_CODE_POINTS,
1657
- listMember: true
1658
- })).join(", ");
1659
- }
1660
- function stackMatchesPattern(stack, pattern) {
1661
- return pathGlobMatches(pattern, stack.displayName ?? stack.stackName) || pattern === stack.stackName;
1662
- }
1663
- function partitionTopLevel(stacks) {
1664
- const topLevel = [];
1665
- const inStages = [];
1666
- for (const stack of stacks) (stack.stagePath === void 0 ? topLevel : inStages).push(stack);
1667
- return {
1668
- topLevel,
1669
- inStages
1670
- };
1671
- }
1672
- function renderAllLeftOutStageStacks(inStages) {
1673
- const n = inStages.length;
1674
- return `--all selects top-level stacks only; ${n} stack${n === 1 ? "" : "s"} inside a CDK Stage ${n === 1 ? "was" : "were"} left out (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
1675
- }
1676
- function renderStagePatternAdvice(inStages) {
1677
- const stagePatterns = [...new Set(inStages.map((s) => s.stagePath).filter((p) => p !== void 0 && displayIdent(p, { maxCodePoints: 1152 }) === p))].map((p) => `'${p}/*'`);
1678
- return stagePatterns.length > 0 ? `Name them with ${stagePatterns.join(", ")}, or select every stack with '**'.` : `Select them with '**'.`;
1679
- }
1680
- function stacksNoLongerSelected(stacks, patterns, selected) {
1681
- const oldRule = (p, s) => globMatches(p, p.includes("/") ? s.displayName ?? s.stackName : s.stackName);
1682
- const dropped = stacks.filter((s) => !selected.has(s.stackName) && patterns.some((p) => oldRule(p, s)));
1683
- return {
1684
- stacks: dropped,
1685
- patterns: [...new Set(patterns)].filter((p) => dropped.some((s) => oldRule(p, s)))
1686
- };
1687
- }
1688
- function renderStacksNoLongerSelected(patterns, dropped) {
1689
- const n = dropped.length;
1690
- const one = patterns.length === 1;
1691
- const inStages = dropped.filter((s) => s.stagePath !== void 0);
1692
- const direct = (s) => s.stagePath !== void 0 && (s.displayName ?? s.stackName).split("/").length === s.stagePath.split("/").length + 1;
1693
- return `${renderPatternList(patterns)} now ${one ? "matches" : "match"} the CDK path, with * inside one segment, and no longer ${one ? "selects" : "select"} ${n} stack${n === 1 ? "" : "s"} ${one ? "it" : "they"} used to (${dropped.map(describeStack).join(", ")}). ` + (inStages.length === dropped.length && inStages.every(direct) ? renderStagePatternAdvice(inStages) : inStages.length > 0 ? "Name each by the CDK path shown in parentheses, or select every stack with '**'." : "Name each by the CDK path shown in parentheses.");
1694
- }
1695
- function renderAllNoTopLevelStacks(inStages) {
1696
- return `--all selects top-level stacks only, and this app has none: every stack is inside a CDK Stage (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
1697
- }
1698
-
1699
902
  // src/utils/yaml.ts
1700
903
  const EMIT_OPTIONS = {
1701
904
  schema: "core",
@@ -2233,7 +1436,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
2233
1436
  // src/provisioning/register-providers.ts
2234
1437
  let providerClasses;
2235
1438
  function loadProviderClasses() {
2236
- providerClasses ??= import("./provider-classes-RMTfwJPz.js");
1439
+ providerClasses ??= import("./provider-classes-CRCHL04N.js");
2237
1440
  return providerClasses;
2238
1441
  }
2239
1442
  function registerAllProviders(registry, classes) {
@@ -3841,7 +3044,7 @@ async function deployStackInScope(ctx, stackInfo, stackRegion, stackAwsClients)
3841
3044
  const syncValidation = validateRecreateTargets({
3842
3045
  template: stackInfo.template,
3843
3046
  state: stateForRecreateCheck?.state ?? {
3844
- version: 16,
3047
+ version: 17,
3845
3048
  stackName: stackInfo.stackName,
3846
3049
  region: stackRegion,
3847
3050
  resources: {},
@@ -3876,7 +3079,7 @@ async function deployStackInScope(ctx, stackInfo, stackRegion, stackAwsClients)
3876
3079
  const replacedReaders = await findReplacedReadersOfRecreateTargets({
3877
3080
  template: stackInfo.template,
3878
3081
  state: stateForRecreateCheck?.state ?? {
3879
- version: 16,
3082
+ version: 17,
3880
3083
  stackName: stackInfo.stackName,
3881
3084
  region: stackRegion,
3882
3085
  resources: {},
@@ -4355,6 +3558,7 @@ function createDeployCommand() {
4355
3558
  ...stackOptions,
4356
3559
  ...deployOptions,
4357
3560
  skipFinalSnapshotOption,
3561
+ noLocalCustomResourcesOption,
4358
3562
  requireApprovalOption,
4359
3563
  outputsFileOption,
4360
3564
  ...contextOptions,
@@ -6148,9 +5352,77 @@ function healerUnderRecordPrintingBag(healer, resources, namingSecrets) {
6148
5352
  return Object.assign((logicalId, resource) => withPrintingSecrets(bagFor(logicalId, resource), () => healer(logicalId, resource)), healer);
6149
5353
  }
6150
5354
 
5355
+ // src/cli/commands/diff-recursive/noecho-macs.ts
5356
+ function macsFor(args) {
5357
+ return createNoEchoValueMacs({
5358
+ template: args.template,
5359
+ parameterValues: args.parameterValues,
5360
+ stackName: args.stackName,
5361
+ region: args.region,
5362
+ stackInstanceId: () => args.stackInstanceId,
5363
+ logger: args.logger,
5364
+ purpose: "diff",
5365
+ ...args.client !== void 0 && { client: args.client }
5366
+ })?.macs() ?? Promise.resolve(void 0);
5367
+ }
5368
+ async function previewNoEchoMacChanges(args) {
5369
+ if (args.nestedChild || args.parameterValues === void 0) return [];
5370
+ if (args.sources.parameters.size === 0) return [];
5371
+ const candidates = [];
5372
+ for (const [logicalId, change] of args.changes) {
5373
+ if (change.changeType !== "NO_CHANGE" && change.changeType !== "UPDATE") continue;
5374
+ const record = Object.hasOwn(args.resources, logicalId) ? args.resources[logicalId] : void 0;
5375
+ if (record === void 0 || noEchoValueMacsOf(record).size === 0) continue;
5376
+ candidates.push([
5377
+ logicalId,
5378
+ change,
5379
+ record
5380
+ ]);
5381
+ }
5382
+ if (candidates.length === 0) return [];
5383
+ const cacheKey = noEchoMacBinding(args.stackInstanceId, args.stackName, args.region);
5384
+ const cached = args.cache?.get(cacheKey);
5385
+ const current = await (cached ?? macsFor(args));
5386
+ if (cached === void 0) args.cache?.set(cacheKey, Promise.resolve(current));
5387
+ if (current === void 0) return [];
5388
+ const moved = [];
5389
+ const writeOnlyLookups = args.writeOnlyLookups ?? /* @__PURE__ */ new Map();
5390
+ for (const [logicalId, change, record] of candidates) {
5391
+ const templateProps = (args.template.Resources?.[logicalId])?.Properties ?? {};
5392
+ const recorded = noEchoValueMacsOf(record);
5393
+ const fingerprints = maskedPropertyFingerprintsOf(record);
5394
+ const unsettled = new Set(record.unsettledProperties ?? []);
5395
+ const writeOnly = await macWriteOnlyKeys(change.resourceType, writeOnlyLookups);
5396
+ const keys = [];
5397
+ for (const [key, entry] of recorded) {
5398
+ if (!Object.hasOwn(templateProps, key)) continue;
5399
+ if (writeOnly?.has(key) !== true || unsettled.has(key)) continue;
5400
+ if (fingerprints.get(key) !== maskedPropertyFingerprint(templateProps[key])) continue;
5401
+ if ((change.propertyChanges ?? []).some((pc) => pc.path === key)) continue;
5402
+ if (!readsOnlyNoEchoParameters(templateProps[key], args.sources.parameters)) continue;
5403
+ const parameters = noEchoMacParametersOf(templateProps[key], args.sources);
5404
+ if (noEchoMacVerdict(entry, parameters, current) === "changed") keys.push(key);
5405
+ }
5406
+ if (keys.length === 0) continue;
5407
+ const createOnly = await getCreateOnlyPropertyPaths(change.resourceType).catch(() => []);
5408
+ for (const key of keys) {
5409
+ if (createOnly.some((path) => path[0] === key)) continue;
5410
+ change.propertyChanges = [...change.propertyChanges ?? [], {
5411
+ path: key,
5412
+ oldValue: change.currentProperties?.[key],
5413
+ newValue: change.desiredProperties?.[key],
5414
+ requiresReplacement: false
5415
+ }];
5416
+ if (change.changeType === "NO_CHANGE") change.changeType = "UPDATE";
5417
+ moved.push(`${logicalId}.${key}`);
5418
+ }
5419
+ }
5420
+ return moved;
5421
+ }
5422
+
6151
5423
  // src/cli/commands/diff-recursive/compute-stack-diff.ts
6152
5424
  async function computeStackDiff(currentState, template, region, stackName, stateBackend, diffCalculator, options = {}) {
6153
- const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict } = options;
5425
+ const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, noEchoMacCache, macWriteOnlyLookups, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict } = options;
6154
5426
  let healResources = currentState.resources ?? {};
6155
5427
  let healNamingSecrets;
6156
5428
  const attributeHealer = unboundAttributeHealer && healerUnderRecordPrintingBag(unboundAttributeHealer, () => healResources, (map) => healNamingSecrets?.(map));
@@ -6303,6 +5575,25 @@ async function computeStackDiff(currentState, template, region, stackName, state
6303
5575
  ...options.inheritedReferenceProvenance && { inherited: options.inheritedReferenceProvenance },
6304
5576
  crossStackOutputs: crossStackOutputProvenanceSource(crossStackReads, crossStackReads, stateBackend)
6305
5577
  });
5578
+ const macConditions = conditions === void 0 ? void 0 : Object.fromEntries(Object.entries(conditions).filter(([name]) => !stillUnknown.includes(name)));
5579
+ const macMoved = await previewNoEchoMacChanges({
5580
+ changes,
5581
+ template: effectiveTemplate,
5582
+ resources: stateForDiff.resources,
5583
+ parameterValues: mergedParameters,
5584
+ sources: {
5585
+ parameters: noEchoParametersOf(effectiveTemplate),
5586
+ ...macConditions !== void 0 && { conditions: macConditions }
5587
+ },
5588
+ nestedChild: inheritedSecrets !== void 0 || inheritedNoEchoParameters !== void 0,
5589
+ stackName,
5590
+ region,
5591
+ stackInstanceId: stateForDiff.stackInstanceId,
5592
+ logger,
5593
+ ...noEchoMacCache !== void 0 && { cache: noEchoMacCache },
5594
+ ...macWriteOnlyLookups !== void 0 && { writeOnlyLookups: macWriteOnlyLookups }
5595
+ });
5596
+ if (macMoved.length > 0) logger.info(safeMsg`Stack ${displayStackName(stackName)}: ${macMoved.sort().join(", ")} read a NoEcho parameter whose value changed since the last deploy (its recorded MAC differs): the deploy sends it.`);
6306
5597
  const noEchoReaders = Object.keys(effectiveTemplate.Resources ?? {}).filter((logicalId) => changes.get(logicalId)?.changeType === "NO_CHANGE" && readsNoEchoSource(effectiveTemplate.Resources?.[logicalId]?.Properties, {
6307
5598
  parameters: noEchoParametersOf(effectiveTemplate),
6308
5599
  ...conditions !== void 0 && { conditions: Object.fromEntries(Object.entries(conditions).filter(([name]) => !stillUnknown.includes(name))) }
@@ -6475,7 +5766,7 @@ async function loadStateOrEmpty(stackName, region, stateBackend, refusalRecovery
6475
5766
  region,
6476
5767
  resources: {},
6477
5768
  outputs: {},
6478
- version: 16,
5769
+ version: 17,
6479
5770
  lastModified: Date.now()
6480
5771
  },
6481
5772
  unreadable: [],
@@ -14043,7 +13334,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
14043
13334
  throw setupError;
14044
13335
  }
14045
13336
  }
14046
- return destroyStackUnderLock({
13337
+ return withCustomResourceStack(stackName, () => destroyStackUnderLock({
14047
13338
  stackName,
14048
13339
  state,
14049
13340
  ctx,
@@ -14058,7 +13349,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
14058
13349
  destroyProviderRegistry,
14059
13350
  destroyAwsClients,
14060
13351
  restoreBaseRegionAndClients
14061
- });
13352
+ }));
14062
13353
  }
14063
13354
 
14064
13355
  // src/cli/commands/destroy-skip-message.ts
@@ -14709,6 +14000,7 @@ function createDestroyCommand() {
14709
14000
  exclusivelyOption("destroy"),
14710
14001
  ...resourceTimeoutOptions,
14711
14002
  skipFinalSnapshotOption,
14003
+ noLocalCustomResourcesOption,
14712
14004
  ...contextOptions
14713
14005
  ].forEach((opt) => cmd.addOption(opt));
14714
14006
  cmd.addOption(deprecatedRegionOption);
@@ -19919,7 +19211,8 @@ function createStateDestroyCommand() {
19919
19211
  ...stateOptions,
19920
19212
  ...resourceTimeoutOptions,
19921
19213
  allowUnsupportedTypesOption,
19922
- skipFinalSnapshotOption
19214
+ skipFinalSnapshotOption,
19215
+ noLocalCustomResourcesOption
19923
19216
  ].forEach((opt) => cmd.addOption(opt));
19924
19217
  cmd.addOption(deprecatedRegionOption);
19925
19218
  return cmd;
@@ -21492,7 +20785,7 @@ async function runRollbackReplay(ctx) {
21492
20785
  ...carriedState,
21493
20786
  ...stackInstanceIdCarriedFrom(baseState),
21494
20787
  ...supersededAfterRollback(baseState, supersededHost),
21495
- version: 16,
20788
+ version: 17,
21496
20789
  region,
21497
20790
  resources: { ...stateResources },
21498
20791
  ...orphansAfterRollback(baseState, mintedOrphans),
@@ -21738,7 +21031,7 @@ async function rollbackCommand(stackArg, options) {
21738
21031
 
21739
21032
  // src/cli/commands/rollback.ts
21740
21033
  function createRollbackCommand() {
21741
- 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", [
21034
+ 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(noLocalCustomResourcesOption).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", [
21742
21035
  "",
21743
21036
  "Examples:",
21744
21037
  " cdkd rollback MyStack",
@@ -23633,6 +22926,8 @@ async function refactorCommand(stacks, options) {
23633
22926
  }
23634
22927
  const plans = [];
23635
22928
  const planStacks = /* @__PURE__ */ new Map();
22929
+ const noEchoMacCache = /* @__PURE__ */ new Map();
22930
+ const macWriteOnlyLookups = /* @__PURE__ */ new Map();
23636
22931
  for (const stackInfo of targetStacks) {
23637
22932
  const stackRegion = await regionForStack(stackInfo.stackName, stackInfo.region);
23638
22933
  const stateData = await stateBackend.getState(stackInfo.stackName, stackRegion);
@@ -23651,6 +22946,8 @@ async function refactorCommand(stacks, options) {
23651
22946
  ...options.cfnFallback === false && { cfnFallback: false },
23652
22947
  producerLookup,
23653
22948
  ...stackInfo.account && { consumerAccount: stackInfo.account },
22949
+ noEchoMacCache,
22950
+ macWriteOnlyLookups,
23654
22951
  refusalRecovery: recovery,
23655
22952
  inheritSecretBearingTemplate: false,
23656
22953
  previewMaskedInputs: true,
@@ -25010,7 +24307,7 @@ function buildStackState(stackName, region, rows, templateParser, template, exis
25010
24307
  }
25011
24308
  if (namesParameter?.failedClosed !== void 0) getLogger().debug(`The template's parameter dependence could not be judged (${namesParameter.failedClosed}): every prior observed-baseline refusal recorded without a reason is carried as an unverifiable-parameter refusal.`);
25012
24309
  return {
25013
- version: 16,
24310
+ version: 17,
25014
24311
  stackName,
25015
24312
  region,
25016
24313
  resources,
@@ -25577,6 +24874,16 @@ function collectMultiple(value, previous) {
25577
24874
  return [...previous ?? [], value];
25578
24875
  }
25579
24876
 
24877
+ // src/cli/options/emulate-role-via.ts
24878
+ function checkEmulateRoleVia(value, args) {
24879
+ if (value === void 0) return;
24880
+ assertFlagRoleArn("--emulate-role-via", value);
24881
+ if (!args.roleRequested) getLogger().warn(safeMsg`--emulate-role-via has no effect without ${args.roleFlag}: it is used only when that flag's AssumeRole is refused.`);
24882
+ }
24883
+ function emulateRoleViaOption(roleFlag) {
24884
+ return new Option("--emulate-role-via <arn>", `When the ${roleFlag} AssumeRole is refused (the role does not trust you), cdkd emulates the role's permissions: it assumes THIS role with the execution role's policies as session policies, so only what both allow is allowed. For callers that are not an IAM user (IAM Identity Center, a role session); an IAM user gets the same through sts:GetFederationToken without this flag. An approximation: resource-based policies, key policies and conditions naming the role, and its permissions boundary, are not reproduced.`);
24885
+ }
24886
+
25580
24887
  // src/utils/local-aws-failure.ts
25581
24888
  function describeLocalAwsFailureForWarn(err, operation) {
25582
24889
  if (err instanceof CdkdError) return withoutTrailingPeriod(displaySafe(err.message));
@@ -26011,334 +25318,6 @@ function createLocalStateProvider$1(options, cdkdStackName, synthRegion, behavio
26011
25318
  return createLocalStateProvider(options, cdkdStackName, synthRegion, cdkdExtraStateProviders, behavior);
26012
25319
  }
26013
25320
 
26014
- // src/local/docker-runner.ts
26015
- const execFileAsync$7 = promisify(execFile);
26016
- var DockerRunnerError = class DockerRunnerError extends Error {
26017
- constructor(message) {
26018
- super(message);
26019
- this.name = "DockerRunnerError";
26020
- Object.setPrototypeOf(this, DockerRunnerError.prototype);
26021
- }
26022
- };
26023
- async function pullImage(image, skipPull) {
26024
- const logger = getLogger().child("docker");
26025
- if (skipPull) {
26026
- logger.debug(`Skipping docker pull for ${image} (--no-pull)`);
26027
- return;
26028
- }
26029
- if (getLogger().getLevel() === "debug") {
26030
- logger.info(`Pulling ${image}...`);
26031
- try {
26032
- await runDockerForeground(["pull", image]);
26033
- } catch (err) {
26034
- throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
26035
- }
26036
- return;
26037
- }
26038
- logger.debug(`Pulling ${image} (silent — pass --verbose to stream progress)`);
26039
- try {
26040
- await runDockerStreaming(["pull", image], { streamLive: false });
26041
- } catch (err) {
26042
- const e = err;
26043
- if (e.exitCode === void 0 || e.exitCode === null) throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
26044
- const detail = describeDockerCapturedOutput(err, ["pull", image], "(no output)");
26045
- throw new DockerRunnerError(`docker pull ${image} exited with code ${e.exitCode}: ${detail}`);
26046
- }
26047
- }
26048
- async function runDetached(opts) {
26049
- const wiring = getActiveWorkloadAwsWiring$1();
26050
- if (!wiring) return runDetachedContainer(opts);
26051
- const wired = await applyLocalAwsWiring(wiring, opts.env, opts.extraMounts ?? [], opts.mounts.map((m) => m.containerPath));
26052
- if (opts.network === "host" && wiring.sidecar?.passthrough && wired.env["AWS_ENDPOINT_URL_SQS"] === wiring.sidecar.endpoint) delete wired.env["AWS_ENDPOINT_URL_SQS"];
26053
- const wiredOpts = {
26054
- ...opts,
26055
- env: wired.env,
26056
- extraMounts: wired.extraMounts
26057
- };
26058
- const ports = loopbackPortsFor(wiring, wired.env, opts.network);
26059
- if (ports.length > 0) await prepareLocalLoopbackForwarder(wiring);
26060
- const id = await runDetachedContainer(wiredOpts);
26061
- await attachLocalLoopbackForwarder(id, ports);
26062
- return id;
26063
- }
26064
- async function runDetachedContainer(opts) {
26065
- const args = [
26066
- "run",
26067
- "-d",
26068
- "--rm"
26069
- ];
26070
- if (opts.name) args.push("--name", opts.name);
26071
- if (opts.network) args.push("--network", opts.network);
26072
- if (opts.platform) args.push("--platform", opts.platform);
26073
- if (opts.extraHosts) for (const entry of opts.extraHosts) args.push("--add-host", `${entry.host}:${entry.ip}`);
26074
- const host = opts.host ?? "127.0.0.1";
26075
- args.push("-p", `${host}:${opts.hostPort}:${opts.containerPort ?? 8080}`);
26076
- if (opts.debugPort !== void 0) args.push("-p", `${host}:${opts.debugPort}:${opts.debugPort}`);
26077
- for (const mount of opts.mounts) {
26078
- const ro = mount.readOnly ? ":ro" : "";
26079
- args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
26080
- }
26081
- if (opts.extraMounts) for (const mount of opts.extraMounts) {
26082
- const ro = mount.readOnly ? ":ro" : "";
26083
- args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
26084
- }
26085
- const sensitiveKeys = opts.sensitiveEnvKeys && opts.sensitiveEnvKeys.size > 0 ? /* @__PURE__ */ new Set([...SENSITIVE_ENV_KEYS, ...opts.sensitiveEnvKeys]) : SENSITIVE_ENV_KEYS;
26086
- const { flags, sensitiveEnv: passthroughEnv, collisions } = partitionSensitiveEnv(opts.env, sensitiveKeys, { ...opts.name !== void 0 && { subject: `Container '${opts.name}'` } });
26087
- args.push(...flags);
26088
- if (opts.tmpfs) args.push("--tmpfs", `${opts.tmpfs.target}:rw,size=${opts.tmpfs.sizeMb}m`);
26089
- if (opts.workingDir) args.push("--workdir", opts.workingDir);
26090
- let entryPointTail = [];
26091
- if (opts.entryPoint && opts.entryPoint.length > 0) {
26092
- args.push("--entrypoint", opts.entryPoint[0]);
26093
- entryPointTail = opts.entryPoint.slice(1);
26094
- }
26095
- args.push(...noImplicitEcrPullArgs(opts.image), opts.image, ...entryPointTail, ...opts.cmd);
26096
- const logger = getLogger().child("docker");
26097
- logger.debug(`${getDockerCmd()} ${redactDockerArgvValues(args).join(" ")}`);
26098
- if (collisions.length > 0) logger.warn(`Env var(s) ${collisions.map((k) => JSON.stringify(k)).join(", ")} share a name with a variable the container client reads (docker, or the CDK_DOCKER binary) or have a malformed name (empty, or containing '=' / NUL), and were NOT passed to the container at all (a colliding name would hijack that client; a malformed name cannot form a valid environment variable). Rename the env var if the container needs it.`);
26099
- const forwardedKeys = Object.keys(passthroughEnv);
26100
- const refusal = finchSecretArgvRefusal(forwardedKeys.filter((k) => opts.sensitiveEnvKeys?.has(k)), `Container for image ${displayIdent(opts.image)}`);
26101
- if (refusal !== void 0) throw new DockerRunnerError(refusal);
26102
- warnFinchArgvExposure(forwardedKeys);
26103
- try {
26104
- const { stdout } = await execFileAsync$7(getDockerCmd(), args, {
26105
- maxBuffer: 10485760,
26106
- env: dockerSpawnEnvWithSensitive(passthroughEnv)
26107
- });
26108
- return stdout.trim();
26109
- } catch (error) {
26110
- throw new DockerRunnerError(`docker run failed: ${describeDockerFailure(error, args)}`);
26111
- }
26112
- }
26113
- function streamLogs(containerId) {
26114
- const stream = followContainerLogs(containerId);
26115
- return () => stream.stop();
26116
- }
26117
- const RESERVATION_ROUTED_SINKS = {
26118
- stdout: (chunk) => {
26119
- if (isStdoutReservedForPayload()) process.stderr.write(chunk);
26120
- else process.stdout.write(chunk);
26121
- },
26122
- stderr: (chunk) => {
26123
- process.stderr.write(chunk);
26124
- }
26125
- };
26126
- function followContainerLogs(containerId, sinks = RESERVATION_ROUTED_SINKS) {
26127
- const proc = spawn(getDockerCmd(), [
26128
- "logs",
26129
- "-f",
26130
- containerId
26131
- ], { stdio: [
26132
- "ignore",
26133
- "pipe",
26134
- "pipe"
26135
- ] });
26136
- proc.stdout?.on("data", (chunk) => sinks.stdout(chunk));
26137
- proc.stderr?.on("data", (chunk) => sinks.stderr(chunk));
26138
- let markClosed = () => void 0;
26139
- const closed = new Promise((resolveClosed) => {
26140
- markClosed = resolveClosed;
26141
- });
26142
- proc.on("close", () => markClosed());
26143
- proc.on("error", () => {
26144
- markClosed();
26145
- });
26146
- const stop = () => {
26147
- if (!proc.killed) proc.kill("SIGTERM");
26148
- };
26149
- return {
26150
- stop,
26151
- drain: async (timeoutMs) => {
26152
- let timer;
26153
- const timedOut = new Promise((resolveTimeout) => {
26154
- timer = setTimeout(() => resolveTimeout(false), timeoutMs);
26155
- });
26156
- try {
26157
- const drained = await Promise.race([closed.then(() => true), timedOut]);
26158
- if (!drained) {
26159
- getLogger().child("docker").debug(safeMsg`docker logs -f ${containerId} did not end within ${timeoutMs}ms; stopping it (later log lines may be missing)`);
26160
- stop();
26161
- }
26162
- return drained;
26163
- } finally {
26164
- clearTimeout(timer);
26165
- }
26166
- }
26167
- };
26168
- }
26169
- async function killContainer(containerId, timeoutMs = 1e4) {
26170
- if (!containerId) return;
26171
- const args = ["kill", containerId];
26172
- try {
26173
- await execFileAsync$7(getDockerCmd(), args, { timeout: timeoutMs });
26174
- } catch (error) {
26175
- getLogger().child("docker").debug(safeMsg`docker kill ${containerId} failed: ${describeDockerFailure(error, args)}`);
26176
- }
26177
- }
26178
- const CONTAINER_LOG_DRAIN_TIMEOUT_MS = 5e3;
26179
- async function killAndDrainContainerLogs(containerId, stream, timeoutMs = CONTAINER_LOG_DRAIN_TIMEOUT_MS) {
26180
- if (!stream) return;
26181
- if (containerId) await killContainer(containerId);
26182
- await stream.drain(timeoutMs);
26183
- }
26184
- async function flushStdio(timeoutMs = 2e3) {
26185
- const flushed = (stream) => new Promise((resolveFlush) => {
26186
- try {
26187
- stream.write("", () => resolveFlush());
26188
- } catch {
26189
- resolveFlush();
26190
- }
26191
- });
26192
- let timer;
26193
- await Promise.race([Promise.all([flushed(process.stdout), flushed(process.stderr)]), new Promise((resolveTimeout) => {
26194
- timer = setTimeout(resolveTimeout, timeoutMs);
26195
- })]);
26196
- clearTimeout(timer);
26197
- }
26198
- async function removeContainer(containerId) {
26199
- if (!containerId) return;
26200
- const logger = getLogger().child("docker");
26201
- const args = [
26202
- "rm",
26203
- "-f",
26204
- containerId
26205
- ];
26206
- try {
26207
- await execFileAsync$7(getDockerCmd(), args);
26208
- logger.debug(`Removed container ${containerId}`);
26209
- } catch (error) {
26210
- logger.debug(`docker rm -f ${containerId} failed: ${describeDockerFailure(error, args)}`);
26211
- }
26212
- }
26213
- async function ensureDockerAvailable() {
26214
- const cmd = getDockerCmd();
26215
- const args = [
26216
- "version",
26217
- "--format",
26218
- "{{.Server.Version}}"
26219
- ];
26220
- try {
26221
- await execFileAsync$7(cmd, args);
26222
- } catch (error) {
26223
- if (error.code === "ENOENT") throw new DockerRunnerError(`${cmd} is not installed or not on PATH. cdkd local invoke needs Docker (or a compatible CLI specified via CDK_DOCKER) — install it and retry.`);
26224
- throw new DockerRunnerError(`${cmd} daemon is not reachable: ${describeDockerFailure(error, args)}. Start Docker Desktop / the docker daemon and retry.`);
26225
- }
26226
- }
26227
- function pickFreePort() {
26228
- return new Promise((resolvePort, rejectPort) => {
26229
- const server = createServer();
26230
- server.unref();
26231
- server.on("error", rejectPort);
26232
- server.listen(0, "127.0.0.1", () => {
26233
- const address = server.address();
26234
- if (!address || typeof address === "string") {
26235
- server.close();
26236
- rejectPort(/* @__PURE__ */ new Error("Could not allocate a host port"));
26237
- return;
26238
- }
26239
- const port = address.port;
26240
- server.close(() => resolvePort(port));
26241
- });
26242
- });
26243
- }
26244
- const SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
26245
- "AWS_ACCESS_KEY_ID",
26246
- "AWS_SECRET_ACCESS_KEY",
26247
- "AWS_SESSION_TOKEN"
26248
- ]);
26249
-
26250
- // src/local/rie-client.ts
26251
- const INVOKE_PATH = "/2015-03-31/functions/function/invocations";
26252
- const NOT_AN_RIE_STATUS = /* @__PURE__ */ new Set([404, 405]);
26253
- async function waitForRieReady(host, port, timeoutMs = 5e3) {
26254
- const deadline = Date.now() + timeoutMs;
26255
- let lastError;
26256
- while (Date.now() < deadline) {
26257
- try {
26258
- if (await httpProbe(host, port, 500)) {
26259
- await setTimeout$1(250);
26260
- return;
26261
- }
26262
- } catch (err) {
26263
- lastError = err;
26264
- }
26265
- await setTimeout$1(100);
26266
- }
26267
- const tail = lastError instanceof Error ? `: ${lastError.message}` : "";
26268
- throw new Error(`RIE did not become ready on ${host} port ${port} within ${timeoutMs}ms${tail}. The container may have exited early — check 'docker logs' output.`);
26269
- }
26270
- async function httpProbe(host, port, timeoutMs) {
26271
- const controller = new AbortController();
26272
- const timer = setTimeout(() => controller.abort(), timeoutMs);
26273
- try {
26274
- await (await fetch(`http://${formatAuthority(host, port)}/`, {
26275
- method: "POST",
26276
- headers: { "Content-Type": "application/json" },
26277
- body: "{}",
26278
- signal: controller.signal
26279
- })).text().catch(() => void 0);
26280
- return true;
26281
- } catch (err) {
26282
- if (isTransientNetworkError(err)) return false;
26283
- throw err;
26284
- } finally {
26285
- clearTimeout(timer);
26286
- }
26287
- }
26288
- function isTransientNetworkError(err) {
26289
- if (!(err instanceof Error)) return false;
26290
- if (err.name === "AbortError") return true;
26291
- if (err.name === "TypeError" && err.message === "fetch failed") return true;
26292
- const cause = err.cause;
26293
- if (cause?.code === "ECONNRESET") return true;
26294
- if (cause?.code === "ECONNREFUSED") return true;
26295
- if (cause?.code === "UND_ERR_SOCKET") return true;
26296
- return false;
26297
- }
26298
- async function invokeRie(host, port, event, timeoutMs) {
26299
- const url = `http://${formatAuthority(host, port)}${INVOKE_PATH}`;
26300
- const body = JSON.stringify(event ?? {});
26301
- const controller = new AbortController();
26302
- const timer = setTimeout(() => controller.abort(), timeoutMs);
26303
- let response;
26304
- try {
26305
- response = await fetchWithStartupRetry(url, body, controller.signal);
26306
- } catch (err) {
26307
- if (err.name === "AbortError") throw new Error(`RIE invoke at ${url} timed out after ${timeoutMs}ms. The handler may be hung; check container logs.`);
26308
- throw err;
26309
- } finally {
26310
- clearTimeout(timer);
26311
- }
26312
- const raw = await response.text();
26313
- 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.`);
26314
- let payload = raw;
26315
- try {
26316
- payload = JSON.parse(raw);
26317
- } catch {}
26318
- return {
26319
- payload,
26320
- raw
26321
- };
26322
- }
26323
- async function fetchWithStartupRetry(url, body, signal) {
26324
- const maxAttempts = 3;
26325
- let lastError;
26326
- for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
26327
- return await fetch(url, {
26328
- method: "POST",
26329
- headers: { "Content-Type": "application/json" },
26330
- body,
26331
- signal
26332
- });
26333
- } catch (err) {
26334
- if (err.name === "AbortError") throw err;
26335
- lastError = err;
26336
- if (attempt === maxAttempts) break;
26337
- await setTimeout$1(200);
26338
- }
26339
- throw lastError;
26340
- }
26341
-
26342
25321
  // src/local/container-pool.ts
26343
25322
  const DEFAULT_IDLE_MS = 6e4;
26344
25323
  const IN_FLIGHT_START_TIMEOUT_MS = 2e4;
@@ -27585,53 +26564,6 @@ function createCallerDynamicReferenceResolver(profile) {
27585
26564
  });
27586
26565
  }
27587
26566
 
27588
- // src/local/layer-tree-copy.ts
27589
- function copyLayerTreeLastWins(src, dest) {
27590
- mkdirSync(dest, { recursive: true });
27591
- copyDirLastWins(realpathSync.native(src), dest);
27592
- }
27593
- function copyDirLastWins(fromDir, toDir) {
27594
- for (const entry of readdirSync(fromDir, { withFileTypes: true })) {
27595
- const from = join(fromDir, entry.name);
27596
- const to = join(toDir, entry.name);
27597
- if (entry.isSymbolicLink()) {
27598
- removeUnless(to, "symlink");
27599
- symlinkSync(readlinkSync(from), to);
27600
- } else if (entry.isDirectory()) {
27601
- removeUnless(to, "directory");
27602
- mkdirSync(to, { recursive: true });
27603
- copyDirLastWins(from, to);
27604
- } else {
27605
- removeUnless(to, "file");
27606
- cpSync(from, to, { force: true });
27607
- }
27608
- }
27609
- }
27610
- function removeUnless(to, kind) {
27611
- let st;
27612
- try {
27613
- st = lstatSync(to);
27614
- } catch {
27615
- return;
27616
- }
27617
- if (kind === "directory" && st.isDirectory()) return;
27618
- if (kind === "file" && st.isFile()) return;
27619
- rmSync(to, {
27620
- recursive: true,
27621
- force: true
27622
- });
27623
- }
27624
-
27625
- // src/local/docker-image-builder.ts
27626
- async function buildContainerImage$1(asset, cdkOutDir, options) {
27627
- try {
27628
- return await buildContainerImage(asset, cdkOutDir, options);
27629
- } catch (e) {
27630
- if (e instanceof LocalInvokeBuildError) throw new LocalInvokeBuildError$1(e.message);
27631
- throw e;
27632
- }
27633
- }
27634
-
27635
26567
  // src/local/ecr-puller.ts
27636
26568
  function canonicalizeImageUriHost(imageUri) {
27637
26569
  const slash = imageUri.indexOf("/");
@@ -28008,337 +26940,6 @@ async function extractRie(platform, target, machine, skipPull) {
28008
26940
  }
28009
26941
  }
28010
26942
 
28011
- // src/local/lambda-resolver/types.ts
28012
- var LocalInvokeResolutionError = class LocalInvokeResolutionError extends Error {
28013
- constructor(message) {
28014
- super(message);
28015
- this.name = "LocalInvokeResolutionError";
28016
- Object.setPrototypeOf(this, LocalInvokeResolutionError.prototype);
28017
- }
28018
- };
28019
-
28020
- // src/local/intrinsic-image.ts
28021
- function derivePseudoParametersFromRegion$1(region, accountId) {
28022
- return derivePseudoParametersFromRegion(canonicalizeRegion(region), accountId);
28023
- }
28024
-
28025
- // src/local/lambda-resolver/asset-code.ts
28026
- function resolveAssetCodeDirectory(opts) {
28027
- const { manifestDir, assetPath, wrapError, assetOutdir, logicalId } = opts;
28028
- if (isAbsolute(assetPath)) {
28029
- const absolute = resolve(assetPath);
28030
- const escape = absoluteAssemblyPathEscape(assetOutdir, absolute);
28031
- if (escape !== void 0) getLogger().warn(`Lambda ${displayIdent(logicalId)} has an absolute Metadata['aws:asset:path'] pointing outside the assembly: ${displayAssemblyPath(absolute)}` + (escape.escape === "symlink" ? ` (through a symbolic link to ${displayAssemblyPath(escape.realPath)})` : "") + ". cdkd will bind-mount that directory into the container read-only, where the code in this assembly can read it. This is what cdk synth --no-staging emits, and is expected for it; if you did not synthesize with that flag, treat this assembly as untrusted.");
28032
- return absolute;
28033
- }
28034
- const resolved = resolveAssemblyPath(manifestDir, assetPath, { containWithin: assetOutdir });
28035
- if (!resolved.contained && resolved.escape === "lexical" && resolved.path === resolve(assetOutdir)) return resolved.path;
28036
- if (!resolved.contained) throw wrapError(`Lambda ${displayIdent(logicalId)} has Metadata['aws:asset:path']=${displayAssemblyPath(assetPath)} which ${renderAssemblyPathEscape(resolved, assetOutdir, "mount it")}`);
28037
- return resolved.path;
28038
- }
28039
- function assetPathDirs(stack) {
28040
- const manifestDir = stack.assetManifestPath ? dirname(stack.assetManifestPath) : stack.assetOutdir ?? process.cwd();
28041
- return {
28042
- manifestDir,
28043
- assetOutdir: stack.assetOutdir ?? manifestDir
28044
- };
28045
- }
28046
- function resolveAssetCodePath$1(stack, logicalId, resource) {
28047
- const assetPath = resource.Metadata?.["aws:asset:path"];
28048
- if (typeof assetPath !== "string" || assetPath.length === 0) throw new LocalInvokeResolutionError(`Lambda ${plainOrDescribed(logicalId, "logical id")} has no Metadata['aws:asset:path']. cdkd local invoke needs this hint to find the local asset directory. Re-synthesize the app (without \`--output '<stale-dir>'\`) and retry.`);
28049
- const { manifestDir, assetOutdir } = assetPathDirs(stack);
28050
- const abs = resolveAssetCodeDirectory({
28051
- manifestDir,
28052
- assetPath,
28053
- wrapError: (message) => new LocalInvokeResolutionError(message),
28054
- assetOutdir,
28055
- logicalId
28056
- });
28057
- if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new LocalInvokeResolutionError(`Lambda ${displayIdent(logicalId)} asset directory ${displayAssemblyPath(abs)} does not exist or is not a directory. Re-synthesize the app and retry.`);
28058
- return abs;
28059
- }
28060
-
28061
- // src/local/lambda-resolver/layers.ts
28062
- function resolveLambdaLayers(stack, logicalId, props) {
28063
- const layers = props["Layers"];
28064
- if (layers === void 0) return [];
28065
- if (!Array.isArray(layers)) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a non-array Layers property. Expected an array of LayerVersion references.`);
28066
- if (layers.length === 0) return [];
28067
- const resources = stack.template.Resources ?? {};
28068
- const out = [];
28069
- for (let i = 0; i < layers.length; i++) {
28070
- const entry = layers[i];
28071
- if (typeof entry === "string") {
28072
- const parsed = classifyLayerVersionArn(entry);
28073
- if (!parsed.ok) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: literal string '${entry}'. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.` + describeLayerArnRejection(parsed.rejection));
28074
- out.push({
28075
- kind: "arn",
28076
- logicalId: parsed.value.arn,
28077
- ...parsed.value
28078
- });
28079
- continue;
28080
- }
28081
- const layerLogicalId = pickLayerLogicalId(entry);
28082
- if (!layerLogicalId) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: ${describeLayerEntry(entry)}. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.`);
28083
- const layerResource = resources[layerLogicalId];
28084
- if (!layerResource) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}', but no resource with that logical ID exists in stack '${stack.stackName}'.`);
28085
- if (layerResource.Type !== "AWS::Lambda::LayerVersion") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}' (${layerResource.Type}), which is not an AWS::Lambda::LayerVersion.`);
28086
- const assetPath = resolveAssetCodePath$1(stack, layerLogicalId, layerResource);
28087
- out.push({
28088
- kind: "asset",
28089
- logicalId: layerLogicalId,
28090
- assetPath
28091
- });
28092
- }
28093
- return out;
28094
- }
28095
- const LAYER_ARN_PATTERN = new RegExp(`^arn:([a-z][a-z0-9-]*):lambda:([a-z]{2,}(?:-[a-z]+)+-\\d+):(\\d{12}):layer:([A-Za-z0-9_-]+):(\\d+)$`);
28096
- function classifyLayerVersionArn(input) {
28097
- const m = LAYER_ARN_PATTERN.exec(input);
28098
- if (!m) return {
28099
- ok: false,
28100
- rejection: { kind: "shape" }
28101
- };
28102
- const partition = m[1];
28103
- const region = m[2];
28104
- const derived = derivePartitionAndUrlSuffix(region).partition;
28105
- if (derived !== partition) return {
28106
- ok: false,
28107
- rejection: {
28108
- kind: "partition",
28109
- partition,
28110
- region,
28111
- derived,
28112
- derivedFromTable: derived !== "aws"
28113
- }
28114
- };
28115
- return {
28116
- ok: true,
28117
- value: {
28118
- arn: input,
28119
- region,
28120
- accountId: m[3],
28121
- name: m[4],
28122
- version: m[5]
28123
- }
28124
- };
28125
- }
28126
- function describeLayerArnRejection(rejection) {
28127
- if (rejection.kind === "shape") return "";
28128
- const { partition, region, derived, derivedFromTable } = rejection;
28129
- const head = ` The partition '${partition}' does not match region '${region}'`;
28130
- return derivedFromTable ? `${head}, which is in partition '${derived}'.` : `${head}: no partition prefix matches that region, so cdkd resolves it to the commercial partition '${derived}'.`;
28131
- }
28132
- function pickLayerLogicalId(entry) {
28133
- if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return void 0;
28134
- const obj = entry;
28135
- if (typeof obj["Ref"] === "string") return obj["Ref"];
28136
- if ("Fn::GetAtt" in obj) {
28137
- const arg = obj["Fn::GetAtt"];
28138
- if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
28139
- }
28140
- }
28141
- function describeLayerEntry(entry) {
28142
- if (typeof entry === "string") return `literal ARN '${entry}'`;
28143
- if (entry === null) return "null";
28144
- if (typeof entry !== "object") return stringifyValue(entry);
28145
- try {
28146
- const json = JSON.stringify(entry);
28147
- return json.length > 120 ? json.substring(0, 117) + "..." : json;
28148
- } catch {
28149
- return Object.prototype.toString.call(entry);
28150
- }
28151
- }
28152
-
28153
- // src/local/lambda-resolver/properties.ts
28154
- function extractLambdaProperties(stack, logicalId, resource, resources) {
28155
- const props = resource.Properties ?? {};
28156
- const memoryMb = typeof props["MemorySize"] === "number" ? props["MemorySize"] : 128;
28157
- const timeoutSec = typeof props["Timeout"] === "number" ? props["Timeout"] : 3;
28158
- const ephemeralStorageMb = extractEphemeralStorageMb(props, logicalId);
28159
- const code = props["Code"] ?? {};
28160
- const imageUri = extractImageUri$1(code["ImageUri"], logicalId, stack.stackName, resources, stack.region);
28161
- if (imageUri !== void 0) return extractImageLambdaProperties({
28162
- stack,
28163
- logicalId,
28164
- resource,
28165
- memoryMb,
28166
- timeoutSec,
28167
- props,
28168
- imageUri,
28169
- ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
28170
- });
28171
- const runtime = typeof props["Runtime"] === "string" ? props["Runtime"] : "";
28172
- const handler = typeof props["Handler"] === "string" ? props["Handler"] : "";
28173
- if (!runtime) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Runtime property and no Code.ImageUri. cdkd cannot tell if this is a ZIP or a container Lambda.`);
28174
- if (!handler) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Handler property.`);
28175
- const inlineCode = typeof code["ZipFile"] === "string" ? code["ZipFile"] : void 0;
28176
- let codePath = null;
28177
- if (!inlineCode) codePath = resolveAssetCodePath$1(stack, logicalId, resource);
28178
- const layers = resolveLambdaLayers(stack, logicalId, props);
28179
- return {
28180
- kind: "zip",
28181
- stack,
28182
- logicalId,
28183
- resource,
28184
- runtime,
28185
- handler,
28186
- memoryMb,
28187
- timeoutSec,
28188
- architecture: extractArchitecture(props, logicalId),
28189
- codePath,
28190
- layers,
28191
- ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb },
28192
- ...inlineCode !== void 0 && { inlineCode }
28193
- };
28194
- }
28195
- function extractEphemeralStorageMb(props, logicalId) {
28196
- const raw = props["EphemeralStorage"];
28197
- if (raw === void 0 || raw === null) return void 0;
28198
- if (typeof raw !== "object" || Array.isArray(raw)) return void 0;
28199
- const size = raw["Size"];
28200
- if (typeof size !== "number") return;
28201
- if (!Number.isFinite(size) || size < 1) return void 0;
28202
- if (size > 10240) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has Properties.EphemeralStorage.Size = ${size} MiB, which exceeds the AWS limit of 10240 MiB. AWS would reject the function at deploy time; cap the value to <= 10240 (10 GiB) and retry.`);
28203
- return Math.floor(size);
28204
- }
28205
- function extractImageUri$1(value, logicalId, stackName, resources, region) {
28206
- if (typeof value === "string" && value.length > 0) return value;
28207
- if (value && typeof value === "object" && !Array.isArray(value)) {
28208
- const obj = value;
28209
- const sub = obj["Fn::Sub"];
28210
- if (typeof sub === "string" && sub.length > 0) return sub;
28211
- if (Array.isArray(sub) && typeof sub[0] === "string") return sub[0];
28212
- if ("Fn::Join" in obj) {
28213
- const pseudoParameters = derivePseudoParametersFromRegion$1(region);
28214
- const joinResolved = tryResolveImageFnJoin(value, resources, pseudoParameters ? { pseudoParameters } : void 0);
28215
- if (joinResolved.kind === "resolved") return joinResolved.uri;
28216
- if (joinResolved.kind === "needs-state") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} references same-stack ECR repository '${joinResolved.repoLogicalId}' via Fn::Join. cdkd local invoke cannot resolve the repository URI without state — deploy the stack first (so cdkd records the repository physical id), rebuild via lambda.DockerImageCode.fromImageAsset, or pin a public image.`);
28217
- if (joinResolved.kind === "unsupported-join") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an unsupported Fn::Join Code.ImageUri shape: ${joinResolved.reason}. cdkd local invoke recognizes the canonical CDK 2.x lambda.DockerImageCode.fromEcr Fn::Join shape (delimiter "" with nested Fn::Select/Fn::Split over an ECR Repository Arn GetAtt + Ref to the repo).`);
28218
- throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an Fn::Join Code.ImageUri that cdkd local invoke cannot resolve${pseudoParameters ? " (likely ${AWS::AccountId}, which cdkd cannot derive without --from-state or STS)" : ` (cdkd could not derive AWS pseudo parameters because stack.region was undefined)`}. Workarounds: deploy first and run with --from-state, or pin a fully-literal public image URI.`);
28219
- }
28220
- }
28221
- }
28222
- function extractArchitecture(props, logicalId) {
28223
- const arches = props["Architectures"];
28224
- if (Array.isArray(arches) && arches.length > 0) {
28225
- const first = arches[0];
28226
- if (first === "arm64") return "arm64";
28227
- if (first === "x86_64") return "x86_64";
28228
- throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has unsupported Architectures value '${String(first)}'. cdkd local invoke supports x86_64 and arm64.`);
28229
- }
28230
- return "x86_64";
28231
- }
28232
- function extractImageLambdaProperties(args) {
28233
- const { stack, logicalId, resource, memoryMb, timeoutSec, ephemeralStorageMb, props, imageUri } = args;
28234
- const rawImageConfig = props["ImageConfig"] ?? {};
28235
- const imageConfig = {};
28236
- if (Array.isArray(rawImageConfig["Command"])) imageConfig.command = rawImageConfig["Command"].filter((s) => typeof s === "string");
28237
- if (Array.isArray(rawImageConfig["EntryPoint"])) imageConfig.entryPoint = rawImageConfig["EntryPoint"].filter((s) => typeof s === "string");
28238
- if (typeof rawImageConfig["WorkingDirectory"] === "string") imageConfig.workingDirectory = rawImageConfig["WorkingDirectory"];
28239
- return {
28240
- kind: "image",
28241
- stack,
28242
- logicalId,
28243
- resource,
28244
- memoryMb,
28245
- timeoutSec,
28246
- imageUri,
28247
- imageConfig,
28248
- architecture: extractArchitecture(props, logicalId),
28249
- layers: [],
28250
- ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
28251
- };
28252
- }
28253
-
28254
- // src/local/lambda-resolver/target.ts
28255
- function parseTarget(target) {
28256
- if (typeof target !== "string" || target.length === 0) throw new LocalInvokeResolutionError("Empty target. Pass a CDK display path (e.g. 'MyStack/MyApi/Handler') or stack-qualified logical ID (e.g. 'MyStack:MyApiHandler1234ABCD').");
28257
- const colonIdx = target.indexOf(":");
28258
- const slashIdx = target.indexOf("/");
28259
- if (colonIdx > 0 && (slashIdx === -1 || colonIdx < slashIdx)) {
28260
- const stackPattern = target.substring(0, colonIdx);
28261
- const pathOrId = target.substring(colonIdx + 1);
28262
- if (pathOrId.length === 0) throw new LocalInvokeResolutionError(`Target '${target}' has no logical ID after ':'.`);
28263
- return {
28264
- stackPattern,
28265
- pathOrId,
28266
- isPath: pathOrId.includes("/")
28267
- };
28268
- }
28269
- if (slashIdx > 0) return {
28270
- stackPattern: target.substring(0, slashIdx),
28271
- pathOrId: target,
28272
- isPath: true
28273
- };
28274
- return {
28275
- stackPattern: null,
28276
- pathOrId: target,
28277
- isPath: false
28278
- };
28279
- }
28280
- function resolveLambdaTarget(target, stacks) {
28281
- if (stacks.length === 0) throw new LocalInvokeResolutionError("No stacks found in the synthesized assembly.");
28282
- const parsed = parseTarget(target);
28283
- const stack = pickStack$1(parsed, stacks, target);
28284
- const template = stack.template;
28285
- const resources = template.Resources ?? {};
28286
- let match;
28287
- if (parsed.isPath) {
28288
- const index = buildCdkPathIndex(template);
28289
- const lambdaMatches = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId }) => resources[logicalId]?.Type === "AWS::Lambda::Function");
28290
- if (lambdaMatches.length === 0) throw notFoundError$1(target, stack, resources);
28291
- if (lambdaMatches.length > 1) throw new LocalInvokeResolutionError(`Target '${target}' matches ${lambdaMatches.length} Lambda functions in ${stack.stackName}: ` + lambdaMatches.map((m) => m.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
28292
- const m = lambdaMatches[0];
28293
- match = {
28294
- logicalId: m.logicalId,
28295
- resource: resources[m.logicalId]
28296
- };
28297
- } else {
28298
- const resource = resources[parsed.pathOrId];
28299
- if (!resource) throw notFoundError$1(target, stack, resources);
28300
- match = {
28301
- logicalId: parsed.pathOrId,
28302
- resource
28303
- };
28304
- }
28305
- const { logicalId, resource } = match;
28306
- if (resource.Type !== "AWS::Lambda::Function") {
28307
- if (resource.Type.startsWith("Custom::")) throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Custom Resource (${resource.Type}), not a Lambda function. Custom Resources are invoked by the deploy framework, not by users. If you want to test the underlying handler, target the ServiceToken Lambda directly.`);
28308
- throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not a Lambda function. cdkd local invoke only works on AWS::Lambda::Function resources in v1.`);
28309
- }
28310
- return extractLambdaProperties(stack, logicalId, resource, resources);
28311
- }
28312
- function pickStack$1(parsed, stacks, target) {
28313
- const selection = selectTargetStack(parsed, target, stacks);
28314
- switch (selection.kind) {
28315
- case "found": return selection.stack;
28316
- case "no-prefix": throw new LocalInvokeResolutionError(`Multiple stacks in app, target '${parsed.pathOrId}' is missing a stack prefix. Use 'StackName:${parsed.pathOrId}' or 'StackName/...' (path form). Available stacks: ${stacks.map(describeStack).join(", ")}.`);
28317
- case "not-found": throw new LocalInvokeResolutionError(`Stack '${selection.pattern}' not found. Available stacks: ${stacks.map(describeStack).join(", ")}.`);
28318
- case "ambiguous": throw new LocalInvokeResolutionError(renderAmbiguousTargetStack(selection.pattern, selection.matched));
28319
- }
28320
- }
28321
- function notFoundError$1(target, stack, resources) {
28322
- const lambdas = [];
28323
- for (const [logicalId, resource] of Object.entries(resources)) {
28324
- if (resource.Type !== "AWS::Lambda::Function") continue;
28325
- const meta = resource.Metadata;
28326
- const cdkPath = typeof meta?.["aws:cdk:path"] === "string" ? meta["aws:cdk:path"] : "";
28327
- lambdas.push({
28328
- displayPath: cdkPath || logicalId,
28329
- logicalId
28330
- });
28331
- }
28332
- let msg = `target '${target}' did not match any Lambda function in ${stack.stackName}.\n\n`;
28333
- if (lambdas.length === 0) msg += `Stack ${stack.stackName} has no Lambda functions.`;
28334
- else {
28335
- const width = Math.max(...lambdas.map((l) => l.displayPath.length));
28336
- msg += `Available Lambda functions in ${stack.stackName}:\n`;
28337
- for (const l of lambdas) msg += ` ${l.displayPath.padEnd(width)} (${l.logicalId})\n`;
28338
- }
28339
- return new LocalInvokeResolutionError(msg.trimEnd());
28340
- }
28341
-
28342
26943
  // src/cli/commands/local-start-api/lambda-resolver.ts
28343
26944
  function resolveLambdaByLogicalId(logicalId, stacks) {
28344
26945
  const owners = stacksDeclaring(logicalId, stacks, LAMBDA_FUNCTION_TYPE);
@@ -28451,7 +27052,7 @@ function resolveAssetCodePath(stack, logicalId, resource) {
28451
27052
  }
28452
27053
 
28453
27054
  // src/cli/commands/local-start-api/env.ts
28454
- function materializeInlineCode$1(handler, source, fileExtension, tmpDirsOut) {
27055
+ function materializeInlineCode(handler, source, fileExtension, tmpDirsOut) {
28455
27056
  const lastDot = handler.lastIndexOf(".");
28456
27057
  if (lastDot <= 0) throw new Error(`Handler '${handler}' is malformed: expected '<modulePath>.<exportName>'.`);
28457
27058
  const modulePath = handler.substring(0, lastDot);
@@ -28502,6 +27103,216 @@ function forwardAwsEnv$2(env) {
28502
27103
  applyCallerIdentityCredentials(env);
28503
27104
  }
28504
27105
 
27106
+ // src/local/role-permission-emulation.ts
27107
+ const SESSION_POLICY_MAX_CHARS = 2048;
27108
+ const SESSION_POLICY_MAX_ARNS = 10;
27109
+ const DENY_ALL_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
27110
+ function buildSessionPolicy(policies) {
27111
+ const { inline, managedArns } = policies;
27112
+ if (managedArns.length > 10) return {
27113
+ ok: false,
27114
+ reason: `the role has ${managedArns.length} managed policies, more than the ${10} STS accepts as session policies`
27115
+ };
27116
+ let policy;
27117
+ if (inline.length === 0) policy = managedArns.length === 0 ? DENY_ALL_POLICY : "";
27118
+ else {
27119
+ const versions = /* @__PURE__ */ new Set();
27120
+ const statements = [];
27121
+ for (const doc of inline) {
27122
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc)) return {
27123
+ ok: false,
27124
+ reason: "an inline policy of the role is not a JSON object"
27125
+ };
27126
+ const record = doc;
27127
+ versions.add(typeof record["Version"] === "string" ? record["Version"] : "");
27128
+ const raw = record["Statement"];
27129
+ for (const statement of Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]) if (statement !== null && typeof statement === "object" && !Array.isArray(statement)) {
27130
+ const { Sid: _sid, ...rest } = statement;
27131
+ statements.push(rest);
27132
+ } else statements.push(statement);
27133
+ }
27134
+ if (versions.size > 1) return {
27135
+ ok: false,
27136
+ reason: "the inline policies of the role use different policy Version values and cannot be combined into one session policy"
27137
+ };
27138
+ const [version] = [...versions];
27139
+ policy = statements.length === 0 ? managedArns.length === 0 ? DENY_ALL_POLICY : "" : JSON.stringify({
27140
+ ...version !== void 0 && version !== "" && { Version: version },
27141
+ Statement: statements
27142
+ });
27143
+ }
27144
+ const chars = policy.length + managedArns.reduce((sum, arn) => sum + arn.length, 0);
27145
+ if (chars > 2048) return {
27146
+ ok: false,
27147
+ reason: `the role's policies take ${chars} characters as session policies, more than the ${SESSION_POLICY_MAX_CHARS} STS accepts`
27148
+ };
27149
+ return {
27150
+ ok: true,
27151
+ policy,
27152
+ policyArns: managedArns
27153
+ };
27154
+ }
27155
+ function isIamUserArn(arn) {
27156
+ return arn !== void 0 && /^arn:[^:]+:iam::\d{12}:user\//.test(arn);
27157
+ }
27158
+ function isAssumeRoleAccessDenied(err) {
27159
+ return err?.name === "AccessDenied";
27160
+ }
27161
+ function roleNameOf(roleArn) {
27162
+ const resource = roleArn.split(":").slice(5).join(":");
27163
+ return resource.slice(resource.lastIndexOf("/") + 1);
27164
+ }
27165
+ const noticedRoles = /* @__PURE__ */ new Set();
27166
+ const failedRoles = /* @__PURE__ */ new Set();
27167
+ async function emulateRoleAfterDeniedAssume(err, args) {
27168
+ if (!isAssumeRoleAccessDenied(err)) return void 0;
27169
+ try {
27170
+ return await emulate(args);
27171
+ } catch (unexpected) {
27172
+ if (failedRoles.has(args.roleArn)) return void 0;
27173
+ failedRoles.add(args.roleArn);
27174
+ getLogger().warn(safeMsg`${args.flag}: emulating the role's permissions failed: ${describeLocalAwsFailureForWarn(unexpected, "role permission emulation")}.`);
27175
+ return;
27176
+ }
27177
+ }
27178
+ async function emulate(args) {
27179
+ const logger = getLogger();
27180
+ const shownRole = displayIdent(args.roleArn, { maxCodePoints: 613 });
27181
+ const cannot = (reason) => {
27182
+ if (failedRoles.has(args.roleArn)) return void 0;
27183
+ failedRoles.add(args.roleArn);
27184
+ logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused, and cdkd cannot emulate the role's permissions instead: ${reason}.`);
27185
+ };
27186
+ const { STSClient, GetCallerIdentityCommand, GetFederationTokenCommand } = await import("@aws-sdk/client-sts");
27187
+ const sts = new STSClient({
27188
+ ...awsClientDefaults({
27189
+ ignoreAssumedRole: true,
27190
+ realAws: args.realAws
27191
+ }),
27192
+ ...args.region && { region: args.region }
27193
+ });
27194
+ try {
27195
+ let callerArn;
27196
+ try {
27197
+ callerArn = (await sts.send(new GetCallerIdentityCommand({}))).Arn;
27198
+ } catch (idErr) {
27199
+ return cannot(describeLocalAwsFailureForWarn(idErr, "STS GetCallerIdentity"));
27200
+ }
27201
+ const roleAccount = parseIamRoleArn(args.roleArn)?.accountId;
27202
+ if (roleAccount === void 0 || roleAccount !== callerArn?.split(":")[4]) return cannot("the role is not in your credentials' account, so its policies cannot be read");
27203
+ if (args.emulateRoleVia === void 0 && !isIamUserArn(callerArn)) return cannot("your credentials are not an IAM user, and only an IAM user can call sts:GetFederationToken. Pass --emulate-role-via <arn> naming a role you can assume, and cdkd assumes it with the role's policies as session policies");
27204
+ let policies;
27205
+ try {
27206
+ policies = await readRolePolicies(args);
27207
+ } catch (readErr) {
27208
+ return cannot(`reading the role's policies failed (it needs iam:GetRole, iam:ListRolePolicies, iam:GetRolePolicy and iam:ListAttachedRolePolicies): ${describeLocalAwsFailureForWarn(readErr, "IAM role policy read")}`);
27209
+ }
27210
+ if (policies.permissionsBoundaryArn !== void 0) return cannot(`the role has a permissions boundary (${displayIdent(policies.permissionsBoundaryArn)}), which session policies cannot reproduce, so the emulation could allow what the role cannot`);
27211
+ const plan = buildSessionPolicy(policies);
27212
+ if (!plan.ok) return cannot(plan.reason);
27213
+ const sessionPolicies = {
27214
+ ...plan.policy !== "" && { Policy: plan.policy },
27215
+ ...plan.policyArns.length > 0 && { PolicyArns: plan.policyArns.map((arn) => ({ arn })) }
27216
+ };
27217
+ let via;
27218
+ let response;
27219
+ try {
27220
+ if (args.emulateRoleVia !== void 0) {
27221
+ via = `AssumeRole of --emulate-role-via ${displayIdent(args.emulateRoleVia, { maxCodePoints: 613 })}`;
27222
+ response = await sts.send(sendableAssumeRoleCommand({
27223
+ RoleArn: args.emulateRoleVia,
27224
+ RoleSessionName: `${args.sessionNamePrefix}-emulate-${Date.now()}`,
27225
+ DurationSeconds: 3600,
27226
+ ...sessionPolicies
27227
+ }));
27228
+ } else {
27229
+ via = "sts:GetFederationToken";
27230
+ response = await sts.send(new GetFederationTokenCommand({
27231
+ Name: `cdkd-${Date.now()}`,
27232
+ DurationSeconds: 3600,
27233
+ ...sessionPolicies
27234
+ }));
27235
+ }
27236
+ } catch (stsErr) {
27237
+ const stsName = stsErr?.name;
27238
+ if (stsName === "PackedPolicyTooLargeException" || stsName === "PackedPolicyTooLarge") return cannot("the role's policies are larger than STS accepts as session policies (PackedPolicyTooLarge)");
27239
+ const rendered = describeLocalAwsFailureForWarn(stsErr, "STS session-policy credentials");
27240
+ return cannot(args.emulateRoleVia === void 0 ? `${rendered}. Temporary IAM user credentials (GetSessionToken / MFA) cannot call sts:GetFederationToken; pass --emulate-role-via <arn> naming a role you can assume instead` : rendered);
27241
+ }
27242
+ const creds = response.Credentials;
27243
+ if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) return cannot("STS returned no usable credentials");
27244
+ if (!noticedRoles.has(args.roleArn)) {
27245
+ noticedRoles.add(args.roleArn);
27246
+ const count = policies.inline.length + policies.managedArns.length;
27247
+ const who = args.emulateRoleVia !== void 0 ? "that role" : "you";
27248
+ const federationNote = args.emulateRoleVia === void 0 ? " A GetFederationToken session cannot call IAM, nor STS except GetCallerIdentity." : "";
27249
+ logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused (the role's trust policy does not allow you), so cdkd EMULATES its permissions: credentials from ${via} with the role's ${policies.inline.length} inline and ${policies.managedArns.length} managed ${count === 1 ? "policy" : "policies"} as session policies, which allow only what both ${who} and the role allow. This is an APPROXIMATION: resource-based policies, KMS key policies and aws:PrincipalArn conditions that name the role see a different principal, and the role's session tags are not reproduced. Policy variables such as aws:username and aws:userid take this session's values, not the role's (a role session has no aws:username).${federationNote}`);
27250
+ }
27251
+ return {
27252
+ accessKeyId: creds.AccessKeyId,
27253
+ secretAccessKey: creds.SecretAccessKey,
27254
+ sessionToken: creds.SessionToken
27255
+ };
27256
+ } finally {
27257
+ sts.destroy();
27258
+ }
27259
+ }
27260
+ async function readRolePolicies(args) {
27261
+ const { IAMClient, GetRoleCommand, ListRolePoliciesCommand, GetRolePolicyCommand, ListAttachedRolePoliciesCommand } = await import("@aws-sdk/client-iam");
27262
+ const iam = new IAMClient({
27263
+ ...awsClientDefaults({
27264
+ ignoreAssumedRole: true,
27265
+ realAws: args.realAws
27266
+ }),
27267
+ ...args.region && { region: args.region }
27268
+ });
27269
+ const RoleName = roleNameOf(args.roleArn);
27270
+ try {
27271
+ const permissionsBoundaryArn = (await iam.send(new GetRoleCommand({ RoleName }))).Role?.PermissionsBoundary?.PermissionsBoundaryArn;
27272
+ const names = [];
27273
+ let marker;
27274
+ do {
27275
+ const page = await iam.send(new ListRolePoliciesCommand({
27276
+ RoleName,
27277
+ ...marker && { Marker: marker }
27278
+ }));
27279
+ names.push(...page.PolicyNames ?? []);
27280
+ marker = page.IsTruncated ? page.Marker : void 0;
27281
+ } while (marker);
27282
+ const inline = [];
27283
+ for (const PolicyName of names) {
27284
+ const got = await iam.send(new GetRolePolicyCommand({
27285
+ RoleName,
27286
+ PolicyName
27287
+ }));
27288
+ let doc;
27289
+ try {
27290
+ doc = JSON.parse(decodeURIComponent(got.PolicyDocument ?? "{}"));
27291
+ } catch {
27292
+ throw new Error("an inline policy document of the role is not valid JSON");
27293
+ }
27294
+ inline.push(doc);
27295
+ }
27296
+ const managedArns = [];
27297
+ let attachedMarker;
27298
+ do {
27299
+ const page = await iam.send(new ListAttachedRolePoliciesCommand({
27300
+ RoleName,
27301
+ ...attachedMarker && { Marker: attachedMarker }
27302
+ }));
27303
+ for (const attached of page.AttachedPolicies ?? []) if (attached.PolicyArn) managedArns.push(attached.PolicyArn);
27304
+ attachedMarker = page.IsTruncated ? page.Marker : void 0;
27305
+ } while (attachedMarker);
27306
+ return {
27307
+ inline,
27308
+ managedArns,
27309
+ ...permissionsBoundaryArn !== void 0 && { permissionsBoundaryArn }
27310
+ };
27311
+ } finally {
27312
+ iam.destroy();
27313
+ }
27314
+ }
27315
+
28505
27316
  // src/cli/commands/local-start-api/credentials.ts
28506
27317
  async function resolveProfileCredentials(profile) {
28507
27318
  const { STSClient } = await import("@aws-sdk/client-sts");
@@ -28536,7 +27347,7 @@ function forceExitShutdownWarning(signal, hostPath) {
28536
27347
  const stranded = strandedProfileCredentialsNotice(hostPath);
28537
27348
  return `Received second ${signal}; force-exiting. Orphan containers may remain — run 'docker ps --filter name=cdkd-local-' and 'docker rm -f' to clean up.` + (stranded === void 0 ? "" : ` ${stranded}`);
28538
27349
  }
28539
- async function assumeLambdaExecutionRole$1(roleArn, region) {
27350
+ async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
28540
27351
  assertSendableRoleArn(roleArn);
28541
27352
  const { STSClient } = await import("@aws-sdk/client-sts");
28542
27353
  const sts = new STSClient({
@@ -28560,6 +27371,15 @@ async function assumeLambdaExecutionRole$1(roleArn, region) {
28560
27371
  };
28561
27372
  } catch (err) {
28562
27373
  if (err instanceof CdkdError) throw err;
27374
+ const emulated = await emulateRoleAfterDeniedAssume(err, {
27375
+ roleArn,
27376
+ region,
27377
+ realAws: mixedModeActive(),
27378
+ ...emulateRoleVia !== void 0 && { emulateRoleVia },
27379
+ flag: "--assume-role",
27380
+ sessionNamePrefix: "cdkd-local-start-api"
27381
+ });
27382
+ if (emulated) return emulated;
28563
27383
  const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
28564
27384
  throw new CdkdError(`--assume-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_START_API_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
28565
27385
  } finally {
@@ -29539,15 +28359,15 @@ async function resolvePseudoParametersForStartApi(stateRegion, options) {
29539
28359
 
29540
28360
  // src/cli/commands/local-start-api/container-spec.ts
29541
28361
  async function buildContainerSpec(args) {
29542
- const { logicalId, stacks, overrides, assumeRole, containerHost, debugPort, stsRegion, inlineTmpDirs, layerTmpDirs, stateByStack, stateSourceActive, skipPull, layerRoleArn, profileCredentials, profileCredsFile, profile, stackRegionOverride } = args;
28362
+ const { logicalId, stacks, overrides, assumeRole, containerHost, debugPort, stsRegion, inlineTmpDirs, layerTmpDirs, stateByStack, stateSourceActive, skipPull, layerRoleArn, emulateRoleVia, profileCredentials, profileCredsFile, profile, stackRegionOverride } = args;
29543
28363
  const lambda = resolveLambdaByLogicalId(logicalId, stacks);
29544
28364
  let codeDir;
29545
28365
  let optDir;
29546
28366
  let imageRef;
29547
28367
  let platform;
29548
28368
  if (lambda.kind === "zip") {
29549
- codeDir = lambda.codePath ?? materializeInlineCode$1(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime), inlineTmpDirs);
29550
- optDir = await materializeLambdaLayers$1(lambda.layers, layerTmpDirs, layerRoleArn, {
28369
+ codeDir = lambda.codePath ?? materializeInlineCode(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime), inlineTmpDirs);
28370
+ optDir = await materializeLambdaLayers(lambda.layers, layerTmpDirs, layerRoleArn, {
29551
28371
  logicalId,
29552
28372
  cdkPath: readCdkPathOrUndefined(lambda.resource)
29553
28373
  });
@@ -29614,15 +28434,20 @@ async function buildContainerSpec(args) {
29614
28434
  lambdaResource: lambda.resource,
29615
28435
  stateBundle
29616
28436
  });
28437
+ const containerRegion = await resolveContainerRegion({
28438
+ region: stsRegion,
28439
+ stackRegion: lambda.stack.region,
28440
+ stateRegion: stateBundle?.region,
28441
+ profile
28442
+ });
29617
28443
  if (roleArn) {
29618
- const creds = await assumeLambdaExecutionRole$1(roleArn, stsRegion);
28444
+ const creds = await assumeLambdaExecutionRole$1(roleArn, containerRegion, emulateRoleVia);
29619
28445
  dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
29620
28446
  dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
29621
28447
  dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
29622
- setContainerRegion(dockerEnv, stsRegion);
28448
+ setContainerRegion(dockerEnv, containerRegion);
29623
28449
  } else {
29624
28450
  forwardAwsEnv$2(dockerEnv);
29625
- const containerRegion = firstUsableRegion(stsRegion, lambda.stack.region);
29626
28451
  setContainerRegion(dockerEnv, containerRegion);
29627
28452
  if (profileCredentials) {
29628
28453
  dockerEnv["AWS_ACCESS_KEY_ID"] = profileCredentials.accessKeyId;
@@ -29688,7 +28513,7 @@ async function buildContainerSpec(args) {
29688
28513
  }
29689
28514
  async function resolveContainerImageForStartApi(lambda, skipPull) {
29690
28515
  const logger = getLogger();
29691
- const localBuild = await resolveLocalBuildPlan$1(lambda);
28516
+ const localBuild = await resolveLocalBuildPlan(lambda);
29692
28517
  if (localBuild) return { imageRef: await buildContainerImage$1(localBuild.asset, localBuild.cdkOutDir, {
29693
28518
  assetOutdir: localBuild.assetOutdir,
29694
28519
  architecture: lambda.architecture,
@@ -29707,7 +28532,7 @@ async function resolveContainerImageForStartApi(lambda, skipPull) {
29707
28532
  }
29708
28533
  }) };
29709
28534
  }
29710
- async function resolveLocalBuildPlan$1(lambda) {
28535
+ async function resolveLocalBuildPlan(lambda) {
29711
28536
  if (!lambda.stack.assetManifestPath) return void 0;
29712
28537
  const { manifestDir: cdkOutDir, assetOutdir } = assetPathDirs(lambda.stack);
29713
28538
  const manifest = await new AssetManifestLoader().loadStackManifest(lambda.stack, cdkOutDir);
@@ -29720,14 +28545,16 @@ async function resolveLocalBuildPlan$1(lambda) {
29720
28545
  assetOutdir
29721
28546
  };
29722
28547
  }
29723
- async function materializeLambdaLayers$1(layers, layerTmpDirs, layerRoleArn, workload) {
28548
+ async function materializeLambdaLayers(layers, layerTmpDirs, layerRoleArn, workload) {
29724
28549
  if (layers.length === 0) return void 0;
29725
28550
  const flat = [];
29726
28551
  for (const layer of layers) {
29727
28552
  if (layer.kind === "asset") {
28553
+ const asset = await layerAssetDirectory(layer.assetPath);
28554
+ if (asset.tmpDir !== void 0) layerTmpDirs.add(asset.tmpDir);
29728
28555
  flat.push({
29729
28556
  logicalId: layer.logicalId,
29730
- assetPath: layer.assetPath
28557
+ assetPath: asset.dir
29731
28558
  });
29732
28559
  continue;
29733
28560
  }
@@ -29818,6 +28645,10 @@ async function localStartApiCommand(target, options) {
29818
28645
  }
29819
28646
  warnIfDeprecatedRegion(options);
29820
28647
  if (options.layerRoleArn !== void 0) explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn);
28648
+ checkEmulateRoleVia(options.emulateRoleVia, {
28649
+ roleFlag: "--assume-role or --assume-role-auto",
28650
+ roleRequested: options.assumeRole !== void 0 || options.assumeRoleAuto === true
28651
+ });
29821
28652
  await activateLocalAwsAndRoleArn(options);
29822
28653
  const normalizedAssumeRole = normalizeStartApiAssumeRole(options.assumeRole, options.assumeRoleAuto ?? false);
29823
28654
  if (normalizedAssumeRole === void 0) delete options.assumeRole;
@@ -29909,6 +28740,7 @@ async function localStartApiCommand(target, options) {
29909
28740
  stateSourceActive,
29910
28741
  skipPull: options.pull === false,
29911
28742
  ...options.layerRoleArn !== void 0 && { layerRoleArn: options.layerRoleArn },
28743
+ ...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
29912
28744
  ...profileCredentials && { profileCredentials },
29913
28745
  ...profileCredsFile && { profileCredsFile },
29914
28746
  ...dynamicReferenceSpecOptions(options)
@@ -30092,7 +28924,7 @@ async function localStartApiCommand(target, options) {
30092
28924
 
30093
28925
  // src/cli/commands/local-start-api.ts
30094
28926
  function createLocalStartApiCommand() {
30095
- const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser((raw, prev) => parseAssumeRoleToken(raw, prev))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
28927
+ const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser((raw, prev) => parseAssumeRoleToken(raw, prev))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
30096
28928
  [
30097
28929
  ...commonOptions,
30098
28930
  ...appOptions,
@@ -31157,6 +29989,12 @@ async function runEcsTask(task, options, state) {
31157
29989
  const volumeByName = await realizeDockerVolumes(task.volumes, state);
31158
29990
  if (state.closing) throw interruptedError();
31159
29991
  const mergedAddHostFlags = mergeHostGatewayAddHostFlags(options.addHostFlags, options.hostGatewayExtraHosts);
29992
+ const containerRegion = await resolveContainerRegion({
29993
+ region: options.region,
29994
+ stackRegion: options.stackRegion ?? task.stack.region,
29995
+ stateRegion: options.stateRecordRegion,
29996
+ profile: options.profile
29997
+ });
31160
29998
  const dockerCmds = /* @__PURE__ */ new Map();
31161
29999
  const dockerLoopbackPorts = /* @__PURE__ */ new Map();
31162
30000
  const dockerForwarders = /* @__PURE__ */ new Map();
@@ -31181,7 +30019,7 @@ async function runEcsTask(task, options, state) {
31181
30019
  containerHost: options.containerHost,
31182
30020
  roleArn: options.taskRoleArn,
31183
30021
  platformOverride: options.platformOverride,
31184
- region: options.region,
30022
+ region: containerRegion,
31185
30023
  sidecarIp: state.network.sidecarIp,
31186
30024
  ...options.skipHostPortPublish ? { skipHostPortPublish: true } : {},
31187
30025
  ...mergedAddHostFlags.length > 0 ? { addHostFlags: mergedAddHostFlags } : {},
@@ -31329,7 +30167,7 @@ function partitionOfArn(arn) {
31329
30167
  const segment = arn?.split(":")[1];
31330
30168
  return arn?.startsWith("arn:") && segment ? segment : "aws";
31331
30169
  }
31332
- async function assumeTaskRole(roleArn, region, route) {
30170
+ async function assumeTaskRole(roleArn, region, route, emulateRoleVia) {
31333
30171
  assertSendableRoleArn(roleArn);
31334
30172
  const { STSClient } = await import("@aws-sdk/client-sts");
31335
30173
  const sts = new STSClient({
@@ -31353,6 +30191,15 @@ async function assumeTaskRole(roleArn, region, route) {
31353
30191
  };
31354
30192
  } catch (err) {
31355
30193
  if (err instanceof CdkdError) throw err;
30194
+ const emulated = await emulateRoleAfterDeniedAssume(err, {
30195
+ roleArn,
30196
+ region,
30197
+ realAws: route.realAws,
30198
+ ...emulateRoleVia !== void 0 && { emulateRoleVia },
30199
+ flag: "--assume-task-role",
30200
+ sessionNamePrefix: "cdkd-local-run-task"
30201
+ });
30202
+ if (emulated) return emulated;
31356
30203
  const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
31357
30204
  throw new CdkdError(`--assume-task-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_RUN_TASK_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
31358
30205
  } finally {
@@ -31669,6 +30516,10 @@ async function localRunTaskCommand(target, options) {
31669
30516
  try {
31670
30517
  if (typeof options.assumeTaskRole === "string") assertFlagRoleArn("--assume-task-role", options.assumeTaskRole);
31671
30518
  if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn);
30519
+ checkEmulateRoleVia(options.emulateRoleVia, {
30520
+ roleFlag: "--assume-task-role",
30521
+ roleRequested: options.assumeTaskRole === true || typeof options.assumeTaskRole === "string"
30522
+ });
31672
30523
  await activateLocalAwsAndRoleArn(options);
31673
30524
  await ensureDockerAvailable();
31674
30525
  const appCmd = resolveApp(options.app);
@@ -31751,7 +30602,7 @@ async function localRunTaskCommand(target, options) {
31751
30602
  logger.warn(taskRoleNameIsLogicalIdWarning(logicalId, !stateProvider ? "no-state-source" : taskRoleRecordIsEmulatorSide() ? "mixed-mode-emulator-iam" : reason === "no-state" ? "state-not-read" : reason));
31752
30603
  }
31753
30604
  resolvedRoleArn = options.assumeTaskRole === true ? await resolvePlaceholderAccount(roleArnTemplate, options, { realAws }) : roleArnTemplate;
31754
- const creds = await assumeTaskRole(resolvedRoleArn, options.region, { realAws });
30605
+ const creds = await assumeTaskRole(resolvedRoleArn, options.region, { realAws }, options.emulateRoleVia);
31755
30606
  if (realAws) assumedCredentials = creds;
31756
30607
  else emulatorTaskCredentials = creds;
31757
30608
  }
@@ -31837,7 +30688,7 @@ async function applyPerContainerNames(task, target, stacks, candidate, options,
31837
30688
 
31838
30689
  // src/cli/commands/local-run-task.ts
31839
30690
  function createLocalRunTaskCommand() {
31840
- const cmd = new Command("run-task").description("Run an AWS::ECS::TaskDefinition locally — pulls/builds images, sets up a per-task docker network with the AWS-published metadata-endpoints sidecar, and starts every container in dependsOn order. Target accepts a CDK display path (MyStack/MyService/TaskDef) or stack-qualified logical ID (MyStack:MyServiceTaskDefXYZ1234). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the AWS::ECS::TaskDefinition to run").addOption(new Option("--cluster <name>", "Cluster name surfaced to ECS_CONTAINER_METADATA_URI_V4 and used as the docker network prefix").default("cdkd-local")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"ContainerName\":{\"KEY\":\"VALUE\"}, \"Parameters\":{}})")).addOption(new Option("--container-host <ip>", "Host IP to bind published container ports to. Must be a numeric IP (Docker rejects hostnames here)").default("127.0.0.1")).addOption(new Option("--assume-task-role [arn]", "Assume the task definition's TaskRoleArn (or the supplied ARN) and forward STS-issued temp credentials via the metadata sidecar so containers run with the deployed function role. Bare flag uses the template's TaskRoleArn; pass an explicit ARN to override.")).addOption(new Option("--no-pull", "Skip docker pull for every container image and the metadata sidecar")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--platform <platform>", "Force docker --platform (linux/amd64 or linux/arm64). Default: inferred from task RuntimePlatform.CpuArchitecture")).addOption(new Option("--keep-running", "Don't docker rm -f the user containers on task exit (network + sidecar are still torn down). Use when you want to docker exec into a stopped container for post-mortems.").default(false)).addOption(new Option("--detach", "Start the containers in the background and exit (skip log streaming + auto teardown). Useful in CI smoke tests; caller manages container lifecycle.").default(false)).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Fn::Sub / Fn::GetAtt references to same-stack AWS::ECR::Repository resources with the deployed URI. Off by default — only the AWS pseudo-parameter tier (${AWS::AccountId} / ${AWS::Region}) is resolved without this flag.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in container env vars / secrets / image URIs with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localRunTaskCommand));
30691
+ const cmd = new Command("run-task").description("Run an AWS::ECS::TaskDefinition locally — pulls/builds images, sets up a per-task docker network with the AWS-published metadata-endpoints sidecar, and starts every container in dependsOn order. Target accepts a CDK display path (MyStack/MyService/TaskDef) or stack-qualified logical ID (MyStack:MyServiceTaskDefXYZ1234). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the AWS::ECS::TaskDefinition to run").addOption(new Option("--cluster <name>", "Cluster name surfaced to ECS_CONTAINER_METADATA_URI_V4 and used as the docker network prefix").default("cdkd-local")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"ContainerName\":{\"KEY\":\"VALUE\"}, \"Parameters\":{}})")).addOption(new Option("--container-host <ip>", "Host IP to bind published container ports to. Must be a numeric IP (Docker rejects hostnames here)").default("127.0.0.1")).addOption(new Option("--assume-task-role [arn]", "Assume the task definition's TaskRoleArn (or the supplied ARN) and forward STS-issued temp credentials via the metadata sidecar so containers run with the deployed function role. Bare flag uses the template's TaskRoleArn; pass an explicit ARN to override.")).addOption(emulateRoleViaOption("--assume-task-role")).addOption(new Option("--no-pull", "Skip docker pull for every container image and the metadata sidecar")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--platform <platform>", "Force docker --platform (linux/amd64 or linux/arm64). Default: inferred from task RuntimePlatform.CpuArchitecture")).addOption(new Option("--keep-running", "Don't docker rm -f the user containers on task exit (network + sidecar are still torn down). Use when you want to docker exec into a stopped container for post-mortems.").default(false)).addOption(new Option("--detach", "Start the containers in the background and exit (skip log streaming + auto teardown). Useful in CI smoke tests; caller manages container lifecycle.").default(false)).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Fn::Sub / Fn::GetAtt references to same-stack AWS::ECR::Repository resources with the deployed URI. Off by default — only the AWS pseudo-parameter tier (${AWS::AccountId} / ${AWS::Region}) is resolved without this flag.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in container env vars / secrets / image URIs with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localRunTaskCommand));
31841
30692
  addImageOverrideOptions(cmd);
31842
30693
  [
31843
30694
  ...commonOptions,
@@ -32265,7 +31116,11 @@ async function buildContainerEnvWith(resolved, options, profileCredentials, prof
32265
31116
  const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
32266
31117
  await applyAgentCoreCredentialEnv(dockerEnv, {
32267
31118
  ...assumeRoleArn !== void 0 && { assumeRoleArn },
31119
+ ...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
32268
31120
  ...options.region !== void 0 && { region: options.region },
31121
+ ...resolved.stack.region !== void 0 && { stackRegion: resolved.stack.region },
31122
+ ...loaded?.region !== void 0 && { stateRegion: loaded.region },
31123
+ ...options.profile !== void 0 && { profile: options.profile },
32269
31124
  ...profileCredentials !== void 0 && { profileCredentials },
32270
31125
  ...profileCredsFile !== void 0 && { profileCredsFile: {
32271
31126
  containerPath: profileCredsFile.containerPath,
@@ -32306,10 +31161,16 @@ async function resolveStackAccountId(region, profile, fromState, fromCfnStack) {
32306
31161
  async function applyAgentCoreCredentialEnv(dockerEnv, args) {
32307
31162
  const logger = getLogger();
32308
31163
  let assumeSucceeded = false;
31164
+ const containerRegion = await resolveContainerRegion({
31165
+ region: args.region,
31166
+ stackRegion: args.stackRegion,
31167
+ stateRegion: args.stateRegion,
31168
+ profile: args.profile
31169
+ });
32309
31170
  if (args.assumeRoleArn) {
32310
- const stsRegion = canonicalizeRegion(args.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"]);
31171
+ const stsRegion = containerRegion;
32311
31172
  try {
32312
- const creds = await assumeAgentCoreExecutionRole(args.assumeRoleArn, stsRegion);
31173
+ const creds = await assumeAgentCoreExecutionRole(args.assumeRoleArn, stsRegion, args.emulateRoleVia);
32313
31174
  dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
32314
31175
  dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
32315
31176
  dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
@@ -32321,7 +31182,7 @@ async function applyAgentCoreCredentialEnv(dockerEnv, args) {
32321
31182
  }
32322
31183
  if (!assumeSucceeded) {
32323
31184
  forwardAwsEnv$1(dockerEnv);
32324
- setContainerRegion(dockerEnv, canonicalizeRegion(args.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"]));
31185
+ setContainerRegion(dockerEnv, containerRegion);
32325
31186
  applyProfileCredentialsOverlay(dockerEnv, args.profileCredentials, false);
32326
31187
  if (args.profileCredsFile) {
32327
31188
  dockerEnv["AWS_SHARED_CREDENTIALS_FILE"] = args.profileCredsFile.containerPath;
@@ -32374,7 +31235,7 @@ function forwardAwsEnv$1(env) {
32374
31235
  }
32375
31236
  applyCallerIdentityCredentials(env);
32376
31237
  }
32377
- async function assumeAgentCoreExecutionRole(roleArn, region) {
31238
+ async function assumeAgentCoreExecutionRole(roleArn, region, emulateRoleVia) {
32378
31239
  assertSendableRoleArn(roleArn, (m) => new CdkdError(m, "LOCAL_INVOKE_AGENTCORE_ASSUME_ROLE_INVALID"));
32379
31240
  const { STSClient } = await import("@aws-sdk/client-sts");
32380
31241
  const sts = new STSClient({
@@ -32385,11 +31246,26 @@ async function assumeAgentCoreExecutionRole(roleArn, region) {
32385
31246
  ...region && { region }
32386
31247
  });
32387
31248
  try {
32388
- const creds = (await sts.send(sendableAssumeRoleCommand({
32389
- RoleArn: roleArn,
32390
- RoleSessionName: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore-${Date.now()}`,
32391
- DurationSeconds: 3600
32392
- }))).Credentials;
31249
+ let response;
31250
+ try {
31251
+ response = await sts.send(sendableAssumeRoleCommand({
31252
+ RoleArn: roleArn,
31253
+ RoleSessionName: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore-${Date.now()}`,
31254
+ DurationSeconds: 3600
31255
+ }));
31256
+ } catch (err) {
31257
+ const emulated = await emulateRoleAfterDeniedAssume(err, {
31258
+ roleArn,
31259
+ region,
31260
+ realAws: mixedModeActive(),
31261
+ ...emulateRoleVia !== void 0 && { emulateRoleVia },
31262
+ flag: "--assume-role",
31263
+ sessionNamePrefix: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore`
31264
+ });
31265
+ if (emulated) return emulated;
31266
+ throw err;
31267
+ }
31268
+ const creds = response.Credentials;
32393
31269
  if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_AGENTCORE_ASSUMEROLE_NO_CREDS");
32394
31270
  return {
32395
31271
  accessKeyId: creds.AccessKeyId,
@@ -32545,7 +31421,7 @@ async function resolveAgentCoreCodeImageFromS3(resolved, code, s3Source, options
32545
31421
  const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
32546
31422
  let credentials;
32547
31423
  if (assumeRoleArn) try {
32548
- credentials = await assumeAgentCoreExecutionRole(assumeRoleArn, region);
31424
+ credentials = await assumeAgentCoreExecutionRole(assumeRoleArn, region, options.emulateRoleVia);
32549
31425
  } catch (err) {
32550
31426
  logger.warn(assumeRoleFallbackWarning({
32551
31427
  assumeRoleArn,
@@ -32792,7 +31668,7 @@ async function resolveHostCredentialsForSigV4(options, resolved, loaded, region)
32792
31668
  };
32793
31669
  const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
32794
31670
  if (assumeRoleArn) try {
32795
- return await assumeAgentCoreExecutionRole(assumeRoleArn, region);
31671
+ return await assumeAgentCoreExecutionRole(assumeRoleArn, region, options.emulateRoleVia);
32796
31672
  } catch (err) {
32797
31673
  logger.warn(assumeRoleFallbackWarning({
32798
31674
  assumeRoleArn,
@@ -32907,6 +31783,10 @@ async function localInvokeAgentCoreCommand(target, options) {
32907
31783
  try {
32908
31784
  if (typeof options.assumeRole === "string") explicitRoleArnOrThrow("--assume-role", options.assumeRole, (message) => new CdkdError(message, "LOCAL_INVOKE_AGENTCORE_ASSUME_ROLE_INVALID"));
32909
31785
  if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn, (message) => new CdkdError(message, "LOCAL_INVOKE_AGENTCORE_ECR_ROLE_ARN_INVALID"));
31786
+ checkEmulateRoleVia(options.emulateRoleVia, {
31787
+ roleFlag: "--assume-role",
31788
+ roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
31789
+ });
32910
31790
  await activateLocalAwsAndRoleArn(options);
32911
31791
  await ensureDockerAvailable();
32912
31792
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
@@ -33148,7 +32028,7 @@ function parseTimeoutMs(raw) {
33148
32028
  return parsed;
33149
32029
  }
33150
32030
  function createLocalInvokeAgentCoreCommand() {
33151
- const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(parseTimeoutMs)).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
32031
+ const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(parseTimeoutMs)).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
33152
32032
  await localInvokeAgentCoreCommand(target, options);
33153
32033
  }));
33154
32034
  [
@@ -33230,18 +32110,21 @@ function createLocalStartMicrovmCommand$1() {
33230
32110
  async function applyLambdaCredentialEnv(dockerEnv, args) {
33231
32111
  const logger = getLogger();
33232
32112
  let assumeSucceeded = false;
33233
- if (args.assumeRoleArn) {
33234
- const stsRegion = canonicalizeRegion(args.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"]);
33235
- try {
33236
- const creds = await assumeLambdaExecutionRole(args.assumeRoleArn, stsRegion);
33237
- dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
33238
- dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
33239
- dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
33240
- setContainerRegion(dockerEnv, stsRegion);
33241
- assumeSucceeded = true;
33242
- } catch (err) {
33243
- logger.warn(`--assume-role: STS AssumeRole(${displayIdent(args.assumeRoleArn, { maxCodePoints: 613 })}) failed: ${describeLocalAwsFailureForWarn(err, "STS AssumeRole")}. Falling back to the developer's shell credentials.`);
33244
- }
32113
+ const containerRegion = await resolveContainerRegion({
32114
+ region: args.region,
32115
+ stackRegion: args.stackRegion,
32116
+ stateRegion: args.stateRegion,
32117
+ profile: args.profile
32118
+ });
32119
+ if (args.assumeRoleArn) try {
32120
+ const creds = await assumeLambdaExecutionRole(args.assumeRoleArn, containerRegion, args.emulateRoleVia);
32121
+ dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
32122
+ dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
32123
+ dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
32124
+ setContainerRegion(dockerEnv, containerRegion);
32125
+ assumeSucceeded = true;
32126
+ } catch (err) {
32127
+ logger.warn(`--assume-role: STS AssumeRole(${displayIdent(args.assumeRoleArn, { maxCodePoints: 613 })}) failed: ${describeLocalAwsFailureForWarn(err, "STS AssumeRole")}. Falling back to the developer's shell credentials.`);
33245
32128
  }
33246
32129
  if (!assumeSucceeded) {
33247
32130
  forwardAwsEnv(dockerEnv);
@@ -33250,11 +32133,10 @@ async function applyLambdaCredentialEnv(dockerEnv, args) {
33250
32133
  dockerEnv["AWS_SHARED_CREDENTIALS_FILE"] = args.profileCredsFile.containerPath;
33251
32134
  dockerEnv["AWS_PROFILE"] = args.profileCredsFile.profileName;
33252
32135
  }
33253
- const containerRegion = firstUsableRegion(args.region, process.env["AWS_REGION"], process.env["AWS_DEFAULT_REGION"], args.stackRegion);
33254
32136
  setContainerRegion(dockerEnv, containerRegion);
33255
32137
  }
33256
32138
  }
33257
- async function assumeLambdaExecutionRole(roleArn, region) {
32139
+ async function assumeLambdaExecutionRole(roleArn, region, emulateRoleVia) {
33258
32140
  assertSendableRoleArn(roleArn, (m) => new CdkdError(m, "LOCAL_INVOKE_ASSUME_ROLE_INVALID"));
33259
32141
  const { STSClient } = await import("@aws-sdk/client-sts");
33260
32142
  const sts = new STSClient({
@@ -33265,11 +32147,26 @@ async function assumeLambdaExecutionRole(roleArn, region) {
33265
32147
  ...region && { region }
33266
32148
  });
33267
32149
  try {
33268
- const creds = (await sts.send(sendableAssumeRoleCommand({
33269
- RoleArn: roleArn,
33270
- RoleSessionName: `cdkd-local-invoke-${Date.now()}`,
33271
- DurationSeconds: 3600
33272
- }))).Credentials;
32150
+ let response;
32151
+ try {
32152
+ response = await sts.send(sendableAssumeRoleCommand({
32153
+ RoleArn: roleArn,
32154
+ RoleSessionName: `cdkd-local-invoke-${Date.now()}`,
32155
+ DurationSeconds: 3600
32156
+ }));
32157
+ } catch (err) {
32158
+ const emulated = await emulateRoleAfterDeniedAssume(err, {
32159
+ roleArn,
32160
+ region,
32161
+ realAws: mixedModeActive(),
32162
+ ...emulateRoleVia !== void 0 && { emulateRoleVia },
32163
+ flag: "--assume-role",
32164
+ sessionNamePrefix: "cdkd-local-invoke"
32165
+ });
32166
+ if (emulated) return emulated;
32167
+ throw err;
32168
+ }
32169
+ const creds = response.Credentials;
33273
32170
  if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_ASSUMEROLE_NO_CREDS");
33274
32171
  return {
33275
32172
  accessKeyId: creds.AccessKeyId,
@@ -33390,141 +32287,6 @@ function pickReferencedLogicalId(intrinsic) {
33390
32287
  }
33391
32288
  }
33392
32289
 
33393
- // src/cli/commands/local-invoke/inline-code.ts
33394
- function resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler) {
33395
- const resolved = resolveAssemblyPath(dir, `${modulePath}${fileExtension}`);
33396
- if (!resolved.contained) throw new Error(`Handler ${displayAssemblyPath(handler)} names a module path that ${renderAssemblyPathEscape(resolved, dir, "materialize it", "A Handler's module path names a file inside the function's own code directory; one that leaves it would write the inline Code.ZipFile body to an arbitrary path on this machine. Refusing to materialize it.")}`);
33397
- return resolved.path;
33398
- }
33399
- function materializeInlineCode(handler, source, fileExtension) {
33400
- const lastDot = handler.lastIndexOf(".");
33401
- if (lastDot <= 0) throw new Error(`Handler '${handler}' is malformed: expected '<modulePath>.<exportName>'.`);
33402
- const modulePath = handler.substring(0, lastDot);
33403
- const dir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-"));
33404
- try {
33405
- const filePath = resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler);
33406
- mkdirSync(path.dirname(filePath), { recursive: true });
33407
- writeFileSync(filePath, source, "utf-8");
33408
- } catch (e) {
33409
- try {
33410
- rmSync(dir, {
33411
- recursive: true,
33412
- force: true
33413
- });
33414
- } catch {}
33415
- throw e;
33416
- }
33417
- return dir;
33418
- }
33419
-
33420
- // src/cli/commands/local-invoke/image-plan.ts
33421
- async function resolveZipImagePlan(lambda, options) {
33422
- let inlineTmpDir;
33423
- let codeDir = lambda.codePath;
33424
- if (codeDir === null) {
33425
- inlineTmpDir = materializeInlineCode(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime));
33426
- codeDir = inlineTmpDir;
33427
- }
33428
- const image = resolveRuntimeImage(lambda.runtime);
33429
- await pullImage(image, options.pull === false);
33430
- const layerPlan = await materializeLambdaLayersIncludingArns(lambda.layers, options, {
33431
- logicalId: lambda.logicalId,
33432
- cdkPath: readCdkPathOrUndefined(lambda.resource)
33433
- });
33434
- const containerCodePath = resolveRuntimeCodeMountPath(lambda.runtime);
33435
- const tmpfs = resolveTmpfsForLambda(lambda);
33436
- return {
33437
- image,
33438
- mounts: [{
33439
- hostPath: codeDir,
33440
- containerPath: containerCodePath,
33441
- readOnly: true
33442
- }],
33443
- extraMounts: layerPlan.mount ? [layerPlan.mount] : [],
33444
- cmd: [lambda.handler],
33445
- platform: architectureToPlatform(lambda.architecture),
33446
- ...inlineTmpDir !== void 0 && { inlineTmpDir },
33447
- ...layerPlan.tmpDir !== void 0 && { layersTmpDir: layerPlan.tmpDir },
33448
- ...layerPlan.extraTmpDirs.length > 0 && { layerArnTmpDirs: layerPlan.extraTmpDirs },
33449
- ...tmpfs !== void 0 && { tmpfs }
33450
- };
33451
- }
33452
- async function materializeLambdaLayersIncludingArns(layers, options, workload) {
33453
- const extraTmpDirs = [];
33454
- const flat = [];
33455
- for (const layer of layers) {
33456
- if (layer.kind === "asset") {
33457
- flat.push({
33458
- logicalId: layer.logicalId,
33459
- assetPath: layer.assetPath
33460
- });
33461
- continue;
33462
- }
33463
- const dir = await materializeLayerFromArn(layer, {
33464
- ...workload && { workload },
33465
- ...options.layerRoleArn !== void 0 && { roleArn: explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn) }
33466
- });
33467
- extraTmpDirs.push(dir);
33468
- flat.push({
33469
- logicalId: layer.arn,
33470
- assetPath: dir
33471
- });
33472
- }
33473
- return {
33474
- ...materializeLambdaLayers(flat),
33475
- extraTmpDirs
33476
- };
33477
- }
33478
- function resolveTmpfsForLambda(lambda) {
33479
- if (lambda.ephemeralStorageMb === void 0) return void 0;
33480
- const logger = getLogger();
33481
- if (lambda.kind === "image") logger.info(`Lambda ${lambda.logicalId}: capping /tmp at ${lambda.ephemeralStorageMb} MiB via --tmpfs (overlays any base-image /tmp content)`);
33482
- else logger.debug(`Lambda ${lambda.logicalId}: applying EphemeralStorage cap via --tmpfs /tmp:size=${lambda.ephemeralStorageMb}m`);
33483
- return {
33484
- target: "/tmp",
33485
- sizeMb: lambda.ephemeralStorageMb
33486
- };
33487
- }
33488
- function materializeLambdaLayers(layers) {
33489
- if (layers.length === 0) return {};
33490
- if (layers.length === 1) return { mount: {
33491
- hostPath: layers[0].assetPath,
33492
- containerPath: "/opt",
33493
- readOnly: true
33494
- } };
33495
- const tmpDir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-layers-"));
33496
- try {
33497
- for (const layer of layers) copyLayerTreeLastWins(layer.assetPath, tmpDir);
33498
- } catch (error) {
33499
- rmSync(tmpDir, {
33500
- recursive: true,
33501
- force: true
33502
- });
33503
- throw error;
33504
- }
33505
- return {
33506
- mount: {
33507
- hostPath: tmpDir,
33508
- containerPath: "/opt",
33509
- readOnly: true
33510
- },
33511
- tmpDir
33512
- };
33513
- }
33514
- async function resolveLocalBuildPlan(lambda) {
33515
- if (!lambda.stack.assetManifestPath) return void 0;
33516
- const { manifestDir: cdkOutDir, assetOutdir } = assetPathDirs(lambda.stack);
33517
- const manifest = await new AssetManifestLoader().loadStackManifest(lambda.stack, cdkOutDir);
33518
- if (!manifest) return void 0;
33519
- const entry = getDockerImageBySourceHash(manifest, lambda.imageUri);
33520
- if (!entry) return void 0;
33521
- return {
33522
- asset: entry.asset,
33523
- cdkOutDir,
33524
- assetOutdir
33525
- };
33526
- }
33527
-
33528
32290
  // src/cli/commands/local-invoke/template-env.ts
33529
32291
  function envHasIntrinsicValue(templateEnv) {
33530
32292
  if (!templateEnv) return false;
@@ -33682,6 +32444,10 @@ async function localInvokeCommand(target, options) {
33682
32444
  if (typeof options.assumeRole === "string") explicitRoleArnOrThrow("--assume-role", options.assumeRole);
33683
32445
  if (options.layerRoleArn !== void 0) explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn);
33684
32446
  if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn);
32447
+ checkEmulateRoleVia(options.emulateRoleVia, {
32448
+ roleFlag: "--assume-role",
32449
+ roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
32450
+ });
33685
32451
  await activateLocalAwsAndRoleArn(options);
33686
32452
  await ensureDockerAvailable();
33687
32453
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
@@ -33707,7 +32473,7 @@ async function localInvokeCommand(target, options) {
33707
32473
  const targetLabel = lambda.kind === "zip" ? lambda.runtime : "container image";
33708
32474
  logger.info(`Target: ${lambda.stack.stackName}/${lambda.logicalId} (${targetLabel})`);
33709
32475
  imagePlan = await resolveImagePlan(lambda, options);
33710
- const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint } = await resolveInvokeTemplateEnv(lambda, options);
32476
+ const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint, stateRegion } = await resolveInvokeTemplateEnv(lambda, options);
33711
32477
  let resolvedAssumeRoleArn;
33712
32478
  if (typeof options.assumeRole === "string") resolvedAssumeRoleArn = explicitRoleArnOrThrow("--assume-role", options.assumeRole);
33713
32479
  else if (options.assumeRole === true) {
@@ -33726,8 +32492,11 @@ async function localInvokeCommand(target, options) {
33726
32492
  };
33727
32493
  await applyLambdaCredentialEnv(dockerEnv, {
33728
32494
  ...resolvedAssumeRoleArn && { assumeRoleArn: resolvedAssumeRoleArn },
32495
+ ...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
33729
32496
  ...options.region !== void 0 && { region: options.region },
33730
32497
  ...lambda.stack.region !== void 0 && { stackRegion: lambda.stack.region },
32498
+ ...stateRegion !== void 0 && { stateRegion },
32499
+ ...options.profile !== void 0 && { profile: options.profile },
33731
32500
  ...profileCredentials && { profileCredentials },
33732
32501
  ...profileCredsFile && { profileCredsFile }
33733
32502
  });
@@ -33864,7 +32633,8 @@ async function resolveInvokeTemplateEnvWith(lambda, options, dynamicRefs) {
33864
32633
  return {
33865
32634
  env: dynamic.env,
33866
32635
  sensitiveEnvKeys: /* @__PURE__ */ new Set([...stateAudit?.sensitiveKeys ?? [], ...dynamic.resolvedKeys]),
33867
- ...stateForRoleHint !== void 0 && { stateForRoleHint }
32636
+ ...stateForRoleHint !== void 0 && { stateForRoleHint },
32637
+ ...ownerRegion !== void 0 && { stateRegion: ownerRegion }
33868
32638
  };
33869
32639
  }
33870
32640
  async function resolveImagePlan(lambda, options) {
@@ -33874,7 +32644,7 @@ async function resolveImagePlan(lambda, options) {
33874
32644
  async function resolveContainerImagePlan(lambda, options) {
33875
32645
  const logger = getLogger();
33876
32646
  const platform = architectureToPlatform(lambda.architecture);
33877
- const localBuild = await resolveLocalBuildPlan(lambda);
32647
+ const localBuild = await resolveLocalBuildPlan$1(lambda);
33878
32648
  let imageRef;
33879
32649
  if (localBuild) imageRef = await buildContainerImage$1(localBuild.asset, localBuild.cdkOutDir, {
33880
32650
  assetOutdir: localBuild.assetOutdir,
@@ -33959,7 +32729,7 @@ function createLocalCommand() {
33959
32729
  setEmbedConfig(CDKD_EMBED_CONFIG);
33960
32730
  setAwsEndpointOverrideSource(mixedModeEmulatorOverride);
33961
32731
  const local = new Command("local").description("Local execution of Lambda functions (RIE) and ECS task definitions (Docker required)");
33962
- const invoke = new Command("invoke").description("Run a Lambda function locally in a Docker container (RIE-backed). Target accepts a CDK display path (MyStack/MyApi/Handler) or stack-qualified logical ID (MyStack:MyApiHandler1234ABCD). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the Lambda to invoke").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for IMAGE local-build path; `docker build` does not pull base layers by default")).addOption(new Option("--no-build", "Skip docker build on the IMAGE local-build path (use the previously-built tag). Requires the deterministic tag to already be in the local registry; errors with an actionable message when missing. No-op for ZIP Lambdas and the IMAGE ECR-pull path. Compatible with --no-pull.")).addOption(new Option("--debug-port <port>", "Node --inspect-brk port (default: off)")).addOption(new Option("--container-host <host>", "Host to bind the RIE port to").default("127.0.0.1")).addOption(new Option("--assume-role [arn]", "Assume the Lambda's deployed execution role and forward STS-issued temp credentials to the container so the handler runs with the deployed function's narrow permissions (closes the \"developer admin / function narrow\" skew). Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) auto-resolves the function's execution role ARN from cdkd state (requires --from-state); (3) `--no-assume-role` explicitly opts out (forces dev creds even with --from-state). Off by default — when omitted, the developer's shell credentials are forwarded unchanged (SAM-compatible default). STS failures degrade to a warn + dev-creds fallback.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the deployed execution role: forward your ambient AWS credentials (or the --profile overlay) even when --from-state is set, and suppress the \"run with --assume-role\" hint. Distinct from omitting the flag, which still prints that hint.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub in env vars with the deployed physical IDs / attributes. Off by default — keep PR 1 warn-and-drop semantics; turn on for stacks already deployed via cdkd deploy.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localInvokeCommand));
32732
+ const invoke = new Command("invoke").description("Run a Lambda function locally in a Docker container (RIE-backed). Target accepts a CDK display path (MyStack/MyApi/Handler) or stack-qualified logical ID (MyStack:MyApiHandler1234ABCD). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the Lambda to invoke").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for IMAGE local-build path; `docker build` does not pull base layers by default")).addOption(new Option("--no-build", "Skip docker build on the IMAGE local-build path (use the previously-built tag). Requires the deterministic tag to already be in the local registry; errors with an actionable message when missing. No-op for ZIP Lambdas and the IMAGE ECR-pull path. Compatible with --no-pull.")).addOption(new Option("--debug-port <port>", "Node --inspect-brk port (default: off)")).addOption(new Option("--container-host <host>", "Host to bind the RIE port to").default("127.0.0.1")).addOption(new Option("--assume-role [arn]", "Assume the Lambda's deployed execution role and forward STS-issued temp credentials to the container so the handler runs with the deployed function's narrow permissions (closes the \"developer admin / function narrow\" skew). Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) auto-resolves the function's execution role ARN from cdkd state (requires --from-state); (3) `--no-assume-role` explicitly opts out (forces dev creds even with --from-state). Off by default — when omitted, the developer's shell credentials are forwarded unchanged (SAM-compatible default). STS failures degrade to a warn + dev-creds fallback.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the deployed execution role: forward your ambient AWS credentials (or the --profile overlay) even when --from-state is set, and suppress the \"run with --assume-role\" hint. Distinct from omitting the flag, which still prints that hint.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub in env vars with the deployed physical IDs / attributes. Off by default — keep PR 1 warn-and-drop semantics; turn on for stacks already deployed via cdkd deploy.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localInvokeCommand));
33963
32733
  [
33964
32734
  ...commonOptions,
33965
32735
  ...appOptions,
@@ -34010,6 +32780,7 @@ function buildProgram() {
34010
32780
  } catch (err) {
34011
32781
  handleError(err);
34012
32782
  }
32783
+ setLocalCustomResourceRuntimeEnabled(actionCommand.optsWithGlobals().localCustomResources !== false, actionCommand.parent?.parent ? `${actionCommand.parent.name()} ${actionCommand.name()}` : actionCommand.name());
34013
32784
  await resolveS3ClientDefaults({ profile });
34014
32785
  });
34015
32786
  program.addCommand(createBootstrapCommand());
@@ -34050,4 +32821,4 @@ function collectVerbFlags(program) {
34050
32821
  }
34051
32822
 
34052
32823
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
34053
- //# sourceMappingURL=program-DSlYCm_d.js.map
32824
+ //# sourceMappingURL=program-BBGm88gl.js.map