diff --git a/packages/cultcache-ts/src/codec.ts b/packages/cultcache-ts/src/codec.ts index 7381c348..508fb9d6 100644 --- a/packages/cultcache-ts/src/codec.ts +++ b/packages/cultcache-ts/src/codec.ts @@ -1,48 +1,117 @@ -import { decode, encode } from "@msgpack/msgpack"; - import type { CultCacheDocumentFormatter, CultCacheSchemaCatalogMember } from "./types"; +import { readWire, WireFloat, writeWire } from "./wire"; -// A codec turns a value into the MessagePack-ready shape the reference runtimes write and back. Slot records are -// positional arrays with nil gaps; a union value is { kind: armName, ...armFields }, written [armKey, [armSlots...]]. -// Refusals name the union or the slot and the key or code, and never echo a decoded value. +// A codec turns a value into the shape the reference runtimes write and back. Slot records are positional arrays with +// nil gaps; a union value is { kind: armName, ...armFields }, written [armKey, [armSlots...]]. Refusals name the union +// or the slot and the key or code, and never echo a decoded value. `typeName` is the reference's name for the type +// (CultSchemaTypeNames.FromType): a store's schema catalog carries it per slot, and the reference refuses a store whose +// slot names another type. The leaves know theirs; a union or a record the codec cannot name from C# is given it. export interface Codec { encode(value: TValue): unknown; decode(raw: unknown): TValue; + readonly typeName?: string; + // True for a type the reference makes Nullable when the slot may be nil (int, long, float, double, bool). + readonly valueType?: boolean; } export interface SlotsCodec extends Codec { + // Throws when a slot's codec has no typeName: the catalog cannot be derived without the reference's names. readonly members: readonly CultCacheSchemaCatalogMember[]; readonly names: readonly string[]; } +function kindOf(raw: unknown): string { + if (raw === null || raw === undefined) return "nil"; + if (Array.isArray(raw)) return "array"; + if (raw instanceof WireFloat) return "float"; + if (typeof raw === "bigint") return "integer"; + return typeof raw; +} + +function refuse(what: string, found: string): never { + throw new Error(`expected ${what}, found ${found}`); +} + function expect(raw: unknown, what: string, ok: boolean): asserts ok { - if (!ok) { - throw new Error(`expected ${what}, found ${raw === null ? "nil" : Array.isArray(raw) ? "array" : typeof raw}`); - } + if (!ok) refuse(what, kindOf(raw)); } export const string: Codec = { + typeName: "System.String", encode: (value) => (expect(value, "a string", typeof value === "string"), value), decode: (raw) => (expect(raw, "a string", typeof raw === "string"), raw as string), }; -export const number: Codec = { - encode: (value) => (expect(value, "a number", Number.isFinite(value)), value), - decode: (raw) => (expect(raw, "a number", Number.isFinite(raw)), raw as number), -}; - export const boolean: Codec = { + typeName: "System.Boolean", + valueType: true, encode: (value) => (expect(value, "a boolean", typeof value === "boolean"), value), decode: (raw) => (expect(raw, "a boolean", typeof raw === "boolean"), raw as boolean), }; export const bytes: Codec = { + typeName: "System.Byte[]", encode: (value) => (expect(value, "bytes", value instanceof Uint8Array), value), decode: (raw) => (expect(raw, "bytes", raw instanceof Uint8Array), raw as Uint8Array), }; -export function list(item: Codec): Codec { +// A C# integer slot: written as the smallest MessagePack integer and read from any integer encoding in range. A float is +// refused even when it holds a whole number, as the reference refuses it. +function integerCodec(typeName: string, what: string, low: bigint, high: bigint): Codec { + const inRange = (value: number | bigint) => value >= low && value <= high; return { + typeName, + valueType: true, + encode(value) { + if (typeof value === "bigint") { + if (!inRange(value)) refuse(what, "an integer out of range"); + return value; + } + if (typeof value !== "number") refuse(what, kindOf(value)); + if (!Number.isSafeInteger(value)) { + refuse(what, Number.isInteger(value) ? "a number beyond 2^53, which needs a bigint" : "a non-integer number"); + } + if (!inRange(value)) refuse(what, "an integer out of range"); + return value; + }, + decode(raw) { + if (typeof raw !== "number" && typeof raw !== "bigint") refuse(what, kindOf(raw)); + if (!inRange(raw)) refuse(what, "an integer out of range"); + return raw; + }, + }; +} + +// C# int. Always a number. +export const int32 = integerCodec("System.Int32", "an int32", -(2n ** 31n), 2n ** 31n - 1n) as Codec; +// C# long. A number when the value is a safe integer, a bigint beyond 2^53 (so 64-bit values never lose precision). +export const int64 = integerCodec("System.Int64", "an int64", -(2n ** 63n), 2n ** 63n - 1n); + +function floatCodec(typeName: string, wide: boolean): Codec { + const what = wide ? "a float64" : "a float32"; + return { + typeName, + valueType: true, + encode(value) { + expect(value, what, typeof value === "number"); + return new WireFloat(value, wide); + }, + decode(raw) { + if (raw instanceof WireFloat) return wide ? raw.value : Math.fround(raw.value); + if (typeof raw === "number" || typeof raw === "bigint") return wide ? Number(raw) : Math.fround(Number(raw)); + return refuse(what, kindOf(raw)); + }, + }; +} + +// C# float, written as MessagePack float 32. +export const float32 = floatCodec("System.Single", false); +// C# double, written as MessagePack float 64. +export const float64 = floatCodec("System.Double", true); + +function sequence(item: Codec, nameOf: (itemName: string) => string): Codec { + return { + get typeName() { return item.typeName === undefined ? undefined : nameOf(item.typeName); }, encode(value) { expect(value, "an array", Array.isArray(value)); return value.map((element, index) => at(`element ${index}`, () => item.encode(element))); @@ -54,8 +123,22 @@ export function list(item: Codec): Codec { }; } +// C# List. +export function list(item: Codec): Codec { + return sequence(item, (name) => `System.Collections.Generic.List<${name}>`); +} + +// C# T[]. The same wire as list. +export function array(item: Codec): Codec { + return sequence(item, (name) => `${name}[]`); +} + +// A slot that may be nil. For a value type the reference's name is Nullable; for a reference type it is unchanged. export function nullable(inner: Codec): Codec { return { + get typeName() { + return inner.typeName !== undefined && inner.valueType ? `System.Nullable<${inner.typeName}>` : inner.typeName; + }, encode: (value) => (value === null || value === undefined ? null : inner.encode(value)), decode: (raw) => (raw === null ? null : inner.decode(raw)), }; @@ -65,6 +148,8 @@ export function lazy(get: () => Codec): Codec { let resolved: Codec | undefined; const codec = () => (resolved ??= get()); return { + get typeName() { return codec().typeName; }, + get valueType() { return codec().valueType; }, encode: (value) => codec().encode(value), decode: (raw) => codec().decode(raw), }; @@ -85,13 +170,19 @@ type SlotSpec = type SlotsSpec = Readonly }[keyof TValue & string]>>; -function slotKeys(spec: Readonly>, owner: string): number[] { +const INT32_MAX = 2 ** 31 - 1; + +// The declared keys, ascending. An arm key is an Int32 in the reference, so a union refuses a wider key at definition. +function slotKeys(spec: Readonly>, owner: string, max = Number.MAX_SAFE_INTEGER): number[] { // Object.keys lists integer keys in ascending order, so the declared keys come back sorted. return Object.keys(spec).map((text) => { const key = Number(text); if (!Number.isInteger(key) || key < 0 || String(key) !== text) { throw new Error(`${owner} declares the key "${text}", which is not a non-negative integer.`); } + if (key > max) { + throw new Error(`${owner} declares the key ${key}, which is outside Int32.`); + } return key; }); } @@ -107,7 +198,7 @@ function pascalCase(name: string): string { // A positional record: slot `key` holds field `name`. Gaps are written nil and skipped on read, extra trailing slots // are skipped, and a slot missing from the payload takes its declared default or is refused. A nil in a slot that // declares a default also takes the default (cultcache-py's rule). -export function slots(spec: SlotsSpec): SlotsCodec { +export function slots(spec: SlotsSpec, typeName?: string): SlotsCodec { const keys = slotKeys(spec, "A slot record"); if (keys.length === 0) { throw new Error("A slot record declares no slots."); @@ -129,7 +220,15 @@ export function slots(spec: SlotsSpec): SlotsCode return { names: fields.map((field) => field.name), - members: fields.map((field) => ({ slot: field.key, memberName: pascalCase(field.name), typeName: "System.Object" })), + typeName, + get members() { + return fields.map((field) => { + if (field.codec.typeName === undefined) { + throw new Error(`${field.name} (slot ${field.key}) has no C# type name for the schema catalog; give its union or record a typeName, or give the document its members.`); + } + return { slot: field.key, memberName: pascalCase(field.name), typeName: field.codec.typeName }; + }); + }, encode(value) { expect(value, "a record", typeof value === "object" && value !== null); const out: unknown[] = new Array(length).fill(null); @@ -170,8 +269,9 @@ type ArmSpec = readonly [armName: TKind, body: SlotsCodec< export function union( name: string, arms: Readonly>>, + typeName?: string, ): Codec { - const keys = slotKeys(arms, `Union ${name}`); + const keys = slotKeys(arms, `Union ${name}`, INT32_MAX); if (keys.length === 0) { throw new Error(`Union ${name} declares no arms.`); } @@ -191,6 +291,7 @@ export function union( const declared = keys.join(", "); return { + typeName, encode(value) { if (value === null || value === undefined) { return null; @@ -210,10 +311,13 @@ export function union( throw new Error(`Union ${name}: expected [key, slots] and found something else.`); } const key: unknown = raw[0]; - if (typeof key !== "number" || !Number.isInteger(key)) { + if (typeof key !== "number" && typeof key !== "bigint") { throw new Error(`Union ${name}: the arm key is not an integer (declared keys: ${declared}).`); } - const arm = byKey.get(key); + if (key < -(2 ** 31) || key > INT32_MAX) { + throw new Error(`Union ${name}: the arm key is outside Int32 (declared keys: ${declared}).`); + } + const arm = byKey.get(Number(key)); if (arm === undefined) { throw new Error(`Union ${name}: unknown arm key ${key} (declared keys: ${declared}).`); } @@ -226,7 +330,7 @@ export function union( // The formatter a document gets from a slot codec: the codec's value as one MessagePack payload. export function codecFormatter(codec: SlotsCodec): CultCacheDocumentFormatter { return { - encode: (value) => encode(codec.encode(value)), - decode: (payload) => codec.decode(decode(payload)), + encode: (value) => writeWire(codec.encode(value)), + decode: (payload) => codec.decode(readWire(payload)), }; } diff --git a/packages/cultcache-ts/src/cult-cache.ts b/packages/cultcache-ts/src/cult-cache.ts index a1c0a3d4..94247d49 100644 --- a/packages/cultcache-ts/src/cult-cache.ts +++ b/packages/cultcache-ts/src/cult-cache.ts @@ -1,6 +1,4 @@ -import { decode, encode } from "@msgpack/msgpack"; - -import { codecFormatter } from "./codec"; +import { resolveDocumentFormatter, resolveDocumentMembers } from "./document"; import type { AnyCultCacheDocumentDefinition, CacheBackingStore, @@ -677,10 +675,7 @@ export class CultCache { } #createFormatter(definition: AnyCultCacheDocumentDefinition): CultCacheDocumentFormatter { - const userFormatter = definition.formatter ?? (definition.codec ? codecFormatter(definition.codec) : { - encode: (value: unknown) => encode(value), - decode: (payload: Uint8Array) => decode(payload), - }); + const userFormatter = resolveDocumentFormatter(definition); return { encode: (value: unknown) => { @@ -700,7 +695,7 @@ export class CultCache { const canonicalSchemaJson = definition.canonicalSchemaJson ?? JSON.stringify({ schemaName, schemaVersion, - members: [...(definition.members ?? [])] + members: [...resolveDocumentMembers(definition)] .sort((left, right) => left.slot - right.slot) .map((member) => ({ slot: member.slot, @@ -725,7 +720,7 @@ export class CultCache { contentHash: definition.contentHash ?? schemaId, canonicalSchemaJson, compatibleSchemaIds, - members: [...(definition.members ?? [])] + members: [...resolveDocumentMembers(definition)] .sort((left, right) => left.slot - right.slot) .map((member) => ({ slot: member.slot, diff --git a/packages/cultcache-ts/src/document.ts b/packages/cultcache-ts/src/document.ts index 70cdd7b2..276e7caa 100644 --- a/packages/cultcache-ts/src/document.ts +++ b/packages/cultcache-ts/src/document.ts @@ -1,5 +1,10 @@ +import { decode, encode } from "@msgpack/msgpack"; + +import { codecFormatter } from "./codec"; import type { AnyCultCacheDocumentDefinition, + CultCacheDocumentFormatter, + CultCacheSchemaCatalogMember, CultCacheDocumentDefinition, CultCacheDocumentRegistry, CultCacheSchema, @@ -66,24 +71,38 @@ export function defineDocumentType( } } - if (definition.codec) { - const codec = definition.codec; - if (definition.formatter) { - throw new Error(`CultCache document type "${definition.type}" declares both a codec and a formatter.`); - } - const indexAlias = (slotName: string) => - !Array.isArray(definition.indexes) && definition.indexes - ? Object.entries(definition.indexes).find(([, accessor]) => accessor === slotName)?.[0] ?? null - : null; - const members = definition.members ?? codec.members.map((member, index) => ({ - ...member, - isName: definition.name === codec.names[index], - indexAlias: indexAlias(codec.names[index]), - })); - return Object.freeze({ ...definition, members }); - } + resolveDocumentFormatter(definition); + return Object.freeze(definition.codec ? { ...definition, members: resolveDocumentMembers(definition) } : { ...definition }); +} - return Object.freeze({ ...definition }); +// The one place that decides how a document is encoded: its own formatter, or its codec's, or a plain map. A codec and a +// formatter are two answers to one question, so a definition that carries both is refused wherever it enters (the +// builder resolves through here as well). +export function resolveDocumentFormatter(definition: AnyCultCacheDocumentDefinition): CultCacheDocumentFormatter { + if (definition.codec && definition.formatter) { + throw new Error(`CultCache document type "${definition.type}" declares both a codec and a formatter.`); + } + return definition.formatter ?? (definition.codec ? codecFormatter(definition.codec) : { + encode: (value: unknown) => encode(value), + decode: (payload: Uint8Array) => decode(payload), + }); +} + +// The schema members of a document: the ones it declares, else those its codec derives, else none. +export function resolveDocumentMembers(definition: AnyCultCacheDocumentDefinition): readonly CultCacheSchemaCatalogMember[] { + if (definition.members || !definition.codec) { + return definition.members ?? []; + } + const codec = definition.codec; + const indexAlias = (slotName: string) => + !Array.isArray(definition.indexes) && definition.indexes + ? Object.entries(definition.indexes).find(([, accessor]) => accessor === slotName)?.[0] ?? null + : null; + return codec.members.map((member, index) => ({ + ...member, + isName: definition.name === codec.names[index], + indexAlias: indexAlias(codec.names[index]), + })); } export function defineDocumentRegistry< diff --git a/packages/cultcache-ts/src/wire.ts b/packages/cultcache-ts/src/wire.ts new file mode 100644 index 00000000..d57ff049 --- /dev/null +++ b/packages/cultcache-ts/src/wire.ts @@ -0,0 +1,130 @@ +// The slice of MessagePack a codec value uses: nil, booleans, integers, floats, strings, binaries and arrays. A codec +// must tell an integer from a float and keep 64-bit integers whole, which a general decoder that hands back JS numbers +// cannot; so the codec path owns its reader and writer. An integer decodes to a number, or to a bigint when it is +// outside the safe range. A float decodes to a WireFloat, whatever its value. + +export class WireFloat { + constructor(readonly value: number, readonly wide: boolean) {} +} + +const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER); +const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER); +const utf8 = new TextEncoder(); +const utf8Decoder = new TextDecoder(); + +export function writeWire(tree: unknown): Uint8Array { + const parts: number[] = []; + put(tree, parts); + return Uint8Array.from(parts); +} + +function be(parts: number[], bytes: number, value: bigint): void { + for (let shift = BigInt((bytes - 1) * 8); shift >= 0n; shift -= 8n) { + parts.push(Number((value >> shift) & 0xffn)); + } +} + +function putInt(value: bigint, parts: number[]): void { + if (value >= 0n) { + if (value < 128n) parts.push(Number(value)); + else if (value < 0x100n) { parts.push(0xcc); be(parts, 1, value); } + else if (value < 0x10000n) { parts.push(0xcd); be(parts, 2, value); } + else if (value < 0x100000000n) { parts.push(0xce); be(parts, 4, value); } + else if (value < 0x10000000000000000n) { parts.push(0xcf); be(parts, 8, value); } + else throw new Error("cannot write an integer wider than 64 bits."); + } else if (value >= -32n) parts.push(0x100 + Number(value)); + else if (value >= -0x80n) { parts.push(0xd0); be(parts, 1, value & 0xffn); } + else if (value >= -0x8000n) { parts.push(0xd1); be(parts, 2, value & 0xffffn); } + else if (value >= -0x80000000n) { parts.push(0xd2); be(parts, 4, value & 0xffffffffn); } + else if (value >= -0x8000000000000000n) { parts.push(0xd3); be(parts, 8, value & 0xffffffffffffffffn); } + else throw new Error("cannot write an integer wider than 64 bits."); +} + +function putLength(length: number, parts: number[], fix: number, fixMax: number, codes: readonly [number, number, number]): void { + if (length <= fixMax) parts.push(fix | length); + else if (codes[0] !== 0 && length < 0x100) { parts.push(codes[0]); be(parts, 1, BigInt(length)); } + else if (length < 0x10000) { parts.push(codes[1]); be(parts, 2, BigInt(length)); } + else { parts.push(codes[2]); be(parts, 4, BigInt(length)); } +} + +function put(node: unknown, parts: number[]): void { + if (node === null || node === undefined) parts.push(0xc0); + else if (typeof node === "boolean") parts.push(node ? 0xc3 : 0xc2); + else if (typeof node === "bigint") putInt(node, parts); + else if (typeof node === "number") { + if (!Number.isSafeInteger(node)) throw new Error("cannot write a number that is not a safe integer; floats are WireFloat."); + putInt(BigInt(node), parts); + } else if (node instanceof WireFloat) { + const view = new DataView(new ArrayBuffer(8)); + if (node.wide) { view.setFloat64(0, node.value); parts.push(0xcb); } else { view.setFloat32(0, node.value); parts.push(0xca); } + for (let index = 0; index < (node.wide ? 8 : 4); index += 1) parts.push(view.getUint8(index)); + } else if (typeof node === "string") { + const text = utf8.encode(node); + putLength(text.length, parts, 0xa0, 31, [0xd9, 0xda, 0xdb]); + for (const byte of text) parts.push(byte); + } else if (node instanceof Uint8Array) { + putLength(node.length, parts, 0, -1, [0xc4, 0xc5, 0xc6]); + for (const byte of node) parts.push(byte); + } else if (Array.isArray(node)) { + putLength(node.length, parts, 0x90, 15, [0, 0xdc, 0xdd]); + for (const element of node) put(element, parts); + } else { + throw new Error("cannot write this kind of value."); + } +} + +export function readWire(payload: Uint8Array): unknown { + const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + let offset = 0; + + const take = (count: number): number => { + if (count < 0 || offset + count > payload.length) throw new Error("the MessagePack payload is truncated."); + offset += count; + return offset - count; + }; + const integer = (value: bigint): number | bigint => (value >= SAFE_MIN && value <= SAFE_MAX ? Number(value) : value); + const string = (length: number): string => utf8Decoder.decode(payload.subarray(take(length), offset)); + const binary = (length: number): Uint8Array => payload.slice(take(length), offset); + const array = (length: number): unknown[] => { + if (length > payload.length - offset) throw new Error("the MessagePack payload is truncated."); + const out: unknown[] = []; + for (let index = 0; index < length; index += 1) out.push(next()); + return out; + }; + + function next(): unknown { + const head = payload[take(1)]; + if (head < 0x80) return head; + if (head >= 0xe0) return head - 0x100; + if (head >= 0xa0 && head <= 0xbf) return string(head & 0x1f); + if (head >= 0x90 && head <= 0x9f) return array(head & 0x0f); + switch (head) { + case 0xc0: return null; + case 0xc2: return false; + case 0xc3: return true; + case 0xc4: return binary(view.getUint8(take(1))); + case 0xc5: return binary(view.getUint16(take(2))); + case 0xc6: return binary(view.getUint32(take(4))); + case 0xca: return new WireFloat(view.getFloat32(take(4)), false); + case 0xcb: return new WireFloat(view.getFloat64(take(8)), true); + case 0xcc: return view.getUint8(take(1)); + case 0xcd: return view.getUint16(take(2)); + case 0xce: return view.getUint32(take(4)); + case 0xcf: return integer(view.getBigUint64(take(8))); + case 0xd0: return view.getInt8(take(1)); + case 0xd1: return view.getInt16(take(2)); + case 0xd2: return view.getInt32(take(4)); + case 0xd3: return integer(view.getBigInt64(take(8))); + case 0xd9: return string(view.getUint8(take(1))); + case 0xda: return string(view.getUint16(take(2))); + case 0xdb: return string(view.getUint32(take(4))); + case 0xdc: return array(view.getUint16(take(2))); + case 0xdd: return array(view.getUint32(take(4))); + default: throw new Error("the MessagePack payload holds a type a codec does not read (map, extension or reserved)."); + } + } + + const tree = next(); + if (offset !== payload.length) throw new Error("the MessagePack payload has bytes after its value."); + return tree; +} diff --git a/packages/cultcache-ts/test/union-parity.test.ts b/packages/cultcache-ts/test/union-parity.test.ts index 8aca877d..52dfd76a 100644 --- a/packages/cultcache-ts/test/union-parity.test.ts +++ b/packages/cultcache-ts/test/union-parity.test.ts @@ -11,11 +11,15 @@ import { z } from "zod"; import { codecs } from "../src"; import type { Codec } from "../src/codec"; import { CultCache } from "../src/cult-cache"; +import { readWire, WireFloat, writeWire } from "../src/wire"; import { defineDocumentType } from "../src/document"; import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store"; import type { CacheBackingStore, CultCacheEnvelope } from "../src/types"; -const { boolean, bytes, lazy, list, nullable, number, slots, string, union, unit } = codecs; +const { array, boolean, bytes, float32, float64, int32, int64, lazy, list, nullable, slots, string, union, unit } = codecs; + +// The names the C# reference gives the fixture's types (CultSchemaTypeNames.FromType), as union-surface.cc carries them. +const CS = "GameCult.Caching.Tests.UnionParityVectorTests+"; // The golden is tests/vectors/union-parity, written by the C# reference. Everything below that is bytes or an expected // outcome is read from those committed files; only the value the payload must decode to is spelled here. @@ -50,7 +54,7 @@ interface Surface { missing: Node | null; } -const composition = slots({ 0: ["name", string], 1: ["body", lazy(() => node)] }); +const composition = slots({ 0: ["name", string], 1: ["body", lazy(() => node)] }, `${CS}Composition`); const node: Codec = union("Node", { 0: ["Box", slots<{ id: string; children: (Node | null)[] }>({ 0: ["id", string], 1: ["children", list(lazy(() => node))] })], 1: ["Text", slots<{ id: string; content: string }>({ 0: ["id", string], 1: ["content", string] })], @@ -58,29 +62,29 @@ const node: Codec = union("Node", { 0: ["id", string], 1: ["composition", composition], 2: ["slots", list(lazy(() => node))], })], 5: ["Image", slots<{ id: string; uri: string; alt: string }>({ 0: ["id", string], 1: ["uri", string], 3: ["alt", string] })], -}); +}, `${CS}Node`); const outcome = union("Outcome", { 0: ["Pending", slots<{ message: string }>({ 0: ["message", string] })], - 1: ["Completed", slots<{ sourceVersion: number }>({ 0: ["sourceVersion", number] })], + 1: ["Completed", slots<{ sourceVersion: number }>({ 0: ["sourceVersion", int32] })], 2: ["Denied", unit], -}); -const toolArm = slots<{ name: string; uses: number }>({ 0: ["name", string], 1: ["uses", number] }); -const partArm = slots<{ name: string; count: number }>({ 0: ["name", string], 1: ["count", number] }); +}, `${CS}Outcome`); +const toolArm = slots<{ name: string; uses: number }>({ 0: ["name", string], 1: ["uses", int32] }); +const partArm = slots<{ name: string; count: number }>({ 0: ["name", string], 1: ["count", int32] }); const item = union("Item", { 0: ["Gem", slots<{ name: string }>({ 0: ["name", string] })], 1: ["Tool", toolArm], 2: ["Part", partArm], -}); -const craftedItem = union("CraftedItem", { 0: ["Tool", toolArm], 1: ["Part", partArm] }); +}, `${CS}Item`); +const craftedItem = union("CraftedItem", { 0: ["Tool", toolArm], 1: ["Part", partArm] }, `${CS}CraftedItem`); const surfaceCodec = slots({ 0: ["id", string], - 1: ["version", number], + 1: ["version", int32], 2: ["root", node], 3: ["outcomes", list(outcome)], 4: ["part", item], 5: ["crafted", craftedItem], 6: ["missing", node, null], -}); +}, `${CS}UnionSurface`); const nodeSchema: z.ZodType = z.lazy(() => z.union([ @@ -175,10 +179,10 @@ async function outcomeEntries() { test("the union surface vector decodes to the constructed value and re-encodes byte-identical", async () => { const committed = await read("union-surface.msgpack"); - const decoded = surfaceCodec.decode(decode(committed)); + const decoded = surfaceCodec.decode(readWire(committed)); assert.deepEqual(decoded, golden); - assert.equal(hex(encode(surfaceCodec.encode(decoded))), hex(committed)); - assert.equal(hex(encode(surfaceCodec.encode(golden))), hex(committed)); + assert.equal(hex(writeWire(surfaceCodec.encode(decoded))), hex(committed)); + assert.equal(hex(writeWire(surfaceCodec.encode(golden))), hex(committed)); }); test("a unit arm is written [key, []] and its payload must be an array", () => { @@ -219,7 +223,7 @@ test("every outcome vector is listed and holds: refusals name the union and key, refused += 1; if (Buffer.from(payload).includes(CANARY)) carrying.push(file); assert.throws( - () => surfaceCodec.decode(decode(payload)), + () => surfaceCodec.decode(readWire(payload)), (error: Error) => { assert.ok(!error.message.includes(CANARY), `${file}: the refusal echoed the payload`); if (detail === "arity") { @@ -234,7 +238,7 @@ test("every outcome vector is listed and holds: refusals name the union and key, } else { readOnly += 1; assert.equal(expected, "read-only"); - assert.deepEqual(surfaceCodec.decode(decode(payload)), golden, `${file}: the extra slot is read past`); + assert.deepEqual(surfaceCodec.decode(readWire(payload)), golden, `${file}: the extra slot is read past`); } } assert.deepEqual([refused, readOnly], [5, 4]); @@ -243,7 +247,7 @@ test("every outcome vector is listed and holds: refusals name the union and key, test("a refusal lists the declared keys, so a key only the outer union declares is unknown to the inner", async () => { const entry = (await outcomeEntries()).find((candidate) => candidate.file === "inner-union-outer-key.msgpack")!; - const payload = decode(await read(entry.file)) as unknown[]; + const payload = readWire(await read(entry.file)) as unknown[]; assert.throws( () => surfaceCodec.decode(payload), /Union CraftedItem: unknown arm key 2 \(declared keys: 0, 1\)\./u, @@ -275,7 +279,7 @@ test("a union encodes by kind and refuses a kind it does not declare without ech }); test("slots: a gap writes nil, a missing slot reads its default, one without a default is refused naming the slot", () => { - const record = slots<{ a: string; c: string; d: number }>({ 0: ["a", string], 2: ["c", string], 4: ["d", number, 9] }); + const record = slots<{ a: string; c: string; d: number }>({ 0: ["a", string], 2: ["c", string], 4: ["d", int32, 9] }); assert.deepEqual(record.encode({ a: "x", c: "y", d: 1 }), ["x", null, "y", null, 1]); assert.deepEqual(record.decode(["x", null, "y"]), { a: "x", c: "y", d: 9 }); assert.deepEqual(record.decode(["x", 5, "y", null, null]), { a: "x", c: "y", d: 9 }); @@ -301,9 +305,15 @@ test("a slot refusal names the field and slot and never the value", () => { test("leaf codecs refuse the wrong shape on both sides, saying what was expected and what kind was found", () => { const table: [string, Codec, string, unknown, string][] = [ ["string", string, "a string", 5, "number"], - ["number", number, "a number", "5", "string"], - ["number", number, "a number", Number.POSITIVE_INFINITY, "number"], - ["number", number, "a number", Number.NaN, "number"], + ["int32", int32, "an int32", "5", "string"], + ["int32", int32, "an int32", Number.POSITIVE_INFINITY, "a non-integer number"], + ["int32", int32, "an int32", Number.NaN, "a non-integer number"], + ["int32", int32, "an int32", 1.5, "a non-integer number"], + ["int32", int32, "an int32", 2 ** 31, "an integer out of range"], + ["int64", int64, "an int64", 2 ** 53, "a number beyond 2^53, which needs a bigint"], + ["int64", int64, "an int64", 2n ** 63n, "an integer out of range"], + ["float64", float64, "a float64", "1.5", "string"], + ["float32", float32, "a float32", null, "nil"], ["boolean", boolean, "a boolean", "true", "string"], ["bytes", bytes, "bytes", [1, 2], "array"], ["string", string, "a string", null, "nil"], @@ -311,25 +321,27 @@ test("leaf codecs refuse the wrong shape on both sides, saying what was expected ]; for (const [label, codec, what, bad, found] of table) { for (const side of ["encode", "decode"] as const) { + // Decode sees the wire's shapes: a JS float or a number beyond 2^53 never arrives from a payload. + if (side === "decode" && (typeof bad === "number" && (!Number.isInteger(bad) || Math.abs(bad) >= 2 ** 53))) continue; assert.throws(() => codec[side](bad), new RegExp(`^Error: expected ${what}, found ${found}$`, "u"), `${label} ${side}`); } } - for (const [codec, good] of [[string, "s"], [number, 1.5], [boolean, false], [bytes, new Uint8Array([7])], [list(number), [1, 2]]] as [Codec, unknown][]) { + for (const [codec, good] of [[string, "s"], [int32, 1], [int64, 5], [float64, 1.5], [float32, 1.5], [boolean, false], [bytes, new Uint8Array([7])], [list(int32), [1, 2]]] as [Codec, unknown][]) { assert.deepEqual(codec.decode(codec.encode(good)), good); } }); test("a list element refusal names the element, and nullable writes nil for null and undefined", () => { - const numbers = list(number); - assert.throws(() => numbers.encode([1, "x" as unknown as number]), /^Error: element 1: expected a number, found string$/u); - assert.throws(() => numbers.decode([1, 2, null]), /^Error: element 2: expected a number, found nil$/u); - const maybe = nullable(number); + const numbers = list(int32); + assert.throws(() => numbers.encode([1, "x" as unknown as number]), /^Error: element 1: expected an int32, found string$/u); + assert.throws(() => numbers.decode([1, 2, null]), /^Error: element 2: expected an int32, found nil$/u); + const maybe = nullable(int32); assert.equal(maybe.encode(null), null); assert.equal(maybe.encode(undefined as unknown as null), null); assert.equal(maybe.encode(0), 0); assert.equal(maybe.decode(null), null); assert.equal(maybe.decode(0), 0); - assert.throws(() => maybe.decode("x"), /expected a number/u); + assert.throws(() => maybe.decode("x"), /expected an int32/u); }); test("a record refuses what is not a record and names the field and slot of a bad value", () => { @@ -384,8 +396,8 @@ test("a codec supplies the document's catalog members unless it is given its own indexes: { byB: "the_b" }, }); assert.deepEqual(document.members, [ - { slot: 0, memberName: "A", typeName: "System.Object", isName: true, indexAlias: null }, - { slot: 3, memberName: "TheB", typeName: "System.Object", isName: false, indexAlias: "byB" }, + { slot: 0, memberName: "A", typeName: "System.String", isName: true, indexAlias: null }, + { slot: 3, memberName: "TheB", typeName: "System.String", isName: false, indexAlias: "byB" }, ]); const given = [{ slot: 9, memberName: "Mine", typeName: "System.String" }]; const own = defineDocumentType({ type: "t", schema: z.object({ a: z.string() }), codec: slots<{ a: string }>({ 0: ["a", string] }), members: given });