/**
 * HTML-safe JSON serialization for embedding in `<script>` tags.
 *
 * `JSON.stringify` does not escape `<`, `>`, or `&`, so a payload
 * containing `</script>` (or a stray `<`) can break out of the script
 * tag and become XSS. We escape the four dangerous characters with
 * their `\u` escapes — safe to embed directly in HTML and still valid
 * JSON when parsed.
 *
 * Use this anywhere a JSON payload is embedded as text inside a
 * `<script>` element, e.g. JSON-LD (`application/ld+json`),
 * hydration data (`application/json`), or inline initial state.
 */
export function serializeJsonForScript(value: unknown): string {
  return JSON.stringify(value)
    .replace(/</g, "\\u003c")
    .replace(/>/g, "\\u003e")
    .replace(/&/g, "\\u0026")
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029");
}
