All files / src/commands api.ts

86.26% Statements 270/313
85.77% Branches 217/253
88.63% Functions 39/44
86.17% Lines 268/311

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304                                      12x     12x                                           12x                   6x   6x 6x     6x                       150x 150x 50x       100x                                   518x 518x 2x       518x     518x           518x 55x       512x 512x   341x       171x 171x 171x 518x                     465x 465x   375x         12x     12x     12x                           1183x 1183x 55x     1128x 1128x       1183x 717x     1183x                 1027x 1581x     1581x 352x               1229x 50x                         13x 3x   10x 2x   8x               77x 77x 71x   6x             18x                         77x   77x 5x           72x 8x                               625x   625x 254x 254x     254x       254x 254x   254x 77x   177x     241x     612x                                                 1028x 1028x   1028x 1028x     1028x 161x 451x 449x                                                         638x 158x     480x   624x 322x           302x 293x     9x     9x 7x 7x 7x 7x     7x       2x                               355x     355x 5x 2x 2x   3x           350x 350x 350x 355x                                   199x   199x 346x     193x               36x 5x   31x                               27x   27x 32x 32x 3x           29x     29x 3x     26x 26x       26x 6x   20x       21x                               69x   69x 74x 74x 53x           21x 21x 1x           20x     20x 20x 2x 1x   1x     18x       15x                                   65x   65x     65x                                         278x 278x 278x 278x   278x 54x     224x   166x       58x                       7x   7x 7x 7x 2x           5x 5x 5x     5x                               164x 164x   54x                     4x 4x 7x 7x 2x       5x     4x                                         16x 4x         12x 9x                 3x 3x 6x   3x                                   598x 250x   348x 19x     329x 329x   1x                                             423x 54x       369x   369x 598x   598x 270x 270x     328x 52x             276x 276x 598x         317x                                 5x 2x   3x 2x 1x   3x 1x   2x       4x 4x   2x                                 176x 176x   176x 4x       172x     176x 8x 9x       172x                     7x 2x   5x 2x   3x                               155x 155x     155x 155x 155x                                 195x 195x 195x 262x   195x 39x   195x                                     262x 262x           262x 209x 209x 209x       262x 262x 158x   2x           156x       104x 145x   104x 52x               104x           157x                                     166x 52x             114x       53x             61x 59x     59x 6x     53x     2x       2x                                                                                                     12x                                                                                                                                                                                                                                                                                                                                                                                              
/**
 * sentry api
 *
 * Make raw authenticated API requests to Sentry.
 * Similar to 'gh api' for GitHub.
 */
 
import { access, readFile } from "node:fs/promises";
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import type { SentryContext } from "../context.js";
import { buildSearchParams, rawApiRequest } from "../lib/api-client.js";
import { buildCommand } from "../lib/command.js";
import { OutputError, ValidationError } from "../lib/errors.js";
import { CommandOutput } from "../lib/formatters/output.js";
import { validateEndpoint } from "../lib/input-validation.js";
import { logger } from "../lib/logger.js";
import { getDefaultSdkConfig } from "../lib/sentry-client.js";
 
const log = logger.withTag("api");
 
/** Strips line breaks and surrounding indentation from copy-pasted endpoints. */
const LINE_BREAK_PATTERN = /[ \t]*[\r\n]+[ \t]*/g;
 
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
 
type ApiFlags = {
  readonly method: HttpMethod;
  readonly data?: string;
  readonly field?: string[];
  readonly "raw-field"?: string[];
  readonly header?: string[];
  readonly input?: string;
  readonly silent: boolean;
  readonly verbose: boolean;
  readonly "dry-run": boolean;
  /** Injected by buildCommand via output config */
  readonly json: boolean;
  /** Injected by buildCommand via output config */
  readonly fields?: string[];
};
 
// Request Parsing
 
const VALID_METHODS: HttpMethod[] = ["GET", "POST", "PUT", "DELETE", "PATCH"];
 
/**
 * Read all data from stdin as a string.
 * Uses Bun's native stream handling for efficiency.
 * @internal Exported for testing
 */
export async function readStdin(
  stdin: NodeJS.ReadStream & { fd: 0 }
): Promise<string> {
  const chunks: Buffer[] = [];
 
  for await (const chunk of stdin) {
    chunks.push(Buffer.from(chunk));
  }
 
  return Buffer.concat(chunks).toString("utf-8");
}
 
/**
 * Parse and validate HTTP method from string.
 *
 * @param value - HTTP method string (case-insensitive)
 * @returns Normalized uppercase HTTP method
 * @throws {Error} When method is not one of GET, POST, PUT, DELETE, PATCH
 * @internal Exported for testing
 */
export function parseMethod(value: string): HttpMethod {
  const upper = value.toUpperCase();
  if (!VALID_METHODS.includes(upper as HttpMethod)) {
    throw new Error(
      `Invalid method: ${value}. Must be one of: ${VALID_METHODS.join(", ")}`
    );
  }
  return upper as HttpMethod;
}
 
/**
 * Normalize an API endpoint to ensure the path has a trailing slash.
 * Sentry API requires trailing slashes on endpoints.
 * Handles query strings correctly by only modifying the path portion.
 *
 * @param endpoint - API endpoint path (may include query string)
 * @returns Endpoint with trailing slash on path, query string preserved
 * @internal Exported for testing
 */
