cdk-real-drift 0.2.49 → 0.2.51

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.
package/README.md CHANGED
@@ -462,13 +462,17 @@ ignore:
462
462
  ```
463
463
 
464
464
  - Every rule is a mapping `{ path, stack?, account?, region? }`. `cdkrd ignore`
465
- writes the unscoped form (and is **comment-preserving and append-only**: it keeps
466
- your existing comments and layout, and appends new rules at the end — you own the
467
- order). `path` is an exact `<constructPath>.<path>` — the construct path WITHIN the
468
- stack (the stack/Stage prefix stripped), byte-identical to what `cdkrd check` prints, so
469
- you can copy what you see (or `<logicalId>.<path>` on a non-CDK stack). Rules written with
470
- the older full `<stack>/<constructPath>.<path>` form still match. The optional `stack` /
471
- `account` / `region` scopes are a hand-edit.
465
+ stamps the current **stack / account / region** onto each rule it writes (the same
466
+ three identity axes a baseline file is keyed on), so ignoring a within-stack path on
467
+ one stack never leaks to a same-named twin stack in another account/region — an
468
+ unscoped `{ path }` was match-all (#757). The verb is **comment-preserving and
469
+ append-only**: it keeps your existing comments and layout, and appends new rules at
470
+ the end — you own the order. `path` is an exact `<constructPath>.<path>` — the
471
+ construct path WITHIN the stack (the stack/Stage prefix stripped), byte-identical to
472
+ what `cdkrd check` prints, so you can copy what you see (or `<logicalId>.<path>` on a
473
+ non-CDK stack). Rules written with the older full `<stack>/<constructPath>.<path>`
474
+ form still match. Widening a stamped scope to a `*` glob (to intentionally ignore a
475
+ path across every stack/account/region) stays a hand-edit.
472
476
  - All four fields accept the same `*` / `?` glob, and a parent `path` covers child
473
477
  paths. The three scope axes — **stack, account, region** — are exactly the
474
478
  baseline file's identity axes. **Account** keeps a `stack: "Prod*"` rule from
@@ -533,13 +537,67 @@ reserved for picker rows you aren't on. Piped / CI / `--json` output is plain te
533
537
 
534
538
  ### JSON output contract
535
539
 
536
- `--json` emits
537
- `{ "stack": "<name> (<region>)", "drifted": <n>, "findings": [...] }`.
538
- Each finding has a stable shape: `tier` (`deleted` | `declared` | `undeclared` |
539
- `readGap` | `unresolved` | `skipped` | `ignored`), `logicalId`, `resourceType`,
540
- `path`, `desired`, `actual`, `note`, `physicalId`, `constructPath`. An unrecorded
541
- value keeps `tier: "undeclared"` and carries `"unrecorded": true`; `drifted`
542
- excludes it. The output always carries every finding regardless of `--verbose`.
540
+ `--json` emits **one top-level JSON array for the whole invocation — one element per
541
+ stack**:
542
+
543
+ ```json
544
+ [
545
+ { "stack": "stackA (us-east-1)", "drifted": 1, "findings": [ ... ] },
546
+ { "stack": "stackB (us-east-1)", "drifted": 0, "findings": [] }
547
+ ]
548
+ ```
549
+
550
+ The whole stdout stream is a single `JSON.parse`-able value. This holds even for a
551
+ single-stack run — it is an **array of one** (never a bare object), so a consumer's
552
+ `JSON.parse` always yields an array and never has to special-case the count. (Earlier
553
+ builds printed one pretty-printed `{...}` per stack back-to-back, which was neither one
554
+ valid JSON value nor JSONL; multi-stack `--json` was unparseable — issue #755.) All
555
+ `note` / `warning` / progress lines go to **stderr**, so stdout stays pure JSON.
556
+
557
+ A **stack that errored or was skipped** before it could be checked still appears as an
558
+ element so a consumer sees which stacks ran: it carries `"error": "<reason>"` alongside
559
+ `"drifted": 0` and an empty `"findings": []`. (`error` is absent on a
560
+ successfully-checked stack.)
561
+
562
+ Each stack element is `{ "stack": "<name> (<region>)", "drifted": <n>, "findings": [...] }`
563
+ (`error` added only on failure). Each **finding** has a stable shape:
564
+
565
+ - Always present: `tier`, `logicalId`, `resourceType`, `path`.
566
+ - Usually present: `desired`, `actual`, `note`, `physicalId`, `constructPath` (any of
567
+ these may be omitted when it doesn't apply — e.g. an undeclared finding has no
568
+ `desired`).
569
+ - `tier` is one of `deleted` | `added` | `declared` | `undeclared` | `atDefault` |
570
+ `generated` | `ignored` | `readGap` | `unresolved` | `skipped`. The output carries
571
+ **every** finding of every tier (including the informational `atDefault` / `generated`
572
+ / `ignored` / `readGap` / `unresolved` / `skipped` ones the text report folds into its
573
+ `info:` footer), regardless of `--verbose`.
574
+ - `drifted` counts only confirmed-drift tiers (`deleted` / `declared` / `undeclared` /
575
+ `added`) that are not `unrecorded`; the informational tiers and unrecorded values are
576
+ excluded.
577
+
578
+ Optional per-finding fields, present only when they apply:
579
+
580
+ - `hint` — a non-classifying, human-facing note on where a live value likely came from
581
+ (e.g. an account/region-level auto-instrumentation footprint). Display-only; it never
582
+ changes the tier.
583
+ - `unrecorded` (`true`) — a live-only value (`undeclared` or `added`) with no baseline
584
+ entry yet: **potential drift**, not confirmed drift. Excluded from `drifted`.
585
+ - `attributeKey` — for a `declared` drift inside an identity-keyed attribute bag (ELB
586
+ `LoadBalancerAttributes` / `TargetGroupAttributes`), the `Key` of the changed
587
+ attribute (`path` stays at the bag property; `desired`/`actual` are the scalar value).
588
+ - `arrayDelta` — for an `undeclared` recorded identity-keyed array that changed vs the
589
+ baseline, the element-level delta (`{ identityField, added, changed, removed }`) so a
590
+ consumer sees which element(s) differ, not the whole-array dump.
591
+ - `nested` (`true`) — an `undeclared` value is a live sub-key inside a property you
592
+ _did_ declare (dotted `path`). `freeFormKey` (`true`) additionally marks it as living
593
+ inside a free-form map (e.g. a Lambda env var).
594
+ - `modelReadFailed` (`true`) — an `added` resource whose full live model could not be
595
+ read this run (`actual` is only the enumerator's identity snippet); it exists but is
596
+ not change-watchable until the next check.
597
+ - On an `added` finding, `desired` carries the **recorded baseline model** and `actual`
598
+ the live one (so a recorded `added` resource that changed shows the delta), and
599
+ `unrecorded` marks a never-recorded one as potential drift.
600
+
543
601
  After publication this shape is a backward-compatible API.
544
602
 
545
603
  ## IAM permissions
package/dist/cli.js CHANGED
@@ -433,21 +433,29 @@ function validateIgnoreEntry(entry, index) {
433
433
  ]) if (obj[k] !== void 0 && typeof obj[k] !== "string") throw new Error(`${at}: "${k}" must be a string`);
434
434
  }
435
435
  /**
436
- * The exact ignore rule the `ignore` verb writes for a finding — always the unscoped
437
- * rule (just `path`); the optional `stack` / `region` scopes stay hand-authored (the
438
- * verb writes the simplest rule; narrowing is a manual edit). Prefer the human-friendly
439
- * `<constructPath>.<path>` when present (CDK stacks): it is what `cdk-local` targets on
440
- * and readable in the git-committed config diff. The construct path is written WITHIN the
441
- * stack (the stack/Stage prefix stripped, given `stackName`) so it is byte-identical to
442
- * what the report prints for the finding — copy what you see. Naturally stack-scoped even
443
- * without the prefix (a `stack:` scope narrows further). Falls back to `<logicalId>.<path>`,
444
- * ALWAYS present (the CloudFormation key) so a rule is writable even on a non-CDK /
445
- * metadata-stripped stack. Pure + exported; `applyIgnores` matches the within-stack path,
446
- * the full construct path (older rules), AND the logicalId, so every form works.
436
+ * The exact ignore rule the `ignore` verb (and check's inline ignore) writes for a
437
+ * finding. The rule is STAMPED with the current stack / account / region scope (the same
438
+ * three identity axes a baseline file is keyed on), so ignoring a within-stack path on one
439
+ * stack does NOT leak to a same-named twin stack in another account/region — an unscoped
440
+ * `{ path }` was match-all, silently silencing the identical path everywhere (issue #757).
441
+ * The literal identity values are valid exact globs; hand-widening to a `*` glob stays a
442
+ * manual edit. A scope field is omitted only when genuinely unavailable (empty string).
443
+ * Prefer the human-friendly `<constructPath>.<path>` for `path` when present (CDK stacks):
444
+ * it is what `cdk-local` targets on and readable in the git-committed config diff. The
445
+ * construct path is written WITHIN the stack (the stack/Stage prefix stripped, given
446
+ * `stackName`) so it is byte-identical to what the report prints for the finding — copy
447
+ * what you see. Falls back to `<logicalId>.<path>`, ALWAYS present (the CloudFormation
448
+ * key) so a rule is writable even on a non-CDK / metadata-stripped stack. Pure + exported;
449
+ * `applyIgnores` matches the within-stack path, the full construct path (older rules), AND
450
+ * the logicalId, so every form works.
447
451
  */
448
- function ignoreRuleFor(finding, stackName = "") {
452
+ function ignoreRuleFor(finding, stackName = "", accountId = "", region = "") {
449
453
  const id = finding.constructPath ? withinStackPath(finding.constructPath, stackName) : finding.logicalId;
450
- return { path: finding.path ? `${id}.${finding.path}` : id };
454
+ const rule = { path: finding.path ? `${id}.${finding.path}` : id };
455
+ if (stackName) rule.stack = stackName;
456
+ if (accountId) rule.account = accountId;
457
+ if (region) rule.region = region;
458
+ return rule;
451
459
  }
452
460
  /** Canonical identity of a rule (path + the three optional scopes), for dedupe. */
453
461
  function ruleKey(r) {
@@ -744,7 +752,12 @@ async function resolveStacks(a) {
744
752
  };
745
753
  const known = () => discovered.map((s) => s.stackName).join(", ") || "none";
746
754
  for (const name of a.stackNames) if (isGlob(name)) {
747
- for (const s of discovered) if (matchesGlob(name, s.stackName)) add(s.stackName, s.region ?? fallbackRegion, s.template);
755
+ let matched = 0;
756
+ for (const s of discovered) if (matchesGlob(name, s.stackName)) {
757
+ matched++;
758
+ add(s.stackName, s.region ?? fallbackRegion, s.template);
759
+ }
760
+ if (matched === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
748
761
  } else {
749
762
  const hit = discovered.find((s) => s.stackName === name);
750
763
  if (!hit) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
@@ -3258,8 +3271,9 @@ function buildResolverContext(template, stackParams, physIds, region, accountId,
3258
3271
  };
3259
3272
  }
3260
3273
  const exportsCache = /* @__PURE__ */ new Map();
3261
- async function listExports(client, region) {
3262
- const cached = exportsCache.get(region);
3274
+ async function listExports(client, accountId, region) {
3275
+ const cacheKey = `${accountId}:${region}`;
3276
+ const cached = exportsCache.get(cacheKey);
3263
3277
  if (cached) return cached;
3264
3278
  const exports = {};
3265
3279
  let next;
@@ -3268,7 +3282,7 @@ async function listExports(client, region) {
3268
3282
  for (const e of res.Exports ?? []) if (e.Name) exports[e.Name] = e.Value ?? "";
3269
3283
  next = res.NextToken;
3270
3284
  } while (next);
3271
- exportsCache.set(region, exports);
3285
+ exportsCache.set(cacheKey, exports);
3272
3286
  return exports;
3273
3287
  }
3274
3288
  async function listStackResources(client, stackName) {
@@ -3319,7 +3333,12 @@ async function loadDesired(client, stackName, region, templateOverride, recovery
3319
3333
  const ctx = buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId);
3320
3334
  const notificationArns = stack?.NotificationARNs ?? [];
3321
3335
  if (notificationArns.length > 0) ctx.params["AWS::NotificationARNs"] = notificationArns;
3322
- if (JSON.stringify(template).includes("Fn::ImportValue")) ctx.exports = await listExports(client, region);
3336
+ if (JSON.stringify(template).includes("Fn::ImportValue")) try {
3337
+ ctx.exports = await listExports(client, accountId, region);
3338
+ } catch (err) {
3339
+ const msg = err instanceof Error ? err.message : String(err);
3340
+ console.error(`warning: ${stackName}: cloudformation:ListExports failed — Fn::ImportValue references will resolve UNRESOLVED (their declared properties are skipped, not compared). Grant cloudformation:ListExports for full coverage. (${msg})`);
3341
+ }
3323
3342
  const resources = [];
3324
3343
  const principalsWithSiblingPolicy = collectPrincipalsWithSiblingPolicies(template.Resources ?? {}, ctx);
3325
3344
  const clustersWithSiblingCapacityProviders = collectClustersWithSiblingCapacityProviders(template.Resources ?? {});
@@ -4877,11 +4896,22 @@ const READ_RETRY = {
4877
4896
  //#endregion
4878
4897
  //#region src/read/kms-aliases.ts
4879
4898
  const cache$1 = /* @__PURE__ */ new Map();
4899
+ /** True when the error is a DEFINITIVE access-denial (cacheable), NOT a transient blip.
4900
+ * Matches an AccessDenied(Exception) / UnauthorizedOperation by name or code, or the AWS
4901
+ * HTTP 403 status. Anything else (throttle, network, 5xx, timeout) is treated as
4902
+ * transient and must NOT be cached. */
4903
+ function isDefinitiveDenial(err) {
4904
+ const e = err;
4905
+ if (!e) return false;
4906
+ const definitive = /^(AccessDenied(Exception)?|UnauthorizedOperation)$/;
4907
+ if (e.name && definitive.test(e.name)) return true;
4908
+ if (e.code && definitive.test(e.code)) return true;
4909
+ return e.$metadata?.httpStatusCode === 403;
4910
+ }
4880
4911
  async function fetchManagedAliasTargets(region) {
4881
4912
  const cached = cache$1.get(region);
4882
4913
  if (cached) return cached;
4883
4914
  const targets = {};
4884
- let result;
4885
4915
  try {
4886
4916
  const c = new KMSClient({
4887
4917
  region,
@@ -4896,18 +4926,27 @@ async function fetchManagedAliasTargets(region) {
4896
4926
  for (const a of r.Aliases ?? []) if (a.AliasName?.startsWith("alias/aws/") && a.TargetKeyId) targets[a.AliasName] = a.TargetKeyId;
4897
4927
  marker = r.Truncated ? r.NextMarker : void 0;
4898
4928
  } while (marker);
4899
- result = {
4929
+ const result = {
4900
4930
  targets,
4901
4931
  denied: false
4902
4932
  };
4903
- } catch {
4904
- result = {
4933
+ cache$1.set(region, result);
4934
+ return result;
4935
+ } catch (e) {
4936
+ if (isDefinitiveDenial(e)) {
4937
+ const result = {
4938
+ targets: {},
4939
+ denied: true
4940
+ };
4941
+ cache$1.set(region, result);
4942
+ return result;
4943
+ }
4944
+ return {
4905
4945
  targets: {},
4906
- denied: true
4946
+ denied: true,
4947
+ transient: true
4907
4948
  };
4908
4949
  }
4909
- cache$1.set(region, result);
4910
- return result;
4911
4950
  }
4912
4951
  /** The one-line warning emitted when ListAliases is denied but the stack declares an
4913
4952
  * AWS-managed alias: the managed-vs-customer key check degrades to shape-only, which
@@ -8408,10 +8447,11 @@ const EMPTY = {
8408
8447
  freeFormMapPaths: []
8409
8448
  };
8410
8449
  async function getSchemaInfo(client, resourceType) {
8411
- const cached = cache.get(resourceType);
8450
+ const cacheKey = `${await client.config.region()}\0${resourceType}`;
8451
+ const cached = cache.get(cacheKey);
8412
8452
  if (cached) return cached;
8413
8453
  const info = await fetch$1(client, resourceType);
8414
- cache.set(resourceType, info);
8454
+ cache.set(cacheKey, info);
8415
8455
  return info;
8416
8456
  }
8417
8457
  const OVERRIDE_READABLE_WRITEONLY = {
@@ -9263,7 +9303,7 @@ function splitRecordedByBaseline(recorded, baseline) {
9263
9303
  function selectRecorded(findings, selectedKeys) {
9264
9304
  return buildRecorded(findings).filter((e) => selectedKeys.has(recordedKey(e)));
9265
9305
  }
9266
- const topSegment = (p) => p.split(".")[0] ?? p;
9306
+ const isTopLevelPath = (p) => !p.includes(".") && !p.includes("[");
9267
9307
  /**
9268
9308
  * Reconcile undeclared findings against the recorded baseline (per ENTRY, R62):
9269
9309
  * - an undeclared finding matching an recorded entry (same value) is suppressed;
@@ -9377,7 +9417,7 @@ function applyBaseline(findings, baseline, opts = {}) {
9377
9417
  removedFromTemplate.push(`${a.logicalId}.${a.path}`);
9378
9418
  continue;
9379
9419
  }
9380
- if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {
9420
+ if (isTopLevelPath(a.path) && opts.declaredByLogical?.get(a.logicalId)?.has(a.path)) {
9381
9421
  promotedStale.push(`${a.logicalId}.${a.path}`);
9382
9422
  continue;
9383
9423
  }
@@ -11921,7 +11961,7 @@ function ignoreSelectOptions(ignorable, stackName = "") {
11921
11961
  * ignore` and (PR-B2) check's interactive flow, so both write rules identically.
