All files / src/lib/formatters json.ts

96.42% Statements 54/56
94.73% Branches 54/57
100% Functions 10/10
96.36% Lines 53/55

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                                                        1400x         1400x 232x       1168x 1168x 1234x         2x   1232x 1107x   125x   59x                                         291x 232x 232x   59x 59x 59x 62x 62x     62x         61x   62x   59x 59x 59x                                         732x 51x 134x       681x 50x     631x   631x 1400x 1400x       291x 291x       631x                               361x       1650x                   263x                               6x 6x                                                                             17x   17x 6x     17x 17x 2x   17x 1x   17x 2x     17x    
/**
 * JSON output utilities
 *
 * Provides formatting, field filtering, and streaming helpers for
 * `--json` output across all CLI commands.
 */
 
import type { Writer } from "../../types/index.js";
 
/**
 * Get a nested value from an object using a dot-notated path.
 *
 * First checks for the path as a literal property name (e.g.,
 * `"gen_ai.usage.input_tokens"` as a flat key), then falls back to
 * dot-separated nested traversal (e.g., `"contexts.trace.traceId"`).
 * This ensures custom span attributes with dotted names are found.
 *
 * Returns `{ found: true, value }` when the path resolves, even if the
 * leaf value is `undefined` or `null`. Returns `{ found: false }` when
 * any intermediate segment is not an object (or is missing).
 *
 * @param obj - Source object to traverse
 * @param path - Key path: literal property name or dot-separated nesting
 */
function getNestedValue(
  obj: unknown,
  path: string
): { found: true; value: unknown } | { found: false } {
  Iif (obj === null || obj === undefined || typeof obj !== "object") {
    return { found: false };
  }
 
  // Fast path: literal property name (handles dotted keys like "gen_ai.usage.input_tokens")
  if (Object.hasOwn(obj, path)) {
    return { found: true, value: (obj as Record<string, unknown>)[path] };
  }
 
  // Fall back to dot-separated nested traversal
  let current: unknown = obj;
  for (const segment of path.split(".")) {
    if (
      current === null ||
      current === undefined ||
      typeof current !== "object"
    ) {
      return { found: false };
    }
    if (!Object.hasOwn(current, segment)) {
      return { found: false };
    }
    current = (current as Record<string, unknown>)[segment];
  }
  return { found: true, value: current };
}
 
/**
 * Set a nested value in an object, creating intermediate objects as needed.
 *
 * When `literalKey` is true, the path is used as a literal property name
 * (no dot splitting). This preserves dotted attribute names like
 * `"gen_ai.usage.input_tokens"` as flat keys in the output.
 *
 * @param target - Target object to write into (mutated in place)
 * @param path - Key path: literal name or dot-separated nesting
 * @param value - Value to set at the leaf
 * @param literalKey - When true, skip dot splitting
 */
function setNestedValue(
  target: Record<string, unknown>,
  path: string,
  value: unknown,
  literalKey = false
): void {
  if (literalKey) {
    target[path] = value;
    return;
  }
  const segments = path.split(".");
  let current: Record<string, unknown> = target;
  for (let i = 0; i < segments.length - 1; i++) {
    const seg = segments.at(i);
    Iif (seg === undefined) {
      continue;
    }
    if (
      current[seg] === undefined ||
      current[seg] === null ||
      typeof current[seg] !== "object"
    ) {
      current[seg] = {};
    }
    current = current[seg] as Record<string, unknown>;
  }
  const lastSeg = segments.at(-1);
  Eif (lastSeg !== undefined) {
    current[lastSeg] = value;
  }
}
 
/**
 * Filter an object (or array of objects) to include only the specified fields.
 *
 * Supports dot-notation for nested field access:
 * ```ts
 * filterFields({ a: 1, b: { c: 2, d: 3 } }, ["a", "b.c"])
 * // → { a: 1, b: { c: 2 } }
 * ```
 *
 * When `data` is an array, each element is filtered independently.
 * Fields that don't exist in the source are silently skipped.
 *
 * @param data - Source data to filter
 * @param fields - List of field paths to include (dot-separated for nesting)
 * @returns Filtered copy of the data — original is never mutated
 */
