feat(ui): pretty JSON rendering tool outputs (#9767)

Co-authored-by: Bryan Morgan <bryanmorgan@google.com>
This commit is contained in:
Aaron Smith
2026-01-27 12:55:06 +00:00
committed by GitHub
parent 88d3df912f
commit 312a72acb8
5 changed files with 304 additions and 2 deletions
+46
View File
@@ -0,0 +1,46 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import stripAnsi from 'strip-ansi';
export function checkInput(input: string | null | undefined): boolean {
if (input === null || input === undefined) {
return false;
}
const trimmed = input.trim();
if (!trimmed) {
return false;
}
if (!/^(?:\[|\{)/.test(trimmed)) {
return false;
}
if (stripAnsi(trimmed) !== trimmed) return false;
return true;
}
export function tryParseJSON(input: string): object | null {
if (!checkInput(input)) return null;
const trimmed = input.trim();
try {
const parsed = JSON.parse(trimmed);
if (parsed === null || typeof parsed !== 'object') {
return null;
}
if (Array.isArray(parsed) && parsed.length === 0) {
return null;
}
if (!Array.isArray(parsed) && Object.keys(parsed).length === 0) return null;
return parsed;
} catch (_err) {
return null;
}
}