File size: 961 Bytes
84aa3bf | 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 | /**
* @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: unknown = 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 {
return null;
}
}
|