export function filterFields<T>(data: T, fields: string[]): Partial<T> {
  if (Array.isArray(data)) {
    return data.map((item) =>
      filterFields(item, fields)
    ) as unknown as Partial<T>;
  }
 
  if (data === null || data === undefined || typeof data !== "object") {
    return data as Partial<T>;
  }
 
  const result: Record<string, unknown> = {};
 
  for (const field of fields) {
    const lookup = getNestedValue(data, field);
    if (lookup.found) {
      // Use literal key when the field name exists as a direct property
      // (e.g., "gen_ai.usage.input_tokens" as a flat key)
      const isLiteral =
        typeof data === "object" && data !== null && Object.hasOwn(data, field);
      setNestedValue(result, field, lookup.value, isLiteral);
    }
  }
 
  return result as Partial<T>;
}
 
/**
 * Parse a comma-separated fields string into a trimmed, deduplicated array.
 *
 * Handles whitespace around commas and filters out empty segments:
 * ```ts
 * parseFieldsList("id, title , status")  // → ["id", "title", "status"]
 * parseFieldsList("id,,title")           // → ["id", "title"]
 * ```
 *
 * @param input - Raw `--fields` flag value
 * @returns Parsed field path list (may be empty if input is all whitespace/commas)
 */
export function parseFieldsList(input: string): string[] {
  return [
    ...new Set(
      input
        .split(",")
        .map((f) => f.trim())
        .filter(Boolean)
    ),
  ];
}
 
/**
 * Format data as pretty-printed JSON
 */
export function formatJson<T>(data: T): string {
  return JSON.stringify(data, null, 2);
}
 
/**
 * Output JSON to a write stream.
 *
 * When `fields` is provided, the output is filtered to include only
 * the specified field paths before serialization. This supports the
 * `--fields` flag for reducing token consumption in agent workflows.
 *
 * @param stream - Output writer (typically stdout)
 * @param data - Data to serialize
 * @param fields - Optional field paths to include (dot-notation supported)
 */
export function writeJson<T>(stream: Writer, data: T, fields?: string[]): void {
  const output =
    fields && fields.length > 0 ? filterFields(data, fields) : data;
  stream.write(`${formatJson(output)}\n`);
}
 
/**
 * Output a paginated list as JSON with metadata wrapper.
 *
 * Wraps an array of items in a `{ data, hasMore, nextCursor? }` envelope.
 * When `fields` is provided, filtering is applied to each **array element**
 * inside `data`, not to the wrapper itself. This ensures that
 * `--fields id,title` filters each item, while metadata keys (`hasMore`,
 * `nextCursor`) are always preserved.
 *
 * @param stream - Output writer (typically stdout)
 * @param items - Array of items to wrap in `data`
 * @param options - Pagination metadata and optional field filtering
 *
 * @example
 * ```ts
 * // Without fields: full output
 * writeJsonList(stdout, issues, { hasMore: true, nextCursor: "abc" });
 * // → { "data": [...], "nextCursor": "abc", "hasMore": true }
 *
 * // With fields: each item filtered, wrapper preserved
 * writeJsonList(stdout, issues, { hasMore: true, fields: ["id", "title"] });
 * // → { "data": [{ "id": "1", "title": "Bug" }, ...], "hasMore": true }
 * ```
 */
export function writeJsonList<T>(
  stream: Writer,
  items: T[],
  options: {
    hasMore: boolean;
    nextCursor?: string | null;
    errors?: unknown[];
    fields?: string[];
    /** Arbitrary extra metadata to include in the wrapper (e.g. `{ hint }`) */
    extra?: Record<string, unknown>;
  }
): void {
  const { hasMore, nextCursor, errors, fields, extra } = options;
  const filtered =
    fields && fields.length > 0
      ? items.map((item) => filterFields(item, fields))
      : items;
 
  const output: Record<string, unknown> = { data: filtered, hasMore };
  if (nextCursor !== null && nextCursor !== undefined && nextCursor !== "") {
    output.nextCursor = nextCursor;
  }
  if (errors && errors.length > 0) {
    output.errors = errors;
  }
  if (extra) {
    Object.assign(output, extra);
  }
 
  stream.write(`${formatJson(output)}\n`);
}