11922
11962
  */
11923
11963
  async function ignoreStack(p) {
11924
- const { stackName, findings, yes, interactive } = p;
11964
+ const { stackName, findings, yes, interactive, accountId = "", region = "" } = p;
11925
11965
  const ignorable = findings.filter((f) => f.tier === "declared" || f.tier === "undeclared" || f.tier === "added");
11926
11966
  if (ignorable.length === 0) {
11927
11967
  console.log(style.clean(`${stackName}: no ignorable drift to ignore.`));
@@ -11961,7 +12001,7 @@ async function ignoreStack(p) {
11961
12001
  };
11962
12002
  }
11963
12003
  }
11964
- const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName)));
12004
+ const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName, accountId, region)));
11965
12005
  if (added.length > 0) {
11966
12006
  const dup = alreadyPresent.length > 0 ? `, ${alreadyPresent.length} already present` : "";
11967
12007
  console.log(style.ok(`ignore rule(s) added: ${path} (${added.length} new${dup})`));
@@ -12405,7 +12445,9 @@ async function runIgnore(args) {
12405
12445
  region
12406
12446
  }, config),
12407
12447
  yes: a.yes,
12408
- interactive: isInteractive()
12448
+ interactive: isInteractive(),
12449
+ accountId: desired.accountId,
12450
+ region
12409
12451
  });