export function normalizeEndpoint(endpoint: string): string {
  // Strip line breaks and surrounding indentation from copy-pasted
  // endpoints. Users often paste multi-line URLs from docs or scripts,
  // producing newlines and indentation (CLI-FR, 215 events).
  // Other control characters (NUL, etc.) are left for validateEndpoint
  // to reject — those indicate corruption, not copy-paste.
  const cleaned = endpoint.replace(LINE_BREAK_PATTERN, "").trim();
  if (cleaned !== endpoint) {
    log.warn("Stripped line breaks from endpoint (copy-paste artifact)");
  }
 
  // Reject path traversal and remaining control characters after cleaning
  validateEndpoint(cleaned);
 
  // Remove leading slash if present (rawApiRequest handles the base URL)
  let trimmed = cleaned.startsWith("/") ? cleaned.slice(1) : cleaned;
 
  // Strip api/0/ prefix if user accidentally included it — the base URL
  // already includes /api/0/, so keeping it would produce a doubled path
  // like /api/0/api/0/... (see CLI-K1).
  // Also strip bare "api/0" to maintain idempotency.
  if (trimmed.startsWith("api/0/") || trimmed === "api/0") {
    trimmed = trimmed.slice(trimmed.startsWith("api/0/") ? 6 : 5);
  }
 
  // Split path and query string
  const queryIndex = trimmed.indexOf("?");
  if (queryIndex === -1) {
    // No query string - just ensure trailing slash
    return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
  }
 
  // Has query string - add trailing slash to path only
  const path = trimmed.substring(0, queryIndex);
  const query = trimmed.substring(queryIndex);
  const normalizedPath = path.endsWith("/") ? path : `${path}/`;
  return `${normalizedPath}${query}`;
}
 
/**
 * Parse a field value, attempting JSON parse first.
 *
 * @param value - Raw string value to parse
 * @returns Parsed JSON value, or original string if not valid JSON
 * @internal Exported for testing
 */
export function parseFieldValue(value: string): unknown {
  try {
    return JSON.parse(value);
  } catch {
    return value;
  }
}
 
/** Keys that could cause prototype pollution if used in nested object assignment */
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
 
/** Regex to match field key format: baseKey followed by zero or more [bracket] segments */
const FIELD_KEY_REGEX = /^([^[\]]+)((?:\[[^[\]]*\])*)$/;
 
/** Regex to extract bracket contents from a field key */
const BRACKET_CONTENTS_REGEX = /\[([^[\]]*)\]/g;
 
/**
 * Parse a field key into path segments.
 * Supports bracket notation: "user[name]" -> ["user", "name"]
 * Supports array syntax: "tags[]" -> ["tags", ""]
 * Supports deep nesting: "a[b][c]" -> ["a", "b", "c"]
 *
 * @param key - Field key with optional bracket notation
 * @returns Array of path segments
 * @throws {Error} When key format is invalid
 * @internal Exported for testing
 */
export function parseFieldKey(key: string): string[] {
  const match = key.match(FIELD_KEY_REGEX);
  if (!match?.[1]) {
    throw new ValidationError(`Invalid field key format: ${key}`, "field");
  }
 
  const baseKey = match[1];
  const brackets = match[2] ?? "";
 
  // Extract bracket contents: "[name][age]" -> ["name", "age"]
  // Empty brackets [] result in empty string "" for array push
  const segments: string[] = brackets
    ? [...brackets.matchAll(BRACKET_CONTENTS_REGEX)].map((m) => m[1] ?? "")
    : [];
 
  return [baseKey, ...segments];
}
 
/**
 * Validate path segments for security and correctness.
 * @throws {Error} When a segment is __proto__, constructor, or prototype
 * @throws {Error} When empty brackets appear before the last segment (e.g., a[][b])
 */
function validatePathSegments(path: string[]): void {
  for (let i = 0; i < path.length; i++) {
    const segment = path[i] as string; // Safe: loop bounds guarantee index exists
 
    // Check for prototype pollution
    if (DANGEROUS_KEYS.has(segment)) {
      throw new ValidationError(
        `Invalid field key: "${segment}" is not allowed`,
        "field"
      );
    }
 
    // Empty brackets ("") are only valid at the end of the path (array push syntax)
    // Reject patterns like a[][b] which would silently lose data
    if (segment === "" && i < path.length - 1) {
      throw new ValidationError(
        "Invalid field key: empty brackets [] can only appear at the end of a key",
        "field"
      );
    }
  }
}
 
/**
 * Get a human-readable type name for error messages.
 * Returns "array" for arrays, "map" for objects, and typeof for primitives.
 */
function getTypeName(value: unknown): string {
  if (Array.isArray(value)) {
    return "array";
  }
  if (value !== null && typeof value === "object") {
    return "map";
  }
  return typeof value;
}
 
/**
 * Format path segments into a bracket-notation string for error messages.
 * E.g., ["user", "name"] at index 1 -> "user[name]"
 */
function formatPathForError(path: string[], endIndex: number): string {
  const segments = path.slice(0, endIndex + 1);
  if (segments.length === 1) {
    return segments[0] ?? "";
  }
  return `${segments[0]}[${segments.slice(1).join("][")}]`;
}
 
/**
 * Check if value can be traversed into (is a plain object, not array or primitive).
 */
