peachScript.test.ts

2.2 KB · raw

1import { describe, expect, test } from "vitest";2import {3  decodePeachScript,4  encodePeachScript,5  isPeachScript,6  normalisePeachScript,7} from "./peachScript";89describe("peachScript", () => {10  test("byte 0 maps to U+E000", () => {11    const out = encodePeachScript(new Uint8Array([0]));12    expect(out.codePointAt(0)).toBe(0xe000);13  });1415  test("byte 255 maps to U+E0FF", () => {16    const out = encodePeachScript(new Uint8Array([255]));17    expect(out.codePointAt(0)).toBe(0xe0ff);18  });1920  test("round-trip identity for all 256 byte values", () => {21    const bytes = new Uint8Array(256);22    for (let i = 0; i < 256; i++) bytes[i] = i;23    const encoded = encodePeachScript(bytes);24    const decoded = decodePeachScript(encoded);25    expect(decoded).toEqual(bytes);26  });2728  test("empty bytes round-trip to empty string and back", () => {29    expect(encodePeachScript(new Uint8Array())).toBe("");30    expect(decodePeachScript("")).toEqual(new Uint8Array());31  });3233  test("decode throws on character outside PUA range", () => {34    expect(() => decodePeachScript("hello")).toThrow("INVALID_PEACHSCRIPT_CHARACTER");35    expect(() => decodePeachScript(String.fromCodePoint(0xe100))).toThrow(36      "INVALID_PEACHSCRIPT_CHARACTER"37    );38    expect(() => decodePeachScript(String.fromCodePoint(0xdfff))).toThrow(39      "INVALID_PEACHSCRIPT_CHARACTER"40    );41  });4243  test("random-payload round-trip preserves bytes", () => {44    const payload = crypto.getRandomValues(new Uint8Array(2048));45    const decoded = decodePeachScript(encodePeachScript(payload));46    expect(decoded).toEqual(payload);47  });4849  test("normalisePeachScript strips whitespace", () => {50    const encoded = encodePeachScript(new Uint8Array([1, 2, 3, 4]));51    const wrapped = encoded.slice(0, 2) + "\n  " + encoded.slice(2);52    expect(normalisePeachScript(wrapped)).toBe(encoded);53  });5455  test("isPeachScript accepts only PUA strings", () => {56    expect(isPeachScript(encodePeachScript(new Uint8Array([1, 2, 3])))).toBe(true);57    expect(isPeachScript("")).toBe(false);58    expect(isPeachScript("hello")).toBe(false);59    const mixed = encodePeachScript(new Uint8Array([1])) + "x";60    expect(isPeachScript(mixed)).toBe(false);61  });62});