12410
12452
  if (result.wrote) wroteAny = true;
12411
12453
  if (result.refused) worst = Math.max(worst, 2);
@@ -12590,6 +12632,19 @@ function groupReasons(items) {
12590
12632
  }
12591
12633
  return [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([k, c]) => `${k} ${c}`).join(", ");
12592
12634
  }
12635
+ function buildStackJson(rawFindings, header) {
12636
+ const findings = annotateHints(rawFindings);
12637
+ const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12638
+ const drifted = findings.filter(isDriftHere).length;
12639
+ return {
12640
+ json: {
12641
+ stack: header,
12642
+ drifted,
12643
+ findings
12644
+ },
12645
+ code: drifted === 0 ? 0 : 1
12646
+ };
12647
+ }
12593
12648
  function report(rawFindings, header, opts = {}) {
12594
12649
  const log = opts.log ?? console.log;
12595
12650
  const stackName = stackNameFromHeader(header);
@@ -12597,11 +12652,7 @@ function report(rawFindings, header, opts = {}) {
12597
12652
  const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12598
12653
  const drifted = findings.filter(isDriftHere).length;
12599
12654
  if (opts.json) {
12600
- log(JSON.stringify({
12601
- stack: header,
12602
- drifted,
12603
- findings
12604
- }, null, 2));
12655
+ log(JSON.stringify(buildStackJson(rawFindings, header).json, null, 2));
12605
12656
  return drifted === 0 ? 0 : 1;
12606
12657
  }
12607
12658
  const byTier = (t) => findings.filter((f) => f.tier === t && !f.unrecorded);
@@ -13105,7 +13156,9 @@ async function ignoreAll(p) {
13105
13156
  stackName: p.stackName,
13106
13157
  findings,
13107
13158
  yes: p.yes,
13108
- interactive: true
13159
+ interactive: true,
13160
+ accountId: p.desired.accountId,
13161
+ region: p.region
13109
13162
  })).wrote ? {
13110
13163
  exit: await recomputeExit(p, /* @__PURE__ */ new Set()),
13111
13164
  awsMutated: false
@@ -13170,7 +13223,9 @@ async function perFinding(p, decidable) {
13170
13223
  stackName: p.stackName,
13171
13224
  findings: groups.ignore,
13172
13225
  yes: true,
13173
- interactive: true
13226
+ interactive: true,
13227
+ accountId: p.desired.accountId,
13228
+ region: p.region
13174
13229
  });