function isTraversableObject(value: unknown): boolean {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
 
/**
 * Validate that existing value is compatible with expected traversal type.
 * @throws {Error} When type conflict is detected
 */
function validateTypeCompatibility(
  existing: unknown,
  expectsArray: boolean,
  path: string[],
  index: number
): void {
  const pathStr = formatPathForError(path, index);
 
  if (expectsArray && !Array.isArray(existing)) {
    throw new ValidationError(
      `expected array type under "${pathStr}", got ${getTypeName(existing)}`,
      "field"
    );
  }
 
  if (!(expectsArray || isTraversableObject(existing))) {
    throw new ValidationError(
      `expected map type under "${pathStr}", got ${getTypeName(existing)}`,
      "field"
    );
  }
}
 
/**
 * Navigate/create nested structure to the parent of the target key.
 * @returns The object/array that will contain the final value
 * @throws {Error} When attempting to traverse into a non-object (type conflict)
 */
function navigateToParent(
  obj: Record<string, unknown>,
  path: string[]
): unknown {
  let current: unknown = obj;
 
  for (let i = 0; i < path.length - 1; i++) {
    const segment = path[i] as string; // Safe: loop bounds guarantee index exists
    const nextSegment = path[i + 1] as string;
 
    // Empty segment only at end for arrays - skip if encountered mid-path
    Iif (segment === "") {
      continue;
    }
 
    const currentObj = current as Record<string, unknown>;
    const expectsArray = nextSegment === "";
 
    if (Object.hasOwn(currentObj, segment)) {
      validateTypeCompatibility(currentObj[segment], expectsArray, path, i);
    } else {
      currentObj[segment] = expectsArray ? [] : {};
    }
 
    current = currentObj[segment];
  }
 
  return current;
}
 
/**
 * Set a nested value in an object using bracket notation key.
 * Creates intermediate objects or arrays as needed.
 *
 * Supports:
 * - Simple keys: "name" -> { name: value }
 * - Nested objects: "user[name]" -> { user: { name: value } }
 * - Deep nesting: "a[b][c]" -> { a: { b: { c: value } } }
 * - Array push: "tags[]" with value -> { tags: [value] }
 * - Empty array: "tags[]" with undefined -> { tags: [] }
 *
 * @param obj - Target object to modify
 * @param key - Bracket-notation key (e.g., "user[name]", "tags[]")
 * @param value - Value to set (undefined for empty array initialization)
 * @throws {Error} When key contains dangerous segments (__proto__, constructor, prototype)
 * @internal Exported for testing
 */
export function setNestedValue(
  obj: Record<string, unknown>,
  key: string,
  value: unknown
): void {
  const path = parseFieldKey(key);
  validatePathSegments(path);
 
  const current = navigateToParent(obj, path);
  const lastSegment = path.at(-1);
 
  // Array push syntax: key[]=value
  if (lastSegment === "" && Array.isArray(current) && value !== undefined) {
    current.push(value);
  } else if (lastSegment !== undefined && lastSegment !== "") {
    (current as Record<string, unknown>)[lastSegment] = value;
  }
}
 
/**
 * Auto-correct fields that use ':' instead of '=' as the separator, and warn
 * the user via the module logger.
 *
 * This recovers from a common mistake where users write Sentry search-query
 * style syntax (`-F status:resolved`) instead of the required key=value form
 * (`-F status=resolved`).  The correction is safe to apply unconditionally
 * because this function is only called for fields that have already been
 * confirmed to contain no '=' — at that point the request would fail anyway.
 *
 * Splitting on the *first* ':' is intentional so that values that themselves
 * contain colons (e.g. ISO timestamps, URLs) are preserved intact:
 *   `since:2026-02-25T11:20:00` → key=`since`, value=`2026-02-25T11:20:00`
 *
 * Fields with no ':' (truly uncorrectable) are returned unchanged so that the
 * downstream parser can throw its normal error.
 *
 * @param fields - Raw field strings from --field or --raw-field flags
 * @returns New array with corrected field strings (or the original array if no
 *   corrections were needed)
 * @internal Exported for testing
 */
export function normalizeFields(
  fields: string[] | undefined
): string[] | undefined {
  if (!fields || fields.length === 0) {
    return fields;
  }
 
  return fields.map((field) => {
    // Already valid: has '=' or is the empty-array syntax "key[]"
    if (field.includes("=") || field.endsWith("[]")) {
      return field;
    }
 
    // JSON-shaped strings (starting with { or [) must not be "corrected" —
    // the colon inside is JSON syntax, not a key:value separator.  Let the
    // downstream pipeline handle it (extractJsonBody or processField error).
    if (field.startsWith("{") || field.startsWith("[")) {
      return field;
    }
 
    const colonIndex = field.indexOf(":");
    // ':' must exist and not be the very first character (that would make an
    // empty key, which the parser rejects regardless)
    if (colonIndex > 0) {
      const key = field.substring(0, colonIndex);
      const value = field.substring(colonIndex + 1);
      const corrected = `${key}=${value}`;
      log.warn(
        `field '${field}' looks like it uses ':' instead of '=' — interpreting as '${corrected}'`
      );
      return corrected;
    }
 
    // No correction possible; let the downstream parser throw.
    return field;
  });
}
 
/**
 * Process a single field string and set its value in the result object.
 * @param result - Target object to modify
 * @param field - Field string in "key=value" or "key[]" format
 * @param raw - If true, keep value as string (no JSON parsing)
 * @throws {ValidationError} When field format is invalid
 */
function processField(
  result: Record<string, unknown>,
  field: string,
  raw: boolean
): void {
  const eqIndex = field.indexOf("=");
 
  // Handle empty array syntax: "key[]" without "="
  if (eqIndex === -1) {
    if (field.endsWith("[]")) {
      setNestedValue(result, field, undefined);
      return;
    }
    throw new ValidationError(
      `Invalid field format: ${field}. Expected key=value`,
      "field"
    );
  }
 
  const key = field.substring(0, eqIndex);
  const rawValue = field.substring(eqIndex + 1);
  const value = raw ? rawValue : parseFieldValue(rawValue);
  setNestedValue(result, key, value);
}
 
/**
 * Parse field arguments into request body object.
 * Supports bracket notation for nested keys (e.g., "user[name]=value")
 * and array syntax (e.g., "tags[]=value" or "tags[]" for empty array).
 *
 * @param fields - Array of "key=value" strings (or "key[]" for empty arrays)
 * @param raw - If true, treat all values as strings (no JSON parsing)
 * @returns Parsed object with nested structure
 * @throws {Error} When field format is invalid
 * @internal Exported for testing
 */
export function parseFields(
  fields: string[],
  raw = false
): Record<string, unknown> {
  const result: Record<string, unknown> = {};
 
  for (const field of fields) {
    processField(result, field, raw);
  }
 
  return result;
}
 
/**
 * Convert a value to string, JSON-stringifying objects to avoid "[object Object]".
 * @internal
 */
function stringifyValue(value: unknown): string {
  if (typeof value === "object" && value !== null) {
    return JSON.stringify(value);
  }
  return String(value);
}
 
/**
 * Build query parameters from typed field strings (--field/-F) for GET requests.
 * Unlike parseFields(), this produces a flat structure suitable for URL query strings.
 * Arrays are represented as string[] for repeated keys (e.g., tags=1&tags=2&tags=3).
 *
 * @param fields - Array of "key=value" strings
 * @returns Record suitable for URLSearchParams
 * @throws {Error} When field doesn't contain "=" or key format is invalid
 * @internal Exported for testing
 */
export function buildQueryParams(
  fields: string[]
): Record<string, string | string[]> {
  const result: Record<string, string | string[]> = {};
 
  for (const field of fields) {
    const eqIndex = field.indexOf("=");
    if (eqIndex === -1) {
      throw new ValidationError(
        `Invalid field format: ${field}. Expected key=value`,
        "field"
      );
    }
 
    const key = field.substring(0, eqIndex);
 
    // Validate key format (same validation as parseFieldKey for consistency)
    if (!FIELD_KEY_REGEX.test(key)) {
      throw new ValidationError(`Invalid field key format: ${key}`, "field");
    }
 
    const rawValue = field.substring(eqIndex + 1);
    const value = parseFieldValue(rawValue);
 
    // Handle arrays by creating string[] for repeated keys
    // Use stringifyValue to handle objects (avoid "[object Object]")
    if (Array.isArray(value)) {
      result[key] = value.map(stringifyValue);
    } else {
      result[key] = stringifyValue(value);
    }
  }
 
  return result;
}
 
/**
 * Build query parameters from raw field strings (--raw-field/-f) for GET requests.
 * Raw fields are passed directly without any processing (no JSON parsing, no bracket
 * notation, no URI encoding). Values are kept exactly as provided.
 *
 * @param fields - Array of "key=value" strings
 * @returns Record suitable for URLSearchParams
 * @throws {ValidationError} When field doesn't contain "=" or key is empty
 * @internal Exported for testing
 */
export function buildRawQueryParams(
  fields: string[]
): Record<string, string | string[]> {
  const result: Record<string, string | string[]> = {};
 
  for (const field of fields) {
    const eqIndex = field.indexOf("=");
    if (eqIndex === -1) {
      throw new ValidationError(
        `Invalid field format: ${field}. Expected key=value`,
        "field"
      );
    }
 
    const key = field.substring(0, eqIndex);
    if (key === "") {
      throw new ValidationError(
        "Invalid field key format: key cannot be empty",
        "field"
      );
    }
 
    const value = field.substring(eqIndex + 1);
 
    // For raw fields, handle repeated keys by creating string[]
    const existing = result[key];
    if (existing !== undefined) {
      if (Array.isArray(existing)) {
        existing.push(value);
      } else {
        result[key] = [existing, value];
      }
    } else {
      result[key] = value;
    }
  }
 
  return result;
}
 
/**
 * Build query parameters from both typed and raw field strings for GET requests.
 * Typed fields (--field/-F) are parsed with JSON conversion and bracket notation.
 * Raw fields (--raw-field/-f) are passed directly without any processing.
 *
 * @param typedFields - Array of typed "key=value" strings (JSON parsed)
 * @param rawFields - Array of raw "key=value" strings (no processing)
 * @returns Merged record suitable for URLSearchParams
 * @internal Exported for testing
 */
export function buildQueryParamsFromFields(
  typedFields?: string[],
  rawFields?: string[]
): Record<string, string | string[]> {
  const typedParams =
    typedFields && typedFields.length > 0 ? buildQueryParams(typedFields) : {};
  const rawParams =
    rawFields && rawFields.length > 0 ? buildRawQueryParams(rawFields) : {};
 
  // Merge params: raw fields can override typed fields if same key
  return { ...typedParams, ...rawParams };
}
 
/**
 * Prepare request options by routing fields to body or params based on HTTP method.
 * GET requests send fields as query parameters, other methods send as JSON body.
 *
 * @param method - HTTP method
 * @param typedFields - Array of "key=value" field strings (--field, values parsed as JSON)
 * @param rawFields - Array of "key=value" field strings (--raw-field, values kept as strings)
 * @returns Object with either body or params set (or neither if no fields)
 * @internal Exported for testing
 */
export function prepareRequestOptions(
  method: HttpMethod,
  typedFields?: string[],
  rawFields?: string[]
): {
  body?: Record<string, unknown>;
  params?: Record<string, string | string[]>;
} {
  const hasTypedFields = typedFields && typedFields.length > 0;
  const hasRawFields = rawFields && rawFields.length > 0;
  const hasFields = hasTypedFields || hasRawFields;
  const isBodyMethod = method !== "GET";
 
  if (!hasFields) {
    return {};
  }
 
  if (isBodyMethod) {
    // For body methods (POST, PUT, etc.), merge typed and raw fields
    return { body: buildBodyFromFields(typedFields, rawFields) };
  }
 
  // For GET requests, build query params from both typed and raw fields
  return { params: buildQueryParamsFromFields(typedFields, rawFields) };
}
 
/**
 * Parse header arguments into headers object.
 *
 * @param headers - Array of "Key: Value" strings
 * @returns Object mapping header names to values
 * @throws {Error} When header doesn't contain ":"
 * @internal Exported for testing
 */
export function parseHeaders(headers: string[]): Record<string, string> {
  const result: Record<string, string> = {};
 
  for (const header of headers) {
    const colonIndex = header.indexOf(":");
    if (colonIndex === -1) {
      throw new ValidationError(
        `Invalid header format: ${header}. Expected Key: Value`,
        "header"
      );
    }
 
    const key = header.substring(0, colonIndex).trim();
    const value = header.substring(colonIndex + 1).trim();
    result[key] = value;
  }
 
  return result;
}
 
// Request Body Building
 
/**
 * Parse an inline string as a request body.  Tries JSON first; falls back to
 * the raw string so non-JSON payloads still work.
 *
 * @param data - Raw string from --data flag
 * @returns Parsed JSON object/array, or the original string
 * @internal Exported for testing
 */
export function parseDataBody(
  data: string
): Record<string, unknown> | unknown[] | string {
  try {
    return JSON.parse(data) as Record<string, unknown> | unknown[];
  } catch {
    return data;
  }
}
 
/**
 * Parse a URL-encoded string into a query parameter map.
 * Duplicate keys are collected into arrays.
 */
function parseUrlEncodedParams(
  data: string
): Record<string, string | string[]> {
  const params: Record<string, string | string[]> = {};
  for (const [key, value] of new URLSearchParams(data)) {
    const existing = params[key];
    if (existing !== undefined) {
      params[key] = Array.isArray(existing)
        ? [...existing, value]
        : [existing, value];
    } else {
      params[key] = value;
    }
  }
  return params;
}
 
/**
 * Convert `--data` content to query parameters for bodyless HTTP methods
 * (GET, HEAD, OPTIONS).
 *
 * Handles two formats:
 * - URL-encoded strings: `"stat=received&resolution=1d"` → `{ stat: "received", resolution: "1d" }`
 * - JSON objects: `{ "stat": "received" }` → `{ stat: "received" }`
 *
 * Duplicate keys in URL-encoded strings are collected into arrays.
 *
 * @param data - Parsed output from {@link parseDataBody}
 * @returns Query parameter map suitable for `rawApiRequest`'s `params` option
 * @throws {ValidationError} When data is a JSON array or primitive (cannot be query params)
 * @internal Exported for testing
 */
export function dataToQueryParams(
  data: Record<string, unknown> | unknown[] | string
): Record<string, string | string[]> {
  if (typeof data === "string") {
    return parseUrlEncodedParams(data);
  }
 
  // JSON arrays and primitives (null, boolean, number) can't be query params.
  // parseDataBody uses `as` to narrow JSON.parse output, but primitives slip through.
  if (data === null || typeof data !== "object" || Array.isArray(data)) {
    throw new ValidationError(
      "Cannot use --data with a JSON primitive or array for GET requests. " +
        "Only JSON objects and URL-encoded strings can be converted to query parameters. " +
        "Use --method POST to send this data as a request body.",
      "data"
    );
  }
 
  // JSON object: stringify non-string values
  const params: Record<string, string | string[]> = {};
  for (const [key, value] of Object.entries(data)) {
    params[key] = typeof value === "string" ? value : JSON.stringify(value);
  }
  return params;
}
 
/**
 * Try to parse a single field as a bare JSON **object or array** body.
 *
 * The `startsWith` guard is intentional — not just an optimisation.  It
 * restricts detection to objects (`{`) and arrays (`[`), excluding JSON
 * primitives like `42`, `true`, `"string"`.  Without this guard those
 * primitives would be extracted as the body, and downstream code (e.g. the
 * `k in body` key-conflict check) would throw a `TypeError` because the `in`
 * operator requires an object on the right-hand side.
 *
 * @internal
 */
function tryParseJsonField(
  field: string
): Record<string, unknown> | unknown[] | undefined {
  if (field.includes("=")) {
    return;
  }
  if (!(field.startsWith("{") || field.startsWith("["))) {
    return;
  }
 
  try {
    return JSON.parse(field) as Record<string, unknown> | unknown[];
  } catch {
    return;
  }
}
 
/**
 * Scan a field list for bare JSON **object or array** values (no `=`) and
 * extract the first one as the intended request body.  This handles the
 * common mistake of passing `-f '{"status":"ignored"}'` instead of
 * `-d '{"status":"ignored"}'`.
 *
 * Detection is conservative: the field must have no `=`, start with `{` or
 * `[`, and parse as valid JSON.  Only one JSON body is allowed — multiple
 * JSON fields are ambiguous and produce a {@link ValidationError}.
 *
 * @returns An object with the extracted `body` (if any) and the `remaining`
 *   fields that are normal key=value entries, or `undefined` if the input
 *   was empty/undefined.
 * @internal Exported for testing
 */
export function extractJsonBody(fields: string[] | undefined): {
  body?: Record<string, unknown> | unknown[];
  remaining?: string[];
} {
  if (!fields || fields.length === 0) {
    return {};
  }
 
  let jsonBody: Record<string, unknown> | unknown[] | undefined;
  const remaining: string[] = [];
 
  for (const field of fields) {
    const parsed = tryParseJsonField(field);
 
    if (parsed === undefined) {
      remaining.push(field);
      continue;
    }
 
    if (jsonBody !== undefined) {
      throw new ValidationError(
        "Multiple JSON bodies detected in field arguments. " +
          "Use --data/-d to pass an inline JSON body explicitly.",
        "field"
      );
    }
 
    jsonBody = parsed;
    const preview = field.length > 60 ? `${field.substring(0, 57)}...` : field;
    log.info(
      `'${preview}' was used as the request body. Use --data/-d to pass inline JSON next time.`
    );
  }
 
  return {
    body: jsonBody,
    remaining: remaining.length > 0 ? remaining : undefined,
  };
}
 
/**
 * Build request body from --input flag (file or stdin).
 * Tries to parse the content as JSON, otherwise returns as string.
 * @internal Exported for testing
 */
export async function buildBodyFromInput(
  inputPath: string,
  stdin: NodeJS.ReadStream & { fd: 0 }
): Promise<Record<string, unknown> | string> {
  let content: string;
 
  if (inputPath === "-") {
    content = await readStdin(stdin);
  } else {
    const exists = await access(inputPath).then(
      () => true,
      () => false
    );
    if (!exists) {
      throw new ValidationError(`File not found: ${inputPath}`, "input");
    }
    content = await readFile(inputPath, "utf-8");
  }
 
  // Try to parse as JSON for the API client
  try {
    return JSON.parse(content) as Record<string, unknown>;
  } catch {
    return content;
  }
}
 
/**
 * Build request body from --field and --raw-field flags.
 * Processes typed fields first, then raw fields, allowing raw fields
 * to overwrite typed fields at the same path. Both field types are
 * merged into a single object, properly handling nested keys.
 *
 * @returns Merged object or undefined if no fields provided
 * @internal Exported for testing
 */
export function buildBodyFromFields(
  typedFields: string[] | undefined,
  rawFields: string[] | undefined
): Record<string, unknown> | undefined {
  const hasTypedFields = typedFields && typedFields.length > 0;
  const hasRawFields = rawFields && rawFields.length > 0;
 
  if (!(hasTypedFields || hasRawFields)) {
    return;
  }
 
  // Start with typed fields (JSON parsing enabled)
  const result = hasTypedFields ? parseFields(typedFields, false) : {};
 
  // Merge raw fields on top (no JSON parsing, can overwrite typed)
  if (hasRawFields) {
    for (const field of rawFields) {
      processField(result, field, true);
    }
  }
 
  return Object.keys(result).length > 0 ? result : undefined;
}
 
// Response Output
 
/**
 * Format a raw response body value for human-readable output.
 * Objects are pretty-printed as JSON, strings pass through, null/undefined → empty.
 * @internal Exported for testing
 */
export function formatApiResponse(data: unknown): string {
  if (data === null || data === undefined) {
    return "";
  }
  if (typeof data === "object") {
    return JSON.stringify(data, null, 2);
  }
  return String(data);
}
 
/**
 * Resolve the full URL that rawApiRequest would use for a request.
 *
 * Mirrors the URL construction in rawApiRequest:
 * `${baseUrl}/api/0/${endpoint}?${queryString}`
 * @internal Exported for testing
 */
export function resolveRequestUrl(
  endpoint: string,
  params?: Record<string, string | string[]>
): string {
  // Use getDefaultSdkConfig().baseUrl — same as rawApiRequest — to ensure
  // trailing slashes are stripped and the URL matches what would be sent.
  const { baseUrl } = getDefaultSdkConfig();
  const normalizedEndpoint = endpoint.startsWith("/")
    ? endpoint.slice(1)
    : endpoint;
  const searchParams = buildSearchParams(params);
  const queryString = searchParams ? `?${searchParams.toString()}` : "";
  return `${baseUrl}/api/0/${normalizedEndpoint}${queryString}`;
}
 
/**
 * Resolve effective request headers, mirroring rawApiRequest logic.
 *
 * Auto-adds Content-Type: application/json for non-string object bodies
 * when no Content-Type was explicitly provided.
 *
 * @internal Exported for testing
 */
export function resolveEffectiveHeaders(
  customHeaders: Record<string, string> | undefined,
  body: unknown
): Record<string, string> {
  // Mirror rawApiRequest exactly: auto-add Content-Type for any non-string,
  // non-undefined body when no Content-Type was explicitly provided.
  const isStringBody = typeof body === "string";
  const headers = { ...(customHeaders ?? {}) };
  const hasContentType = Object.keys(headers).some(
    (k) => k.toLowerCase() === "content-type"
  );
  if (!(isStringBody || hasContentType) && body !== undefined) {
    headers["Content-Type"] = "application/json";
  }
  return headers;
}
 
/**
 * Build body and params from field flags, auto-detecting bare JSON bodies.
 *
 * Runs colon-to-equals normalization, extracts any JSON body passed as a
 * field value (with a logged hint about `--data`), and routes the remaining
 * fields to body or query params based on the HTTP method.
 *
 * @internal Exported for testing
 */
export function buildFromFields(
  method: HttpMethod,
  flags: Pick<ApiFlags, "field" | "raw-field">
): {
  body?: Record<string, unknown> | unknown[];
  params?: Record<string, string | string[]>;
} {
  const field = normalizeFields(flags.field);
  let rawField = normalizeFields(flags["raw-field"]);
 
  // Auto-detect bare JSON passed as a field value (common mistake).
  // GET requests don't have a body — skip detection so JSON-shaped values
  // fall through to query-param routing (which will throw a clear error).
  let body: Record<string, unknown> | unknown[] | undefined;
  if (method !== "GET") {
    const extracted = extractJsonBody(rawField);
    body = extracted.body;
    rawField = extracted.remaining;
  }
 
  // Route remaining fields to body (merge) or params based on HTTP method
  const options = prepareRequestOptions(method, field, rawField);
  if (options.body) {
    if (Array.isArray(body)) {
      // Can't meaningfully merge key=value fields into a JSON array body.
      throw new ValidationError(
        "Cannot combine a JSON array body with field flags (-F/-f). " +
          "Use --data/-d to pass the array as the full body without extra fields.",
        "field"
      );
    }
    if (body) {
      // Detect top-level key conflicts before merging — a shallow spread would
      // silently drop nested fields from the JSON body (e.g. statusDetails.ignoreCount
      // overwritten by statusDetails[minCount]=5).
      const conflicts = Object.keys(options.body).filter(
        (k) => k in (body as Record<string, unknown>)
      );
      if (conflicts.length > 0) {
        throw new ValidationError(
          `Field flag(s) conflict with detected JSON body at key(s): ${conflicts.join(", ")}. ` +
            "Use --data/-d to pass the full JSON body, or use only field flags (-F/-f).",
          "field"
        );
      }
    }
    // Merge field-built key=value entries into the auto-detected JSON object body
    body =
      body && typeof body === "object"
        ? { ...(body as Record<string, unknown>), ...options.body }
        : options.body;
  }
 
  return { body, params: options.params };
}
 
/**
 * Resolve the request body and query params from the user-provided flags.
 *
 * Priority order: `--data` > `--input` > field flags (`-F`/`-f`).
 * Mutually-exclusive combinations throw {@link ValidationError}.
 *
 * @returns body and params ready for the API request
 * @internal Exported for testing
 */
export async function resolveBody(
  flags: Pick<ApiFlags, "method" | "data" | "input" | "field" | "raw-field">,
  stdin: NodeJS.ReadStream & { fd: 0 }
): Promise<{
  body?: Record<string, unknown> | unknown[] | string;
  params?: Record<string, string | string[]>;
}> {
  if (flags.data !== undefined && flags.input !== undefined) {
    throw new ValidationError(
      "Cannot use --data and --input together. " +
        "Use --data/-d for inline JSON, or --input for file/stdin.",
      "data"
    );
  }
 
  if (
    flags.data !== undefined &&
    (flags.field?.length || flags["raw-field"]?.length)
  ) {
    throw new ValidationError(
      "Cannot use --data with --field or --raw-field. " +
        "Use --data/-d for a full JSON body, or -F/-f for individual fields.",
      "data"
    );
  }
 
  if (flags.data !== undefined) {
    const parsed = parseDataBody(flags.data);
 
    // GET/HEAD/OPTIONS cannot have a body — convert data to query params
    if (flags.method === "GET") {
      return { params: dataToQueryParams(parsed) };
    }
 
    return { body: parsed };
  }
 
  Iif (flags.input !== undefined) {
    return { body: await buildBodyFromInput(flags.input, stdin) };
  }
 
  return buildFromFields(flags.method, flags);
}
 
// Command Definition
 
/**
 * Record API error attributes on the active telemetry span.
 *
 * Since `OutputError` is excluded from `Sentry.captureException` (it signals
 * an intentional non-zero exit, not a CLI bug), these span attributes are the
 * only telemetry signal for `sentry api` HTTP errors. They're queryable in
 * Discover via `api_error.status`, matching the pattern used by
 * `recordApiErrorOnSpan` for `ApiError`-based errors in other commands.
 */
function recordApiErrorAttributes(
  status: number,
  endpoint: string,
  method: string
): void {
  const span = Sentry.getActiveSpan();
  if (span) {
    span.setAttribute("api_error.status", status);
    span.setAttribute("api_error.endpoint", endpoint);
    span.setAttribute("api_error.method", method);
  }
}
 
/** Log outgoing request details in `> ` curl-verbose style. */
function logRequest(
  method: string,
  endpoint: string,
  headers: Record<string, string> | undefined
): void {
  log.debug(`> ${method} /api/0/${endpoint}`);
  if (headers) {
    for (const [key, value] of Object.entries(headers)) {
      log.debug(`> ${key}: ${value}`);
    }
  }
  log.debug(">");
}
 
/** Log incoming response details in `< ` curl-verbose style. */
function logResponse(response: { status: number; headers: Headers }): void {
  log.debug(`< HTTP ${response.status}`);
  response.headers.forEach((value, key) => {
    log.debug(`< ${key}: ${value}`);
  });
  log.debug("<");
}
 
export const apiCommand = buildCommand({
  output: { human: formatApiResponse },
  docs: {
    brief: "Make an authenticated API request",
    fullDescription:
      "Make a raw API request to the Sentry API. Similar to 'gh api' for GitHub. " +
      "The endpoint is relative to /api/0/ (do not include the prefix). " +
      "Authentication is handled automatically using your stored credentials.\n\n" +
      "Body options:\n" +
      '  --data/-d \'{"key":"value"}\'   Inline JSON body (like curl -d)\n' +
      '  --input/-i file.json          Read body from file (or "-" for stdin)\n\n' +
      "Field syntax (--field/-F):\n" +
      "  key=value          Simple field (values parsed as JSON if valid)\n" +
      "  key[sub]=value     Nested object: {key: {sub: value}}\n" +
      "  key[]=value        Array append: {key: [value]}\n" +
      "  key[]              Empty array: {key: []}\n\n" +
      "Use --raw-field/-f to send values as strings without JSON parsing.\n\n" +
      "Examples:\n" +
      "  sentry api organizations/\n" +
      "  sentry api issues/123/ -X PUT -F status=resolved\n" +
      '  sentry api issues/123/ -X PUT -d \'{"status":"resolved"}\'\n' +
      "  sentry api projects/my-org/my-project/ -F options[sampleRate]=0.5\n" +
      "  sentry api teams/my-org/my-team/members/ -F user[email]=user@example.com",
  },
  parameters: {
    positional: {
      kind: "tuple",
      parameters: [
        {
          brief: "API endpoint relative to /api/0/ (e.g., organizations/)",
          parse: String,
          placeholder: "endpoint",
        },
      ],
    },
    flags: {
      method: {
        kind: "parsed",
        parse: parseMethod,
        brief: "The HTTP method for the request",
        default: "GET" as const,
        placeholder: "method",
      },
      data: {
        kind: "parsed",
        parse: String,
        brief: "Inline JSON body for the request (like curl -d)",
        optional: true,
        placeholder: "json",
      },
      field: {
        kind: "parsed",
        parse: String,
        brief: "Add a typed parameter (key=value, key[sub]=value, key[]=value)",
        variadic: true,
        optional: true,
      },
      "raw-field": {
        kind: "parsed",
        parse: String,
        brief: "Add a string parameter without JSON parsing",
        variadic: true,
        optional: true,
      },
      header: {
        kind: "parsed",
        parse: String,
        brief: "Add a HTTP request header in key:value format",
        variadic: true,
        optional: true,
      },
      input: {
        kind: "parsed",
        parse: String,
        brief:
          'The file to use as body for the HTTP request (use "-" to read from standard input)',
        optional: true,
        placeholder: "file",
      },
      silent: {
        kind: "boolean",
        brief: "Do not print the response body",
        default: false,
      },
      verbose: {
        kind: "boolean",
        brief: "Include full HTTP request and response in the output",
        default: false,
      },
      "dry-run": {
        kind: "boolean",
        brief: "Show the resolved request without sending it",
        default: false,
      },
    },
    aliases: {
      X: "method",
      d: "data",
      F: "field",
      f: "raw-field",
      H: "header",
      n: "dry-run",
    },
  },
  async *func(this: SentryContext, flags: ApiFlags, endpoint: string) {
    const { stdin } = this;
 
    const normalizedEndpoint = normalizeEndpoint(endpoint);
 
    // Detect whether normalizeEndpoint stripped the api/0/ prefix (CLI-K1).
    // Compare against the cleaned endpoint (line breaks removed, trimmed,
    // leading slash removed) since normalizeEndpoint also strips copy-paste
    // artifacts before the api/0/ check. Without this, line-break removal
    // alone would shrink the length and trigger a false api/0/ warning.
    const cleaned = endpoint.replace(LINE_BREAK_PATTERN, "").trim();
    const baseLen = cleaned.startsWith("/")
      ? cleaned.length - 1
      : cleaned.length;
    if (normalizedEndpoint.length < baseLen) {
      // Silent auto-fix — not a warning. Users commonly copy/paste URLs
      // that include the /api/0/ prefix; we strip it transparently and
      // only surface the detail at debug level for troubleshooting
      // (getsentry/cli#785 item #11).
      log.debug(
        "Stripped /api/0/ prefix from endpoint (auto-added by the API client)"
      );
    }
    const { body, params } = await resolveBody(flags, stdin);
 
    const headers =
      flags.header && flags.header.length > 0
        ? parseHeaders(flags.header)
        : undefined;
 
    // Dry-run mode: preview the request that would be sent
    if (flags["dry-run"]) {
      yield new CommandOutput({
        method: flags.method,
        url: resolveRequestUrl(normalizedEndpoint, params),
        headers: resolveEffectiveHeaders(headers, body),
        body: body ?? null,
      });
      return;
    }
 
    const verbose = flags.verbose && !flags.silent;
 
    if (verbose) {
      logRequest(flags.method, normalizedEndpoint, headers);
    }
 
    const response = await rawApiRequest(normalizedEndpoint, {
      method: flags.method,
      body,
      params,
      headers,
    });
 
    const isError = response.status >= 400;
 
    if (verbose) {
      logResponse(response);
    }
 
    // Record API error attributes on the active span for Discover queryability.
    // OutputError is excluded from Sentry.captureException (it's an intentional
    // non-zero exit, not a bug), so span attributes are the only telemetry signal.
    if (isError) {
      recordApiErrorAttributes(
        response.status,
        normalizedEndpoint,
        flags.method
      );
    }
 
    // Silent mode — no output, just exit code
    if (flags.silent) {
      if (isError) {
        throw new OutputError(null);
      }
      return;
    }
 
    // Always return raw body — --fields filters it directly
    if (isError) {
      throw new OutputError(response.body);
    }
 
    return yield new CommandOutput(response.body);
  },
});