import assert from "node:assert/strict";
import { test } from "node:test";
import { canonicalize } from "../src/jcs.ts";
import { decodeGeohash } from "../src/geohash.ts";
// These mirror internal/jcs/jcs_test.go.
test("canonical JSON matches the Go test vectors", () => {
const cases: [unknown, string][] = [
[{ b: 1, a: 2, c: [3, 1] }, `{"a":2,"b":1,"c":[3,1]}`],
[{ z: { y: true, x: null } }, `{"z":{"x":null,"y":true}}`],
[`&`, `"&"`],
["a\tb\nc\u0001", `"a\\tb\\nc\\u0001"`],
["ä€😀
", `"ä€😀
"`],
["\u007f", `"\u007f"`],
[{ "😀": 1, "": 2 }, `{"😀":1,"":2}`], // UTF-16 order: surrogates sort first
[-42, "-42"],
];
for (const [input, want] of cases) assert.equal(canonicalize(input), want);
});
test("floats and non-JSON values are rejected", () => {
for (const bad of [1.5, NaN, Infinity, 2 ** 60, undefined, () => 1, 10n]) {
assert.throws(() => canonicalize(bad));
}
});
test("geohash decoding", () => {
const a = decodeGeohash("ezs42")!; // the classic example: 42.605, -5.603
assert.ok(Math.abs(a.lat - 42.605) < 0.03 && Math.abs(a.lon + 5.603) < 0.03);
const kiel = decodeGeohash("u1xjhx")!; // near Kiel: 54.36 N, 10.05 E
assert.ok(Math.abs(kiel.lat - 54.358) < 0.01 && Math.abs(kiel.lon - 10.047) < 0.01);
assert.ok(kiel.latErr < 0.003 && kiel.lonErr < 0.006, "precision 6 is about a kilometre");
// Hamburg (53.55 N, 9.99 E) lies inside the 3-character region cell u1x.
const region = decodeGeohash("u1x")!;
assert.ok(Math.abs(53.55 - region.lat) < region.latErr && Math.abs(9.99 - region.lon) < region.lonErr);
assert.equal(decodeGeohash("u1xja"), null, "'a' is not in the geohash alphabet");
});