import { describe, expect, it } from "vitest";
import {
  MAXIMUM_PORTABLE_REQUEST_JSON_BYTES,
  stringifyBoundedJsonRequest,
} from "./json-request";

describe("portable JSON request transport", () => {
  it("counts the exact UTF-8 JSON representation including control escaping", () => {
    const request = { subject: '\u0000\n"\\' };
    const encoded = JSON.stringify(request);
    const encodedBytes = new TextEncoder().encode(encoded).byteLength;

    expect(encoded).toContain("\\u0000");
    expect(
      stringifyBoundedJsonRequest(request, encodedBytes, "Test bridge"),
    ).toBe(encoded);
    expect(() =>
      stringifyBoundedJsonRequest(request, encodedBytes - 1, "Test bridge"),
    ).toThrow(/encoded JSON limit/u);
  });

  it("covers sixfold escaping for every accepted native string field", () => {
    expect(MAXIMUM_PORTABLE_REQUEST_JSON_BYTES).toBe(103_874_560);
  });

  it("normalizes serialization failures", () => {
    const cyclic: { self?: unknown } = {};
    cyclic.self = cyclic;
    expect(() =>
      stringifyBoundedJsonRequest(cyclic, 1_024, "Test bridge"),
    ).toThrow(/could not serialize/u);
  });
});