13175
13230
  let revertResolved = /* @__PURE__ */ new Set();
13176
13231
  let revertExit = 0;
@@ -13291,11 +13346,22 @@ async function runCheck(args) {
13291
13346
  }
13292
13347
  let worst = 0;
13293
13348
  let anyDrift = false;
13349
+ const jsonReports = [];
13350
+ const jsonError = (stackName, region, message) => {
13351
+ if (a.json) jsonReports.push({
13352
+ stack: region ? `${stackName} (${region})` : stackName,
13353
+ drifted: 0,
13354
+ findings: [],
13355
+ error: message
13356
+ });
13357
+ };
13294
13358
  const separate = stackSeparator();
13295
13359
  const showProgress = !a.json && isInteractive();
13296
13360
  for (const [idx, { stackName, region, template }] of stacks.entries()) {
13297
13361
  if (!region) {
13298
- console.error(`error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`);
13362
+ const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
13363
+ console.error(`error: ${stackName}: ${msg}`);
13364
+ jsonError(stackName, region, msg);
13299
13365
  worst = Math.max(worst, 2);
13300
13366
  continue;
13301
13367
  }
@@ -13304,6 +13370,7 @@ async function runCheck(args) {
13304
13370
  const sKey = synthKey(stackName, region);
13305
13371
  if (synthTemplates && !synthTemplates.has(sKey)) {
13306
13372
  console.error(`note: ${stackName}: not in the synth output — skipped (--pre-deploy)`);
13373
+ jsonError(stackName, region, "not in the synth output — skipped (--pre-deploy)");
13307
13374
  continue;
13308
13375
  }
13309
13376
  const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, synthTemplates?.get(sKey), template));
