From c74bee925e1a5e359d268bad8bfba1b80ab2ca3f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:50:47 +0100 Subject: [PATCH] thing-contract-ts: tests for the nil vector, presence on encode and in the factories, deep-frozen results, names Co-Authored-By: Claude Sonnet 5.5 --- packages/thing-contract/test/codecs.test.ts | 6 - packages/thing-contract/test/names.test.ts | 55 ++++++++ .../thing-contract/test/nil-positions.test.ts | 84 +++++++++++++ packages/thing-contract/test/presence.test.ts | 117 ++++++++++++++++++ .../thing-contract/test/result-frozen.test.ts | 69 +++++++++++ 5 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 packages/thing-contract/test/names.test.ts create mode 100644 packages/thing-contract/test/nil-positions.test.ts create mode 100644 packages/thing-contract/test/presence.test.ts create mode 100644 packages/thing-contract/test/result-frozen.test.ts diff --git a/packages/thing-contract/test/codecs.test.ts b/packages/thing-contract/test/codecs.test.ts index d3eb8d2..a349306 100644 --- a/packages/thing-contract/test/codecs.test.ts +++ b/packages/thing-contract/test/codecs.test.ts @@ -23,12 +23,6 @@ test("every codec's type name is a type of the C# package", () => { assert.equal(new Set(entries.map(([, codec]) => codec.typeName)).size, entries.length, "no two codecs share a name"); }); -test("ParamName and Scalar are Rust names the C# package does not have", () => { - for (const [key, codec] of entries) assert.doesNotMatch(codec.typeName ?? "", /\.(ParamName|Scalar)$/u, key); - assert.equal(names.has("GameCult.Thing.Contract.ParamName"), false); - assert.equal(names.has("GameCult.Thing.Contract.Scalar"), false); -}); - test("every union refuses an unknown arm by its own name, and the twenty-nine unions are all of them", () => { const unions: string[] = []; for (const [key, codec] of entries) { diff --git a/packages/thing-contract/test/names.test.ts b/packages/thing-contract/test/names.test.ts new file mode 100644 index 0000000..7f89226 --- /dev/null +++ b/packages/thing-contract/test/names.test.ts @@ -0,0 +1,55 @@ +// The type names the package gives its codecs are the C# package's (tests/thing-contract-parity), and the member names +// follow the owner's: Rust names that C# flattens into arm classes have one codec per arm, a list slot names +// IReadOnlyList, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind. +import assert from "node:assert/strict"; +import { join } from "node:path"; +import test from "node:test"; + +import { codecs } from "@gamecult/thing-contract"; + +import { nonEmptyLines, parityDir } from "./builders.js"; + +const NS = "GameCult.Thing.Contract."; +const names = new Set(nonEmptyLines(join(parityDir, "type-names.txt"))); +const entries = Object.entries(codecs) as [string, { typeName?: string; members?: readonly { typeName: string }[] }][]; + +test("ParamName and Scalar are Rust names the C# package does not have; each arm has its own codec", () => { + assert.equal(names.has(`${NS}ParamName`), false); + assert.equal(names.has(`${NS}Scalar`), false); + for (const [key, codec] of entries) assert.doesNotMatch(codec.typeName ?? "", /\.(ParamName|Scalar)$/u, key); + const arms = { + textSourceParam: "TextSourceParam", + numberSourceParam: "NumberSourceParam", + boolSourceParam: "BoolSourceParam", + collectionSourceParam: "CollectionSourceParam", + commandRefParam: "CommandRefParam", + dimensionPx: "DimensionPx", + dimensionPercent: "DimensionPercent", + dimensionFr: "DimensionFr", + }; + for (const [key, name] of Object.entries(arms)) { + assert.equal((codecs as unknown as Record)[key].typeName, `${NS}${name}`, key); + assert.ok(names.has(`${NS}${name}`), name); + } +}); + +test("a list slot is named IReadOnlyList, never List, and the element is a type of the C# package", () => { + let lists = 0; + for (const [key, codec] of entries) { + for (const member of codec.members ?? []) { + if (!/List$/u.exec(member.typeName); + assert.ok(element !== null, `${key}: ${member.typeName}`); + assert.ok(element[1] === "System.String" || names.has(element[1]), `${key}: ${member.typeName}`); + } + } + assert.equal(lists, 14); +}); + +test("TextInputNode's slot 2 is inputKind, and the name set holds no Kind-only spelling", () => { + const textInputNode = codecs.textInputNode as unknown as { names: readonly string[] }; + assert.equal(textInputNode.names[2], "inputKind"); + assert.ok(names.has(`${NS}InputKind`)); + assert.equal([...names].filter((name) => name.endsWith(".Kind")).length, 0); +}); diff --git a/packages/thing-contract/test/nil-positions.test.ts b/packages/thing-contract/test/nil-positions.test.ts new file mode 100644 index 0000000..caea138 --- /dev/null +++ b/packages/thing-contract/test/nil-positions.test.ts @@ -0,0 +1,84 @@ +// The nil vector, written by the Rust crate and read here (crates/thing-contract/tests/goldens/nil-positions.tsv): for +// every array element of every value golden, the golden with that element replaced by nil, and whether Rust's decode +// door accepted it. A slot is required exactly when its Rust type is not optional, so this package keeps no list of +// required slots: it is held to every row, and an accepted row re-encodes to the spliced bytes. +import assert from "node:assert/strict"; +import { join } from "node:path"; +import test from "node:test"; + +import { + decodeDocumentPayload, + documentPayloadBytes, + documentPayloadFromBytes, + encodeDocumentPayload, +} from "@gamecult/cultcache-ts"; +import { + assetCatalogDocument, + commandInvocationDocument, + commandResultDocument, + compositionDocument, + surfaceDocument, +} from "@gamecult/thing-contract"; + +import { golden, goldensDir, nonEmptyLines } from "./builders.js"; + +type Definition = Parameters[0]; + +const kinds: Record = { + "surface-all-arms": surfaceDocument, + "composition-all-params": compositionDocument, + "invocation-all-inputs": commandInvocationDocument, + "result-pending": commandResultDocument, + "result-completed": commandResultDocument, + "result-completed-open-surface": commandResultDocument, + "result-completed-open-external": commandResultDocument, + "result-denied": commandResultDocument, + "result-denied-no-node": commandResultDocument, + "result-failed": commandResultDocument, + "asset-catalog": assetCatalogDocument, +}; + +interface Row { + golden: string; + path: string; + start: number; + end: number; + accept: boolean; +} + +const rows: Row[] = nonEmptyLines(join(goldensDir, "nil-positions.tsv")).map((line) => { + const cells = line.split("\t"); + assert.equal(cells.length, 5, line); + assert.ok(cells[4] === "ACCEPT" || cells[4] === "REFUSE", line); + return { golden: cells[0], path: cells[1], start: Number(cells[2]), end: Number(cells[3]), accept: cells[4] === "ACCEPT" }; +}); + +test("the vector names every value golden and nothing else", () => { + assert.deepEqual([...new Set(rows.map((row) => row.golden))].sort(), Object.keys(kinds).sort()); + assert.ok(rows.length > 1500); + assert.ok(rows.some((row) => row.accept)); +}); + +for (const [name, definition] of Object.entries(kinds)) { + test(`${name}: every nil position is decided as Rust decided it`, () => { + const bytes = golden(`${name}.bin`); + const own = rows.filter((row) => row.golden === name); + assert.ok(own.length > 0); + const wrong: string[] = []; + for (const row of own) { + const spliced = new Uint8Array([...bytes.subarray(0, row.start), 0xc0, ...bytes.subarray(row.end)]); + let decoded: unknown; + try { + decoded = decodeDocumentPayload(definition, documentPayloadFromBytes(spliced)); + } catch { + if (row.accept) wrong.push(`${row.path}: refused though Rust accepted`); + continue; + } + if (!row.accept) wrong.push(`${row.path}: accepted though Rust refused`); + else if (!Buffer.from(documentPayloadBytes(encodeDocumentPayload(definition, decoded))).equals(spliced)) { + wrong.push(`${row.path}: accepted but re-encodes to other bytes`); + } + } + assert.deepEqual(wrong.slice(0, 20), [], `${name}: ${wrong.length} rows differ from Rust`); + }); +} diff --git a/packages/thing-contract/test/presence.test.ts b/packages/thing-contract/test/presence.test.ts new file mode 100644 index 0000000..758be64 --- /dev/null +++ b/packages/thing-contract/test/presence.test.ts @@ -0,0 +1,117 @@ +// Presence on the encode door and in the factories (the decode door is nil-positions.test.ts). Every builder value with +// one property set to null, or to undefined, is encoded: the encodes the Rust nil vector accepted are the optional +// slots, so the bytes of an accepted encode must be a spliced golden the vector marked ACCEPT, and every ACCEPT row of +// those goldens must be reached. This package keeps no list of required or optional slots. +import assert from "node:assert/strict"; +import { join } from "node:path"; +import test from "node:test"; + +import { documentPayloadBytes, encodeDocumentPayload } from "@gamecult/cultcache-ts"; +import { + CommandResult, + assetCatalogDocument, + commandInvocationDocument, + commandResultDocument, + compositionDocument, + surfaceDocument, +} from "@gamecult/thing-contract"; + +import { assetCatalogValue, fullComposition, fullSurface, golden, goldensDir, invocation, nonEmptyLines } from "./builders.js"; + +type Definition = Parameters[0]; + +const answered = invocation(); + +/** The value with the property at `where` replaced; objects and arrays on the way are copied, bytes are shared. */ +function replaced(value: unknown, where: (string | number)[], replacement: unknown): unknown { + if (where.length === 0) return replacement; + const [head, ...rest] = where; + if (Array.isArray(value)) return value.map((element, index) => (index === head ? replaced(element, rest, replacement) : element)); + const copy: Record = { ...(value as Record) }; + copy[head as string] = replaced(copy[head as string], rest, replacement); + return copy; +} + +/** The path of every property and array element below `value`, parents first. */ +function* paths(value: unknown, here: (string | number)[] = []): Generator<(string | number)[]> { + if (Array.isArray(value)) { + for (let index = 0; index < value.length; index++) { + yield [...here, index]; + yield* paths(value[index], [...here, index]); + } + } else if (typeof value === "object" && value !== null && !(value instanceof Uint8Array)) { + for (const [key, member] of Object.entries(value)) { + yield [...here, key]; + yield* paths(member, [...here, key]); + } + } +} + +const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString("hex"); + +/** The spliced goldens the Rust decode door accepted, as hex. */ +function acceptedSplices(name: string): Set { + const bytes = golden(`${name}.bin`); + const accepted = new Set(); + for (const line of nonEmptyLines(join(goldensDir, "nil-positions.tsv"))) { + const [file, , start, end, answer] = line.split("\t"); + if (file === name && answer === "ACCEPT") { + accepted.add(hex(new Uint8Array([...bytes.subarray(0, Number(start)), 0xc0, ...bytes.subarray(Number(end))]))); + } + } + return accepted; +} + +const cases: [string, Definition, unknown][] = [ + ["surface-all-arms", surfaceDocument, fullSurface()], + ["composition-all-params", compositionDocument, fullComposition()], + ["invocation-all-inputs", commandInvocationDocument, answered], + ["asset-catalog", assetCatalogDocument, assetCatalogValue()], +]; + +for (const [name, definition, value] of cases) { + test(`${name}: a null or undefined property is refused unless Rust made the slot optional`, () => { + const allowed = acceptedSplices(name); + const reached = new Set(); + let refused = 0; + for (const where of paths(value)) { + const outcomes = [null, undefined].map((replacement) => { + try { + return hex(documentPayloadBytes(encodeDocumentPayload(definition, replaced(value, where, replacement)))); + } catch { + return null; + } + }); + assert.equal(outcomes[0], outcomes[1], `${where.join(".")}: null and undefined are decided alike`); + if (outcomes[0] === null) { + refused++; + continue; + } + assert.ok(allowed.has(outcomes[0]), `${where.join(".")}: accepted, and Rust did not accept that nil`); + reached.add(outcomes[0]); + } + assert.ok(refused > 0); + assert.deepEqual([...allowed].filter((splice) => !reached.has(splice)), [], "every optional slot of the golden is reached"); + }); +} + +test("a factory refuses a null message, reason or invocation id at the call", () => { + assert.throws(() => CommandResult.pending(answered, 1, null as unknown as string), /Presence/); + assert.throws(() => CommandResult.pending(answered, 1, undefined as unknown as string), /Presence/); + assert.throws(() => CommandResult.denied(answered, 1, null as unknown as string, null), /Presence/); + assert.throws(() => CommandResult.failed(answered, 1, null as unknown as string), /Presence/); + assert.throws(() => CommandResult.pending({ ...answered, invocationId: null as unknown as string }, 1, "m"), /Presence/); +}); + +test("completed holds the Version and boolean domains at the call, naming the domain and not the value", () => { + assert.throws(() => CommandResult.completed(answered, 1, -5, false, null), (error: Error) => /Version must be at least 0/.test(error.message) && !error.message.includes("-5")); + assert.throws(() => CommandResult.completed(answered, 1, null, null as unknown as boolean, null), /boolean/); + assert.throws(() => CommandResult.completed(answered, 1, null, undefined as unknown as boolean, null), /boolean/); + const completed = CommandResult.completed(answered, 1, 8, true, null); + assert.equal(completed.outcome.kind, "Completed"); +}); + +test("a valid completed result encodes to result-completed's bytes", () => { + const built = CommandResult.completed(answered, 2, 8, true, null); + assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(commandResultDocument, built)), golden("result-completed.bin")); +}); diff --git a/packages/thing-contract/test/result-frozen.test.ts b/packages/thing-contract/test/result-frozen.test.ts new file mode 100644 index 0000000..b0fff8b --- /dev/null +++ b/packages/thing-contract/test/result-frozen.test.ts @@ -0,0 +1,69 @@ +// A CommandResult is frozen deep, on both doors: the outcome, its effect and the effect's resume command cannot be +// rewritten after a factory or the decode door produced them, and a factory copies what it is given. +import assert from "node:assert/strict"; +import test from "node:test"; + +import { decodeDocumentPayload, documentPayloadBytes, documentPayloadFromBytes, encodeDocumentPayload } from "@gamecult/cultcache-ts"; +import { CommandResult, commandResultDocument } from "@gamecult/thing-contract"; +import type { Effect } from "@gamecult/thing-contract"; + +import { golden, invocation } from "./builders.js"; + +const answered = invocation(); +const bytesOf = (result: CommandResult) => documentPayloadBytes(encodeDocumentPayload(commandResultDocument, result)); +const decoded = (file: string) => decodeDocumentPayload(commandResultDocument, documentPayloadFromBytes(golden(file))); + +// The assignments are made through a mutable view: the types are readonly, the run time is what is under test. +const rewrite = (target: object, key: string, value: unknown) => () => { + (target as Record)[key] = value; +}; + +test("a factory result is frozen to its outcome", () => { + const pending = CommandResult.pending(answered, 1, "working"); + const before = bytesOf(pending); + assert.ok(Object.isFrozen(pending.outcome)); + assert.throws(rewrite(pending.outcome, "kind", "Failed"), TypeError); + assert.throws(rewrite(pending.outcome, "message", "other"), TypeError); + assert.throws(rewrite(pending, "outcome", null), TypeError); + assert.deepEqual(bytesOf(pending), before); + + const denied = CommandResult.denied(answered, 2, "no", "go"); + const deniedBytes = bytesOf(denied); + assert.throws(rewrite(denied.outcome, "reason", null), TypeError); + assert.deepEqual(bytesOf(denied), deniedBytes); +}); + +test("a factory result is frozen to its effect and the effect's resume command", () => { + const effect: Effect = { kind: "OpenExternal", url: "https://example.test/", resume: { kind: "Id", id: "resume" } }; + const result = CommandResult.completed(answered, 3, null, false, effect); + const before = bytesOf(result); + const held = result.outcome as { effect: Effect & { resume: object } }; + assert.ok(Object.isFrozen(held.effect)); + assert.ok(Object.isFrozen(held.effect.resume)); + assert.throws(rewrite(held.effect, "url", "https://other.test/"), TypeError); + assert.throws(rewrite(held.effect.resume, "id", "other"), TypeError); + assert.deepEqual(bytesOf(result), before); +}); + +test("a factory copies what it is given: the caller's effect is neither frozen nor aliased", () => { + const effect = { kind: "OpenSurface" as const, key: "a.b" }; + const result = CommandResult.completed(answered, 1, null, false, effect); + const before = bytesOf(result); + effect.key = "changed"; + assert.ok(!Object.isFrozen(effect)); + assert.deepEqual(bytesOf(result), before); +}); + +test("a decoded result is frozen the same way", () => { + for (const file of ["result-pending.bin", "result-completed-open-external.bin", "result-denied.bin", "result-failed.bin"]) { + const result = decoded(file); + const before = bytesOf(result); + assert.ok(Object.isFrozen(result), file); + assert.ok(Object.isFrozen(result.outcome), file); + assert.throws(rewrite(result.outcome, "kind", "Failed"), TypeError, file); + assert.deepEqual(bytesOf(result), before, file); + } + const external = decoded("result-completed-open-external.bin").outcome as { effect: { resume: object } }; + assert.ok(Object.isFrozen(external.effect)); + assert.ok(Object.isFrozen(external.effect.resume)); +});