@cdkd/cli 0.373.1 → 0.373.3

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 (74) hide show
  1. package/dist/{ambient-client-defaults-BLKND30a.js → ambient-client-defaults-ChOenyD2.js} +18 -4
  2. package/dist/ambient-client-defaults-ChOenyD2.js.map +1 -0
  3. package/dist/{asg-provider-DXL1CE4m.js → asg-provider-Bfinx42n.js} +8 -8
  4. package/dist/{asg-provider-DXL1CE4m.js.map → asg-provider-Bfinx42n.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{replacement-rules-BkUZIP44.js → created-resource-sink-D7iM5jwM.js} +1394 -1474
  7. package/dist/created-resource-sink-D7iM5jwM.js.map +1 -0
  8. package/dist/{custom-resource-runtime-DK4-5kRC.js → custom-resource-runtime-9fjsDVrs.js} +6 -6
  9. package/dist/{custom-resource-runtime-DK4-5kRC.js.map → custom-resource-runtime-9fjsDVrs.js.map} +1 -1
  10. package/dist/{db-associated-roles-zv71gI1O.js → db-associated-roles-Bn8HCQ2r.js} +2 -2
  11. package/dist/{db-associated-roles-zv71gI1O.js.map → db-associated-roles-Bn8HCQ2r.js.map} +1 -1
  12. package/dist/{delete-started-E38sSyUX.js → delete-started-CiTP5c3_.js} +4 -4
  13. package/dist/{delete-started-E38sSyUX.js.map → delete-started-CiTP5c3_.js.map} +1 -1
  14. package/dist/{deploy-engine-BDueF79_.js → deploy-engine-D7Iv9v8e.js} +3573 -2888
  15. package/dist/deploy-engine-D7Iv9v8e.js.map +1 -0
  16. package/dist/{ec2-termination-protection-DI-aPxET.js → ec2-termination-protection-BXy91mrW.js} +3 -3
  17. package/dist/{ec2-termination-protection-DI-aPxET.js.map → ec2-termination-protection-BXy91mrW.js.map} +1 -1
  18. package/dist/{ecr-uri-kW_K5U02.js → ecr-uri-DUDwEekn.js} +2 -2
  19. package/dist/{ecr-uri-kW_K5U02.js.map → ecr-uri-DUDwEekn.js.map} +1 -1
  20. package/dist/{emr-cluster-provider-BcqnxYsN.js → emr-cluster-provider-MokUAEGh.js} +11 -11
  21. package/dist/emr-cluster-provider-MokUAEGh.js.map +1 -0
  22. package/dist/{expected-bucket-owner-j5BCLzAB.js → expected-bucket-owner-BrzB1C4p.js} +2 -2
  23. package/dist/{expected-bucket-owner-j5BCLzAB.js.map → expected-bucket-owner-BrzB1C4p.js.map} +1 -1
  24. package/dist/{iam-role-provider-BlUbRjQo.js → iam-role-provider-CB--BYVm.js} +12 -12
  25. package/dist/{iam-role-provider-BlUbRjQo.js.map → iam-role-provider-CB--BYVm.js.map} +1 -1
  26. package/dist/{identity-read-denied-BhnkMyxk.js → identity-read-denied-CoeMBkCz.js} +5 -6
  27. package/dist/identity-read-denied-CoeMBkCz.js.map +1 -0
  28. package/dist/{image-plan-CUvO0Qe2.js → image-plan-RNp8hqc4.js} +8 -8
  29. package/dist/{image-plan-CUvO0Qe2.js.map → image-plan-RNp8hqc4.js.map} +1 -1
  30. package/dist/index.d.ts +13 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +5 -5
  33. package/dist/{logger-B673mhBe.js → logger-Bfz63gW5.js} +2 -2
  34. package/dist/{logger-B673mhBe.js.map → logger-Bfz63gW5.js.map} +1 -1
  35. package/dist/{neptune-provider-BOIjF_i3.js → neptune-provider-BFwovty1.js} +9 -9
  36. package/dist/{neptune-provider-BOIjF_i3.js.map → neptune-provider-BFwovty1.js.map} +1 -1
  37. package/dist/{program-avOxa_7W.js → program-DR3X8-7x.js} +563 -233
  38. package/dist/program-DR3X8-7x.js.map +1 -0
  39. package/dist/{provider-classes-BMrkl7zN.js → provider-classes-BNZGFwNO.js} +375 -129
  40. package/dist/provider-classes-BNZGFwNO.js.map +1 -0
  41. package/dist/{rds-provider-DD8ka8NG.js → rds-provider-evebINWq.js} +13 -13
  42. package/dist/{rds-provider-DD8ka8NG.js.map → rds-provider-evebINWq.js.map} +1 -1
  43. package/dist/{read-replica-Ddvkib9A.js → read-replica-BGoRAh10.js} +3 -3
  44. package/dist/{read-replica-Ddvkib9A.js.map → read-replica-BGoRAh10.js.map} +1 -1
  45. package/dist/{redacted-delete-address-CkcTwr-O.js → redacted-delete-address-rTL8ikg4.js} +5 -5
  46. package/dist/redacted-delete-address-rTL8ikg4.js.map +1 -0
  47. package/dist/replacement-rules-roVU6gYR.js +1967 -0
  48. package/dist/replacement-rules-roVU6gYR.js.map +1 -0
  49. package/dist/{resource-deadline-B2z0yyKo.js → resource-deadline-B4Rp-3f7.js} +2 -2
  50. package/dist/{resource-deadline-B2z0yyKo.js.map → resource-deadline-B4Rp-3f7.js.map} +1 -1
  51. package/dist/{restore-source-guard-1UD7ucv5.js → restore-source-guard-Dz_vQPiM.js} +5 -5
  52. package/dist/restore-source-guard-Dz_vQPiM.js.map +1 -0
  53. package/dist/{run-cli-Dm2l-FUd.js → run-cli-vKsR6JeT.js} +2 -2
  54. package/dist/{run-cli-Dm2l-FUd.js.map → run-cli-vKsR6JeT.js.map} +1 -1
  55. package/dist/{secret-reference-immutable-Bk60ZfqH.js → secret-reference-immutable-BF02Wobz.js} +108 -10
  56. package/dist/{secret-reference-immutable-Bk60ZfqH.js.map → secret-reference-immutable-BF02Wobz.js.map} +1 -1
  57. package/dist/{settle-own-write-members-YQxWAEvB.js → settle-own-write-members-CF-RPYMD.js} +10 -10
  58. package/dist/{settle-own-write-members-YQxWAEvB.js.map → settle-own-write-members-CF-RPYMD.js.map} +1 -1
  59. package/dist/{tag-list-C8pMq_W3.js → tag-list-DbmXev9Z.js} +4 -4
  60. package/dist/{tag-list-C8pMq_W3.js.map → tag-list-DbmXev9Z.js.map} +1 -1
  61. package/dist/{version-D2qdiEuf.js → version-CP9RYTCy.js} +2 -2
  62. package/dist/{version-D2qdiEuf.js.map → version-CP9RYTCy.js.map} +1 -1
  63. package/package.json +1 -1
  64. package/dist/ambient-client-defaults-BLKND30a.js.map +0 -1
  65. package/dist/created-resource-sink-DlVo2nqB.js +0 -1397
  66. package/dist/created-resource-sink-DlVo2nqB.js.map +0 -1
  67. package/dist/deploy-engine-BDueF79_.js.map +0 -1
  68. package/dist/emr-cluster-provider-BcqnxYsN.js.map +0 -1
  69. package/dist/identity-read-denied-BhnkMyxk.js.map +0 -1
  70. package/dist/program-avOxa_7W.js.map +0 -1
  71. package/dist/provider-classes-BMrkl7zN.js.map +0 -1
  72. package/dist/redacted-delete-address-CkcTwr-O.js.map +0 -1
  73. package/dist/replacement-rules-BkUZIP44.js.map +0 -1
  74. package/dist/restore-source-guard-1UD7ucv5.js.map +0 -1
@@ -1,7 +1,159 @@
1
- import { P as safeMsg, x as SAFE_MSG_ALTERED_CHAR } from "./version-D2qdiEuf.js";
2
- import { n as getLogger } from "./logger-B673mhBe.js";
1
+ import { A as displayStackName, M as isPlainIdent, N as plainIdentOr, P as safeMsg, S as SECRET_REF_MAX_CODE_POINTS, _ as shellQuote, d as pasteableCommand, j as isPasteableIdent, k as displaySafe, m as proseQuoted, p as plainOrDescribed, r as SHELL_ACTIVE, s as commandHole, u as isInertUnquoted, w as UNRENDERABLE, x as SAFE_MSG_ALTERED_CHAR } from "./version-CP9RYTCy.js";
2
+ import { J as getCurrentStackName, u as describeAwsFailure } from "./logger-Bfz63gW5.js";
3
+ import { B as isTransientServerError, D as markReplayMayCollide, F as isAmbiguousOutcomeError, U as isMarkedNonRetryable, V as retryClassificationText, ot as ProvisioningError, x as hasReplayMayCollide, z as isRetryableTransientError } from "./ambient-client-defaults-ChOenyD2.js";
4
+ import { a as getAssumedRoleCredentials, f as ambientRegion, i as awsEndpointOverrideUrl } from "./aws-client-defaults-DAebi99J.js";
3
5
  import { AsyncLocalStorage } from "node:async_hooks";
4
- import { isDeepStrictEqual } from "node:util";
6
+
7
+ // src/state/record-keys.ts
8
+ function injectivePairKey(first, second) {
9
+ return JSON.stringify([first, second]);
10
+ }
11
+ function injectiveKey(...parts) {
12
+ return JSON.stringify(parts);
13
+ }
14
+ function injectiveKeyPrefix(first) {
15
+ return JSON.stringify([first]).slice(0, -1) + ",";
16
+ }
17
+ function producerRecordKey(stackName, region) {
18
+ return injectivePairKey(stackName, region);
19
+ }
20
+ function producerCoordinateKey(stackName, exportOrOutputName) {
21
+ return injectivePairKey(stackName, exportOrOutputName);
22
+ }
23
+
24
+ // src/utils/pasteable-aws-profile.ts
25
+ let explicitProfile;
26
+ let emulatorCaBundle;
27
+ function setPasteableAwsCaBundle(path) {
28
+ emulatorCaBundle = path;
29
+ }
30
+ function setPasteableAwsProfile(profile) {
31
+ explicitProfile = profile;
32
+ }
33
+ function pasteableAwsProfileFlag() {
34
+ const emulator = awsEndpointOverrideUrl();
35
+ if (emulator !== void 0) {
36
+ const endpoint = `--endpoint-url ${isInertUnquoted(emulator) ? emulator : commandHole("endpoint-url")}`;
37
+ const ca = emulatorCaBundle;
38
+ if (ca === void 0) return endpoint;
39
+ return `${endpoint} --ca-bundle ${isInertUnquoted(ca) ? ca : commandHole("ca-bundle")}`;
40
+ }
41
+ if (getAssumedRoleCredentials() !== void 0) return `--profile ${commandHole("role-profile")}`;
42
+ const profile = explicitProfile;
43
+ if (profile === void 0 || profile === "") return "";
44
+ if (displaySafe(profile) !== profile || profile.startsWith("-") || SHELL_ACTIVE.test(profile)) return `--profile ${commandHole("profile")}`;
45
+ return `--profile ${shellQuote(profile)}`;
46
+ }
47
+ function withPasteableAwsProfile(literal) {
48
+ const flag = pasteableAwsProfileFlag();
49
+ if (flag === "") return literal;
50
+ return literal.replace(/(^|[\s;&|(])aws (?=[a-z]|$)/g, (_m, pre) => `${pre}aws ${flag} `);
51
+ }
52
+
53
+ // src/state/state-prefix.ts
54
+ const DEFAULT_STATE_PREFIX = "cdkd";
55
+ const CUSTOM_RESOURCE_RESPONSE_PREFIX = "custom-resource-responses";
56
+ const WAIT_CONDITION_SIGNAL_PREFIX = "wait-condition-signals";
57
+
58
+ // src/state/lock-contention-message.ts
59
+ function formatLockExpiry(expiresAt) {
60
+ if (!Number.isFinite(expiresAt)) return "expires at an unknown time";
61
+ const remainingMs = expiresAt - Date.now();
62
+ return remainingMs > 0 ? `expires in ${formatDuration(remainingMs)}` : `expired ${formatDuration(-remainingMs)} ago`;
63
+ }
64
+ const LOCK_OWNER_DESCRIBED = "a lock owner that is not a plain identifier";
65
+ const LOCK_OPERATION_DESCRIBED = "a lock operation that is not a plain identifier";
66
+ function formatLockOwner(owner) {
67
+ if (owner === "") return "an unnamed holder";
68
+ return owner.includes(",") ? LOCK_OWNER_DESCRIBED : plainIdentOr(owner, LOCK_OWNER_DESCRIBED);
69
+ }
70
+ function formatLockOperation(operation) {
71
+ return operation.includes(",") ? LOCK_OPERATION_DESCRIBED : plainIdentOr(operation, LOCK_OPERATION_DESCRIBED);
72
+ }
73
+ function formatDuration(ms) {
74
+ const seconds = Math.floor(ms / 1e3);
75
+ if (seconds < 60) return `${seconds}s`;
76
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
77
+ }
78
+ function buildForceUnlockCommand(stackName, region, recovery) {
79
+ const recoveryFlags = recoveryCommandFlags(recovery);
80
+ const built = pasteableCommand("cdkd force-unlock", region === void 0 ? [{
81
+ value: stackName,
82
+ hole: "stack",
83
+ opts: { plainIdent: true }
84
+ }] : [{
85
+ value: stackName,
86
+ hole: "stack",
87
+ opts: { plainIdent: true }
88
+ }, {
89
+ flag: "--stack-region",
90
+ value: region,
91
+ hole: "region",
92
+ opts: { plainIdent: true }
93
+ }], recoveryFlags.flags);
94
+ if (!built.exact || !recoveryFlags.exact) return "";
95
+ return built.command;
96
+ }
97
+ function recoveryCommandFlags(recovery) {
98
+ const gated = (value) => {
99
+ const v = sanitizeRecoveryValue(value);
100
+ return {
101
+ text: v.text,
102
+ exact: v.exact && isInertUnquoted(v.text)
103
+ };
104
+ };
105
+ const profile = gated(recovery?.profile);
106
+ const stateBucket = gated(recovery?.stateBucket);
107
+ const statePrefix = gated(recovery?.statePrefix);
108
+ const flags = [];
109
+ if (profile.text || !profile.exact) flags.push(profile.exact ? `--profile ${shellQuote(profile.text)}` : `--profile ${commandHole("profile")}`);
110
+ if (stateBucket.text || !stateBucket.exact) flags.push(stateBucket.exact ? `--state-bucket ${shellQuote(stateBucket.text)}` : `--state-bucket ${commandHole("bucket")}`);
111
+ const prefix = recovery?.statePrefix;
112
+ if (prefix !== void 0 && prefix !== "cdkd") flags.push(statePrefix.exact ? `--state-prefix ${shellQuote(statePrefix.text)}` : `--state-prefix ${commandHole("prefix")}`);
113
+ return {
114
+ flags,
115
+ exact: profile.exact && stateBucket.exact && statePrefix.exact
116
+ };
117
+ }
118
+ function sanitizeRecoveryValue(value) {
119
+ if (value === void 0) return {
120
+ text: "",
121
+ exact: true
122
+ };
123
+ const text = displaySafe(value);
124
+ return {
125
+ text,
126
+ exact: text === value
127
+ };
128
+ }
129
+ const UNREPRODUCIBLE_LOCK_VALUES = "the name, region, profile, state bucket or state prefix";
130
+ const UNREPRODUCIBLE_LOCK_CLAUSE = `Inspect the lock object directly: ${UNREPRODUCIBLE_LOCK_VALUES} recorded for this stack cannot be reproduced safely on a command line (changed by sanitizing, unrenderable, empty, too long, not a plain identifier, beginning with '-', which cdkd refuses rather than risk it parsing as an option, or holding whitespace or a character a shell treats specially), so no command is shown: one built from it could address a different lock or run part of it as shell.`;
131
+ function forceQuitRecoveryClause(stackName, region, recovery) {
132
+ const command = buildForceUnlockCommand(stackName, region, recovery);
133
+ return command ? ` If the next run reports a lock, run: ${command}` : ` ${UNREPRODUCIBLE_LOCK_CLAUSE}`;
134
+ }
135
+ async function buildLockContentionMessage(args) {
136
+ const { lockManager, stackName, region, subject = "stack", recovery, heldClause, suffix } = args;
137
+ let held = heldClause ?? "another cdkd process holds it";
138
+ let sawHolder = false;
139
+ try {
140
+ const info = await lockManager.getLockInfo(stackName, region);
141
+ if (info) {
142
+ const operation = info.operation ? `, operation: ${formatLockOperation(info.operation)}` : "";
143
+ const expires = formatLockExpiry(info.expiresAt);
144
+ const owner = displaySafe(info.owner);
145
+ const holder = owner ? `held by ${formatLockOwner(owner)}${operation}` : `held by an unnamed holder`;
146
+ held = `${heldClause ? `${heldClause} — ` : ""}${holder}, ${expires}`;
147
+ if (owner) sawHolder = true;
148
+ }
149
+ } catch {}
150
+ const advice = sawHolder ? `That process is still running — wait for it to finish. Only if you are certain it is gone` : `Wait for it to finish, or if you are certain no other process is active`;
151
+ const recoveryCommand = buildForceUnlockCommand(stackName, region, recovery);
152
+ const safeRegion = displaySafe(region, { asciiOnly: true }) || "<unrenderable>";
153
+ const head = `Could not acquire lock for ${subject} ${displayStackName(stackName)} (${safeRegion}) — ${held}.` + (suffix ? ` ${suffix}` : "");
154
+ if (!recoveryCommand) return `${head} ${advice}. No recovery command can be shown: ${UNREPRODUCIBLE_LOCK_VALUES} recorded for this lock cannot be reproduced safely on a command line (changed by sanitizing, unrenderable, empty, too long, not a plain identifier, beginning with '-', which cdkd refuses rather than risk it parsing as an option, or holding whitespace or a character a shell treats specially), so no command is shown: one built from it could address a different lock or run part of it as shell — inspect the lock object directly.`;
155
+ return `${head} ${advice}, run: ${recoveryCommand}`;
156
+ }
5
157
 
6
158
  // src/deployment/secret-redaction/rules.ts
7
159
  const MIN_NEEDLE_LENGTH = 4;
@@ -969,7 +1121,7 @@ function placements(anchors, bag, leadingGap, trailingGap, side) {
969
1121
  function isNoValue(node) {
970
1122
  return isPlainObject(node) && Object.keys(node).length === 1 && node["Ref"] === "AWS::NoValue";
971
1123
  }
972
- const MAX_DEPTH = 16;
1124
+ const MAX_DEPTH$2 = 16;
973
1125
  const GAP = [{ gap: true }];
974
1126
  const MAX_SEGMENTS = 512;
975
1127
  const MAX_VISITS = 4096;
@@ -977,7 +1129,7 @@ let visits = 0;
977
1129
  function renderSegments(node, depth) {
978
1130
  if (depth === 0) visits = 0;
979
1131
  if (++visits > MAX_VISITS) return void 0;
980
- if (depth > MAX_DEPTH) return void 0;
1132
+ if (depth > MAX_DEPTH$2) return void 0;
981
1133
  if (typeof node === "string") return stringSegments(node);
982
1134
  if (typeof node === "number" || typeof node === "boolean") return [{ text: String(node) }];
983
1135
  if (!isPlainObject(node) || Object.keys(node).length !== 1) return GAP;
@@ -1410,11 +1562,11 @@ function substitutionSpelling(resolvedValue, sourceLeaf, secrets, name) {
1410
1562
  secrets
1411
1563
  }));
1412
1564
  const spelled = placed === TAINTED_WITHOUT_SPAN ? "***" : placed;
1413
- if (spelled === "***") {
1565
+ if (isMaskLeaf(spelled)) {
1414
1566
  recordDerivedMaskOnlyValue(secrets, resolvedValue);
1415
1567
  markAttributionRefusedParameter(secrets, name, "masked");
1416
1568
  }
1417
- return spelled === void 0 || spelled === "***" || spelled === resolvedValue ? void 0 : spelled;
1569
+ return spelled === void 0 || isMaskLeaf(spelled) || spelled === resolvedValue ? void 0 : spelled;
1418
1570
  }
1419
1571
  function holdsConsumedSubFloorSecret(value, sourceLeaf, secrets) {
1420
1572
  const tokens = typeof sourceLeaf === "string" ? dynamicReferenceTokens(sourceLeaf) : isPlainObject(sourceLeaf) ? [...referencesConsumedBy(secrets, sourceLeaf)] : [];
@@ -1428,7 +1580,7 @@ function holdsConsumedSubFloorSecret(value, sourceLeaf, secrets) {
1428
1580
  function holdsSubFloorSecret(value, secrets) {
1429
1581
  for (const [plaintext, expression] of secrets) {
1430
1582
  if (plaintext === "" || plaintext.length >= 4) continue;
1431
- if (expression !== "***" && value.includes(plaintext)) return true;
1583
+ if (!isMaskLeaf(expression) && value.includes(plaintext)) return true;
1432
1584
  }
1433
1585
  return false;
1434
1586
  }
@@ -1849,7 +2001,7 @@ const plainSplit = (text, delimiter) => text.split(delimiter);
1849
2001
  function evaluatePureRead(node, bind, pseudo, split, choose, depth = 0) {
1850
2002
  if (depth > MAX_REREAD_DEPTH) return void 0;
1851
2003
  const evaluate = (child) => evaluatePureRead(child, bind, pseudo, split, choose, depth + 1);
1852
- if (typeof node === "string") return node.includes("{{resolve:") ? void 0 : { value: node };
2004
+ if (typeof node === "string") return mentionsDynamicReference(node) ? void 0 : { value: node };
1853
2005
  if (Array.isArray(node)) {
1854
2006
  const out = [];
1855
2007
  for (const element of node) {
@@ -1900,7 +2052,7 @@ function evaluatePureRead(node, bind, pseudo, split, choose, depth = 0) {
1900
2052
  }
1901
2053
  function evaluatePureSub(args, bind, pseudo, evaluate) {
1902
2054
  const [text, variables] = typeof args === "string" ? [args, {}] : Array.isArray(args) && args.length === 2 ? [args[0], args[1]] : [void 0, void 0];
1903
- if (typeof text !== "string" || text.includes("{{resolve:") || !isPlainObject(variables)) return;
2055
+ if (typeof text !== "string" || mentionsDynamicReference(text) || !isPlainObject(variables)) return;
1904
2056
  const bound = /* @__PURE__ */ new Map();
1905
2057
  for (const [name, variable] of Object.entries(variables)) {
1906
2058
  const evaluated = evaluate(variable);
@@ -1986,7 +2138,7 @@ function rereadUnder(source, bind, parentSecrets, choose) {
1986
2138
  }
1987
2139
  function namesParameterOnBranches(node, choose, isParameter, depth = 0) {
1988
2140
  if (depth > MAX_REREAD_DEPTH) return true;
1989
- if (typeof node === "string") return node.includes("{{resolve:");
2141
+ if (typeof node === "string") return mentionsDynamicReference(node);
1990
2142
  if (Array.isArray(node)) return node.some((element) => namesParameterOnBranches(element, choose, isParameter, depth + 1));
1991
2143
  if (!isPlainObject(node)) return false;
1992
2144
  if (Object.hasOwn(node, "Fn::If")) {
@@ -2664,8 +2816,8 @@ function isUncertifiedBaselineMaskPosition(properties, path) {
2664
2816
  if (cursor === null || typeof cursor !== "object" || Array.isArray(cursor) || !Object.hasOwn(cursor, segment)) return false;
2665
2817
  cursor = cursor[segment];
2666
2818
  }
2667
- if (typeof cursor === "string") return isDynamicReferenceString(cursor) && cursor !== "***";
2668
- return subtreeHasDynamicReference(cursor) && !carriesSecretMask(cursor);
2819
+ if (typeof cursor === "string") return isDynamicReferenceString(cursor) && !isMaskLeaf(cursor);
2820
+ return subtreeHasDynamicReference(cursor) && !holdsMaskLeaf(cursor);
2669
2821
  }
2670
2822
 
2671
2823
  // src/deployment/secret-redaction/redact-path.ts
@@ -3222,7 +3374,7 @@ function embeddedPhysicalNameRewrites(secrets, legacySecrets = secrets) {
3222
3374
  provenance: "value-scan",
3223
3375
  secrets: legacySecrets
3224
3376
  });
3225
- if (typeof legacy === "string" && legacy !== name && legacy.includes("{{resolve:") && !isSingleDynamicReferenceToken(legacy) && !legacy.includes("***")) pairs.push([legacy, name]);
3377
+ if (typeof legacy === "string" && legacy !== name && mentionsDynamicReference(legacy) && !isSingleDynamicReferenceToken(legacy) && !mentionsMask(legacy)) pairs.push([legacy, name]);
3226
3378
  }
3227
3379
  });
3228
3380
  return pairs;
@@ -4551,1561 +4703,1329 @@ function carryRedactionMarks(from, to) {
4551
4703
  return to;
4552
4704
  }
4553
4705
 
4554
- // src/deployment/secret-redaction/unresolved-token-frame.ts
4555
- function liveMatchesUnresolvedTokenFrame(send, live, unresolvedTokens, secrets) {
4556
- const wildcards = dynamicReferenceSpans(send).filter((span) => unresolvedTokens.has(send.slice(span.start, span.end)));
4557
- if (wildcards.length === 0) return false;
4558
- if (wildcardOverlapsResolvedPlaintext(send, wildcards, secrets)) return false;
4559
- const literals = [];
4560
- let at = 0;
4561
- for (const span of wildcards) {
4562
- literals.push(send.slice(at, span.start));
4563
- at = span.end;
4564
- }
4565
- literals.push(send.slice(at));
4566
- const first = literals[0];
4567
- const last = literals[literals.length - 1];
4568
- if (live.length < first.length + last.length) return false;
4569
- if (!live.startsWith(first) || !live.endsWith(last)) return false;
4570
- let pos = first.length;
4571
- const end = live.length - last.length;
4572
- for (let i = 1; i < literals.length - 1; i++) {
4573
- const literal = literals[i];
4574
- const found = live.indexOf(literal, pos);
4575
- if (found < 0 || found + literal.length > end) return false;
4576
- pos = found + literal.length;
4577
- }
4578
- return true;
4706
+ // src/deployment/secret-redaction/recorded-secrecy.ts
4707
+ function isMaskLeaf(value) {
4708
+ return value === "***";
4579
4709
  }
4580
- function wildcardOverlapsResolvedPlaintext(send, wildcards, secrets) {
4581
- for (const plaintext of secrets.keys()) {
4582
- if (plaintext === "") continue;
4583
- for (let from = send.indexOf(plaintext); from >= 0; from = send.indexOf(plaintext, from + 1)) {
4584
- const to = from + plaintext.length;
4585
- if (wildcards.some((span) => span.start < to && from < span.end)) return true;
4586
- }
4710
+ function holdsMaskLeaf(value) {
4711
+ return carriesSecretMask(value);
4712
+ }
4713
+ function mentionsMask(value) {
4714
+ if (typeof value === "string") return value.includes("***");
4715
+ return (JSON.stringify(value) ?? "").includes("***");
4716
+ }
4717
+ function mentionsMaskedIdSegment(value) {
4718
+ return (JSON.stringify(value) ?? "").includes("****");
4719
+ }
4720
+ const DYNAMIC_REFERENCE_OPENER = "{{resolve:";
4721
+ function mentionsDynamicReference(text) {
4722
+ return text.includes(DYNAMIC_REFERENCE_OPENER);
4723
+ }
4724
+ function valueMentionsDynamicReference(value) {
4725
+ return mentionsDynamicReference(JSON.stringify(value) ?? "");
4726
+ }
4727
+ function mentionsDynamicReferenceTo(text, service) {
4728
+ return text.includes(`${DYNAMIC_REFERENCE_OPENER}${service}:`);
4729
+ }
4730
+ function opensDynamicReferenceTo(text, service) {
4731
+ return text.startsWith(`${DYNAMIC_REFERENCE_OPENER}${service}:`);
4732
+ }
4733
+ function countDynamicReferenceOpenings(text, service) {
4734
+ const openers = dynamicReferenceOpeners(text);
4735
+ return service === void 0 ? openers.length : openers.filter(({ rest }) => rest.startsWith(`${service}:`)).length;
4736
+ }
4737
+ function dynamicReferenceOpeners(text) {
4738
+ const out = [];
4739
+ let at = text.indexOf(DYNAMIC_REFERENCE_OPENER);
4740
+ while (at >= 0) {
4741
+ out.push({
4742
+ at,
4743
+ rest: text.slice(at + 10)
4744
+ });
4745
+ at = text.indexOf(DYNAMIC_REFERENCE_OPENER, at + 10);
4587
4746
  }
4588
- return false;
4747
+ return out;
4748
+ }
4749
+ function usableRecordedName(value) {
4750
+ if (typeof value !== "string" || value === "" || isMaskLeaf(value)) return void 0;
4751
+ return mentionsDynamicReference(value) ? void 0 : value;
4752
+ }
4753
+ function dynamicReferenceBody(token, service) {
4754
+ const prefix = `${DYNAMIC_REFERENCE_OPENER}${service}:`;
4755
+ if (!token.startsWith(prefix) || !token.endsWith("}}")) return void 0;
4756
+ return token.slice(prefix.length, -2);
4757
+ }
4758
+ function isMaskRun(text) {
4759
+ return /^\*{3,}$/.test(text);
4760
+ }
4761
+ function recordedSecrecyOf(record, at) {
4762
+ if (record === void 0 || record === null || typeof record !== "object") return "unknown";
4763
+ const bag = record[at.field];
4764
+ if (bag === null || typeof bag !== "object" || Array.isArray(bag)) return "unknown";
4765
+ const value = Object.hasOwn(bag, at.key) ? bag[at.key] : void 0;
4766
+ if (mentionsMask(value) || valueMentionsDynamicReference(value)) return "masked";
4767
+ if (at.field === "attributes") {
4768
+ const names = record.noEchoAttributeNames;
4769
+ return Array.isArray(names) && names.includes(at.key) ? "masked" : "clear";
4770
+ }
4771
+ const leaves = record.noEchoLeaves;
4772
+ if (Array.isArray(leaves) && leaves.some((c) => Array.isArray(c) && c[0] === at.key)) return "masked";
4773
+ const fingerprints = record.maskedPropertyFingerprints;
4774
+ if (fingerprints !== null && typeof fingerprints === "object" && !Array.isArray(fingerprints) && Object.hasOwn(fingerprints, at.key)) return "masked";
4775
+ return "clear";
4589
4776
  }
4590
4777
 
4591
- // src/deployment/secret-redaction/noecho-leaves.ts
4592
- const SUB_VARIABLE = /\$\{([^}!][^}]*)\}/g;
4593
- function intrinsicKeyOf(node) {
4594
- const keys = Object.keys(node);
4595
- if (keys.length !== 1) return void 0;
4596
- const key = keys[0];
4597
- return key === "Ref" || key.startsWith("Fn::") ? key : void 0;
4598
- }
4599
- function conditionVerdict(sources, name) {
4600
- if (typeof name !== "string" || sources.conditions === void 0) return void 0;
4601
- return Object.hasOwn(sources.conditions, name) ? sources.conditions[name] : void 0;
4602
- }
4603
- function getAttReadsNoEcho(argument, sources) {
4604
- if (sources.attributeIsNoEcho === void 0) return false;
4605
- let target;
4606
- let attribute;
4607
- if (typeof argument === "string") {
4608
- const dot = argument.indexOf(".");
4609
- if (dot <= 0) return false;
4610
- target = argument.slice(0, dot);
4611
- attribute = argument.slice(dot + 1);
4612
- } else if (Array.isArray(argument) && argument.length === 2) [target, attribute] = argument;
4613
- else return false;
4614
- if (typeof target !== "string") return false;
4615
- if (typeof attribute !== "string") return readsNoEchoSource(attribute, sources);
4616
- return sources.attributeIsNoEcho(target, attribute);
4617
- }
4618
- function subStringReadsNoEcho(text, variables, sources) {
4619
- for (const match of text.matchAll(SUB_VARIABLE)) {
4620
- const name = match[1].trim();
4621
- if (variables !== void 0 && Object.hasOwn(variables, name)) continue;
4622
- if (sources.parameters.has(name)) return true;
4623
- const dot = name.indexOf(".");
4624
- if (dot > 0 && sources.attributeIsNoEcho?.(name.slice(0, dot), name.slice(dot + 1)) === true) return true;
4778
+ // src/provisioning/auxiliary-failure.ts
4779
+ const AUXILIARY_LOGICAL_ID_SUFFIX = "/auxiliary";
4780
+ const MAX_DEPTH$1 = 5;
4781
+ function auxiliaryLogicalId(ownerLogicalId) {
4782
+ return `${ownerLogicalId}${AUXILIARY_LOGICAL_ID_SUFFIX}`;
4783
+ }
4784
+ const RETRY_AUXILIARY_OWNER = "withRetry";
4785
+ function isAuxiliaryMarkOf(link, ownerLogicalId) {
4786
+ try {
4787
+ if (typeof link !== "object" && typeof link !== "function" || link === null) return false;
4788
+ const own = Object.getOwnPropertyDescriptor(link, "logicalId");
4789
+ return isAuxiliaryMark(own) && own?.value === auxiliaryLogicalId(ownerLogicalId);
4790
+ } catch {
4791
+ return false;
4625
4792
  }
4626
- return false;
4627
4793
  }
4628
- function readsNoEchoSource(node, sources) {
4629
- const seen = /* @__PURE__ */ new Set();
4630
- const walk = (value) => {
4631
- if (value === null || typeof value !== "object") return false;
4632
- if (seen.has(value)) return false;
4633
- seen.add(value);
4634
- if (Array.isArray(value)) return value.some(walk);
4635
- const record = value;
4636
- const intrinsic = intrinsicKeyOf(record);
4637
- if (intrinsic === "Ref") return typeof record["Ref"] === "string" && sources.parameters.has(record["Ref"]);
4638
- if (intrinsic === "Fn::GetAtt") return getAttReadsNoEcho(record["Fn::GetAtt"], sources);
4639
- if (intrinsic === "Fn::Sub") {
4640
- const argument = record["Fn::Sub"];
4641
- if (typeof argument === "string") return subStringReadsNoEcho(argument, void 0, sources);
4642
- if (Array.isArray(argument)) {
4643
- const [text, variables] = argument;
4644
- const vars = isPlainObject(variables) ? variables : void 0;
4645
- if (typeof text === "string" && subStringReadsNoEcho(text, vars, sources)) return true;
4646
- return vars !== void 0 && Object.values(vars).some(walk);
4647
- }
4648
- return walk(argument);
4649
- }
4650
- if (intrinsic === "Fn::If") {
4651
- const argument = record["Fn::If"];
4652
- if (Array.isArray(argument) && argument.length === 3) {
4653
- const verdict = conditionVerdict(sources, argument[0]);
4654
- if (verdict !== void 0) return walk(verdict ? argument[1] : argument[2]);
4655
- return walk(argument[1]) || walk(argument[2]);
4656
- }
4657
- return walk(argument);
4794
+ function isAuxiliaryMark(descriptor) {
4795
+ return descriptor !== void 0 && descriptor.enumerable === false && descriptor.writable === false && typeof descriptor.value === "string" && descriptor.value.endsWith(AUXILIARY_LOGICAL_ID_SUFFIX);
4796
+ }
4797
+ function isAuxiliaryFailure(error) {
4798
+ try {
4799
+ let current = error;
4800
+ for (let depth = 0; depth < MAX_DEPTH$1 && typeof current === "object" && current !== null; depth++) {
4801
+ if (isAuxiliaryMark(Object.getOwnPropertyDescriptor(current, "logicalId"))) return true;
4802
+ current = current.cause;
4658
4803
  }
4659
- return Object.values(record).some(walk);
4804
+ } catch {}
4805
+ return false;
4806
+ }
4807
+ const CREATED_BEFORE_FAILURE = Symbol.for("cdkd.createdBeforeFailure");
4808
+ function markCreatedBeforeFailure(error, ownerLogicalId, resourceType, physicalId, createdResourceIdentity) {
4809
+ try {
4810
+ if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
4811
+ if (physicalId === "") return error;
4812
+ Object.defineProperty(error, CREATED_BEFORE_FAILURE, {
4813
+ value: Object.freeze({
4814
+ logicalId: ownerLogicalId,
4815
+ resourceType,
4816
+ physicalId,
4817
+ ...typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" && { createdResourceIdentity }
4818
+ }),
4819
+ enumerable: false,
4820
+ writable: false,
4821
+ configurable: true
4822
+ });
4823
+ } catch {}
4824
+ return error;
4825
+ }
4826
+ function createdMarkOn(link) {
4827
+ const value = link[CREATED_BEFORE_FAILURE];
4828
+ if (typeof value !== "object" || value === null) return void 0;
4829
+ const { logicalId, resourceType, physicalId, createdResourceIdentity } = value;
4830
+ if (typeof logicalId !== "string" || typeof resourceType !== "string" || typeof physicalId !== "string" || physicalId === "") return;
4831
+ return typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" ? {
4832
+ logicalId,
4833
+ resourceType,
4834
+ physicalId,
4835
+ createdResourceIdentity
4836
+ } : {
4837
+ logicalId,
4838
+ resourceType,
4839
+ physicalId
4660
4840
  };
4661
- return walk(node);
4662
4841
  }
4663
- function literalIndex(index) {
4664
- if (typeof index === "number" && Number.isInteger(index)) return index;
4665
- if (typeof index === "string" && /^\d+$/.test(index)) return Number(index);
4842
+ function createdBeforeFailure(error, logicalId, resourceType) {
4843
+ return anchoredCreatedMark(error, logicalId, resourceType)?.physicalId;
4666
4844
  }
4667
- function noEchoCoordinatesOf(template, resolved, sources, onCoordinate) {
4668
- const coordinates = [];
4669
- const push = (path, node) => {
4670
- coordinates.push(path);
4671
- onCoordinate?.(path, node);
4672
- };
4673
- const ancestors = /* @__PURE__ */ new Set();
4674
- const parametersOnly = {
4675
- parameters: sources.parameters,
4676
- ...sources.conditions !== void 0 && { conditions: sources.conditions }
4677
- };
4678
- const isBareDeclaredGetAtt = (node) => isPlainObject(node) && intrinsicKeyOf(node) === "Fn::GetAtt" && getAttReadsNoEcho(node["Fn::GetAtt"], sources);
4679
- const walk = (source, value, path) => {
4680
- if (value === void 0) return;
4681
- if (source === null || typeof source !== "object") return;
4682
- if (ancestors.has(source)) return;
4683
- ancestors.add(source);
4684
- try {
4685
- if (Array.isArray(source)) {
4686
- if (!readsNoEchoSource(source, sources)) return;
4687
- if (Array.isArray(value) && value.length === source.length) source.forEach((item, index) => walk(item, value[index], [...path, index]));
4688
- else if (readsNoEchoSource(source, parametersOnly) || source.some(isBareDeclaredGetAtt)) push(path, source);
4689
- return;
4690
- }
4691
- const record = source;
4692
- const intrinsic = intrinsicKeyOf(record);
4693
- if (intrinsic === void 0) {
4694
- if (!isPlainObject(value)) {
4695
- if (readsNoEchoSource(record, parametersOnly)) push(path, source);
4696
- return;
4697
- }
4698
- for (const [key, child] of Object.entries(record)) if (Object.hasOwn(value, key)) walk(child, value[key], [...path, key]);
4699
- return;
4700
- }
4701
- if (intrinsic === "Fn::If") {
4702
- const argument = record["Fn::If"];
4703
- if (Array.isArray(argument) && argument.length === 3) {
4704
- const verdict = conditionVerdict(sources, argument[0]);
4705
- if (verdict !== void 0) {
4706
- walk(verdict ? argument[1] : argument[2], value, path);
4707
- return;
4708
- }
4709
- if (isBareDeclaredGetAtt(argument[1]) || isBareDeclaredGetAtt(argument[2])) {
4710
- push(path, source);
4711
- return;
4712
- }
4713
- }
4714
- }
4715
- if (intrinsic === "Fn::Select") {
4716
- const argument = record["Fn::Select"];
4717
- if (Array.isArray(argument) && argument.length === 2 && Array.isArray(argument[1])) {
4718
- const index = literalIndex(argument[0]);
4719
- const list = argument[1];
4720
- if (index !== void 0 && index < list.length) {
4721
- walk(list[index], value, path);
4722
- return;
4723
- }
4724
- }
4725
- }
4726
- if (intrinsic === "Fn::GetAtt") {
4727
- if (getAttReadsNoEcho(record["Fn::GetAtt"], sources)) push(path, source);
4728
- return;
4729
- }
4730
- if (readsNoEchoSource(record, parametersOnly)) push(path, source);
4731
- } finally {
4732
- ancestors.delete(source);
4733
- }
4734
- };
4735
- walk(template, resolved, []);
4736
- return coordinates;
4737
- }
4738
- function noEchoParameterNodesAt(templateProperties, shape, noEchoParameters, conditions) {
4739
- const nodes = /* @__PURE__ */ new Map();
4740
- noEchoCoordinatesOf(templateProperties ?? {}, shape, {
4741
- parameters: noEchoParameters,
4742
- ...conditions !== void 0 && { conditions }
4743
- }, (coordinate, node) => nodes.set(canonicalJson(coordinate), {
4744
- coordinate,
4745
- node
4746
- }));
4747
- return nodes;
4748
- }
4749
- function recordedNoEchoValuesOf(templateProperties, record, noEchoParameterNames, conditions) {
4750
- const bag = /* @__PURE__ */ new Map();
4751
- const properties = record?.properties;
4752
- if (properties === null || typeof properties !== "object") return bag;
4753
- const coordinates = /* @__PURE__ */ new Map();
4754
- if (noEchoParameterNames.size > 0 && templateProperties !== void 0) for (const [key, { coordinate }] of noEchoParameterNodesAt(templateProperties, properties, noEchoParameterNames, conditions)) coordinates.set(key, coordinate);
4755
- for (const coordinate of noEchoLeavesOf(record ?? {}) ?? []) coordinates.set(canonicalJson(coordinate), coordinate);
4756
- const recordLeaf = (leaf) => {
4757
- if (typeof leaf === "string") {
4758
- if (leaf === "***" || leaf.includes("{{resolve:")) return;
4759
- recordLogOnlyValue(bag, leaf);
4760
- } else if (typeof leaf === "number") recordLogOnlyValue(bag, String(leaf));
4761
- };
4762
- const seen = /* @__PURE__ */ new Set();
4763
- const walk = (value) => {
4764
- if (value === null || typeof value !== "object") {
4765
- recordLeaf(value);
4766
- return;
4845
+ function createdResourceIdentityBeforeFailure(error, logicalId, resourceType) {
4846
+ return anchoredCreatedMark(error, logicalId, resourceType)?.createdResourceIdentity;
4847
+ }
4848
+ function anchoredCreatedMark(error, logicalId, resourceType) {
4849
+ try {
4850
+ let current = error;
4851
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
4852
+ const mark = createdMarkOn(current);
4853
+ if (mark) return mark.logicalId === logicalId && mark.resourceType === resourceType ? mark : void 0;
4854
+ const own = Object.getOwnPropertyDescriptor(current, "logicalId");
4855
+ if (typeof own?.value === "string" && own.value !== logicalId && !isAuxiliaryMarkOf(current, logicalId)) return;
4856
+ current = current.cause;
4767
4857
  }
4768
- if (seen.has(value)) return;
4769
- seen.add(value);
4770
- for (const child of Object.values(value)) walk(child);
4771
- };
4772
- for (const coordinate of coordinates.values()) walk(valueAtCoordinate(properties, coordinate));
4773
- return bag;
4858
+ } catch {}
4774
4859
  }
4775
- function maskWholeValue(value) {
4776
- if (value === null || value === void 0) return value;
4777
- if (typeof value === "string" && isSingleDynamicReferenceToken(value)) return value;
4778
- if (Array.isArray(value)) return value.map(maskWholeValue);
4779
- if (isPlainObject(value)) {
4780
- const out = {};
4781
- for (const [key, child] of Object.entries(value)) Object.defineProperty(out, key, {
4782
- value: maskWholeValue(child),
4783
- enumerable: true,
4784
- writable: true,
4785
- configurable: true
4786
- });
4787
- return out;
4788
- }
4789
- return "***";
4860
+ function clearCreatedBeforeFailure(error) {
4861
+ try {
4862
+ let current = error;
4863
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
4864
+ if (Object.getOwnPropertyDescriptor(current, CREATED_BEFORE_FAILURE)?.configurable) delete current[CREATED_BEFORE_FAILURE];
4865
+ current = current.cause;
4866
+ }
4867
+ } catch {}
4868
+ return error;
4790
4869
  }
4791
- function readAt(bag, coordinate) {
4792
- let node = bag;
4793
- for (const segment of coordinate) {
4794
- if (typeof segment === "number") {
4795
- if (!Array.isArray(node) || segment >= node.length) return {
4796
- found: false,
4797
- value: void 0
4798
- };
4799
- node = node[segment];
4800
- continue;
4870
+ function hasCreatedBeforeFailure(error) {
4871
+ try {
4872
+ let current = error;
4873
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
4874
+ if (createdMarkOn(current)) return true;
4875
+ current = current.cause;
4801
4876
  }
4802
- if (!isPlainObject(node) || !Object.hasOwn(node, segment)) return {
4803
- found: false,
4804
- value: void 0
4805
- };
4806
- node = node[segment];
4877
+ } catch {}
4878
+ return false;
4879
+ }
4880
+ function firstCreatedMark(error) {
4881
+ let current = error;
4882
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
4883
+ const mark = createdMarkOn(current);
4884
+ if (mark) return mark;
4885
+ current = current.cause;
4807
4886
  }
4808
- return {
4809
- found: true,
4810
- value: node
4811
- };
4812
4887
  }
4813
- function valueAtCoordinate(bag, coordinate) {
4814
- return readAt(bag, coordinate).value;
4888
+ const SUPERSEDES_EARLIER_CREATE = Symbol.for("cdkd.supersedesEarlierCreate");
4889
+ function markSupersedesEarlierCreate(error) {
4890
+ try {
4891
+ if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
4892
+ Object.defineProperty(error, SUPERSEDES_EARLIER_CREATE, {
4893
+ value: true,
4894
+ enumerable: false,
4895
+ writable: false,
4896
+ configurable: true
4897
+ });
4898
+ } catch {}
4899
+ return error;
4815
4900
  }
4816
- function isWhollyMask(value) {
4817
- if (value === "***") return true;
4818
- if (Array.isArray(value)) return value.length > 0 && value.every(isWhollyMask);
4819
- if (value !== null && typeof value === "object") {
4820
- const children = Object.values(value);
4821
- return children.length > 0 && children.every(isWhollyMask);
4901
+ function supersedesEarlierCreate(error) {
4902
+ let current = error;
4903
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
4904
+ if (current[SUPERSEDES_EARLIER_CREATE] === true) return true;
4905
+ current = current.cause;
4822
4906
  }
4823
4907
  return false;
4824
4908
  }
4825
- function isStaleNoEchoLeaf(recorded, today, coordinate) {
4826
- if (!isWhollyMask(valueAtCoordinate(recorded, coordinate))) return false;
4827
- const value = valueAtCoordinate(today, coordinate);
4828
- return value !== void 0 && !carriesSecretMask(value);
4829
- }
4830
- function cloneContainer(node) {
4831
- if (Array.isArray(node)) return [...node];
4832
- if (isPlainObject(node)) return { ...node };
4833
- return node;
4834
- }
4835
- function maskAtCoordinates(bag, coordinates) {
4836
- if (coordinates.length === 0) return bag;
4837
- let root = bag;
4838
- for (const coordinate of coordinates) {
4839
- if (!readAt(root, coordinate).found) continue;
4840
- if (coordinate.length === 0) {
4841
- root = maskWholeValue(root);
4842
- continue;
4843
- }
4844
- root = cloneContainer(root);
4845
- let node = root;
4846
- for (let i = 0; i < coordinate.length - 1; i++) {
4847
- const segment = coordinate[i];
4848
- const next = cloneContainer(node[segment]);
4849
- node[segment] = next;
4850
- node = next;
4851
- }
4852
- const last = coordinate[coordinate.length - 1];
4853
- node[last] = maskWholeValue(node[last]);
4909
+ function replayMadeAnotherResource(earlier, later) {
4910
+ try {
4911
+ const before = firstCreatedMark(earlier);
4912
+ const after = firstCreatedMark(later);
4913
+ if (before === void 0 || after === void 0 || before.logicalId !== after.logicalId || before.resourceType !== after.resourceType || supersedesEarlierCreate(later)) return false;
4914
+ const members = (id) => id.split(",").filter((member) => member !== "");
4915
+ const earlierMembers = new Set(members(before.physicalId));
4916
+ return !members(after.physicalId).some((member) => earlierMembers.has(member));
4917
+ } catch {
4918
+ return false;
4854
4919
  }
4855
- return root;
4856
4920
  }
4857
- function replaceAtCoordinates(bag, entries) {
4858
- let root = bag;
4859
- for (const { coordinate, value } of entries) {
4860
- if (!readAt(root, coordinate).found) continue;
4861
- if (coordinate.length === 0) {
4862
- root = value;
4863
- continue;
4864
- }
4865
- root = cloneContainer(root);
4866
- let node = root;
4867
- for (let i = 0; i <= coordinate.length - 1; i++) {
4868
- const segment = coordinate[i];
4869
- const next = i === coordinate.length - 1 ? value : cloneContainer(node[segment]);
4870
- if (typeof segment === "number") node[segment] = next;
4871
- else Object.defineProperty(node, segment, {
4872
- value: next,
4873
- enumerable: true,
4874
- writable: true,
4875
- configurable: true
4876
- });
4877
- node = next;
4878
- }
4879
- }
4880
- return root;
4881
- }
4882
- function maskReadbackAtCoordinates(readback, properties, coordinates) {
4883
- let result = readback;
4884
- for (const coordinate of coordinates) {
4885
- const target = readbackPathFor(result, properties, coordinate);
4886
- if (target !== void 0) result = maskAtCoordinates(result, [target]);
4887
- }
4888
- return result;
4889
- }
4890
- function readbackPathFor(readback, properties, coordinate) {
4891
- const path = [];
4892
- let live = readback;
4893
- let desired = properties;
4894
- for (const segment of coordinate) {
4895
- if (typeof segment === "number") {
4896
- if (!Array.isArray(live)) return path.length === 0 ? void 0 : path;
4897
- const key = Array.isArray(desired) ? identityKeyFor(live, desired) : void 0;
4898
- const element = Array.isArray(desired) ? desired[segment] : void 0;
4899
- if (key === void 0 || !isPlainObject(element)) return path;
4900
- const identity = element[key];
4901
- const index = live.findIndex((item) => isPlainObject(item) && item[key] === identity);
4902
- if (index < 0) return path;
4903
- path.push(index);
4904
- live = live[index];
4905
- desired = element;
4906
- continue;
4921
+ function unionOfSharedMembers(earlier, later) {
4922
+ if (earlier.logicalId !== later.logicalId || earlier.resourceType !== later.resourceType) return;
4923
+ const members = (id) => id.split(",").filter((member) => member !== "");
4924
+ const laterMembers = members(later.physicalId);
4925
+ const earlierMembers = members(earlier.physicalId);
4926
+ if (!earlierMembers.some((member) => laterMembers.includes(member))) return void 0;
4927
+ const missing = earlierMembers.filter((member) => !laterMembers.includes(member));
4928
+ return missing.length === 0 ? void 0 : [...laterMembers, ...missing].join(",");
4929
+ }
4930
+ function carryCreatedBeforeFailure(from, to) {
4931
+ try {
4932
+ if (typeof to !== "object" || to === null) return to;
4933
+ let current = from;
4934
+ let mark;
4935
+ for (let depth = 0; depth < 10 && typeof current === "object" && current !== null && !mark; depth++) {
4936
+ mark = createdMarkOn(current);
4937
+ current = current.cause;
4938
+ }
4939
+ if (!mark) return to;
4940
+ let probe = to;
4941
+ for (let depth = 0; depth < 10 && typeof probe === "object" && probe !== null; depth++) {
4942
+ const own = createdMarkOn(probe);
4943
+ if (own) {
4944
+ const union = unionOfSharedMembers(mark, own);
4945
+ if (union !== void 0) markCreatedBeforeFailure(probe, own.logicalId, own.resourceType, union, own.createdResourceIdentity);
4946
+ return to;
4947
+ }
4948
+ probe = probe.cause;
4907
4949
  }
4908
- if (!isPlainObject(live)) return path.length === 0 ? void 0 : path;
4909
- if (!Object.hasOwn(live, segment)) return void 0;
4910
- path.push(segment);
4911
- live = live[segment];
4912
- desired = isPlainObject(desired) ? desired[segment] : void 0;
4913
- }
4914
- return path;
4915
- }
4916
- function canonicalCoordinates(coordinates) {
4917
- const keyed = /* @__PURE__ */ new Map();
4918
- for (const coordinate of coordinates) keyed.set(JSON.stringify(coordinate), [...coordinate]);
4919
- const all = [...keyed.values()];
4920
- const covered = (inner) => all.some((outer) => outer.length < inner.length && outer.every((segment, i) => segment === inner[i]));
4921
- return all.filter((coordinate) => !covered(coordinate)).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
4922
- }
4923
- function noEchoLeavesOf(record) {
4924
- const field = record.noEchoLeaves;
4925
- if (!Array.isArray(field)) return void 0;
4926
- const out = [];
4927
- for (const entry of field) {
4928
- if (!Array.isArray(entry)) return void 0;
4929
- if (!entry.every((s) => typeof s === "string" || typeof s === "number" && Number.isInteger(s))) return void 0;
4930
- out.push(entry);
4950
+ return markCreatedBeforeFailure(to, mark.logicalId, mark.resourceType, mark.physicalId, mark.createdResourceIdentity);
4951
+ } catch {
4952
+ return to;
4931
4953
  }
4932
- return out;
4933
4954
  }
4934
- function isMarkedCoordinate(coordinate, marked) {
4935
- return marked.some((outer) => outer.length <= coordinate.length && outer.every((segment, i) => segment === coordinate[i]));
4936
- }
4937
- function witnessNormalize(stored, today, v11) {
4938
- const confirmed = [];
4939
- const differing = [];
4940
- const walk = (s, t, v, path) => {
4941
- if (v !== "***" && containsMask(v) && (Array.isArray(v) ? !Array.isArray(s) || s.length !== v.length : isPlainObject(v) ? !isPlainObject(s) : false)) {
4942
- if (s === void 0 || containsMask(s)) return s;
4943
- if (jsonEqual(s, t)) {
4944
- confirmed.push(path);
4945
- return v;
4955
+ function markAuxiliaryFailure(error, ownerLogicalId) {
4956
+ try {
4957
+ let current = error;
4958
+ for (let depth = 0; depth < MAX_DEPTH$1 && typeof current === "object" && current !== null; depth++) {
4959
+ const own = Object.getOwnPropertyDescriptor(current, "logicalId");
4960
+ if (typeof own?.value === "string") {
4961
+ if (isAuxiliaryMark(own)) return error;
4962
+ } else {
4963
+ if (Object.isExtensible(current) && own?.configurable !== false) Object.defineProperty(current, "logicalId", {
4964
+ value: auxiliaryLogicalId(ownerLogicalId),
4965
+ enumerable: false,
4966
+ writable: false,
4967
+ configurable: true
4968
+ });
4969
+ return error;
4946
4970
  }
4947
- differing.push(path);
4948
- return s;
4971
+ current = current.cause;
4949
4972
  }
4950
- if (v === "***") {
4951
- if (s === void 0 || containsMask(s)) return s;
4952
- if (jsonEqual(s, t)) {
4953
- confirmed.push(path);
4954
- return v;
4973
+ } catch {}
4974
+ return error;
4975
+ }
4976
+
4977
+ // src/provisioning/masked-retry-logger.ts
4978
+ function maskerOrIdentity(maskSecrets) {
4979
+ return maskSecrets ?? ((text) => text);
4980
+ }
4981
+ function createMaskedRetryLogger(logger, maskSecrets) {
4982
+ const mask = maskerOrIdentity(maskSecrets);
4983
+ return {
4984
+ debug: (message) => logger.debug(mask(message)),
4985
+ warn: (message) => logger.warn(mask(message))
4986
+ };
4987
+ }
4988
+ function createMaskedLogSinks(logger, maskSecrets) {
4989
+ const mask = maskerOrIdentity(maskSecrets);
4990
+ return {
4991
+ mask,
4992
+ value: (value) => mask(String(value)),
4993
+ debug: (message) => logger.debug(mask(message)),
4994
+ warn: (message) => logger.warn(mask(message))
4995
+ };
4996
+ }
4997
+ function isSecretDerivedValue(raw, mask) {
4998
+ return typeof raw === "string" && raw !== "" && (mask(raw) !== raw || raw.includes("{{resolve:") || raw === "***");
4999
+ }
5000
+ function withDerivedNameMasks(logger, sinks, pairs) {
5001
+ const base = sinks.mask;
5002
+ const derivedNames = pairs.filter((pair) => typeof pair[0] === "string" && pair[0] !== "" && typeof pair[1] === "string" && pair[1] !== "" && isSecretDerivedValue(pair[0], base)).map(([, derived]) => derived);
5003
+ if (derivedNames.length === 0) return sinks;
5004
+ const mask = (text) => {
5005
+ const masked = base(text);
5006
+ const needles = [];
5007
+ for (const derived of new Set(derivedNames)) {
5008
+ if (derived.length < 4) {
5009
+ needles.push(derived);
5010
+ continue;
4955
5011
  }
4956
- differing.push(path);
4957
- return s;
4958
- }
4959
- if (Array.isArray(v) && Array.isArray(s)) {
4960
- if (s.length !== v.length) return s;
4961
- const tt = Array.isArray(t) ? t : [];
4962
- let changed = false;
4963
- const out = s.map((item, i) => {
4964
- const next = walk(item, tt[i], v[i], [...path, i]);
4965
- if (next !== item) changed = true;
4966
- return next;
4967
- });
4968
- return changed ? out : s;
4969
- }
4970
- if (isPlainObject(v) && isPlainObject(s)) {
4971
- const tt = isPlainObject(t) ? t : {};
4972
- let out;
4973
- for (const key of Object.keys(v)) {
4974
- if (!Object.hasOwn(s, key)) continue;
4975
- const next = walk(s[key], tt[key], v[key], [...path, key]);
4976
- if (next !== s[key]) {
4977
- out ??= { ...s };
4978
- out[key] = next;
4979
- }
5012
+ const rendered = base(derived);
5013
+ if (rendered === "***") continue;
5014
+ for (let i = text.indexOf(derived); i !== -1;) {
5015
+ const j = i + derived.length;
5016
+ if (masked !== base(text.slice(0, i)) + rendered + base(text.slice(j))) return "***";
5017
+ i = text.indexOf(derived, i + 1);
4980
5018
  }
4981
- return out ?? s;
5019
+ needles.push(rendered);
4982
5020
  }
4983
- return s;
5021
+ let out = masked;
5022
+ for (const needle of needles.sort((a, b) => b.length - a.length)) out = out.split(needle).join("***");
5023
+ return out;
4984
5024
  };
4985
5025
  return {
4986
- current: walk(stored, today, v11, []),
4987
- confirmed,
4988
- differing
5026
+ mask,
5027
+ value: (value) => mask(String(value)),
5028
+ debug: (message) => logger.debug(mask(message)),
5029
+ warn: (message) => logger.warn(mask(message))
4989
5030
  };
4990
5031
  }
4991
- function containsMask(value) {
4992
- if (value === "***") return true;
4993
- if (Array.isArray(value)) return value.some(containsMask);
4994
- if (isPlainObject(value)) return Object.values(value).some(containsMask);
4995
- return false;
4996
- }
4997
- function jsonEqual(a, b) {
4998
- return canonicalJson(a) === canonicalJson(b);
4999
- }
5000
- function canonicalJson(value) {
5001
- return JSON.stringify(value, (_key, node) => {
5002
- if (node === null || typeof node !== "object" || Array.isArray(node)) return node;
5003
- const sorted = Object.create(null);
5004
- for (const key of Object.keys(node).sort()) sorted[key] = node[key];
5005
- return sorted;
5006
- });
5032
+ const MASK_WALK_MAX_DEPTH = 8;
5033
+ const MASK_WALK_DEPTH_CAP_MARKER = "***";
5034
+ const BASE_MASKER_SUBSTRING_FLOOR = 4;
5035
+ function maskDeep(value, mask, depth = 0) {
5036
+ if (typeof value === "string") return mask(value);
5037
+ if (depth >= 8) return "***";
5038
+ if (Array.isArray(value)) return value.map((entry) => maskDeep(entry, mask, depth + 1));
5039
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [mask(k), maskDeep(v, mask, depth + 1)]));
5040
+ return value;
5007
5041
  }
5008
- const PREVIOUS_NOECHO_VALUE = "(previous NoEcho value)";
5009
- function noEchoParametersReadBy(node, sources) {
5010
- return [...sources.parameters].filter((name) => readsNoEchoSource(node, {
5011
- parameters: /* @__PURE__ */ new Set([name]),
5012
- ...sources.conditions !== void 0 && { conditions: sources.conditions }
5013
- }));
5042
+
5043
+ // src/provisioning/state-orphan-remedy.ts
5044
+ function stateOrphanRecordRemedy(context, logicalId) {
5045
+ const resource = {
5046
+ flag: "--resource",
5047
+ value: logicalId,
5048
+ hole: "logicalId",
5049
+ opts: { plainIdent: true }
5050
+ };
5051
+ const target = [{ hole: "stack" }, {
5052
+ flag: "--stack-region",
5053
+ hole: "region"
5054
+ }];
5055
+ if (context?.stackDestroy === true) {
5056
+ const resourceArg = `--resource ${pasteableCommand("cdkd state orphan", [resource]).withheld.length === 0 ? logicalId : commandHole("logicalId")}`;
5057
+ return `${pasteableCommand("cdkd state orphan", [...target]).command}, which drops every record the stack still has in that region, not just this one (add ${proseQuoted(resourceArg)} to drop only this one)`;
5058
+ }
5059
+ return `${pasteableCommand("cdkd state orphan", [...target, resource]).command}, which drops only this record — never run it without --resource on a stack that is still deployed, where that drops every resource's record and the next deploy re-creates or collides with all of them`;
5014
5060
  }
5015
- function noEchoComparison(options) {
5016
- const { sources, values, minNeedleLength, publicTokens } = options;
5017
- return ({ templateProperties, desired, current }) => {
5018
- const coordinates = noEchoCoordinatesOf(templateProperties, desired, sources);
5019
- const needles = [];
5020
- for (const name of noEchoParametersReadBy(templateProperties, sources)) {
5021
- const value = values[name];
5022
- const leaves = Array.isArray(value) ? value : [value];
5023
- for (const leaf of leaves) if (typeof leaf === "string" && leaf.length >= minNeedleLength && !isSingleDynamicReferenceToken(leaf)) needles.push(leaf);
5024
- }
5025
- if (coordinates.length === 0 && needles.length === 0) return void 0;
5026
- let masked = maskAtCoordinates(desired, coordinates);
5027
- if (needles.length > 0) {
5028
- const walk = (node) => {
5029
- if (typeof node === "string") {
5030
- if (node === "***") return node;
5031
- const outside = node.replace(DYNAMIC_REFERENCE_TOKEN_SCAN, "");
5032
- return needles.some((needle) => node === needle || publicTokens?.has(needle) !== true && outside.includes(needle)) ? "***" : node;
5033
- }
5034
- if (Array.isArray(node)) {
5035
- const out = node.map(walk);
5036
- return out.some((item, i) => item !== node[i]) ? out : node;
5037
- }
5038
- if (isPlainObject(node)) {
5039
- let out;
5040
- for (const [key, child] of Object.entries(node)) {
5041
- const next = walk(child);
5042
- if (next !== child) {
5043
- out ??= { ...node };
5044
- out[key] = next;
5045
- }
5046
- }
5047
- return out ?? node;
5048
- }
5049
- return node;
5050
- };
5051
- masked = walk(masked);
5052
- }
5053
- const witnessed = witnessNormalize(current, desired, masked);
5054
- const shown = maskAtCoordinatesWith(witnessed.current, witnessed.differing, PREVIOUS_NOECHO_VALUE);
5055
- return {
5056
- desired: masked,
5057
- current: shown
5058
- };
5061
+
5062
+ // src/provisioning/composite-id.ts
5063
+ const COMPOSITE_ID_SEPARATOR = "|";
5064
+ function canonicalizeRoute53QueryName(name) {
5065
+ const lowered = name.toLowerCase().replaceAll("*", "\\052").replaceAll("|", "\\174");
5066
+ return lowered.endsWith(".") ? lowered : `${lowered}.`;
5067
+ }
5068
+ function segmentAfterAnchor(physicalId, anchor) {
5069
+ if (typeof anchor !== "string" || anchor === "") return void 0;
5070
+ const prefix = `${anchor}${"|"}`;
5071
+ if (!physicalId.startsWith(prefix)) return void 0;
5072
+ const rest = physicalId.slice(prefix.length);
5073
+ return rest === "" ? void 0 : rest;
5074
+ }
5075
+ const QUOTABLE_VALUE = /^(?:[A-Za-z0-9:_@./+=,~|*-]+| *)$/;
5076
+ function quotedOr(value, quote, description) {
5077
+ return QUOTABLE_VALUE.test(value) ? `${quote}${value}${quote}` : description;
5078
+ }
5079
+ function logicalIdShown(logicalId) {
5080
+ return plainOrDescribed(logicalId, "logical id");
5081
+ }
5082
+ const RESOURCE_TYPE_SHAPE = /^[A-Za-z0-9]+(?:::[A-Za-z0-9_@-]+)+$/;
5083
+ function resourceTypeShown(resourceType) {
5084
+ return RESOURCE_TYPE_SHAPE.test(resourceType) && plainIdentOr(resourceType, "") === resourceType ? resourceType : "a resource type that is not a plain identifier";
5085
+ }
5086
+ function idShape(segments) {
5087
+ return segments.map((segment) => `<${segment.name}>`).join("|");
5088
+ }
5089
+ function compositeIdSeparatorRefusal(resourceType, logicalId, segments, maskSecrets) {
5090
+ const offending = segments.filter((segment) => String(segment.value).includes("|"));
5091
+ if (offending.length === 0) return void 0;
5092
+ const mask = maskerOrIdentity(maskSecrets);
5093
+ const named = offending.map((segment) => `${segment.name} ${quotedOr(mask(String(segment.value)), "'", "(its value is not shown: it is not a plain identifier)")}`).join(" and ");
5094
+ return `${resourceTypeShown(resourceType)} ${logicalIdShown(logicalId)}: ${named} contains '${"|"}', which cdkd uses as the separator in this type's physical id (${idShape(segments)}). Recording it would produce an id that decodes back to a DIFFERENT resource, so a later cdkd destroy / drift / update would target the wrong one — or silently skip it while the real resource stays alive. cdkd cannot record a value containing '${"|"}' in this position. Change the named value so it does not contain '${"|"}', or manage the resource outside cdkd.`;
5095
+ }
5096
+ function packCompositeId(resourceType, logicalId, segments, options) {
5097
+ const refusal = compositeIdSeparatorRefusal(resourceType, logicalId, segments, options?.maskSecrets);
5098
+ if (refusal !== void 0) {
5099
+ if (options?.onRefusal) options.onRefusal(`${refusal} Continuing with the ambiguous id because the value comes from a cdkd state record, which no template edit can repair; the same value is REFUSED on a template-path create.`);
5100
+ else throw new ProvisioningError(refusal, resourceType, logicalId);
5101
+ }
5102
+ return segments.map((segment) => String(segment.value)).join("|");
5103
+ }
5104
+ function formatShape(segments) {
5105
+ return segments.map((segment) => `<${segment}>`).join("|");
5106
+ }
5107
+ function compositeIdFormatMessage(format, logicalId, physicalId, options) {
5108
+ const accepted = format.alsoAccepts ? `"${formatShape(format.segments)}" or ${format.alsoAccepts}` : `"${formatShape(format.segments)}"`;
5109
+ const head = `Invalid physicalId format for ${format.label} ${logicalIdShown(logicalId)}: expected ${accepted}, got ${quotedOr(physicalId, "\"", "an id that is not a plain identifier")}`;
5110
+ if (!options?.skipping) return head;
5111
+ return `${head}. Skipping the delete — no AWS call is issued, so the resource is LEFT IN PLACE. The state record is KEPT and the run reports the skip: on 'cdkd destroy' / 'cdkd state destroy' (which exits non-zero) and, since issue 1762, on the plain DELETE of a resource removed from the template during cdkd deploy (which re-attempts it on the next deploy). So repair the id in state.json and re-run, or delete the resource by hand and drop the record with ${stateOrphanRecordRemedy(options.context, logicalId)}. NOTE a deploy-side REPLACEMENT or rollback delete instead FAILS the resource (https://github.com/go-to-k/cdkd/issues/1762) — the old resource is left untracked there, so delete it by hand.`;
5112
+ }
5113
+ const COMPOSITE_ID_SKIP_REASON = "malformed physicalId in state — no delete issued";
5114
+ function compositeIdSkipResult() {
5115
+ return {
5116
+ outcome: "skipped",
5117
+ reason: COMPOSITE_ID_SKIP_REASON
5059
5118
  };
5060
5119
  }
5061
- function maskAtCoordinatesWith(bag, coordinates, replacement) {
5062
- let root = bag;
5063
- for (const coordinate of coordinates) {
5064
- if (coordinate.length === 0 || !readAt(root, coordinate).found) continue;
5065
- root = cloneContainer(root);
5066
- let node = root;
5067
- for (let i = 0; i < coordinate.length - 1; i++) {
5068
- const segment = coordinate[i];
5069
- const next = cloneContainer(node[segment]);
5070
- node[segment] = next;
5071
- node = next;
5072
- }
5073
- node[coordinate[coordinate.length - 1]] = replacement;
5074
- }
5075
- return root;
5076
- }
5077
- function noEchoOutputsComparison(templateValues, sources) {
5078
- return (current, desired) => {
5079
- const coordinates = noEchoCoordinatesOf(templateValues, desired, sources);
5080
- const maskedKeys = new Set(coordinates.map((coordinate) => coordinate[0]).filter((key) => typeof key === "string"));
5081
- const maskedValues = new Set([...maskedKeys].map((key) => canonicalJson(desired[key])));
5082
- for (const key of Object.keys(desired)) if (!Object.hasOwn(templateValues, key) && maskedValues.has(canonicalJson(desired[key]))) maskedKeys.add(key);
5083
- if (maskedKeys.size === 0) return {
5084
- current,
5085
- desired,
5086
- masked: []
5087
- };
5088
- const maskedDesired = { ...desired };
5089
- for (const key of maskedKeys) maskedDesired[key] = maskWholeValue(desired[key]);
5090
- let normalized = current;
5091
- if (current !== void 0 && current !== null && typeof current === "object") for (const key of maskedKeys) {
5092
- if (!Object.hasOwn(current, key)) continue;
5093
- const stored = current[key];
5094
- if (containsMask(stored)) continue;
5095
- normalized = { ...normalized ?? {} };
5096
- normalized[key] = canonicalJson(stored) === canonicalJson(desired[key]) ? maskedDesired[key] : PREVIOUS_NOECHO_VALUE;
5120
+
5121
+ // src/provisioning/interrupt-watch.ts
5122
+ var InterruptedWaitError = class InterruptedWaitError extends Error {
5123
+ constructor(what) {
5124
+ super(`${what} interrupted by user (SIGINT)`);
5125
+ this.name = "InterruptedWaitError";
5126
+ Object.setPrototypeOf(this, InterruptedWaitError.prototype);
5127
+ }
5128
+ };
5129
+ function isInterruptedWaitError(error) {
5130
+ const seen = /* @__PURE__ */ new Set();
5131
+ let current = error;
5132
+ while (current !== void 0 && current !== null) {
5133
+ if (current instanceof InterruptedWaitError) return true;
5134
+ if (!(current instanceof Error)) return false;
5135
+ if (seen.has(current)) return false;
5136
+ seen.add(current);
5137
+ current = current.cause;
5138
+ }
5139
+ return false;
5140
+ }
5141
+ const liveWatches = /* @__PURE__ */ new Set();
5142
+ let sharedSigintHandler;
5143
+ let sigintLatched = false;
5144
+ const interruptWatchTestSeam = {};
5145
+ let commandInterruptScopeDepth = 0;
5146
+ function commandOwnsInterrupts() {
5147
+ const override = interruptWatchTestSeam.commandOwnsInterrupts;
5148
+ if (override !== void 0) return override();
5149
+ return commandInterruptScopeDepth > 0;
5150
+ }
5151
+ function armSharedSigintHandler() {
5152
+ if (sharedSigintHandler !== void 0) return;
5153
+ if (!commandOwnsInterrupts()) return;
5154
+ const handler = () => {
5155
+ sigintLatched = true;
5156
+ for (const live of liveWatches) live.interrupted = true;
5157
+ if (process.listeners("SIGINT").filter((l) => l !== handler).length === 0) {
5158
+ process.stderr.write(`
5159
+ Interrupted.
5160
+ If the next run reports a stack lock, release it with: ${pasteableCommand("cdkd force-unlock", [{ hole: "stack-name" }]).command}\n`);
5161
+ (interruptWatchTestSeam.forceQuit ?? ((code) => process.exit(code)))(130);
5097
5162
  }
5098
- return {
5099
- current: normalized,
5100
- desired: maskedDesired,
5101
- masked: [...maskedKeys]
5102
- };
5103
5163
  };
5104
- }
5105
- function maskedLeafCoordinatesOf(bag) {
5106
- const coordinates = [];
5107
- const ancestors = /* @__PURE__ */ new Set();
5108
- const walk = (node, path) => {
5109
- if (node === "***") {
5110
- coordinates.push(path);
5111
- return;
5164
+ sharedSigintHandler = handler;
5165
+ process.on("SIGINT", handler);
5166
+ }
5167
+ function startInterruptWatch(what) {
5168
+ armSharedSigintHandler();
5169
+ const state = { interrupted: sigintLatched };
5170
+ liveWatches.add(state);
5171
+ let disposed = false;
5172
+ return {
5173
+ isInterrupted: () => state.interrupted,
5174
+ onInterrupted: () => new InterruptedWaitError(what),
5175
+ dispose: () => {
5176
+ if (disposed) return;
5177
+ disposed = true;
5178
+ liveWatches.delete(state);
5112
5179
  }
5113
- if (node === null || typeof node !== "object" || ancestors.has(node)) return;
5114
- ancestors.add(node);
5115
- if (Array.isArray(node)) node.forEach((item, index) => walk(item, [...path, index]));
5116
- else for (const [key, child] of Object.entries(node)) walk(child, [...path, key]);
5117
- ancestors.delete(node);
5118
5180
  };
5119
- walk(bag, []);
5120
- return coordinates;
5121
5181
  }
5122
- const passedNoEchoParameters = /* @__PURE__ */ new WeakMap();
5123
- function recordPassedNoEchoParameters(bag, parameters, sources) {
5124
- const names = /* @__PURE__ */ new Set();
5125
- if (sources !== void 0 && parameters !== null && typeof parameters === "object") {
5126
- for (const [name, value] of Object.entries(parameters)) if (readsNoEchoSource(value, sources)) names.add(name);
5127
- }
5128
- if (names.size > 0) passedNoEchoParameters.set(bag, names);
5129
- else passedNoEchoParameters.delete(bag);
5182
+ function resetInterruptWatchLatch() {
5183
+ sigintLatched = false;
5184
+ for (const live of liveWatches) live.interrupted = false;
5130
5185
  }
5131
- function passedNoEchoParametersOf(bag) {
5132
- return bag === void 0 ? void 0 : passedNoEchoParameters.get(bag);
5186
+ function beginCommandInterruptScope() {
5187
+ commandInterruptScopeDepth += 1;
5188
+ if (commandInterruptScopeDepth === 1) resetInterruptWatchLatch();
5133
5189
  }
5134
-
5135
- // src/analyzer/replacement-rules/batch-compute-environment.ts
5136
- const INFRASTRUCTURE_UPDATE_MEMBERS = [
5137
- "AllocationStrategy",
5138
- "BidPercentage",
5139
- "Ec2Configuration",
5140
- "Ec2KeyPair",
5141
- "ImageId",
5142
- "InstanceRole",
5143
- "InstanceTypes",
5144
- "LaunchTemplate",
5145
- "PlacementGroup",
5146
- "Tags",
5147
- "Type",
5148
- "UpdateToLatestImageVersion"
5149
- ];
5150
- const CREATE_ONLY_PATHS = [
5151
- ["SpotIamFleetRole"],
5152
- [
5153
- "ManagedInstancesProvider",
5154
- "InstanceLaunchTemplate",
5155
- "CapacityOptionType"
5156
- ],
5157
- [
5158
- "ManagedInstancesProvider",
5159
- "InstanceLaunchTemplate",
5160
- "FipsEnabled"
5161
- ]
5162
- ];
5163
- function at(value, path) {
5164
- let cursor = value;
5165
- for (const segment of path) {
5166
- if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) return void 0;
5167
- cursor = cursor[segment];
5190
+ function endCommandInterruptScope() {
5191
+ commandInterruptScopeDepth = Math.max(0, commandInterruptScopeDepth - 1);
5192
+ if (commandInterruptScopeDepth > 0) return;
5193
+ if (sharedSigintHandler !== void 0) {
5194
+ process.removeListener("SIGINT", sharedSigintHandler);
5195
+ sharedSigintHandler = void 0;
5168
5196
  }
5169
- return cursor;
5170
- }
5171
- function noInfrastructureUpdate(current) {
5172
- const type = at(current, ["Type"]);
5173
- if (type === "FARGATE" || type === "FARGATE_SPOT") return "fargate";
5174
- const strategy = at(current, ["AllocationStrategy"]);
5175
- return strategy === void 0 || strategy === "BEST_FIT" ? "best-fit" : void 0;
5197
+ resetInterruptWatchLatch();
5176
5198
  }
5177
- function isExplicitFalse(value) {
5178
- return value === false || value === "false";
5179
- }
5180
- function batchComputeResourcesChangeReplaces(oldValue, newValue, siblings) {
5181
- if (CREATE_ONLY_PATHS.some((p) => !isDeepStrictEqual(at(oldValue, p), at(newValue, p)))) return true;
5182
- const changed = (member) => !isDeepStrictEqual(at(oldValue, [member]), at(newValue, [member]));
5183
- const bestFit = noInfrastructureUpdate(oldValue) === "best-fit" || noInfrastructureUpdate(newValue) === "best-fit";
5184
- if (!(INFRASTRUCTURE_UPDATE_MEMBERS.some(changed) || bestFit && (changed("Subnets") || changed("SecurityGroupIds"))) || siblings === void 0) return false;
5185
- return !isExplicitFalse(siblings.newProperties["ReplaceComputeEnvironment"]);
5199
+ function interruptWatchListenerCount() {
5200
+ return sharedSigintHandler === void 0 ? 0 : 1;
5186
5201
  }
5187
5202
 
5188
- // src/utils/lambda-function-name.ts
5189
- function parseLambdaFunctionAddress(value) {
5190
- const full = /^arn:([^:]+):lambda:([^:]+):(\d{12}):function:([^:]+)$/.exec(value);
5191
- if (full) return {
5192
- partition: full[1],
5193
- region: full[2],
5194
- account: full[3],
5195
- name: full[4]
5203
+ // src/provisioning/iam-policy-targets.ts
5204
+ const IAM_PRINCIPAL_NAME = /^[\w+=,.@-]{1,128}$/;
5205
+ function diffPrincipalNames(desired, recorded) {
5206
+ const keys = (names) => new Set((names ?? []).map((name) => name.toLowerCase()));
5207
+ const unique = (names) => {
5208
+ const seen = /* @__PURE__ */ new Set();
5209
+ return (names ?? []).filter((name) => {
5210
+ const key = name.toLowerCase();
5211
+ if (seen.has(key)) return false;
5212
+ seen.add(key);
5213
+ return true;
5214
+ });
5196
5215
  };
5197
- const partial = /^(\d{12}):function:([^:]+)$/.exec(value);
5198
- if (partial) return {
5199
- account: partial[1],
5200
- name: partial[2]
5216
+ const desiredKeys = keys(desired);
5217
+ const recordedKeys = keys(recorded);
5218
+ return {
5219
+ added: unique(desired).filter((name) => !recordedKeys.has(name.toLowerCase())),
5220
+ removed: unique(recorded).filter((name) => !desiredKeys.has(name.toLowerCase()))
5201
5221
  };
5202
- if (/^[A-Za-z0-9_-]+$/.test(value)) return { name: value };
5203
5222
  }
5204
- function sameLambdaFunctionAddress(a, b) {
5205
- if (a === b) return true;
5206
- const x = parseLambdaFunctionAddress(a);
5207
- const y = parseLambdaFunctionAddress(b);
5208
- if (x === void 0 || y === void 0) return false;
5209
- return x.name === y.name && (x.partition === void 0 || y.partition === void 0 || x.partition === y.partition) && (x.region === void 0 || y.region === void 0 || x.region === y.region) && (x.account === void 0 || y.account === void 0 || x.account === y.account);
5223
+ function readRecordedPrincipals(value) {
5224
+ if (value === void 0 || value === null) return { kind: "absent" };
5225
+ if (!Array.isArray(value)) return {
5226
+ kind: "malformed",
5227
+ detail: `found ${typeof value}`
5228
+ };
5229
+ if (!value.every((v) => typeof v === "string" && IAM_PRINCIPAL_NAME.test(v))) return {
5230
+ kind: "malformed",
5231
+ detail: `a ${value.length}-element list holding a non-name entry`
5232
+ };
5233
+ return {
5234
+ kind: "names",
5235
+ names: value
5236
+ };
5210
5237
  }
5211
- function canonicalLambdaFunctionName(value) {
5212
- return parseLambdaFunctionAddress(value)?.name ?? value;
5238
+ function readPrincipalLists(values) {
5239
+ const lists = {};
5240
+ const malformed = [];
5241
+ const secretDerived = [];
5242
+ for (const key of Object.keys(values)) {
5243
+ const value = values[key];
5244
+ const recorded = readRecordedPrincipals(value);
5245
+ if (recorded.kind === "malformed") {
5246
+ malformed.push(key);
5247
+ if (holdsSecretDerivedEntry(value)) secretDerived.push(key);
5248
+ } else lists[key] = recorded.kind === "names" ? recorded.names : void 0;
5249
+ }
5250
+ return malformed.length > 0 ? {
5251
+ lists,
5252
+ malformed,
5253
+ secretDerived
5254
+ } : { lists };
5255
+ }
5256
+ const SECRET_MASK = "***";
5257
+ function holdsSecretDerivedEntry(value) {
5258
+ const seen = /* @__PURE__ */ new Set();
5259
+ const walk = (v, depth) => {
5260
+ if (typeof v === "string") return v === SECRET_MASK || v.includes("{{resolve:");
5261
+ if (typeof v !== "object" || v === null || depth > 64 || seen.has(v)) return false;
5262
+ seen.add(v);
5263
+ if (Array.isArray(v)) return v.some((e) => walk(e, depth + 1));
5264
+ return Object.entries(v).some(([k, e]) => walk(k, depth + 1) || walk(e, depth + 1));
5265
+ };
5266
+ return walk(value, 0);
5213
5267
  }
5214
- function lambdaFunctionNameForMask(value) {
5215
- return /^(?:arn:[^:]+:lambda:[^:]+:\d{12}:function:|\d{12}:function:)?([A-Za-z0-9_-]+)(?::[^:]+)?$/.exec(value)?.[1] ?? canonicalLambdaFunctionName(value);
5268
+ function onlySecretDerived(read) {
5269
+ return "malformed" in read && read.malformed.every((k) => read.secretDerived.includes(k));
5216
5270
  }
5217
-
5218
- // src/analyzer/replacement-rules/predicates.ts
5219
- function vpcInstanceTenancyChangeReplaces(oldValue, newValue) {
5220
- const tenancyOf = (v) => v == null ? "default" : String(v);
5221
- return tenancyOf(newValue) !== "default" && tenancyOf(newValue) !== tenancyOf(oldValue);
5222
- }
5223
- function instanceSecurityGroupIdsChangeReplaces(oldValue, newValue, siblings) {
5224
- if (siblings === void 0) return false;
5225
- if (Array.isArray(oldValue) && Array.isArray(newValue)) {
5226
- const before = new Set(oldValue.map(String));
5227
- const after = new Set(newValue.map(String));
5228
- if (before.size === after.size && [...before].every((g) => after.has(g))) return false;
5229
- }
5230
- return siblings.newProperties["SubnetId"] == null;
5231
- }
5232
- function instanceTenancyChangeReplaces(oldValue, newValue) {
5233
- if (oldValue == null) return false;
5234
- if (newValue == null) return true;
5235
- const text = (v) => typeof v === "string" ? v : JSON.stringify(v);
5236
- const before = text(oldValue);
5237
- const after = text(newValue);
5238
- if (before === after) return false;
5239
- return before === "default" || after === "default";
5240
- }
5241
- function instancePrivateDnsNameOptionsChangeReplaces(oldValue, newValue) {
5242
- return oldValue != null && newValue == null;
5243
- }
5244
- function instanceBlockDeviceMappingsChangeReplaces(oldValue, newValue) {
5245
- return !blockDeviceMappingsDifferOnlyInDeleteOnTermination(oldValue, newValue);
5246
- }
5247
- function blockDeviceMappingsDifferOnlyInDeleteOnTermination(oldValue, newValue) {
5248
- if (!Array.isArray(oldValue) || !Array.isArray(newValue)) return false;
5249
- if (oldValue.length !== newValue.length) return false;
5250
- const strip = (m) => {
5251
- if (m === null || typeof m !== "object" || Array.isArray(m)) return m;
5252
- const out = { ...m };
5253
- const ebs = out["Ebs"];
5254
- if (ebs !== null && typeof ebs === "object" && !Array.isArray(ebs)) {
5255
- const rest = { ...ebs };
5256
- delete rest["DeleteOnTermination"];
5257
- out["Ebs"] = rest;
5271
+ function recordedPrincipalsRepair(malformed, secretDerived, what, secretDerivedRepair) {
5272
+ const plain = malformed.filter((k) => !secretDerived.includes(k));
5273
+ const parts = [];
5274
+ if (plain.length > 0) parts.push(`repair the recorded ${plain.join(" / ")} in state.json to a list of ${what} and re-run`);
5275
+ if (secretDerived.length > 0) parts.push(`the recorded ${secretDerived.join(" / ")} is secret-derived (cdkd keeps the dynamic reference or its mask in state), so do not write the name into state.json; ` + secretDerivedRepair);
5276
+ return parts.join("; ");
5277
+ }
5278
+ const SECRET_DERIVED_READ_LIVE = "cdkd reads it from IAM instead once every other list is well-formed";
5279
+ const RESOLVED_PREVIOUS_PRINCIPAL_KEYS = {
5280
+ "AWS::IAM::Policy": [
5281
+ "Roles",
5282
+ "Groups",
5283
+ "Users"
5284
+ ],
5285
+ "AWS::IAM::UserToGroupAddition": ["Users"]
5286
+ };
5287
+ const ATTACHMENT_TARGET_KEY = {
5288
+ "AWS::IAM::Policy": "PolicyName",
5289
+ "AWS::IAM::UserToGroupAddition": "GroupName"
5290
+ };
5291
+ function holdsMask(value) {
5292
+ if (typeof value === "string") return value === SECRET_MASK;
5293
+ if (Array.isArray(value)) return value.some(holdsMask);
5294
+ if (typeof value === "object" && value !== null) return Object.values(value).some(holdsMask);
5295
+ return false;
5296
+ }
5297
+ function providerRecordedTarget(resourceType, physicalId) {
5298
+ if (resourceType !== "AWS::IAM::Policy") return void 0;
5299
+ return physicalId.includes(":") ? physicalId.split(":")[0] : physicalId;
5300
+ }
5301
+ function withUnchangedSecretPrincipalLists(resourceType, physicalId, previous, desiredRedacted) {
5302
+ const untouched = {
5303
+ previous,
5304
+ dropped: []
5305
+ };
5306
+ const keys = Object.prototype.hasOwnProperty.call(RESOLVED_PREVIOUS_PRINCIPAL_KEYS, resourceType) ? RESOLVED_PREVIOUS_PRINCIPAL_KEYS[resourceType] : [];
5307
+ if (keys.length === 0) return untouched;
5308
+ const target = ATTACHMENT_TARGET_KEY[resourceType];
5309
+ const recordedTarget = previous[target];
5310
+ const derivedTarget = providerRecordedTarget(resourceType, physicalId);
5311
+ if (holdsSecretDerivedEntry(recordedTarget) || JSON.stringify(recordedTarget) !== JSON.stringify(desiredRedacted[target]) || derivedTarget !== void 0 && recordedTarget !== derivedTarget) return untouched;
5312
+ const rewritten = [];
5313
+ for (const key of keys) {
5314
+ if (!Object.prototype.hasOwnProperty.call(previous, key)) continue;
5315
+ const recorded = previous[key];
5316
+ if (!holdsSecretDerivedEntry(recorded)) continue;
5317
+ const redacted = desiredRedacted[key];
5318
+ if (!Array.isArray(recorded) || !Array.isArray(redacted) || holdsMask(recorded)) return untouched;
5319
+ const kept = [];
5320
+ for (const entry of recorded) {
5321
+ if (!holdsSecretDerivedEntry(entry)) {
5322
+ kept.push(entry);
5323
+ continue;
5324
+ }
5325
+ if (typeof entry !== "string" || !redacted.includes(entry)) return untouched;
5258
5326
  }
5259
- return out;
5327
+ rewritten.push([key, kept]);
5328
+ }
5329
+ if (rewritten.length === 0) return untouched;
5330
+ const out = { ...previous };
5331
+ for (const [key, kept] of rewritten) out[key] = kept;
5332
+ return {
5333
+ previous: out,
5334
+ dropped: rewritten.map(([key]) => key)
5260
5335
  };
5261
- return oldValue.every((m, i) => isDeepStrictEqual(scalarsAsStrings(strip(m)), scalarsAsStrings(strip(newValue[i]))));
5262
- }
5263
- function scalarsAsStrings(value) {
5264
- if (Array.isArray(value)) return value.map(scalarsAsStrings);
5265
- if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0).map(([k, v]) => [k, scalarsAsStrings(v)]));
5266
- return typeof value === "number" || typeof value === "boolean" ? String(value) : value;
5267
5336
  }
5268
- function durableConfigPresenceToggled(oldValue, newValue) {
5269
- return oldValue == null !== (newValue == null);
5337
+
5338
+ // src/provisioning/replacement-protection-advice.ts
5339
+ const DELETION_PROTECTION_DOC_POINTER = "\"Deletion protection blocks a replacement, and deploy cannot clear it\" at https://cdkd.dev/cli-deploy-safety/#deletion-protection-blocks-a-replacement-and-deploy-cannot-clear-it";
5340
+ const UNNAMEABLE_ID_CLAUSE = "Then disable protection out of band, via the console: the physical id cdkd recorded for this resource cannot be reproduced safely on a command line (sanitizing would change it, so a command would act on a different resource, or it holds a character or prefix a pasted shell line, or the AWS CLI itself, would act on, or it is derived from a secret, which a pasted command would print).";
5341
+ const AWS_CLI_ACTIVE_ARG = /^-|^(?:fileb?|https?):\/\/|@=/i;
5342
+ function isAwsCliLiteral(value) {
5343
+ return !AWS_CLI_ACTIVE_ARG.test(value);
5344
+ }
5345
+ function renderDisableCommand(disable) {
5346
+ const resolved = disable;
5347
+ const quoted = pasteableArg(resolved.identifier, resolved.maskSecrets);
5348
+ if (quoted === void 0) return "";
5349
+ const tail = resolved.after ? ` ${resolved.after}` : "";
5350
+ return `${withPasteableAwsProfile(resolved.before)} ${quoted}${tail}`;
5351
+ }
5352
+ function pasteableArg(value, maskSecrets) {
5353
+ if (typeof value !== "string") return void 0;
5354
+ const safe = displaySafe(value, { asciiOnly: true });
5355
+ if (!safe || safe !== value) return void 0;
5356
+ if (maskSecrets && maskSecrets(safe) !== safe) return void 0;
5357
+ if (!isInertUnquoted(safe)) return void 0;
5358
+ if (!isAwsCliLiteral(safe)) return void 0;
5359
+ return shellQuote(safe);
5360
+ }
5361
+ var PasteableAwsCommand = class {
5362
+ text;
5363
+ #origin;
5364
+ constructor(text, origin) {
5365
+ this.text = text;
5366
+ this.#origin = origin;
5367
+ }
5368
+ builtBy(tag) {
5369
+ return this.#origin === tag;
5370
+ }
5371
+ render() {
5372
+ return this.text ?? "[command withheld: a name or id it would carry cannot be printed safely on a command line (inexact, so a pasted copy could act on a different resource, or holding a character or prefix a pasted shell line, or the AWS CLI itself, would act on); use the console]";
5373
+ }
5374
+ };
5375
+ const WITHHELD_AWS_COMMAND = "[command withheld: a name or id it would carry cannot be printed safely on a command line (inexact, so a pasted copy could act on a different resource, or holding a character or prefix a pasted shell line, or the AWS CLI itself, would act on); use the console]";
5376
+ function pasteableAwsCommand(maskSecrets) {
5377
+ const tag = (strings, ...values) => {
5378
+ let text = withPasteableAwsProfile(strings[0] ?? "");
5379
+ for (let i = 0; i < values.length; i++) {
5380
+ const value = values[i];
5381
+ const rendered = value instanceof PasteableAwsCommand ? value.builtBy(tag) ? value.text : void 0 : pasteableArg(value, maskSecrets);
5382
+ if (rendered === void 0) return new PasteableAwsCommand(void 0, tag);
5383
+ text += rendered + withPasteableAwsProfile(strings[i + 1] ?? "");
5384
+ }
5385
+ return new PasteableAwsCommand(text, tag);
5386
+ };
5387
+ return tag;
5270
5388
  }
5271
- function eventInvokeConfigFunctionChanged(oldValue, newValue) {
5272
- if (oldValue === void 0 && newValue === void 0) return true;
5273
- if (typeof oldValue === "string" && typeof newValue === "string") return !sameLambdaFunctionAddress(oldValue, newValue);
5274
- return JSON.stringify(oldValue) !== JSON.stringify(newValue);
5389
+ function protectedReplacementAdvice(args) {
5390
+ const { evidence, replaceFlags } = args;
5391
+ const command = renderDisableCommand(args.disable);
5392
+ const disable = args.disable;
5393
+ const head = `${evidence}, so ${replaceFlags} alone will NOT succeed while AWS still has protection on: the replacement DELETES the resource, AWS refuses that delete while protection is on, and cdkd deploy has no --remove-protection flag to clear it (only cdkd destroy and cdkd state destroy act on one). Read ${DELETION_PROTECTION_DOC_POINTER} BEFORE you disable anything: whether disabling helps at all, and what the flag ends up as, depend on your UpdateReplacePolicy and on whether the deploy completes — neither of which this refusal can see.`;
5394
+ if (!command) return `${head} ${UNNAMEABLE_ID_CLAUSE} Then re-run with ${replaceFlags}.`;
5395
+ return `${head} Then disable protection out of band — \`${command}\`, or via the console.${disable.caveat ? ` ${disable.caveat}` : ""} Then re-run with ${replaceFlags}.`;
5275
5396
  }
5276
- function attributeTypeChangedForSharedAttribute(oldValue, newValue) {
5277
- const toTypeMap = (value) => {
5278
- const map = /* @__PURE__ */ new Map();
5279
- if (Array.isArray(value)) {
5280
- for (const def of value) if (def && typeof def === "object") {
5281
- const name = def["AttributeName"];
5282
- const type = def["AttributeType"];
5283
- if (typeof name === "string" && typeof type === "string") map.set(name, type);
5397
+
5398
+ // src/utils/elapsed-budget.ts
5399
+ const monotonicNowMs = typeof globalThis.performance?.now === "function" ? () => globalThis.performance.now() : () => Date.now();
5400
+ var ElapsedBudget = class {
5401
+ totalMs;
5402
+ clock;
5403
+ startedAt;
5404
+ constructor(totalMs, clock = monotonicNowMs) {
5405
+ if (!Number.isFinite(totalMs) || totalMs <= 0) throw new RangeError(`ElapsedBudget: totalMs must be a positive finite number (got ${totalMs})`);
5406
+ this.totalMs = totalMs;
5407
+ this.clock = clock;
5408
+ this.startedAt = clock();
5409
+ }
5410
+ elapsedMs() {
5411
+ return Math.max(0, this.clock() - this.startedAt);
5412
+ }
5413
+ remainingMs() {
5414
+ return Math.max(0, this.totalMs - this.elapsedMs());
5415
+ }
5416
+ isExhausted() {
5417
+ return this.remainingMs() <= 0;
5418
+ }
5419
+ attemptsWithin(cap, perAttemptMs, minAttempts = 1) {
5420
+ if (!Number.isFinite(cap) || cap <= 0) return 0;
5421
+ if (!Number.isFinite(perAttemptMs) || perAttemptMs <= 0) return Math.min(minAttempts, cap);
5422
+ const affordable = Math.floor(this.remainingMs() / perAttemptMs);
5423
+ return Math.max(Math.min(minAttempts, cap), Math.min(cap, affordable));
5424
+ }
5425
+ };
5426
+ var ElapsedBudgetRegistry = class {
5427
+ budgets = /* @__PURE__ */ new Map();
5428
+ acquire(key, totalMs, clock = monotonicNowMs, reuseWithinMs) {
5429
+ const existing = this.budgets.get(key);
5430
+ if (existing) {
5431
+ if (!(reuseWithinMs !== void 0 && existing.elapsedMs() > reuseWithinMs)) return existing;
5432
+ this.budgets.delete(key);
5433
+ }
5434
+ const created = new ElapsedBudget(totalMs, clock);
5435
+ this.budgets.set(key, created);
5436
+ return created;
5437
+ }
5438
+ release(key) {
5439
+ this.budgets.delete(key);
5440
+ }
5441
+ get size() {
5442
+ return this.budgets.size;
5443
+ }
5444
+ clear() {
5445
+ this.budgets.clear();
5446
+ }
5447
+ };
5448
+
5449
+ // src/provisioning/providers/deletion-protection-compensation/flip-record.ts
5450
+ var ProtectionFlipRegistry = class {
5451
+ records = /* @__PURE__ */ new Map();
5452
+ acquire(key, reuseWithinMs, clock = monotonicNowMs) {
5453
+ const existing = this.records.get(key);
5454
+ if (existing) {
5455
+ if (existing.idle.elapsedMs() <= reuseWithinMs) {
5456
+ existing.idle = new ElapsedBudget(reuseWithinMs, clock);
5457
+ return existing.record;
5284
5458
  }
5459
+ this.records.delete(key);
5285
5460
  }
5286
- return map;
5287
- };
5288
- const oldTypes = toTypeMap(oldValue);
5289
- const newTypes = toTypeMap(newValue);
5290
- for (const [name, oldType] of oldTypes) {
5291
- const newType = newTypes.get(name);
5292
- if (newType !== void 0 && newType !== oldType) return true;
5461
+ const created = {
5462
+ record: {
5463
+ flippedOffByThisRun: false,
5464
+ deleteAccepted: false
5465
+ },
5466
+ idle: new ElapsedBudget(reuseWithinMs, clock)
5467
+ };
5468
+ this.records.set(key, created);
5469
+ return created.record;
5293
5470
  }
5294
- return false;
5471
+ release(key) {
5472
+ this.records.delete(key);
5473
+ }
5474
+ get size() {
5475
+ return this.records.size;
5476
+ }
5477
+ clear() {
5478
+ this.records.clear();
5479
+ }
5480
+ };
5481
+ function protectionFlipKey(resourceType, physicalId, region) {
5482
+ return injectiveKey(resourceType, region ?? "", physicalId);
5295
5483
  }
5296
- function globalTableLocalSecondaryIndexesRemoved(oldValue, newValue) {
5297
- const declares = (value) => Array.isArray(value) && value.length > 0;
5298
- return declares(oldValue) && (newValue === void 0 || newValue === null || Array.isArray(newValue) && newValue.length === 0);
5484
+ const PROTECTION_FLIP_REUSE_WINDOW_MS = 18e5;
5485
+ const finalDeleteAttempt = new AsyncLocalStorage();
5486
+ function runDeleteAttempt(isFinal, attempt) {
5487
+ return finalDeleteAttempt.run(isFinal, attempt);
5299
5488
  }
5300
- function budgetNameChanged(oldValue, newValue) {
5301
- const nameOf = (value) => {
5302
- if (value === null || typeof value !== "object") return void 0;
5303
- const name = value["BudgetName"];
5304
- return typeof name === "string" ? name : void 0;
5305
- };
5306
- const oldName = nameOf(oldValue);
5307
- const newName = nameOf(newValue);
5308
- if (oldName === void 0 && newName === void 0) return false;
5309
- return oldName !== newName;
5310
- }
5311
- function iamRolePathChanged(oldValue, newValue) {
5312
- const effective = (value) => value === void 0 || value === null || value === "" ? "/" : value;
5313
- const oldPath = effective(oldValue);
5314
- const newPath = effective(newValue);
5315
- if (typeof oldPath === "string" && typeof newPath === "string") return oldPath !== newPath;
5316
- return !isDeepStrictEqual(oldPath, newPath);
5317
- }
5318
- function glueTableNameChanged(oldValue, newValue) {
5319
- const nameOf = (value) => {
5320
- if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
5321
- const name = value["Name"];
5322
- return typeof name === "string" ? name : void 0;
5323
- };
5324
- const oldName = nameOf(oldValue);
5325
- const newName = nameOf(newValue);
5326
- if (oldName === void 0 || newName === void 0) return false;
5327
- return oldName.toLowerCase() !== newName.toLowerCase();
5328
- }
5329
- function natZoneAddressesAddedToAutomaticGateway(oldValue, newValue) {
5330
- return oldValue == null && newValue != null;
5331
- }
5332
- function ecsServiceLaunchTypeSetOrChanged(oldValue, newValue) {
5333
- return newValue != null && !isDeepStrictEqual(oldValue, newValue);
5334
- }
5335
- const EMR_INSTANCES_IN_PLACE_MEMBERS = ["TerminationProtected", "UnhealthyNodeReplacement"];
5336
- const EMR_GROUP_IN_PLACE_MEMBERS = ["InstanceCount", "AutoScalingPolicy"];
5337
- const EMR_FLEET_IN_PLACE_MEMBERS = ["TargetOnDemandCapacity", "TargetSpotCapacity"];
5338
- function withoutKeys(value, keys) {
5339
- if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
5340
- const copy = { ...value };
5341
- for (const key of keys) delete copy[key];
5342
- return copy;
5489
+ function isTerminalDeleteFailure(error) {
5490
+ if (isInterruptedWaitError(error)) return true;
5491
+ if (finalDeleteAttempt.getStore() === true) return true;
5492
+ if (isMarkedNonRetryable(error)) return true;
5493
+ const classify = retryClassificationText(error);
5494
+ return !(isRetryableTransientError(error, classify) || classify.includes("Too Many Requests"));
5495
+ }
5496
+
5497
+ // src/provisioning/providers/deletion-protection-compensation/final-snapshot-wait.ts
5498
+ const PROTECTION_FLIP_RETRY_WAIT_MS = 6e5;
5499
+ const FINAL_SNAPSHOT_SETTLE_WAIT_MS = 9e5;
5500
+ const FINAL_SNAPSHOT_COMPENSATION_MARGIN_MS = 6e4;
5501
+ const FLIP_TRANSITION_GRACE_MS = 3e4;
5502
+ function finalSnapshotWaitBudgetMs(opts) {
5503
+ const budgetMs = Math.min(opts.maxWaitMs ?? 9e5, opts.remainingMs - FINAL_SNAPSHOT_COMPENSATION_MARGIN_MS);
5504
+ if (budgetMs <= 0) throw new Error(`--remove-protection turned DeletionProtection off, but the resource timeout leaves no time to wait for the ${opts.noun} to return to 'available', which the final snapshot its DeletionPolicy asks for needs. The delete was not sent and the guard is put back; re-run the destroy with a longer --resource-timeout`);
5505
+ return budgetMs;
5506
+ }
5507
+ const TERMINAL_DB_STATUSES = /* @__PURE__ */ new Set([
5508
+ "deleting",
5509
+ "failed",
5510
+ "stopped",
5511
+ "storage-full",
5512
+ "insufficient-capacity",
5513
+ "restore-error"
5514
+ ]);
5515
+ const PROCEED_DB_STATUSES = /* @__PURE__ */ new Set(["storage-optimization", "storage-initialization"]);
5516
+ function isProceedDbStatus(status) {
5517
+ return status === "available" || status !== void 0 && PROCEED_DB_STATUSES.has(status);
5518
+ }
5519
+ function isTerminalDbStatus(status) {
5520
+ if (status === void 0) return false;
5521
+ return TERMINAL_DB_STATUSES.has(status) || status.startsWith("inaccessible-") || status.startsWith("incompatible-") || status.endsWith("-failed");
5522
+ }
5523
+ function isTerminalDbWaitStatus(status) {
5524
+ return status !== "inaccessible-encryption-credentials-recoverable" && isTerminalDbStatus(status);
5525
+ }
5526
+ async function settleBeforeFinalSnapshot(opts, startTime, budgetMs) {
5527
+ const { noun, label, logicalId } = opts;
5528
+ let delay = 5e3;
5529
+ let graceSleptMs = 0;
5530
+ let sawOff = false;
5531
+ let sawTransitional = false;
5532
+ for (;;) {
5533
+ const current = await opts.read();
5534
+ if (current === void 0) return;
5535
+ const terminal = isTerminalDbStatus(current.status);
5536
+ const operational = current.status !== "available" && isProceedDbStatus(current.status);
5537
+ if (!isProceedDbStatus(current.status) && !terminal) sawTransitional = true;
5538
+ if (current.deletionProtection === false) sawOff = true;
5539
+ if (current.deletionProtection === false && (terminal || operational)) return;
5540
+ if (current.deletionProtection === true && terminal) throw new Error(`--remove-protection turned DeletionProtection off, but the ${noun} still reads it ON in status '${current.status ?? "unknown"}', which does not change on its own, and the final snapshot its DeletionPolicy asks for needs it 'available'. The delete was not sent and the guard is put back; re-run the destroy once the ${noun} is 'available'`);
5541
+ const settled = current.deletionProtection === false && current.status === "available";
5542
+ const inGrace = !sawTransitional && graceSleptMs < 3e4;
5543
+ if (settled && !inGrace) return;
5544
+ const step = inGrace ? Math.min(delay, FLIP_TRANSITION_GRACE_MS - graceSleptMs) : delay;
5545
+ if (Date.now() - startTime + step >= budgetMs) {
5546
+ if (settled) return;
5547
+ if (current.deletionProtection === false && current.status !== void 0 && current.status !== "modifying") return;
5548
+ break;
5549
+ }
5550
+ opts.logger.debug(safeMsg`${label} ${logicalId}: waiting for the DeletionProtection change to settle before the final snapshot (status ${current.status ?? "unknown"})`);
5551
+ await opts.sleep(step);
5552
+ if (sawOff) graceSleptMs += step;
5553
+ delay = Math.min(delay * 2, 1e4);
5554
+ }
5555
+ throw new Error(`--remove-protection turned DeletionProtection off, but the ${noun} did not return to 'available' within ${Math.max(1, Math.round(budgetMs / 6e4))} minutes, and the final snapshot its DeletionPolicy asks for needs it. The delete was not sent and the guard is put back; re-run the destroy once the ${noun} is 'available'`);
5556
+ }
5557
+ function isFinalSnapshotNotAvailableRefusal(error, stateFault) {
5558
+ if (!(error instanceof Error) || error.name !== stateFault) return false;
5559
+ return /(?:isn't|is not|isn’t) (?:currently )?in (?:the )?available state/i.test(error.message);
5560
+ }
5561
+ async function deleteAfterProtectionFlipWithFinalSnapshot(opts) {
5562
+ const budgetMs = finalSnapshotWaitBudgetMs(opts);
5563
+ const startTime = Date.now();
5564
+ await settleBeforeFinalSnapshot(opts, startTime, budgetMs);
5565
+ let delay = 5e3;
5566
+ let refusals = 0;
5567
+ for (;;) try {
5568
+ await opts.send();
5569
+ return;
5570
+ } catch (error) {
5571
+ if (!isFinalSnapshotNotAvailableRefusal(error, opts.stateFault)) throw error;
5572
+ refusals += 1;
5573
+ opts.logger.debug(safeMsg`${opts.label} ${opts.logicalId}: final-snapshot delete refused as not 'available' (refusal ${String(refusals)}); waiting for it to return to 'available' before retrying`);
5574
+ for (;;) {
5575
+ if (Date.now() - startTime + delay >= budgetMs) throw error;
5576
+ await opts.sleep(delay);
5577
+ delay = Math.min(delay * 2, 1e4);
5578
+ const current = await opts.read();
5579
+ if (current === void 0) break;
5580
+ if (current.deletionProtection === false && isProceedDbStatus(current.status)) break;
5581
+ if (current.deletionProtection === true || isTerminalDbStatus(current.status)) throw error;
5582
+ }
5583
+ }
5343
5584
  }
5344
- function emrInstancesReplacingPart(value) {
5345
- if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
5346
- const instances = withoutKeys(value, EMR_INSTANCES_IN_PLACE_MEMBERS);
5347
- const strip = (key, keys) => {
5348
- if (!(key in instances)) return;
5349
- const member = instances[key];
5350
- instances[key] = Array.isArray(member) ? member.map((entry) => withoutKeys(entry, keys)) : withoutKeys(member, keys);
5585
+
5586
+ // src/provisioning/providers/deletion-protection-compensation.ts
5587
+ function rdsFamilyProtectionSite(opts) {
5588
+ return {
5589
+ subject: `${opts.serviceLabel} ${opts.kind === "cluster" ? "DBCluster" : "DBInstance"}`,
5590
+ guardName: "DeletionProtection",
5591
+ noun: opts.kind,
5592
+ isNotFound: opts.isNotFound,
5593
+ notFoundMeaning: `${opts.serviceLabel} answered ${opts.notFoundFault}. That most commonly means the ${opts.kind} is gone, and it can also mean it is not in this region or account.`,
5594
+ commands: () => {
5595
+ const aws = pasteableAwsCommand();
5596
+ const regionArg = opts.region ? aws` --region ${opts.region}` : aws``;
5597
+ const id = opts.physicalId;
5598
+ const svc = opts.cliService;
5599
+ const service = svc === "rds" ? aws`rds` : svc === "docdb" ? aws`docdb` : aws`neptune`;
5600
+ const check = opts.kind === "cluster" ? aws`aws ${service} describe-db-clusters --db-cluster-identifier ${id}${regionArg}` : aws`aws ${service} describe-db-instances --db-instance-identifier ${id}${regionArg}`;
5601
+ const restore = opts.kind === "cluster" ? aws`aws ${service} modify-db-cluster --db-cluster-identifier ${id}${regionArg} --deletion-protection --apply-immediately` : aws`aws ${service} modify-db-instance --db-instance-identifier ${id}${regionArg} --deletion-protection --apply-immediately`;
5602
+ return {
5603
+ check: check.render(),
5604
+ restoreAfterNotFound: restore.render(),
5605
+ restoreLive: restore.render()
5606
+ };
5607
+ }
5351
5608
  };
5352
- strip("CoreInstanceGroup", EMR_GROUP_IN_PLACE_MEMBERS);
5353
- strip("TaskInstanceGroups", EMR_GROUP_IN_PLACE_MEMBERS);
5354
- strip("CoreInstanceFleet", EMR_FLEET_IN_PLACE_MEMBERS);
5355
- strip("TaskInstanceFleets", EMR_FLEET_IN_PLACE_MEMBERS);
5356
- return instances;
5357
- }
5358
- function elastiCachePreferredAvailabilityZonesMovedToDisjoint(oldValue, newValue) {
5359
- if (!Array.isArray(oldValue) || !Array.isArray(newValue)) return false;
5360
- if (oldValue.length === 0 || newValue.length === 0) return false;
5361
- if (![...oldValue, ...newValue].every((z) => typeof z === "string")) return false;
5362
- return !newValue.some((z) => oldValue.includes(z));
5363
- }
5364
- function elastiCacheLeftSingleAzWithoutZones(siblings) {
5365
- if (siblings === void 0) return false;
5366
- const { oldProperties: prev, newProperties: next } = siblings;
5367
- return prev["Engine"] === "memcached" && next["Engine"] === "memcached" && prev["PreferredAvailabilityZone"] == null && next["PreferredAvailabilityZone"] == null && next["PreferredAvailabilityZones"] == null && (next["AZMode"] == null || next["AZMode"] === "single-az");
5368
- }
5369
- function elastiCacheMovedSingleToCrossAz(siblings) {
5370
- if (siblings === void 0) return false;
5371
- const { oldProperties: prev, newProperties: next } = siblings;
5372
- const zones = next["PreferredAvailabilityZones"];
5373
- return prev["Engine"] === "memcached" && next["Engine"] === "memcached" && prev["AZMode"] === "single-az" && next["AZMode"] === "cross-az" && prev["PreferredAvailabilityZone"] == null && next["PreferredAvailabilityZone"] == null && prev["PreferredAvailabilityZones"] == null && Array.isArray(zones) && zones.every((z) => typeof z === "string") && new Set(zones).size >= 2 && isDeepStrictEqual(prev["NumCacheNodes"], next["NumCacheNodes"]) && zones.length === Number(next["NumCacheNodes"]);
5374
- }
5375
- function elastiCacheAzModeRemovedFromSingleAz(oldValue, newValue, siblings) {
5376
- return oldValue === "single-az" && newValue == null && elastiCacheLeftSingleAzWithoutZones(siblings);
5377
- }
5378
- function elastiCachePreferredAvailabilityZonesRemovedFromSingleAz(oldValue, newValue, siblings) {
5379
- return Array.isArray(oldValue) && oldValue.length > 0 && newValue == null && siblings?.oldProperties["AZMode"] === "single-az" && elastiCacheLeftSingleAzWithoutZones(siblings);
5380
- }
5381
- function elastiCachePreferredAvailabilityZonesReplaced(oldValue, newValue, siblings) {
5382
- return elastiCachePreferredAvailabilityZonesMovedToDisjoint(oldValue, newValue) || elastiCachePreferredAvailabilityZonesRemovedFromSingleAz(oldValue, newValue, siblings) || oldValue == null && newValue != null && elastiCacheMovedSingleToCrossAz(siblings);
5383
- }
5384
- function emrClusterInstancesReplaced(oldValue, newValue) {
5385
- if (oldValue === void 0 && newValue === void 0) return true;
5386
- return !isDeepStrictEqual(emrInstancesReplacingPart(oldValue), emrInstancesReplacingPart(newValue));
5387
- }
5388
- const AURORA = "aurora";
5389
- const AURORA_MYSQL = "aurora-mysql";
5390
- const DEPRECATED_ORACLE_SE_ENGINES = /* @__PURE__ */ new Set(["oracle-se", "oracle-se1"]);
5391
- const ORACLE_SE2 = "oracle-se2";
5392
- const ORACLE_CDB_CONVERSIONS = /* @__PURE__ */ new Map([["oracle-ee", "oracle-ee-cdb"], ["oracle-se2", "oracle-se2-cdb"]]);
5393
- const ORACLE_CDB_ENGINES = new Set(ORACLE_CDB_CONVERSIONS.values());
5394
- function enginePair(oldValue, newValue) {
5395
- return typeof oldValue === "string" && typeof newValue === "string" ? [oldValue, newValue] : void 0;
5396
- }
5397
- function dbClusterEngineChangeReplaces(oldValue, newValue) {
5398
- const pair = enginePair(oldValue, newValue);
5399
- if (pair === void 0) return false;
5400
- const [before, after] = pair;
5401
- return !(before === after || before === AURORA && after === AURORA_MYSQL);
5402
- }
5403
- function dbInstanceEngineChangeIsInPlace(oldValue, newValue) {
5404
- const pair = enginePair(oldValue, newValue);
5405
- if (pair === void 0) return false;
5406
- const [before, after] = pair;
5407
- const from = before.toLowerCase();
5408
- const to = after.toLowerCase();
5409
- return before === after || before === AURORA && after === AURORA_MYSQL || DEPRECATED_ORACLE_SE_ENGINES.has(from) && to === ORACLE_SE2 || ORACLE_CDB_CONVERSIONS.get(from) === to || from === to && ORACLE_CDB_ENGINES.has(to);
5410
- }
5411
- function dbInstanceEngineChangeReplaces(oldValue, newValue) {
5412
- if (enginePair(oldValue, newValue) === void 0) return false;
5413
- return !dbInstanceEngineChangeIsInPlace(oldValue, newValue);
5414
- }
5415
- function recordSetGroupRecordZoneChanged(oldValue, newValue, siblings) {
5416
- const groupZone = (props) => props?.["HostedZoneId"] !== void 0 || props?.["HostedZoneName"] !== void 0;
5417
- if (groupZone(siblings?.oldProperties) || groupZone(siblings?.newProperties)) return false;
5418
- const recordZone = (value) => {
5419
- if (!Array.isArray(value)) return void 0;
5420
- for (const record of value) {
5421
- if (record === null || typeof record !== "object" || Array.isArray(record)) continue;
5422
- const r = record;
5423
- if (r["HostedZoneId"] !== void 0 || r["HostedZoneName"] !== void 0) return r;
5609
+ }
5610
+ function isResourceNotFoundException(error) {
5611
+ return typeof error === "object" && error !== null && error.name === "ResourceNotFoundException";
5612
+ }
5613
+ function logGroupProtectionSite(physicalId, region) {
5614
+ return {
5615
+ subject: "Log group",
5616
+ guardName: "DeletionProtectionEnabled",
5617
+ noun: "log group",
5618
+ isNotFound: isResourceNotFoundException,
5619
+ notFoundMeaning: "CloudWatch Logs answered ResourceNotFoundException. That most commonly means the log group is gone, and it can also mean it is not in this region or account.",
5620
+ commands: () => {
5621
+ const aws = pasteableAwsCommand();
5622
+ const regionArg = region ? aws` --region ${region}` : aws``;
5623
+ const restore = aws`aws logs put-log-group-deletion-protection --log-group-identifier ${physicalId}${regionArg} --deletion-protection-enabled`;
5624
+ return {
5625
+ check: aws`aws logs describe-log-groups --log-group-identifiers ${physicalId}${regionArg}`.render(),
5626
+ restoreAfterNotFound: restore.render(),
5627
+ restoreLive: restore.render()
5628
+ };
5424
5629
  }
5425
5630
  };
5426
- const before = recordZone(oldValue);
5427
- const after = recordZone(newValue);
5428
- if (before === void 0 || after === void 0) return false;
5429
- return route53ZoneReferenceChanged(void 0, void 0, {
5430
- oldProperties: before,
5431
- newProperties: after
5432
- });
5433
5631
  }
5434
- function route53ZoneReferenceChanged(_oldValue, _newValue, siblings) {
5435
- if (!siblings) return true;
5436
- const read = (props) => {
5437
- const id = props["HostedZoneId"];
5438
- const name = props["HostedZoneName"];
5439
- return {
5440
- id: typeof id === "string" ? id.replace(/^\/hostedzone\//, "") : id,
5441
- name: typeof name === "string" ? name.replace(/\.$/, "").toLowerCase() : name
5442
- };
5632
+ function userPoolProtectionSite(physicalId, region) {
5633
+ return {
5634
+ subject: "Cognito User Pool",
5635
+ guardName: "DeletionProtection",
5636
+ noun: "user pool",
5637
+ isNotFound: isResourceNotFoundException,
5638
+ notFoundMeaning: "Cognito answered ResourceNotFoundException. That most commonly means the user pool is gone, and it can also mean it is not in this region or account.",
5639
+ commands: () => {
5640
+ const aws = pasteableAwsCommand();
5641
+ const regionArg = region ? aws` --region ${region}` : aws``;
5642
+ const restore = aws`aws cognito-idp update-user-pool --user-pool-id ${physicalId}${regionArg} --deletion-protection ACTIVE`;
5643
+ return {
5644
+ check: aws`aws cognito-idp describe-user-pool --user-pool-id ${physicalId}${regionArg}`.render(),
5645
+ restoreAfterNotFound: restore.render(),
5646
+ restoreLive: restore.render()
5647
+ };
5648
+ },
5649
+ restoreCaveat: "Note UpdateUserPool resets some members a call omits (self sign-up, Lambda triggers, advanced security, AutoVerifiedAttributes and a customer-managed KeyConfiguration among them), so send your complete pool configuration alongside that flag rather than the flag alone."
5443
5650
  };
5444
- const before = read(siblings.oldProperties);
5445
- const after = read(siblings.newProperties);
5446
- const readable = (v) => v === void 0 || typeof v === "string";
5447
- if (![
5448
- before.id,
5449
- before.name,
5450
- after.id,
5451
- after.name
5452
- ].every(readable)) return true;
5453
- if (before.id !== void 0 && after.id !== void 0) return before.id !== after.id;
5454
- if (before.id === void 0 && after.id === void 0) return before.name !== after.name;
5455
- return false;
5456
5651
  }
5457
- function ssmDocumentChangeReplaces(_oldValue, _newValue, siblings) {
5458
- return siblings?.newProperties["UpdateMethod"] !== "NewVersion";
5652
+ async function compensateProtectionFlip(opts) {
5653
+ if (!opts.flip.flippedOffByThisRun) return "not-applicable";
5654
+ if (opts.flip.deleteAccepted) return "not-applicable";
5655
+ if (!isTerminalDeleteFailure(opts.error)) return "not-applicable";
5656
+ const { site } = opts;
5657
+ try {
5658
+ const result = await opts.reEnable();
5659
+ if (result === "read-on-write-failed") {
5660
+ opts.logger.warn(safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection tried to turn ${site.guardName} off; ${opts.physicalId} ` + safeMsg`read it on afterwards, but writing it back failed, so cdkd cannot confirm ` + safeMsg`it. Check with: ${site.commands().check}. The delete failure below is the outcome.`);
5661
+ return "failed";
5662
+ }
5663
+ opts.logger.warn(result === "already-on" ? safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection tried to turn ${site.guardName} off; ${opts.physicalId} ` + safeMsg`already read it on, and cdkd wrote it back (AWS accepted the write). The ` + safeMsg`delete failure below is the outcome.` : safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection had turned ${site.guardName} off, so it was ` + safeMsg`re-enabled on ${opts.physicalId}. The delete failure below is the outcome.`);
5664
+ return "restored";
5665
+ } catch (reEnableError) {
5666
+ const mask = maskerOrIdentity(opts.mask);
5667
+ const failure = describeAwsFailure(reEnableError);
5668
+ const detail = mask(failure.summary);
5669
+ if (failure.redacted) opts.logger.debug(mask(safeMsg`${site.subject} ${opts.logicalId}: re-enabling ${site.guardName} on ` + safeMsg`${opts.physicalId} failed: ${mask(failure.detail)}`));
5670
+ const commands = site.commands();
5671
+ const caveat = site.restoreCaveat ? ` ${site.restoreCaveat}` : "";
5672
+ if (site.isNotFound(reEnableError)) {
5673
+ opts.logger.warn(safeMsg`${site.subject} ${opts.logicalId}: could not re-enable ` + safeMsg`${site.guardName} on ${opts.physicalId} after the delete failed — ` + safeMsg`${site.notFoundMeaning} If it still exists, its deletion protection is OFF. ` + safeMsg`Check with: ${commands.check} and if it is there, restore it with: ` + safeMsg`${commands.restoreAfterNotFound}.${caveat} (${detail})`);
5674
+ return "failed";
5675
+ }
5676
+ opts.logger.error(safeMsg`${site.subject} ${opts.logicalId}: could NOT re-enable ` + safeMsg`${site.guardName} on ${opts.physicalId} after the delete failed — ` + safeMsg`that ${site.noun} is LIVE with its deletion protection still off. Restore it with: ` + safeMsg`${commands.restoreLive}.${caveat} (${detail})`);
5677
+ return "failed";
5678
+ }
5679
+ }
5680
+ async function observeThenDisableProtection(opts) {
5681
+ let observedOn = false;
5682
+ try {
5683
+ observedOn = await opts.observe();
5684
+ } catch (observeError) {
5685
+ const mask = maskerOrIdentity(opts.mask);
5686
+ opts.logger.debug(mask(safeMsg`Could not read ${opts.guardName} on ${mask(opts.physicalId)} before disabling it: ${mask(describeAwsFailure(observeError).detail)}`));
5687
+ }
5688
+ await opts.disable();
5689
+ if (observedOn) opts.flip.flippedOffByThisRun = true;
5459
5690
  }
5460
-
5461
- // src/deployment/deploy-value-equality.ts
5462
- function isReplacementCeiling(pc) {
5463
- return pc.requiresReplacement && (pc.inPlacePropagated === true || pc.replacementPropagated === true);
5464
- }
5465
- function keyOrderFreeJson(value) {
5466
- return JSON.stringify(value, (_key, node) => {
5467
- if (node === null || typeof node !== "object" || Array.isArray(node)) return node;
5468
- const sorted = Object.create(null);
5469
- for (const key of Object.keys(node).sort()) sorted[key] = node[key];
5470
- return sorted;
5471
- });
5691
+ async function deleteWithProtectionCompensation(opts) {
5692
+ const flip = opts.registry.acquire(opts.key, opts.reuseWithinMs ?? 18e5, opts.clock);
5693
+ try {
5694
+ await opts.run(flip);
5695
+ } catch (error) {
5696
+ await settleProtectionFlip({
5697
+ registry: opts.registry,
5698
+ key: opts.key,
5699
+ flip,
5700
+ error,
5701
+ compensation: opts.compensation
5702
+ });
5703
+ throw error;
5704
+ }
5705
+ opts.registry.release(opts.key);
5472
5706
  }
5473
- const IAM_ACTION = /^[a-z0-9-]{1,64}:[A-Za-z0-9*]{1,128}$/;
5474
- const ACTION_IN_MESSAGE = [/\bperform:\s*([a-z0-9-]{1,64}:[A-Za-z0-9*]{1,128})(?=\s|$|[.,;])/, /\ballows the ([a-z0-9-]{1,64}:[A-Za-z0-9*]{1,128}) action\b/];
5475
- const DENIAL_CLASSES = /* @__PURE__ */ new Set([
5476
- "AccessDenied",
5477
- "AccessDeniedException",
5478
- "AuthorizationError",
5479
- "UnauthorizedOperation"
5480
- ]);
5481
- function readDenialOf(error) {
5707
+ async function settleProtectionFlip(opts) {
5708
+ let outcome = "failed";
5482
5709
  try {
5483
- const name = error?.name;
5484
- if (typeof name !== "string" || !DENIAL_CLASSES.has(name)) return void 0;
5485
- const message = error.message;
5486
- let action;
5487
- if (typeof message === "string") for (const pattern of ACTION_IN_MESSAGE) {
5488
- const found = pattern.exec(message)?.[1];
5489
- if (found !== void 0 && IAM_ACTION.test(found)) {
5490
- action = found;
5491
- break;
5492
- }
5493
- }
5494
- return {
5495
- ...action !== void 0 && { action },
5496
- errorClass: name
5497
- };
5498
- } catch {
5499
- return;
5710
+ outcome = await compensateProtectionFlip({
5711
+ ...opts.compensation,
5712
+ flip: opts.flip,
5713
+ error: opts.error
5714
+ });
5715
+ } catch {}
5716
+ if (isTerminalDeleteFailure(opts.error) && outcome !== "failed") {
5717
+ opts.registry.release(opts.key);
5718
+ return true;
5500
5719
  }
5720
+ return false;
5501
5721
  }
5502
- function grantSentence(denied) {
5503
- const what = denied.action !== void 0 ? `the ${denied.action} permission` : `the read permission the provider's readback of this resource type needs`;
5504
- return `AWS denied the read${denied.errorClass !== void 0 ? ` (${denied.errorClass})` : ""}, and re-running would be denied the same way: grant ${what} to the credentials cdkd runs with, then re-run`;
5722
+
5723
+ // src/provisioning/not-gone.ts
5724
+ const NOT_GONE = Symbol.for("cdkd.notGone");
5725
+ const MAX_DEPTH = 10;
5726
+ function markNotGone(error) {
5727
+ try {
5728
+ if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
5729
+ Object.defineProperty(error, NOT_GONE, {
5730
+ value: true,
5731
+ enumerable: false,
5732
+ writable: false,
5733
+ configurable: true
5734
+ });
5735
+ } catch {}
5736
+ return error;
5505
5737
  }
5506
- function liveHoldsFreshLeaves(live, leaves) {
5507
- for (const leaf of leaves) {
5508
- let node = live;
5509
- for (const segment of leaf.path) {
5510
- if (typeof segment === "number") {
5511
- if (!Array.isArray(node) || segment >= node.length) return false;
5512
- node = node[segment];
5513
- continue;
5514
- }
5515
- if (node === null || typeof node !== "object" || Array.isArray(node)) return false;
5516
- if (!Object.prototype.hasOwnProperty.call(node, segment)) return false;
5517
- node = node[segment];
5738
+ function isMarkedNotGone(error) {
5739
+ try {
5740
+ let current = error;
5741
+ for (let depth = 0; depth < MAX_DEPTH && typeof current === "object" && current !== null; depth++) {
5742
+ if (Object.prototype.hasOwnProperty.call(current, NOT_GONE)) return true;
5743
+ current = current.cause;
5518
5744
  }
5519
- if (typeof leaf.plaintext === "string") {
5520
- if (typeof node !== "string" || node !== leaf.plaintext) return false;
5521
- } else if (node === void 0 || keyOrderFreeJson(node) !== keyOrderFreeJson(leaf.plaintext)) return false;
5522
- }
5523
- return true;
5745
+ } catch {}
5746
+ return false;
5524
5747
  }
5525
- function outputMapsEqual(a, b) {
5526
- return deepEqualValue(a, b);
5748
+
5749
+ // src/provisioning/import-helpers.ts
5750
+ function remedyLogicalId(logicalId) {
5751
+ return isPasteableIdent(logicalId) ? logicalId : commandHole("logicalId");
5527
5752
  }
5528
- function deepEqualValue(a, b) {
5529
- if (a === b) return true;
5530
- if (a == null || b == null) return a === b;
5531
- if (typeof a !== typeof b) return false;
5532
- if (typeof a !== "object") return false;
5533
- if (Array.isArray(a) || Array.isArray(b)) {
5534
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
5535
- return a.every((v, i) => deepEqualValue(v, b[i]));
5536
- }
5537
- const ao = a;
5538
- const bo = b;
5539
- const ak = Object.keys(ao);
5540
- if (ak.length !== Object.keys(bo).length) return false;
5541
- for (const k of ak) {
5542
- if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
5543
- if (!deepEqualValue(ao[k], bo[k])) return false;
5753
+ function importRemedyCommand(stackName, assignment) {
5754
+ return pasteableCommand("cdkd import", [
5755
+ stackName !== void 0 && isPasteableIdent(stackName) ? { literal: stackName } : { hole: "stackName" },
5756
+ { literal: "--resource" },
5757
+ { literal: assignment.replace(/(?<!')<([A-Za-z]+)>(?!')/g, (_m, n) => commandHole(n)) }
5758
+ ]).command;
5759
+ }
5760
+ function isPlainImportValue(value) {
5761
+ return isPlainIdent(value, { maxCodePoints: SECRET_REF_MAX_CODE_POINTS });
5762
+ }
5763
+ function isQuotableImportValue(value) {
5764
+ return value.split("|").every((segment) => segment === "" || isPlainImportValue(segment));
5765
+ }
5766
+ function quotedRemedyLogicalId(logicalId) {
5767
+ return isPasteableIdent(logicalId) ? logicalId : "<logicalId>";
5768
+ }
5769
+ function refusalTypeShown(resourceType) {
5770
+ return resourceTypeShown(resourceType) === resourceType ? resourceType : "(resource type not shown: it is not a plain identifier)";
5771
+ }
5772
+ const VALUE_NOT_SHOWN = "(not shown: it is not a plain identifier)";
5773
+ const PLAIN_JSON = /^[A-Za-z0-9"{}[\]:,._@/+=~-]+$/;
5774
+ function isPlainImportJson(value) {
5775
+ const json = JSON.stringify(value);
5776
+ return typeof json === "string" && json.length <= 2048 && PLAIN_JSON.test(json);
5777
+ }
5778
+ function readNameProperty(input, propertyName) {
5779
+ const value = input.properties?.[propertyName];
5780
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5781
+ }
5782
+ function resolveExplicitPhysicalId(input, nameProperty) {
5783
+ if (input.knownPhysicalId) return input.knownPhysicalId;
5784
+ if (nameProperty) {
5785
+ const name = readNameProperty(input, nameProperty);
5786
+ if (name) return name;
5544
5787
  }
5545
- return true;
5788
+ }
5789
+ function normalizeAwsTagsToCfn(tags) {
5790
+ if (!tags) return [];
5791
+ const out = [];
5792
+ if (Array.isArray(tags)) for (const t of tags) {
5793
+ const obj = t;
5794
+ const k = (typeof obj["Key"] === "string" ? obj["Key"] : void 0) ?? (typeof obj["TagKey"] === "string" ? obj["TagKey"] : void 0) ?? (typeof obj["key"] === "string" ? obj["key"] : void 0);
5795
+ const v = (typeof obj["Value"] === "string" ? obj["Value"] : void 0) ?? (typeof obj["TagValue"] === "string" ? obj["TagValue"] : void 0) ?? (typeof obj["value"] === "string" ? obj["value"] : void 0);
5796
+ if (typeof k !== "string" || k.length === 0) continue;
5797
+ if (k.startsWith("aws:")) continue;
5798
+ out.push({
5799
+ Key: k,
5800
+ Value: typeof v === "string" ? v : ""
5801
+ });
5802
+ }
5803
+ else for (const [k, v] of Object.entries(tags)) {
5804
+ if (!k || k.startsWith("aws:")) continue;
5805
+ out.push({
5806
+ Key: k,
5807
+ Value: typeof v === "string" ? v : ""
5808
+ });
5809
+ }
5810
+ out.sort((a, b) => a.Key < b.Key ? -1 : a.Key > b.Key ? 1 : 0);
5811
+ return out;
5546
5812
  }
5547
5813
 
5548
- // src/analyzer/replacement-rules/rds-immutability.ts
5549
- const UNRESOLVED = Symbol("unresolved");
5550
- const UNDECIDABLE = Symbol("undecidable");
5551
- function javaString(value) {
5552
- if (value === void 0 || value === null) return null;
5553
- return typeof value === "string" ? value : UNRESOLVED;
5554
- }
5555
- function stringChange(oldValue, newValue) {
5556
- if (oldValue === void 0 && newValue === void 0) return {
5557
- before: UNRESOLVED,
5558
- after: UNRESOLVED,
5559
- equal: false
5560
- };
5561
- const before = javaString(oldValue);
5562
- const after = javaString(newValue);
5563
- return {
5564
- before,
5565
- after,
5566
- equal: before === UNRESOLVED && after === UNRESOLVED ? keyOrderFreeJson(oldValue) === keyOrderFreeJson(newValue) : before === after
5814
+ // src/provisioning/region-check.ts
5815
+ function holderRefusalRun(context) {
5816
+ return context?.stackDestroy === true ? {
5817
+ noun: "destroy",
5818
+ again: "destroy again",
5819
+ rerun: "run the destroy again"
5820
+ } : {
5821
+ noun: "run",
5822
+ again: "run the command again",
5823
+ rerun: "run the command again"
5567
5824
  };
5568
5825
  }
5569
- function javaBoolean(value) {
5570
- if (value === void 0 || value === null) return null;
5571
- if (value === true || value === "true") return true;
5572
- if (value === false || value === "false") return false;
5573
- return UNDECIDABLE;
5574
- }
5575
- const isNullOrEmpty = (value) => value === null || value === "";
5576
- function dbInstanceRestoreInputChangeReplaces(oldValue, newValue) {
5577
- const { after, equal } = stringChange(oldValue, newValue);
5578
- return !equal && !isNullOrEmpty(after);
5579
- }
5580
- function dbInstanceUseLatestRestorableTimeChangeReplaces(oldValue, newValue) {
5581
- if (oldValue === void 0 && newValue === void 0) return true;
5582
- const before = javaBoolean(oldValue);
5583
- const after = javaBoolean(newValue);
5584
- if (before === UNDECIDABLE || after === UNDECIDABLE) return false;
5585
- return before !== after && after === true;
5586
- }
5587
- function dbInstanceReplicaSourceChangeReplaces(oldValue, newValue) {
5588
- const { before, after, equal } = stringChange(oldValue, newValue);
5589
- if (equal) return false;
5590
- return !(!isNullOrEmpty(before) && isNullOrEmpty(after));
5591
- }
5592
- function dbInstancePerformanceInsightsKmsKeyChangeReplaces(oldValue, newValue) {
5593
- const { before, equal } = stringChange(oldValue, newValue);
5594
- return !isNullOrEmpty(before) && !equal;
5595
- }
5596
- function dbInstanceAvailabilityZoneChangeReplaces(oldValue, newValue, siblings) {
5597
- const { after, equal } = stringChange(oldValue, newValue);
5598
- if (equal) return false;
5599
- if (isNullOrEmpty(after)) {
5600
- if (siblings === void 0) return false;
5601
- const multiAz = javaBoolean(siblings.newProperties["MultiAZ"]);
5602
- if (multiAz === UNDECIDABLE || multiAz === true) return false;
5603
- }
5604
- return true;
5826
+ function holderRefusalMask(context, mask) {
5827
+ const stack = context?.maskStackSecretNames;
5828
+ return stack === void 0 ? mask : (text) => mask(stack(text));
5829
+ }
5830
+ function assertRegionMatch(clientRegion, expectedRegion, resourceType, logicalId, physicalId, phase = "not-found", endpoint = "regional") {
5831
+ if (!expectedRegion) return;
5832
+ if (!clientRegion) throw new ProvisioningError(phase === "not-found" ? `Refusing to treat NotFound as idempotent delete success for ${logicalId} (${resourceType}): AWS client region is unknown but stack state expects ${expectedRegion}. The resource may exist in ${expectedRegion} and would be silently removed from state if this NotFound were trusted.` : `Refusing to ${phaseVerb(phase)} ${logicalId} (${resourceType}): AWS client region is unknown but stack state records the resource in ${expectedRegion}. ` + (endpoint === "global" ? `cdkd cannot confirm that this client was built for the stack this record belongs to, so the ${phaseVerb(phase)} is not issued. Point the ` : `cdkd cannot confirm that the physical id recorded in state names the resource this client would act on, so the ${phaseVerb(phase)} is not issued. Point the `) + `AWS client at ${expectedRegion} (AWS_REGION or your AWS profile) and re-run.`, resourceType, logicalId, physicalId);
5833
+ if (clientRegion !== expectedRegion) throw new ProvisioningError(phase === "not-found" ? `Refusing to treat NotFound as idempotent delete success for ${logicalId} (${resourceType}): AWS client region ${clientRegion} does not match stack state region ${expectedRegion}. The resource likely still exists in ${expectedRegion}; rerun the destroy with the correct region (e.g. --region ${expectedRegion}).` : `Refusing to ${phaseVerb(phase)} ${logicalId} (${resourceType}): AWS client region ${clientRegion} does not match stack state region ${expectedRegion}. ` + (endpoint === "global" ? `This service has one global endpoint, so the call would reach the same resource, but a client in ${clientRegion} was not built for the stack this ${expectedRegion} record belongs to, so the ${phaseVerb(phase)} is not issued. ` : `The physical id recorded in cdkd state names a resource in ${expectedRegion}, so this ${phaseVerb(phase)} would act on whatever carries that id in ${clientRegion} instead — which for a name-shaped physical id is a different resource that usually exists. `) + `Point the AWS client at ${expectedRegion} (AWS_REGION or your AWS profile) and re-run; when the run spans several regions at once (cdkd drift --all), select the stacks in one region per run, because no single client region is correct for all of them. If the recorded region is the wrong one, correct the state record (cdkd state show).`, resourceType, logicalId, physicalId);
5605
5834
  }
5606
- function dbClusterGlobalClusterChangeReplaces(oldValue, newValue) {
5607
- const { before, after, equal } = stringChange(oldValue, newValue);
5608
- if (!isNullOrEmpty(before) && isNullOrEmpty(after)) return false;
5609
- return !equal;
5835
+ function phaseVerb(phase) {
5836
+ return phase === "pre-update" ? "update" : "delete";
5610
5837
  }
5611
5838
 
5612
- // src/analyzer/replacement-rules/rules.ts
5613
- function initializeRules() {
5614
- this.rules.set("AWS::S3::Bucket", {
5615
- replacementProperties: /* @__PURE__ */ new Set([
5616
- "BucketName",
5617
- "BucketNamePrefix",
5618
- "BucketNamespace"
5619
- ]),
5620
- updateableProperties: /* @__PURE__ */ new Set([
5621
- "AbacStatus",
5622
- "MetadataConfiguration",
5623
- "Tags",
5624
- "VersioningConfiguration",
5625
- "LifecycleConfiguration",
5626
- "PublicAccessBlockConfiguration",
5627
- "BucketEncryption",
5628
- "LoggingConfiguration",
5629
- "WebsiteConfiguration",
5630
- "CorsConfiguration",
5631
- "NotificationConfiguration"
5632
- ])
5633
- });
5634
- this.rules.set("AWS::Lambda::Function", {
5635
- replacementProperties: /* @__PURE__ */ new Set(["FunctionName", "TenancyConfig"]),
5636
- updateableProperties: /* @__PURE__ */ new Set([
5637
- "Code",
5638
- "Handler",
5639
- "Runtime",
5640
- "Description",
5641
- "Timeout",
5642
- "MemorySize",
5643
- "Role",
5644
- "Environment",
5645
- "Tags",
5646
- "VpcConfig",
5647
- "DeadLetterConfig",
5648
- "TracingConfig",
5649
- "Layers",
5650
- "FileSystemConfigs",
5651
- "Architectures",
5652
- "CodeSigningConfigArn",
5653
- "RuntimeManagementConfig"
5654
- ]),
5655
- conditionalReplacements: /* @__PURE__ */ new Map([["DurableConfig", durableConfigPresenceToggled]])
5656
- });
5657
- this.rules.set("AWS::Lambda::LayerVersion", { replacementProperties: /* @__PURE__ */ new Set([
5658
- "Content",
5659
- "LayerName",
5660
- "Description",
5661
- "CompatibleRuntimes",
5662
- "CompatibleArchitectures",
5663
- "LicenseInfo"
5664
- ]) });
5665
- this.rules.set("AWS::Lambda::Version", { replacementProperties: /* @__PURE__ */ new Set([
5666
- "CodeSha256",
5667
- "Description",
5668
- "FunctionName",
5669
- "ProvisionedConcurrencyConfig",
5670
- "RuntimePolicy"
5671
- ]) });
5672
- this.rules.set("AWS::Lambda::EventInvokeConfig", {
5673
- replacementProperties: /* @__PURE__ */ new Set(["Qualifier"]),
5674
- conditionalReplacements: /* @__PURE__ */ new Map([["FunctionName", eventInvokeConfigFunctionChanged]]),
5675
- updateableProperties: /* @__PURE__ */ new Set([
5676
- "MaximumEventAgeInSeconds",
5677
- "MaximumRetryAttempts",
5678
- "DestinationConfig"
5679
- ])
5680
- });
5681
- this.rules.set("AWS::Batch::ComputeEnvironment", {
5682
- replacementProperties: /* @__PURE__ */ new Set(),
5683
- conditionalReplacements: /* @__PURE__ */ new Map([["ComputeResources", batchComputeResourcesChangeReplaces]])
5684
- });
5685
- this.rules.set("AWS::DynamoDB::GlobalTable", {
5686
- replacementProperties: /* @__PURE__ */ new Set(),
5687
- conditionalReplacements: /* @__PURE__ */ new Map([["LocalSecondaryIndexes", globalTableLocalSecondaryIndexesRemoved]])
5688
- });
5689
- this.rules.set("AWS::DynamoDB::Table", {
5690
- replacementProperties: /* @__PURE__ */ new Set(["TableName", "KeySchema"]),
5691
- updateableProperties: /* @__PURE__ */ new Set([
5692
- "BillingMode",
5693
- "ProvisionedThroughput",
5694
- "GlobalSecondaryIndexes",
5695
- "LocalSecondaryIndexes",
5696
- "StreamSpecification",
5697
- "SSESpecification",
5698
- "Tags",
5699
- "TimeToLiveSpecification",
5700
- "PointInTimeRecoverySpecification"
5701
- ]),
5702
- conditionalReplacements: /* @__PURE__ */ new Map([["AttributeDefinitions", attributeTypeChangedForSharedAttribute]])
5703
- });
5704
- this.rules.set("AWS::SQS::Queue", {
5705
- replacementProperties: /* @__PURE__ */ new Set(["QueueName", "FifoQueue"]),
5706
- updateableProperties: /* @__PURE__ */ new Set([
5707
- "DelaySeconds",
5708
- "MaximumMessageSize",
5709
- "MessageRetentionPeriod",
5710
- "ReceiveMessageWaitTimeSeconds",
5711
- "VisibilityTimeout",
5712
- "RedrivePolicy",
5713
- "Tags",
5714
- "ContentBasedDeduplication"
5715
- ])
5716
- });
5717
- this.rules.set("AWS::IAM::Role", {
5718
- replacementProperties: /* @__PURE__ */ new Set(["RoleName"]),
5719
- updateableProperties: /* @__PURE__ */ new Set([
5720
- "AssumeRolePolicyDocument",
5721
- "Description",
5722
- "ManagedPolicyArns",
5723
- "MaxSessionDuration",
5724
- "PermissionsBoundary",
5725
- "Policies",
5726
- "Tags"
5727
- ]),
5728
- conditionalReplacements: /* @__PURE__ */ new Map([["Path", iamRolePathChanged]])
5729
- });
5730
- this.rules.set("AWS::SNS::Topic", {
5731
- replacementProperties: /* @__PURE__ */ new Set(["TopicName"]),
5732
- updateableProperties: /* @__PURE__ */ new Set([
5733
- "DisplayName",
5734
- "Subscription",
5735
- "KmsMasterKeyId",
5736
- "Tags"
5737
- ])
5738
- });
5739
- this.rules.set("AWS::CodeCommit::Repository", {
5740
- replacementProperties: /* @__PURE__ */ new Set([]),
5741
- updateableProperties: /* @__PURE__ */ new Set([
5742
- "RepositoryName",
5743
- "RepositoryDescription",
5744
- "KmsKeyId",
5745
- "Tags"
5746
- ])
5747
- });
5748
- this.rules.set("AWS::ECR::Repository", {
5749
- replacementProperties: /* @__PURE__ */ new Set(["RepositoryName"]),
5750
- updateableProperties: /* @__PURE__ */ new Set([
5751
- "ImageScanningConfiguration",
5752
- "ImageTagMutability",
5753
- "LifecyclePolicy",
5754
- "RepositoryPolicyText",
5755
- "Tags"
5756
- ])
5757
- });
5758
- this.rules.set("AWS::Logs::LogGroup", {
5759
- replacementProperties: /* @__PURE__ */ new Set(["LogGroupName"]),
5760
- updateableProperties: /* @__PURE__ */ new Set(["RetentionInDays", "KmsKeyId"])
5761
- });
5762
- this.rules.set("AWS::Kinesis::Stream", {
5763
- replacementProperties: /* @__PURE__ */ new Set(["Name"]),
5764
- updateableProperties: /* @__PURE__ */ new Set([
5765
- "RetentionPeriodHours",
5766
- "ShardCount",
5767
- "StreamModeDetails",
5768
- "StreamEncryption",
5769
- "Tags"
5770
- ])
5771
- });
5772
- this.rules.set("AWS::SecretsManager::Secret", {
5773
- replacementProperties: /* @__PURE__ */ new Set(["Name"]),
5774
- updateableProperties: /* @__PURE__ */ new Set([
5775
- "Description",
5776
- "KmsKeyId",
5777
- "SecretString",
5778
- "GenerateSecretString",
5779
- "ReplicaRegions",
5780
- "Tags"
5781
- ])
5782
- });
5783
- this.rules.set("AWS::StepFunctions::StateMachine", {
5784
- replacementProperties: /* @__PURE__ */ new Set(["StateMachineName", "StateMachineType"]),
5785
- updateableProperties: /* @__PURE__ */ new Set([
5786
- "DefinitionString",
5787
- "DefinitionS3Location",
5788
- "Definition",
5789
- "DefinitionSubstitutions",
5790
- "RoleArn",
5791
- "LoggingConfiguration",
5792
- "TracingConfiguration",
5793
- "Tags",
5794
- "EncryptionConfiguration"
5795
- ])
5796
- });
5797
- this.rules.set("AWS::Events::Rule", {
5798
- replacementProperties: /* @__PURE__ */ new Set(["Name", "EventBusName"]),
5799
- updateableProperties: /* @__PURE__ */ new Set([
5800
- "ScheduleExpression",
5801
- "EventPattern",
5802
- "State",
5803
- "Description",
5804
- "Targets",
5805
- "RoleArn"
5806
- ])
5807
- });
5808
- this.rules.set("AWS::SSM::Parameter", {
5809
- replacementProperties: /* @__PURE__ */ new Set(["Name"]),
5810
- updateableProperties: /* @__PURE__ */ new Set([
5811
- "Value",
5812
- "Description",
5813
- "Type",
5814
- "Tier",
5815
- "AllowedPattern",
5816
- "Policies",
5817
- "DataType",
5818
- "Tags"
5819
- ])
5820
- });
5821
- this.rules.set("AWS::SSM::Document", {
5822
- replacementProperties: /* @__PURE__ */ new Set(["Name", "DocumentType"]),
5823
- conditionalReplacements: new Map([
5824
- "Content",
5825
- "Attachments",
5826
- "DocumentFormat",
5827
- "Requires",
5828
- "TargetType",
5829
- "VersionName"
5830
- ].map((prop) => [prop, ssmDocumentChangeReplaces]))
5831
- });
5832
- this.rules.set("AWS::Budgets::Budget", {
5833
- replacementProperties: /* @__PURE__ */ new Set(),
5834
- updateableProperties: /* @__PURE__ */ new Set(["NotificationsWithSubscribers", "ResourceTags"]),
5835
- conditionalReplacements: /* @__PURE__ */ new Map([["Budget", budgetNameChanged]])
5836
- });
5837
- this.rules.set("AWS::Glue::Table", {
5838
- replacementProperties: /* @__PURE__ */ new Set(),
5839
- conditionalReplacements: /* @__PURE__ */ new Map([["TableInput", glueTableNameChanged]])
5840
- });
5841
- this.rules.set("AWS::Route53::RecordSet", {
5842
- replacementProperties: /* @__PURE__ */ new Set(),
5843
- conditionalReplacements: /* @__PURE__ */ new Map([["HostedZoneId", route53ZoneReferenceChanged], ["HostedZoneName", route53ZoneReferenceChanged]])
5844
- });
5845
- this.rules.set("AWS::Route53::RecordSetGroup", {
5846
- replacementProperties: /* @__PURE__ */ new Set(),
5847
- updateableProperties: /* @__PURE__ */ new Set(["Comment"]),
5848
- conditionalReplacements: /* @__PURE__ */ new Map([
5849
- ["HostedZoneId", route53ZoneReferenceChanged],
5850
- ["HostedZoneName", route53ZoneReferenceChanged],
5851
- ["RecordSets", recordSetGroupRecordZoneChanged]
5852
- ])
5853
- });
5854
- this.rules.set("AWS::CloudWatch::Alarm", {
5855
- replacementProperties: /* @__PURE__ */ new Set(["AlarmName"]),
5856
- updateableProperties: /* @__PURE__ */ new Set([
5857
- "ComparisonOperator",
5858
- "EvaluationPeriods",
5859
- "DatapointsToAlarm",
5860
- "Threshold",
5861
- "TreatMissingData",
5862
- "MetricName",
5863
- "Namespace",
5864
- "Period",
5865
- "Statistic",
5866
- "ExtendedStatistic",
5867
- "Dimensions",
5868
- "Metrics",
5869
- "AlarmDescription",
5870
- "ActionsEnabled",
5871
- "AlarmActions",
5872
- "OKActions",
5873
- "InsufficientDataActions",
5874
- "Unit",
5875
- "EvaluateLowSampleCountPercentile",
5876
- "ThresholdMetricId",
5877
- "Tags"
5878
- ])
5879
- });
5880
- this.rules.set("AWS::ApiGateway::RestApi", {
5881
- replacementProperties: /* @__PURE__ */ new Set(),
5882
- updateableProperties: /* @__PURE__ */ new Set([
5883
- "Name",
5884
- "Description",
5885
- "Version",
5886
- "Body",
5887
- "BodyS3Location",
5888
- "Mode",
5889
- "FailOnWarnings",
5890
- "Parameters",
5891
- "CloneFrom",
5892
- "Policy",
5893
- "EndpointConfiguration",
5894
- "BinaryMediaTypes",
5895
- "MinimumCompressionSize",
5896
- "ApiKeySourceType",
5897
- "DisableExecuteApiEndpoint",
5898
- "SecurityPolicy",
5899
- "EndpointAccessMode",
5900
- "Tags"
5901
- ])
5902
- });
5903
- this.rules.set("AWS::AppSync::GraphQLApi", {
5904
- replacementProperties: /* @__PURE__ */ new Set(["ApiType", "Visibility"]),
5905
- updateableProperties: /* @__PURE__ */ new Set([
5906
- "AuthenticationType",
5907
- "LogConfig",
5908
- "XrayEnabled",
5909
- "Tags",
5910
- "UserPoolConfig",
5911
- "OpenIDConnectConfig",
5912
- "LambdaAuthorizerConfig",
5913
- "AdditionalAuthenticationProviders",
5914
- "EnhancedMetricsConfig",
5915
- "EnvironmentVariables",
5916
- "IntrospectionConfig",
5917
- "QueryDepthLimit",
5918
- "ResolverCountLimit",
5919
- "OwnerContact",
5920
- "MergedApiExecutionRoleArn"
5921
- ])
5922
- });
5923
- this.rules.set("AWS::RDS::DBProxy", { replacementProperties: /* @__PURE__ */ new Set([
5924
- "DBProxyName",
5925
- "EngineFamily",
5926
- "VpcSubnetIds",
5927
- "EndpointNetworkType",
5928
- "TargetConnectionNetworkType"
5929
- ]) });
5930
- this.rules.set("AWS::RDS::DBProxyEndpoint", { replacementProperties: /* @__PURE__ */ new Set([
5931
- "DBProxyName",
5932
- "DBProxyEndpointName",
5933
- "VpcSubnetIds",
5934
- "TargetRole",
5935
- "EndpointNetworkType"
5936
- ]) });
5937
- this.rules.set("AWS::S3Tables::Table", { replacementProperties: /* @__PURE__ */ new Set([
5938
- "TableBucketARN",
5939
- "OpenTableFormat",
5940
- "IcebergMetadata",
5941
- "StorageClassConfiguration",
5942
- "WithoutMetadata"
5943
- ]) });
5944
- this.rules.set("AWS::RDS::DBProxyTargetGroup", { replacementProperties: /* @__PURE__ */ new Set(["DBProxyName", "TargetGroupName"]) });
5945
- this.rules.set("AWS::EC2::VPC", {
5946
- replacementProperties: /* @__PURE__ */ new Set([
5947
- "CidrBlock",
5948
- "Ipv4IpamPoolId",
5949
- "Ipv4NetmaskLength",
5950
- "VpcEncryptionControl"
5951
- ]),
5952
- conditionalReplacements: /* @__PURE__ */ new Map([["InstanceTenancy", vpcInstanceTenancyChangeReplaces]])
5953
- });
5954
- this.rules.set("AWS::RDS::DBCluster", {
5955
- replacementProperties: /* @__PURE__ */ new Set(),
5956
- conditionalReplacements: /* @__PURE__ */ new Map([["Engine", dbClusterEngineChangeReplaces], ["GlobalClusterIdentifier", dbClusterGlobalClusterChangeReplaces]])
5957
- });
5958
- this.rules.set("AWS::RDS::DBInstance", {
5959
- replacementProperties: /* @__PURE__ */ new Set(),
5960
- conditionalReplacements: /* @__PURE__ */ new Map([
5961
- ["Engine", dbInstanceEngineChangeReplaces],
5962
- ["AvailabilityZone", dbInstanceAvailabilityZoneChangeReplaces],
5963
- ["PerformanceInsightsKMSKeyId", dbInstancePerformanceInsightsKmsKeyChangeReplaces],
5964
- ["SourceDBInstanceIdentifier", dbInstanceReplicaSourceChangeReplaces],
5965
- ["SourceDBClusterIdentifier", dbInstanceReplicaSourceChangeReplaces],
5966
- ["DBSnapshotIdentifier", dbInstanceRestoreInputChangeReplaces],
5967
- ["DBClusterSnapshotIdentifier", dbInstanceRestoreInputChangeReplaces],
5968
- ["RestoreTime", dbInstanceRestoreInputChangeReplaces],
5969
- ["SourceDBInstanceAutomatedBackupsArn", dbInstanceRestoreInputChangeReplaces],
5970
- ["SourceDbiResourceId", dbInstanceRestoreInputChangeReplaces],
5971
- ["UseLatestRestorableTime", dbInstanceUseLatestRestorableTimeChangeReplaces]
5972
- ])
5973
- });
5974
- this.rules.set("AWS::EC2::Subnet", {
5975
- replacementProperties: /* @__PURE__ */ new Set([
5976
- "VpcId",
5977
- "CidrBlock",
5978
- "AvailabilityZone",
5979
- "AvailabilityZoneId",
5980
- "Ipv4IpamPoolId",
5981
- "Ipv4NetmaskLength",
5982
- "Ipv6IpamPoolId",
5983
- "Ipv6NetmaskLength",
5984
- "Ipv6Native"
5985
- ]),
5986
- updateableProperties: /* @__PURE__ */ new Set([
5987
- "MapPublicIpOnLaunch",
5988
- "EnableDns64",
5989
- "Ipv6CidrBlock",
5990
- "Tags"
5991
- ])
5992
- });
5993
- this.rules.set("AWS::EC2::Instance", {
5994
- replacementProperties: /* @__PURE__ */ new Set([
5995
- "AvailabilityZone",
5996
- "ImageId",
5997
- "SubnetId",
5998
- "KeyName",
5999
- "NetworkInterfaces",
6000
- "CpuOptions",
6001
- "HibernationOptions",
6002
- "PlacementGroupName",
6003
- "PrivateIpAddress",
6004
- "Ipv6AddressCount",
6005
- "Ipv6Addresses",
6006
- "EnclaveOptions",
6007
- "HostResourceGroupArn",
6008
- "SecurityGroups"
6009
- ]),
6010
- updateableProperties: /* @__PURE__ */ new Set(["EbsOptimized"]),
6011
- conditionalReplacements: /* @__PURE__ */ new Map([
6012
- ["SecurityGroupIds", instanceSecurityGroupIdsChangeReplaces],
6013
- ["BlockDeviceMappings", instanceBlockDeviceMappingsChangeReplaces],
6014
- ["Tenancy", instanceTenancyChangeReplaces],
6015
- ["PrivateDnsNameOptions", instancePrivateDnsNameOptionsChangeReplaces]
6016
- ])
6017
- });
6018
- this.rules.set("AWS::EC2::NatGateway", {
6019
- replacementProperties: /* @__PURE__ */ new Set(),
6020
- conditionalReplacements: /* @__PURE__ */ new Map([["AvailabilityZoneAddresses", natZoneAddressesAddedToAutomaticGateway]])
6021
- });
6022
- this.rules.set("AWS::CertificateManager::Certificate", { replacementProperties: /* @__PURE__ */ new Set(["ValidationMethod"]) });
6023
- this.rules.set("AWS::EC2::Volume", {
6024
- replacementProperties: /* @__PURE__ */ new Set([
6025
- "AvailabilityZone",
6026
- "AvailabilityZoneId",
6027
- "Encrypted",
6028
- "KmsKeyId",
6029
- "OutpostArn",
6030
- "SnapshotId"
6031
- ]),
6032
- updateableProperties: /* @__PURE__ */ new Set([
6033
- "AutoEnableIO",
6034
- "Iops",
6035
- "Size",
6036
- "Throughput",
6037
- "VolumeType",
6038
- "Tags"
6039
- ])
6040
- });
6041
- this.rules.set("AWS::ECS::TaskDefinition", { replacementProperties: /* @__PURE__ */ new Set([
6042
- "Family",
6043
- "ContainerDefinitions",
6044
- "Cpu",
6045
- "Memory",
6046
- "NetworkMode",
6047
- "RequiresCompatibilities",
6048
- "ExecutionRoleArn",
6049
- "TaskRoleArn",
6050
- "Volumes"
6051
- ]) });
6052
- this.rules.set("AWS::ECS::Service", {
6053
- replacementProperties: /* @__PURE__ */ new Set(),
6054
- conditionalReplacements: /* @__PURE__ */ new Map([["LaunchType", ecsServiceLaunchTypeSetOrChanged]])
6055
- });
6056
- this.rules.set("AWS::ElastiCache::CacheCluster", {
6057
- replacementProperties: /* @__PURE__ */ new Set(),
6058
- conditionalReplacements: /* @__PURE__ */ new Map([["AZMode", elastiCacheAzModeRemovedFromSingleAz], ["PreferredAvailabilityZones", elastiCachePreferredAvailabilityZonesReplaced]])
6059
- });
6060
- this.rules.set("AWS::EMR::Cluster", {
6061
- replacementProperties: /* @__PURE__ */ new Set(),
6062
- conditionalReplacements: /* @__PURE__ */ new Map([["Instances", emrClusterInstancesReplaced]])
5839
+ // src/types/resource/read-state.ts
5840
+ const RESOURCE_NOT_FOUND = Symbol("cdkd.resourceNotFound");
5841
+ var DriftReadRefusedError = class extends Error {
5842
+ name = "DriftReadRefusedError";
5843
+ };
5844
+
5845
+ // src/provisioning/providers/ambiguous-create.ts
5846
+ const CREATION_DATE_SKEW_MARGIN_MS = 5e3;
5847
+ const AMBIGUOUS_LATCH_TTL_MS = 18e5;
5848
+ const MAX_TRACKED = 1e4;
5849
+ const createAttemptKey = (scope, logicalId) => injectiveKey(scope, ambientRegion() ?? "", getCurrentStackName() ?? "", logicalId);
5850
+ const setBounded = (map, key, value) => {
5851
+ if (!map.has(key) && map.size >= MAX_TRACKED) {
5852
+ const oldest = map.keys().next();
5853
+ if (!oldest.done) map.delete(oldest.value);
5854
+ }
5855
+ map.set(key, value);
5856
+ };
5857
+ const replayedInSend = (output) => {
5858
+ const attempts = output?.$metadata?.attempts;
5859
+ return typeof attempts === "number" && attempts > 1;
5860
+ };
5861
+ const isObject = (value) => typeof value === "object" && value !== null;
5862
+ const sendsAfterAmbiguous = /* @__PURE__ */ new WeakSet();
5863
+ const outputsAfterAmbiguous = /* @__PURE__ */ new WeakSet();
5864
+ const markReplayFollowedAmbiguous = (output) => {
5865
+ if (isObject(output)) outputsAfterAmbiguous.add(output);
5866
+ };
5867
+ const replayFollowedAmbiguousAttempt = (output) => isObject(output) && outputsAfterAmbiguous.has(output);
5868
+ const AMBIGUOUS_REPLAY_MIDDLEWARE = "cdkdAmbiguousReplayMiddleware";
5869
+ const trackAmbiguousReplays = (client) => {
5870
+ const stack = client.middlewareStack;
5871
+ if (typeof stack?.addRelativeTo !== "function") return;
5872
+ stack.addRelativeTo((next) => async (args) => {
5873
+ try {
5874
+ const result = await next(args);
5875
+ if (sendsAfterAmbiguous.has(args)) markReplayFollowedAmbiguous(result.output);
5876
+ return result;
5877
+ } catch (error) {
5878
+ if (isAmbiguousOutcomeError(error)) sendsAfterAmbiguous.add(args);
5879
+ throw error;
5880
+ }
5881
+ }, {
5882
+ name: AMBIGUOUS_REPLAY_MIDDLEWARE,
5883
+ relation: "after",
5884
+ toMiddleware: "retryMiddleware",
5885
+ override: true
6063
5886
  });
6064
- this.rules.set("AWS::ElasticLoadBalancingV2::ListenerRule", { replacementProperties: /* @__PURE__ */ new Set(["ListenerArn"]) });
6065
- this.logger.debug(`Initialized replacement rules for ${this.rules.size} resource types`);
5887
+ };
5888
+ const replayedSendWindow = (output, attemptStartMs) => replayedInSend(output) ? {
5889
+ floorMs: attemptStartMs - CREATION_DATE_SKEW_MARGIN_MS,
5890
+ ceilingMs: Date.now() + CREATION_DATE_SKEW_MARGIN_MS,
5891
+ replayedInSend: true
5892
+ } : void 0;
5893
+ const ambiguousAttemptLead = (action, logicalId, window) => window.replayedInSend === true ? `The ${action} call for ${logicalId} succeeded only after the AWS SDK sent it again, following an attempt that failed without a definite answer` : `An earlier ${action} attempt for ${logicalId} failed without a definite answer`;
5894
+ const mergeWindow = (existing, next, armedAtMs) => existing === void 0 ? {
5895
+ floorMs: next.floorMs,
5896
+ ceilingMs: next.ceilingMs,
5897
+ armedAtMs
5898
+ } : {
5899
+ floorMs: Math.min(existing.floorMs, next.floorMs),
5900
+ ceilingMs: Math.max(existing.ceilingMs, next.ceilingMs),
5901
+ armedAtMs: Math.max(existing.armedAtMs, armedAtMs)
5902
+ };
5903
+ var AmbiguousCreateLatch = class {
5904
+ entries = /* @__PURE__ */ new Map();
5905
+ scope;
5906
+ constructor(scope) {
5907
+ this.scope = scope;
5908
+ }
5909
+ noteFailure(logicalId, error, attemptStartMs, carried) {
5910
+ if (!isAmbiguousOutcomeError(error) && !hasReplayMayCollide(error)) return;
5911
+ const key = createAttemptKey(this.scope, logicalId);
5912
+ const now = Date.now();
5913
+ let entry = mergeWindow(this.entries.get(key), {
5914
+ floorMs: attemptStartMs - CREATION_DATE_SKEW_MARGIN_MS,
5915
+ ceilingMs: now + CREATION_DATE_SKEW_MARGIN_MS
5916
+ }, now);
5917
+ if (carried !== void 0) entry = mergeWindow(entry, carried, now);
5918
+ setBounded(this.entries, key, entry);
5919
+ }
5920
+ take(logicalId) {
5921
+ const key = createAttemptKey(this.scope, logicalId);
5922
+ const entry = this.entries.get(key);
5923
+ this.entries.delete(key);
5924
+ if (entry === void 0 || Date.now() - entry.armedAtMs > 18e5) return;
5925
+ return {
5926
+ floorMs: entry.floorMs,
5927
+ ceilingMs: entry.ceilingMs
5928
+ };
5929
+ }
5930
+ resetForTests() {
5931
+ this.entries.clear();
5932
+ }
5933
+ };
5934
+ const isInsideWindow = (date, window) => date !== void 0 && date.getTime() >= window.floorMs && date.getTime() <= window.ceilingMs;
5935
+ var RecentIdSet = class {
5936
+ ids = /* @__PURE__ */ new Map();
5937
+ add(id) {
5938
+ setBounded(this.ids, id, true);
5939
+ }
5940
+ has(id) {
5941
+ return this.ids.has(id);
5942
+ }
5943
+ resetForTests() {
5944
+ this.ids.clear();
5945
+ }
5946
+ };
5947
+ const isRetryStrategyV2 = (value) => typeof value === "object" && value !== null && typeof value.acquireInitialRetryToken === "function" && typeof value.refreshRetryTokenForRetry === "function" && typeof value.recordSuccess === "function";
5948
+ function withoutServerErrorRetries(client) {
5949
+ const config = client.config;
5950
+ const base = config?.retryStrategy;
5951
+ if (config === void 0 || typeof base !== "function") return client;
5952
+ trackAmbiguousReplays(client);
5953
+ const resolveBase = base;
5954
+ const afterAmbiguous = /* @__PURE__ */ new WeakSet();
5955
+ config.retryStrategy = async () => {
5956
+ const strategy = await resolveBase();
5957
+ if (!isRetryStrategyV2(strategy)) return strategy;
5958
+ return {
5959
+ acquireInitialRetryToken: (scope) => strategy.acquireInitialRetryToken(scope),
5960
+ refreshRetryTokenForRetry: async (token, errorInfo) => {
5961
+ const ambiguous = isAmbiguousOutcomeError(errorInfo.error);
5962
+ const replayed = isObject(token) && afterAmbiguous.has(token);
5963
+ if (replayed) markReplayMayCollide(errorInfo.error);
5964
+ if (ambiguous && isTransientServerError(errorInfo.error)) throw new Error("cdkd: no SDK retry of a 5xx on a tokenless create");
5965
+ const next = await strategy.refreshRetryTokenForRetry(token, errorInfo);
5966
+ if ((ambiguous || replayed) && isObject(next)) afterAmbiguous.add(next);
5967
+ return next;
5968
+ },
5969
+ recordSuccess: (token) => strategy.recordSuccess(token)
5970
+ };
5971
+ };
5972
+ return client;
6066
5973
  }
6067
5974
 
6068
- // src/analyzer/replacement-rules.ts
6069
- var ReplacementRulesRegistry = class {
6070
- logger = getLogger().child("ReplacementRulesRegistry");
6071
- rules = /* @__PURE__ */ new Map();
6072
- constructor() {
6073
- this.initializeRules();
6074
- }
6075
- requiresReplacement(resourceType, propertyPath, oldValue, newValue, siblings) {
6076
- const rule = this.rules.get(resourceType);
6077
- if (!rule) {
6078
- this.logger.debug(`No replacement rule for ${resourceType}, conservatively assuming replacement may be required for ${propertyPath}`);
6079
- return false;
6080
- }
6081
- if (rule.replacementProperties.has(propertyPath)) {
6082
- this.logger.debug(`Property ${propertyPath} of ${resourceType} requires replacement`);
6083
- return true;
6084
- }
6085
- if (rule.updateableProperties?.has(propertyPath)) return false;
6086
- if (rule.conditionalReplacements?.has(propertyPath)) {
6087
- const condition = rule.conditionalReplacements.get(propertyPath);
6088
- if (condition) {
6089
- const requires = condition(oldValue, newValue, siblings);
6090
- this.logger.debug(`Conditional replacement for ${propertyPath} of ${resourceType}: ${requires}`);
6091
- return requires;
6092
- }
6093
- }
6094
- return false;
5975
+ // src/provisioning/created-resource-sink.ts
5976
+ var CreatedResourceSink = class {
5977
+ logicalId;
5978
+ resourceType;
5979
+ reports = [];
5980
+ constructor(logicalId, resourceType) {
5981
+ this.logicalId = logicalId;
5982
+ this.resourceType = resourceType;
6095
5983
  }
6096
- conditionalReplacementVerdict(resourceType, propertyPath, oldValue, newValue, siblings) {
6097
- const condition = this.rules.get(resourceType)?.conditionalReplacements?.get(propertyPath);
6098
- return condition === void 0 ? void 0 : condition(oldValue, newValue, siblings);
5984
+ get report() {
5985
+ return this.reports.at(-1);
6099
5986
  }
6100
- isClassified(resourceType, propertyPath) {
6101
- const rule = this.rules.get(resourceType);
6102
- if (!rule) return false;
6103
- return rule.replacementProperties.has(propertyPath) || (rule.updateableProperties?.has(propertyPath) ?? false) || (rule.conditionalReplacements?.has(propertyPath) ?? false);
5987
+ record(report) {
5988
+ this.reports.push(report);
6104
5989
  }
6105
- initializeRules() {
6106
- return initializeRules.call(this);
5990
+ clear() {
5991
+ this.reports.length = 0;
5992
+ }
5993
+ retract(physicalId) {
5994
+ for (let i = this.reports.length - 1; i >= 0; i--) if (this.reports[i].physicalId === physicalId) this.reports.splice(i, 1);
6107
5995
  }
6108
5996
  };
5997
+ const storage = new AsyncLocalStorage();
5998
+ function collectCreatedResources(sink, fn) {
5999
+ return storage.run(sink, fn);
6000
+ }
6001
+ function clearCreatedReport() {
6002
+ storage.getStore()?.clear();
6003
+ }
6004
+ function anchoredSink(ownerLogicalId, resourceType) {
6005
+ const sink = storage.getStore();
6006
+ return sink !== void 0 && sink.logicalId === ownerLogicalId && sink.resourceType === resourceType ? sink : void 0;
6007
+ }
6008
+ function reportCreatedResource(ownerLogicalId, resourceType, physicalId, createdResourceIdentity) {
6009
+ try {
6010
+ if (typeof physicalId !== "string" || physicalId === "") return;
6011
+ anchoredSink(ownerLogicalId, resourceType)?.record({
6012
+ physicalId,
6013
+ ...typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" && { createdResourceIdentity }
6014
+ });
6015
+ } catch {}
6016
+ }
6017
+ function reportedCreatedResource(ownerLogicalId, resourceType) {
6018
+ try {
6019
+ return anchoredSink(ownerLogicalId, resourceType)?.report;
6020
+ } catch {
6021
+ return;
6022
+ }
6023
+ }
6024
+ function retractCreatedResource(ownerLogicalId, resourceType, physicalId) {
6025
+ try {
6026
+ anchoredSink(ownerLogicalId, resourceType)?.retract(physicalId);
6027
+ } catch {}
6028
+ }
6109
6029
 
6110
- export { foldRecording as $, WHOLE_DYNAMIC_REFERENCE_PATTERN as $n, inheritedParameterExpression as $t, passedNoEchoParametersOf as A, splitGetAttStringForm as An, overlapRuleAnswered as At, intrinsicLeafResolutionOf as B, markNoEchoParameterClass as Bn, spanNamesResolvableService as Bt, maskedLeafCoordinatesOf as C, dynamicReferenceTokens as Cn, errorCauseChain as Ct, noEchoOutputsComparison as D, withoutConsumptionStamps as Dn, differingStringLeaves as Dt, noEchoLeavesOf as E, withConsumptionScope as En, maskSecretsInText as Et, replaceAtCoordinates as F, isMaskOnlyPlaintext as Fn, repairPhysicalNameCopyLeaves as Ft, recordIntrinsicLeafResolution as G, recordFreshNoEchoValuesIn as Gn, identityKeyFor as Gt, markLeafCertifiedBag as H, pinScopedSecretVerdict as Hn, spelledKeysOf as Ht, valueAtCoordinate as I, isNoEchoParameterPlaintext as In, replaceEmbeddedPhysicalNameRewrites as It, resolvedPlaintextOf as J, recordNoEchoAttributeValues as Jn, standsForInheritedSecret as Jt, recordIntrinsicLeafResolutionAs as K, recordMaskOnlyValue as Kn, rereadParameterExpression as Kt, witnessNormalize as L, isRecordedSecretExpression as Ln, scrubResourceRecord as Lt, readsNoEchoSource as M, carryFreshNoEchoMark as Mn, withLegacyOverlapScan as Mt, recordPassedNoEchoParameters as N, contradictProvenPublicExpression as Nn, embeddedPhysicalNameRewrites as Nt, noEchoParameterNodesAt as O, crossStackSourceKey as On, legacyLeavesWithoutMask as Ot, recordedNoEchoValuesOf as P, freshNoEchoValuesOf as Pn, repairEmbeddedPhysicalNamesTowards as Pt, redactForState as Q, withoutNoEchoParameterEntries as Qn, inheritNestedStackParameterAssociations as Qt, liveMatchesUnresolvedTokenFrame as R, isScopedSecretVerdict as Rn, withPhysicalNameCopies as Rt, maskWholeValue as S, dynamicReferenceSpans as Sn, createSecretMasker as St, noEchoCoordinatesOf as T, noteReferenceConsumed as Tn, maskSecretsInError as Tt, markSameGenerationBag as U, provenPublicValue as Un, pathCrossesDottedKey as Ut, isSameGenerationBag as V, noEchoParameterPlaintextsOf as Vn, isUncertifiedBaselineMaskPosition as Vt, mergeResolvedPairs as W, recordDerivedMaskOnlyValue as Wn, arrayPairsWhateverDrops as Wt, mixedLiteralAnswered as X, recordProvenPublicExpression as Xn, recordInheritedPseudoParameters as Xt, literalTextHoldsSubFloorSecret as Y, recordNoEchoParameterFreshValue as Yn, inheritedPseudoValue as Yt, withLegacyMixedScan as Z, wholeStringLeavesOf as Zn, templateRereadsAccountId as Zt, canonicalJson as _, physicalNameCopiesOf as _n, recordLogOnlyParameterValue as _t, liveHoldsFreshLeaves as a, carriesFreshNoEchoValue as an, recordReferenceProvenanceEntry as at, maskAtCoordinates as b, attributionRefusedParameters as bn, shareLogOnlyValues as bt, blockDeviceMappingsDifferOnlyInDeleteOnTermination as c, recordRecoverableMaskedOutput as cn, carryLogOnlyValues as ct, emrClusterInstancesReplaced as d, nestedStackRowTagSpellingOf as dn, hasLogOnlyValues as dt, inheritedRenderedToken as en, isDynamicReferenceString as er, openRecordingScope as et, canonicalLambdaFunctionName as f, staticTemplateText as fn, hasMaskableValues as ft, canonicalCoordinates as g, secretRerenderPairs as gn, printingCorpusOf as gt, sameLambdaFunctionAddress as h, keepTemplateLiteralLeaves as hn, logOnlyValuesOf as ht, keyOrderFreeJson as i, withdrawRenderedParameterSpelling as in, passReadVersionsFor as it, readbackPathFor as j, carriesSecretMask as jn, replaceWholeLeaves as jt, noEchoParametersReadBy as k, recordCrossStackExpression as kn, legacyReferenceLeavesOnly as kt, dbInstanceEngineChangeIsInPlace as l, recoverMaskedOutput as ln, carryLogOnlyValuesCarriedBy as lt, parseLambdaFunctionAddress as m, recordTakenIfBranch as mn, logOnlyValueCount as mt, grantSentence as n, recordInheritedParameterValue as nn, maskMatchSpans as nr, hasPassProvenance as nt, outputMapsEqual as o, embedsFreshNoEchoValue as on, recordReferenceResolution as ot, lambdaFunctionNameForMask as p, recordDroppedArrayElements as pn, literalSplitDelimitersOf as pt, redactionClaimOf as q, recordMaskOnlyValuesIn as qn, splitOutsideDynamicReferences as qt, isReplacementCeiling as r, redactInheritedParameterValue as rn, passProvenanceFor as rt, readDenialOf as s, freshNoEchoLeafPositions as sn, snapshotPassProvenance as st, ReplacementRulesRegistry as t, recordInheritedParameterRead as tn, isSingleDynamicReferenceToken as tr, recordSecretResolution as tt, ecsServiceLaunchTypeSetOrChanged as u, recordNestedStackParameterExpressions as un, createUnionSecretMasker as ut, isMarkedCoordinate as v, recordAttributeIdCopy as vn, recordLogOnlySplitFragments as vt, noEchoComparison as w, consumptionScopeOpenFor as wn, maskRecordedSecretsInText as wt, maskReadbackAtCoordinates as x, DYNAMIC_REFERENCE_TOKEN_SCAN as xn, unionOfSecretBags as xt, isStaleNoEchoLeaf as y, recordPhysicalNameCopy as yn, recordLogOnlyValue as yt, carryRedactionMarks as z, isSecretExpressionByVerdictOrSpelling as zn, withoutPhysicalNameCopies as zt };
6111
- //# sourceMappingURL=replacement-rules-BkUZIP44.js.map
6030
+ export { ElapsedBudget as $, differingStringLeaves as $n, withConsumptionScope as $r, dynamicReferenceOpeners as $t, readNameProperty as A, maskMatchSpans as Ai, passReadVersionsFor as An, redactInheritedParameterValue as Ar, resourceTypeShown as At, rdsFamilyProtectionSite as B, CUSTOM_RESOURCE_RESPONSE_PREFIX as Bi, logOnlyValueCount as Bn, recordDroppedArrayElements as Br, carryCreatedBeforeFailure as Bt, VALUE_NOT_SHOWN as C, recordProvenPublicExpression as Ci, withLegacyMixedScan as Cn, recordInheritedPseudoParameters as Cr, startInterruptWatch as Ct, isQuotableImportValue as D, isDynamicReferenceString as Di, recordSecretResolution as Dn, inheritedRenderedToken as Dr, compositeIdSkipResult as Dt, isPlainImportValue as E, WHOLE_DYNAMIC_REFERENCE_PATTERN as Ei, openRecordingScope as En, inheritedParameterExpression as Er, compositeIdSeparatorRefusal as Et, markNotGone as F, formatLockExpiry as Fi, carryLogOnlyValuesCarriedBy as Fn, recordRecoverableMaskedOutput as Fr, isSecretDerivedValue as Ft, isFinalSnapshotNotAvailableRefusal as G, withPasteableAwsProfile as Gi, recordLogOnlyValue as Gn, recordAttributeIdCopy as Gr, isAuxiliaryFailure as Gt, userPoolProtectionSite as H, WAIT_CONDITION_SIGNAL_PREFIX as Hi, printingCorpusOf as Hn, keepTemplateLiteralLeaves as Hr, createdBeforeFailure as Ht, compensateProtectionFlip as I, formatLockOperation as Ii, createUnionSecretMasker as In, recoverMaskedOutput as Ir, maskDeep as It, PROTECTION_FLIP_REUSE_WINDOW_MS as J, producerCoordinateKey as Ji, createSecretMasker as Jn, DYNAMIC_REFERENCE_TOKEN_SCAN as Jr, markCreatedBeforeFailure as Jt, isProceedDbStatus as K, injectiveKey as Ki, shareLogOnlyValues as Kn, recordPhysicalNameCopy as Kr, isAuxiliaryMarkOf as Kt, deleteWithProtectionCompensation as L, formatLockOwner as Li, hasLogOnlyValues as Ln, recordNestedStackParameterExpressions as Lr, maskerOrIdentity as Lt, remedyLogicalId as M, buildForceUnlockCommand as Mi, recordReferenceResolution as Mn, carriesFreshNoEchoValue as Mr, stateOrphanRecordRemedy as Mt, resolveExplicitPhysicalId as N, buildLockContentionMessage as Ni, snapshotPassProvenance as Nn, embedsFreshNoEchoValue as Nr, createMaskedLogSinks as Nt, normalizeAwsTagsToCfn as O, isPlainObject as Oi, hasPassProvenance as On, recordInheritedParameterRead as Or, logicalIdShown as Ot, isMarkedNotGone as P, forceQuitRecoveryClause as Pi, carryLogOnlyValues as Pn, freshNoEchoLeafPositions as Pr, createMaskedRetryLogger as Pt, runDeleteAttempt as Q, maskSecretsInText as Qn, noteReferenceConsumed as Qr, dynamicReferenceBody as Qt, logGroupProtectionSite as R, recoveryCommandFlags as Ri, hasMaskableValues as Rn, nestedStackRowTagSpellingOf as Rr, withDerivedNameMasks as Rt, holderRefusalRun as S, recordNoEchoParameterFreshValue as Si, mixedLiteralAnswered as Sn, inheritedPseudoValue as Sr, isInterruptedWaitError as St, isPlainImportJson as T, withoutNoEchoParameterEntries as Ti, foldRecording as Tn, inheritNestedStackParameterAssociations as Tr, compositeIdFormatMessage as Tt, PROTECTION_FLIP_RETRY_WAIT_MS as U, setPasteableAwsCaBundle as Ui, recordLogOnlyParameterValue as Un, secretRerenderPairs as Ur, createdResourceIdentityBeforeFailure as Ut, settleProtectionFlip as V, DEFAULT_STATE_PREFIX as Vi, logOnlyValuesOf as Vn, recordTakenIfBranch as Vr, clearCreatedBeforeFailure as Vt, deleteAfterProtectionFlipWithFinalSnapshot as W, setPasteableAwsProfile as Wi, recordLogOnlySplitFragments as Wn, physicalNameCopiesOf as Wr, hasCreatedBeforeFailure as Wt, isTerminalDeleteFailure as X, maskRecordedSecretsInText as Xn, dynamicReferenceTokens as Xr, replayMadeAnotherResource as Xt, ProtectionFlipRegistry as Y, producerRecordKey as Yi, errorCauseChain as Yn, dynamicReferenceSpans as Yr, markSupersedesEarlierCreate as Yt, protectionFlipKey as Z, maskSecretsInError as Zn, consumptionScopeOpenFor as Zr, countDynamicReferenceOpenings as Zt, withoutServerErrorRetries as _, recordDerivedMaskOnlyValue as _i, recordIntrinsicLeafResolution as _n, arrayPairsWhateverDrops as _r, recordedPrincipalsRepair as _t, reportedCreatedResource as a, carryFreshNoEchoMark as ai, mentionsMask as an, embeddedPhysicalNameRewrites as ar, isAwsCliLiteral as at, assertRegionMatch as b, recordMaskOnlyValuesIn as bi, resolvedPlaintextOf as bn, splitOutsideDynamicReferences as br, endCommandInterruptScope as bt, AmbiguousCreateLatch as c, isMaskOnlyPlaintext as ci, recordedSecrecyOf as cn, replaceEmbeddedPhysicalNameRewrites as cr, renderDisableCommand as ct, ambiguousAttemptLead as d, isScopedSecretVerdict as di, carryRedactionMarks as dn, withoutPhysicalNameCopies as dr, SECRET_DERIVED_READ_LIVE as dt, withoutConsumptionStamps as ei, holdsMaskLeaf as en, legacyLeavesWithoutMask as er, ElapsedBudgetRegistry as et, createAttemptKey as f, isSecretExpressionByVerdictOrSpelling as fi, intrinsicLeafResolutionOf as fn, SPELLED_SECRET_REFERENCE_PREFIXES as fr, diffPrincipalNames as ft, setBounded as g, provenPublicValue as gi, mergeResolvedPairs as gn, pathCrossesDottedKey as gr, readRecordedPrincipals as gt, replayedSendWindow as h, pinScopedSecretVerdict as hi, markSameGenerationBag as hn, spelledKeysOf as hr, readPrincipalLists as ht, reportCreatedResource as i, carriesSecretMask as ii, mentionsDynamicReferenceTo as in, withLegacyOverlapScan as ir, WITHHELD_AWS_COMMAND as it, refusalTypeShown as j, UNREPRODUCIBLE_LOCK_CLAUSE as ji, recordReferenceProvenanceEntry as jn, withdrawRenderedParameterSpelling as jr, segmentAfterAnchor as jt, quotedRemedyLogicalId as k, isSingleDynamicReferenceToken as ki, passProvenanceFor as kn, recordInheritedParameterValue as kr, packCompositeId as kt, CREATION_DATE_SKEW_MARGIN_MS as l, isNoEchoParameterPlaintext as li, usableRecordedName as ln, scrubResourceRecord as lr, IAM_PRINCIPAL_NAME as lt, replayFollowedAmbiguousAttempt as m, noEchoParameterPlaintextsOf as mi, markLeafCertifiedBag as mn, isUncertifiedBaselineMaskPosition as mr, onlySecretDerived as mt, clearCreatedReport as n, recordCrossStackExpression as ni, isMaskRun as nn, overlapRuleAnswered as nr, DELETION_PROTECTION_DOC_POINTER as nt, retractCreatedResource as o, contradictProvenPublicExpression as oi, mentionsMaskedIdSegment as on, repairEmbeddedPhysicalNamesTowards as or, pasteableAwsCommand as ot, isInsideWindow as p, markNoEchoParameterClass as pi, isSameGenerationBag as pn, spanNamesResolvableService as pr, holdsSecretDerivedEntry as pt, isTerminalDbWaitStatus as q, injectiveKeyPrefix as qi, unionOfSecretBags as qn, attributionRefusedParameters as qr, markAuxiliaryFailure as qt, collectCreatedResources as r, splitGetAttStringForm as ri, mentionsDynamicReference as rn, replaceWholeLeaves as rr, UNNAMEABLE_ID_CLAUSE as rt, AMBIGUOUS_LATCH_TTL_MS as s, freshNoEchoValuesOf as si, opensDynamicReferenceTo as sn, repairPhysicalNameCopyLeaves as sr, protectedReplacementAdvice as st, CreatedResourceSink as t, crossStackSourceKey as ti, isMaskLeaf as tn, legacyReferenceLeavesOnly as tr, monotonicNowMs as tt, RecentIdSet as u, isRecordedSecretExpression as ui, valueMentionsDynamicReference as un, withPhysicalNameCopies as ur, RESOLVED_PREVIOUS_PRINCIPAL_KEYS as ut, DriftReadRefusedError as v, recordFreshNoEchoValuesIn as vi, recordIntrinsicLeafResolutionAs as vn, identityKeyFor as vr, withUnchangedSecretPrincipalLists as vt, importRemedyCommand as w, wholeStringLeavesOf as wi, redactForState as wn, templateRereadsAccountId as wr, canonicalizeRoute53QueryName as wt, holderRefusalMask as x, recordNoEchoAttributeValues as xi, literalTextHoldsSubFloorSecret as xn, standsForInheritedSecret as xr, interruptWatchListenerCount as xt, RESOURCE_NOT_FOUND as y, recordMaskOnlyValue as yi, redactionClaimOf as yn, rereadParameterExpression as yr, beginCommandInterruptScope as yt, observeThenDisableProtection as z, sanitizeRecoveryValue as zi, literalSplitDelimitersOf as zn, staticTemplateText as zr, RETRY_AUXILIARY_OWNER as zt };
6031
+ //# sourceMappingURL=created-resource-sink-D7iM5jwM.js.map