@@ -13328,14 +13395,18 @@ async function runCheck(args) {
13328
13395
  const declaredOnly = preDeployFindings(findings);
13329
13396
  if (!a.json) console.error(`note: ${stackName}: --pre-deploy reports declared drift only (undeclared tiers are evaluated against the deployed template — run check without --pre-deploy)`);
13330
13397
  if (!a.json) separate();
13331
- const preDeployCode = report(applyIgnores(declaredOnly, {
13398
+ const preDeployReconciled = applyIgnores(declaredOnly, {
13332
13399
  stackName,
13333
13400
  accountId: desired.accountId,
13334
13401
  region
13335
- }, config), `${posPrefix}${stackName} (${region})`, {
13336
- json: a.json,
13337
- verbose: a.verbose
13338
- });
13402
+ }, config);
13403
+ const preDeployHeader = `${posPrefix}${stackName} (${region})`;
13404
+ let preDeployCode;
13405
+ if (a.json) {
13406
+ const { json, code } = buildStackJson(preDeployReconciled, preDeployHeader);
13407
+ jsonReports.push(json);
13408
+ preDeployCode = code;
13409
+ } else preDeployCode = report(preDeployReconciled, preDeployHeader, { verbose: a.verbose });
13339
13410
  if (preDeployCode === 1) anyDrift = true;
13340
13411
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
13341
13412
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
@@ -13362,8 +13433,13 @@ async function runCheck(args) {
13362
13433
  region
13363
13434
  }, config);
