export const parseJson = function parseJson(text: string, origin: string): unknown { try { return JSON.parse(text); } catch (error) { const detail = error instanceof Error ? error.message : String(error); throw new Error(`${origin} is not readable JSON — ${detail}`, { cause: error }); } }; export const tryParse = function tryParse(text: string): { readonly value: unknown } | null { try { const value: unknown = JSON.parse(text); return { value }; } catch { return null; } }; export const fieldOf = function fieldOf(value: object, key: string): unknown { return Object.getOwnPropertyDescriptor(value, key)?.value; }; export const narrow = function narrow( value: unknown, guard: (candidate: unknown) => candidate is T, origin: string, shape: string, ): T { if (!guard(value)) { throw new Error(`${origin} does not satisfy ${shape}`); } return value; }; export const readJson = function readJson( text: string, guard: (candidate: unknown) => candidate is T, origin: string, shape: string, ): T { return narrow(parseJson(text, origin), guard, origin, shape); };