syntaxai/tdd.md · main · src / c14_request_parse.ts
// c14 — adapter: boundary parsers for external-input strings. Under
// SAMA v2 §4.4 ("external input is parsed only in Layer 2") the
// `new URL()` and `JSON.parse()` constructors must not appear in
// Layer 1 or Layer 3 source. This file owns both: handlers in Layer
// 3 (`c21_handlers_*`) call these helpers instead of constructing
// URL / parsing JSON inline.
//
// Each helper returns a discriminated `{ ok: true, value } | { ok:
// false, error }` instead of throwing — callers decide whether the
// failure path returns 400, falls back, or surfaces. This also
// makes the helpers trivially testable (no try/catch around the
// call site needed in tests).
export type ParseResult<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export const parseUrl = (text: string): ParseResult<URL> => {
try {
return { ok: true, value: new URL(text) };
} catch (e) {
return { ok: false, error: (e as Error).message };
}
};
export const parseJson = <T = unknown>(text: string): ParseResult<T> => {
try {
return { ok: true, value: JSON.parse(text) as T };
} catch (e) {
return { ok: false, error: (e as Error).message };
}
};