13364
13435
  if (!a.json) separate();
13365
- let code = report(reconciled, `${posPrefix}${stackName} (${region})`, {
13366
- json: a.json,
13436
+ const reportHeader = `${posPrefix}${stackName} (${region})`;
13437
+ let code;
13438
+ if (a.json) {
13439
+ const { json, code: jsonCode } = buildStackJson(reconciled, reportHeader);
13440
+ jsonReports.push(json);
13441
+ code = jsonCode;
13442
+ } else code = report(reconciled, reportHeader, {
13367
13443
  verbose: a.verbose,
13368
13444
  expandAtDefault: a.showAll
13369
13445
  });
@@ -13391,16 +13467,20 @@ async function runCheck(args) {
13391
13467
  } catch (e) {
13392
13468
  if (isStackNotDeployed(e)) {
13393
13469
  console.error(`note: ${stackName}: not deployed yet — skipped`);
13470
+ jsonError(stackName, region, "not deployed yet — skipped");
13394
13471
  continue;
13395
13472
  }
13396
13473
  if (e instanceof StackNotCheckableError) {
13397
13474
  console.error(`note: ${stackName}: ${e.message} — skipped`);
13475
+ jsonError(stackName, region, `${e.message} — skipped`);
13398
13476
  continue;
13399
13477
  }
13400
13478
  console.error(`error: ${stackName}: ${e.message}`);
13479
+ jsonError(stackName, region, e.message);
13401
13480
  worst = Math.max(worst, 2);
13402
13481
  }
13403
13482
  }
13483
+ if (a.json) console.log(JSON.stringify(jsonReports, null, 2));
13404
13484
  if (anyDrift && !a.fail && !a.json) console.error("note: drift found — exit 0 (report-only). Pass --fail to make drift fail this command.");
13405
13485
  return worst;
13406
13486
  }