diff --git a/packages/thing-contract/src/codecs.ts b/packages/thing-contract/src/codecs.ts index 40c428a..1c1be30 100644 --- a/packages/thing-contract/src/codecs.ts +++ b/packages/thing-contract/src/codecs.ts @@ -1,132 +1,154 @@ -// One codec per type of crates/thing-contract, built from cultcache-ts's slots, union, list, nullable and lazy at the -// crate's slot and arm keys. Nothing here encodes or decodes by hand, declares a slot default, or checks an arm: the -// library's codecs refuse an unknown arm or a missing slot, and domain.ts holds the five domains. +// One codec per type of crates/thing-contract, built from cultcache-ts's slots, union, nullable and lazy at the crate's +// slot and arm keys. Nothing here encodes or decodes by hand, declares a slot default, or checks an arm: the library's +// codecs refuse an unknown arm or a missing slot, domain.ts holds the five domains and the presence of a slot. // -// Every slots and union codec is named GameCult.Thing.Contract., the reference's full type name, because a -// store's schema catalog carries the type name of each document slot and the reference compares them. +// Presence follows the Rust types: a slot is nullable exactly where the Rust member is an Option, and every other string, +// bytes, record, list and union slot refuses nil on decode and null or undefined on encode (`present`). The vector that +// proves it is crates/thing-contract/tests/goldens/nil-positions.tsv. +// +// Every slots and union codec is named GameCult.Thing.Contract., the reference's full type name, because a +// store's schema catalog carries the type name of each document slot and the reference compares them. The C# package +// owns the names (tests/thing-contract-parity/type-names.txt): where C# flattens a Rust type into its arms, there is one +// codec per arm. // // Definition order is dependency order. The one cycle is Node (through Box, Button, Overlay, Repeat and Slot), and it // closes at slot level with `lazy`, never inside a union's arm table. import { codecs } from "@gamecult/cultcache-ts"; import type { Codec } from "@gamecult/cultcache-ts"; -import { channel, count, segment, version } from "./domain.js"; +import { channel, count, present, segment, text, version } from "./domain.js"; import type * as T from "./types.js"; -const { string, boolean, float64, bytes, list, nullable, lazy, unit } = codecs; +const { string, boolean, float64, bytes, nullable, lazy, unit, list: sequence } = codecs; -const named = (rustName: string): string => `GameCult.Thing.Contract.${rustName}`; +const named = (name: string): string => `GameCult.Thing.Contract.${name}`; -// A union codec reads nil as null. A required union slot is typed without the null; a nil there is CultLib's -// nullable-reference rule (the reference reads nil too), not this package's. -const required = (codec: Codec): Codec => codec as Codec; +const blob = present(bytes); + +// The C# member type of a list slot is IReadOnlyList; cultcache-ts names only List (a stopgap, until +// thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required. +const readOnlyList = (item: Codec): Codec => { + const inner = sequence(item); + const readOnly: Codec = { + get typeName() { + return item.typeName === undefined ? undefined : `System.Collections.Generic.IReadOnlyList<${item.typeName}>`; + }, + encode: (value) => inner.encode(value), + decode: (raw) => inner.decode(raw), + }; + return present(readOnly); +}; // source.rs -export const paramName = codecs.slots({ 0: ["name", string] }, named("ParamName")); -export const textLiteral = codecs.slots({ 0: ["value", string] }, named("TextLiteral")); -export const numberLiteral = codecs.slots({ 0: ["value", float64] }, named("NumberLiteral")); -export const boolLiteral = codecs.slots({ 0: ["value", boolean] }, named("BoolLiteral")); +export const textSourceParam = present(codecs.slots({ 0: ["name", text] }, named("TextSourceParam"))); +export const numberSourceParam = present(codecs.slots({ 0: ["name", text] }, named("NumberSourceParam"))); +export const boolSourceParam = present(codecs.slots({ 0: ["name", text] }, named("BoolSourceParam"))); +export const collectionSourceParam = present(codecs.slots({ 0: ["name", text] }, named("CollectionSourceParam"))); +export const commandRefParam = present(codecs.slots({ 0: ["name", text] }, named("CommandRefParam"))); +export const textLiteral = present(codecs.slots({ 0: ["value", text] }, named("TextLiteral"))); +export const numberLiteral = present(codecs.slots({ 0: ["value", float64] }, named("NumberLiteral"))); +export const boolLiteral = present(codecs.slots({ 0: ["value", boolean] }, named("BoolLiteral"))); -export const memberName = codecs.slots({ 0: ["name", string] }, named("MemberName")); -export const memberIndex = codecs.slots({ 0: ["index", count] }, named("MemberIndex")); -export const memberStep = required( +export const memberName = present(codecs.slots({ 0: ["name", text] }, named("MemberName"))); +export const memberIndex = present(codecs.slots({ 0: ["index", count] }, named("MemberIndex"))); +export const memberStep = present( codecs.union("MemberStep", { 0: ["Name", memberName], 1: ["Index", memberIndex] }, named("MemberStep")), ); -export const memberPath = codecs.slots({ 0: ["steps", list(memberStep)] }, named("MemberPath")); +export const memberPath = present(codecs.slots({ 0: ["steps", readOnlyList(memberStep)] }, named("MemberPath"))); -export const numberFormat = codecs.slots( +export const numberFormat = present(codecs.slots( { 0: ["precision", count], 1: ["percent", boolean], 2: ["unit", nullable(string)] }, named("NumberFormat"), -); -export const affixFormat = codecs.slots({ 0: ["prefix", string], 1: ["suffix", string] }, named("AffixFormat")); -export const format = required( - codecs.union( +)); +export const affixFormat = present(codecs.slots({ 0: ["prefix", text], 1: ["suffix", text] }, named("AffixFormat"))); +const formatRaw = codecs.union( "Format", { 0: ["Number", numberFormat], 1: ["Duration", unit], 2: ["Timestamp", unit], 3: ["Affix", affixFormat] }, named("Format"), - ), ); +export const format = present(formatRaw); -export const stateRef = codecs.slots( - { 0: ["provider", nullable(string)], 1: ["schema", string], 2: ["key", string] }, +export const stateRef = present(codecs.slots( + { 0: ["provider", nullable(string)], 1: ["schema", text], 2: ["key", text] }, named("StateRef"), -); -export const stateSource = required( +)); +export const stateSource = present( codecs.union("StateSource", { 0: ["Record", stateRef], 1: ["Item", unit] }, named("StateSource")), ); -export const bind = codecs.slots( - { 0: ["source", stateSource], 1: ["member", memberPath], 2: ["format", nullable(format)] }, +export const bind = present(codecs.slots( + { 0: ["source", stateSource], 1: ["member", memberPath], 2: ["format", nullable(formatRaw)] }, named("Bind"), -); +)); -export const textSource = required( - codecs.union( +const textSourceRaw = codecs.union( "TextSource", - { 0: ["Literal", textLiteral], 1: ["Bound", bind], 2: ["Param", paramName] }, + { 0: ["Literal", textLiteral], 1: ["Bound", bind], 2: ["Param", textSourceParam] }, named("TextSource"), - ), ); -export const numberSource = required( +export const textSource = present(textSourceRaw); +export const numberSource = present( codecs.union( "NumberSource", - { 0: ["Literal", numberLiteral], 1: ["Bound", bind], 2: ["Param", paramName] }, + { 0: ["Literal", numberLiteral], 1: ["Bound", bind], 2: ["Param", numberSourceParam] }, named("NumberSource"), ), ); -export const boolSource = required( +export const boolSource = present( codecs.union( "BoolSource", - { 0: ["Literal", boolLiteral], 1: ["Bound", bind], 2: ["Param", paramName] }, + { 0: ["Literal", boolLiteral], 1: ["Bound", bind], 2: ["Param", boolSourceParam] }, named("BoolSource"), ), ); -export const recordsSource = codecs.slots( - { 0: ["provider", nullable(string)], 1: ["schema", string], 2: ["keyPrefix", string] }, +export const recordsSource = present(codecs.slots( + { 0: ["provider", nullable(string)], 1: ["schema", text], 2: ["keyPrefix", text] }, named("RecordsSource"), -); -export const collectionSource = required( +)); +export const collectionSource = present( codecs.union( "CollectionSource", - { 0: ["Records", recordsSource], 1: ["Member", bind], 2: ["Param", paramName] }, + { 0: ["Records", recordsSource], 1: ["Member", bind], 2: ["Param", collectionSourceParam] }, named("CollectionSource"), ), ); // style.rs -export const scalar = codecs.slots({ 0: ["value", float64] }, named("Scalar")); -export const dimension = required( +export const dimensionPx = present(codecs.slots({ 0: ["value", float64] }, named("DimensionPx"))); +export const dimensionPercent = present(codecs.slots({ 0: ["value", float64] }, named("DimensionPercent"))); +export const dimensionFr = present(codecs.slots({ 0: ["value", float64] }, named("DimensionFr"))); +export const dimension = present( codecs.union( "Dimension", - { 0: ["Px", scalar], 1: ["Percent", scalar], 2: ["Fr", scalar], 3: ["Auto", unit], 4: ["Content", unit] }, + { 0: ["Px", dimensionPx], 1: ["Percent", dimensionPercent], 2: ["Fr", dimensionFr], 3: ["Auto", unit], 4: ["Content", unit] }, named("Dimension"), ), ); -export const size2 = codecs.slots({ 0: ["width", dimension], 1: ["height", dimension] }, named("Size2")); -export const edges = codecs.slots( +export const size2 = present(codecs.slots({ 0: ["width", dimension], 1: ["height", dimension] }, named("Size2"))); +export const edges = present(codecs.slots( { 0: ["top", dimension], 1: ["right", dimension], 2: ["bottom", dimension], 3: ["left", dimension] }, named("Edges"), -); -export const display = required( +)); +export const display = present( codecs.union("Display", { 0: ["Flex", unit], 1: ["Grid", unit], 2: ["Block", unit] }, named("Display")), ); -export const direction = required( +export const direction = present( codecs.union( "Direction", { 0: ["Row", unit], 1: ["Column", unit], 2: ["RowReverse", unit], 3: ["ColumnReverse", unit] }, named("Direction"), ), ); -export const wrap = required( +export const wrap = present( codecs.union("Wrap", { 0: ["NoWrap", unit], 1: ["Wrap", unit], 2: ["WrapReverse", unit] }, named("Wrap")), ); -export const position = required( +export const position = present( codecs.union("Position", { 0: ["Relative", unit], 1: ["Absolute", unit] }, named("Position")), ); -export const overflow = required( +export const overflow = present( codecs.union("Overflow", { 0: ["Visible", unit], 1: ["Clip", unit], 2: ["Scroll", unit] }, named("Overflow")), ); -export const itemAlign = required( +export const itemAlign = present( codecs.union( "ItemAlign", { @@ -140,7 +162,7 @@ export const itemAlign = required( named("ItemAlign"), ), ); -export const contentAlign = required( +export const contentAlign = present( codecs.union( "ContentAlign", { @@ -156,7 +178,7 @@ export const contentAlign = required( named("ContentAlign"), ), ); -export const boxStyle = codecs.slots( +export const boxStyle = present(codecs.slots( { 0: ["display", display], 1: ["direction", direction], @@ -177,25 +199,25 @@ export const boxStyle = codecs.slots( 16: ["grow", float64], 17: ["shrink", float64], 18: ["basis", dimension], - 19: ["gridColumns", list(dimension)], - 20: ["gridRows", list(dimension)], + 19: ["gridColumns", readOnlyList(dimension)], + 20: ["gridRows", readOnlyList(dimension)], }, named("BoxStyle"), -); -export const themeToken = codecs.slots({ 0: ["name", string] }, named("ThemeToken")); -export const rgba = codecs.slots( +)); +export const themeToken = present(codecs.slots({ 0: ["name", text] }, named("ThemeToken"))); +export const rgba = present(codecs.slots( { 0: ["r", channel], 1: ["g", channel], 2: ["b", channel], 3: ["a", channel] }, named("Rgba"), -); -export const colorRef = required( - codecs.union("ColorRef", { 0: ["Token", themeToken], 1: ["Rgba", rgba] }, named("ColorRef")), -); -export const border = codecs.slots({ 0: ["color", colorRef], 1: ["width", float64] }, named("Border")); -export const paint = codecs.slots( - { 0: ["background", nullable(colorRef)], 1: ["border", nullable(border)], 2: ["radius", float64] }, +)); +const colorRefRaw = codecs.union("ColorRef", { 0: ["Token", themeToken], 1: ["Rgba", rgba] }, named("ColorRef")); +export const colorRef = present(colorRefRaw); +const borderRaw = codecs.slots({ 0: ["color", colorRef], 1: ["width", float64] }, named("Border")); +export const border = present(borderRaw); +export const paint = present(codecs.slots( + { 0: ["background", nullable(colorRefRaw)], 1: ["border", nullable(borderRaw)], 2: ["radius", float64] }, named("Paint"), -); -export const role = required( +)); +export const role = present( codecs.union( "Role", { @@ -212,72 +234,71 @@ export const role = required( ); // command.rs -export const commandDecl = codecs.slots( - { 0: ["id", string], 1: ["payloadSchema", string], 2: ["captures", list(string)], 3: ["confirm", nullable(string)] }, +export const commandDecl = present(codecs.slots( + { 0: ["id", text], 1: ["payloadSchema", text], 2: ["captures", readOnlyList(string)], 3: ["confirm", nullable(string)] }, named("CommandDecl"), +)); +export const commandIdRef = present(codecs.slots({ 0: ["id", text] }, named("CommandIdRef"))); +export const commandRef = present( + codecs.union("CommandRef", { 0: ["Id", commandIdRef], 1: ["Param", commandRefParam] }, named("CommandRef")), ); -export const commandIdRef = codecs.slots({ 0: ["id", string] }, named("CommandIdRef")); -export const commandRef = required( - codecs.union("CommandRef", { 0: ["Id", commandIdRef], 1: ["Param", paramName] }, named("CommandRef")), -); -export const recordPayload = codecs.slots( - { 0: ["schema", string], 1: ["bytes", bytes] }, +export const recordPayload = present(codecs.slots( + { 0: ["schema", text], 1: ["bytes", blob] }, named("RecordPayload"), -); -export const textValue = codecs.slots({ 0: ["value", string] }, named("TextValue")); -export const numberValue = codecs.slots({ 0: ["value", float64] }, named("NumberValue")); -export const boolValue = codecs.slots({ 0: ["value", boolean] }, named("BoolValue")); -export const choiceValue = codecs.slots({ 0: ["value", string] }, named("ChoiceValue")); -export const inputValue = required( +)); +export const textValue = present(codecs.slots({ 0: ["value", text] }, named("TextValue"))); +export const numberValue = present(codecs.slots({ 0: ["value", float64] }, named("NumberValue"))); +export const boolValue = present(codecs.slots({ 0: ["value", boolean] }, named("BoolValue"))); +export const choiceValue = present(codecs.slots({ 0: ["value", text] }, named("ChoiceValue"))); +export const inputValue = present( codecs.union( "InputValue", { 0: ["Text", textValue], 1: ["Number", numberValue], 2: ["Bool", boolValue], 3: ["Choice", choiceValue] }, named("InputValue"), ), ); -export const capturedInput = codecs.slots( - { 0: ["node", string], 1: ["value", inputValue] }, +export const capturedInput = present(codecs.slots( + { 0: ["node", text], 1: ["value", inputValue] }, named("CapturedInput"), -); +)); export const commandInvocation = codecs.slots( { - 0: ["invocationId", string], - 1: ["surfaceKey", string], + 0: ["invocationId", text], + 1: ["surfaceKey", text], 2: ["surfaceVersion", version], - 3: ["command", string], + 3: ["command", text], 4: ["payload", recordPayload], - 5: ["captured", list(capturedInput)], - 6: ["client", string], - 7: ["issuedAt", string], + 5: ["captured", readOnlyList(capturedInput)], + 6: ["client", text], + 7: ["issuedAt", text], 8: ["delegation", nullable(string)], }, named("CommandInvocation"), ); // result.rs -export const pendingOutcome = codecs.slots({ 0: ["message", string] }, named("PendingOutcome")); -export const openSurfaceEffect = codecs.slots({ 0: ["key", string] }, named("OpenSurfaceEffect")); -export const openExternalEffect = codecs.slots( - { 0: ["url", string], 1: ["resume", commandRef] }, +export const pendingOutcome = present(codecs.slots({ 0: ["message", text] }, named("PendingOutcome"))); +export const openSurfaceEffect = present(codecs.slots({ 0: ["key", text] }, named("OpenSurfaceEffect"))); +export const openExternalEffect = present(codecs.slots( + { 0: ["url", text], 1: ["resume", commandRef] }, named("OpenExternalEffect"), -); -export const effect = required( - codecs.union( +)); +const effectRaw = codecs.union( "Effect", { 0: ["OpenSurface", openSurfaceEffect], 1: ["OpenExternal", openExternalEffect] }, named("Effect"), - ), ); -export const completedOutcome = codecs.slots( - { 0: ["sourceVersion", nullable(version)], 1: ["clearDrafts", boolean], 2: ["effect", nullable(effect)] }, +export const effect = present(effectRaw); +export const completedOutcome = present(codecs.slots( + { 0: ["sourceVersion", nullable(version)], 1: ["clearDrafts", boolean], 2: ["effect", nullable(effectRaw)] }, named("CompletedOutcome"), -); -export const deniedOutcome = codecs.slots( - { 0: ["reason", string], 1: ["node", nullable(string)] }, +)); +export const deniedOutcome = present(codecs.slots( + { 0: ["reason", text], 1: ["node", nullable(string)] }, named("DeniedOutcome"), -); -export const failedOutcome = codecs.slots({ 0: ["reason", string] }, named("FailedOutcome")); -export const outcome = required( +)); +export const failedOutcome = present(codecs.slots({ 0: ["reason", text] }, named("FailedOutcome"))); +export const outcome = present( codecs.union( "Outcome", { 0: ["Pending", pendingOutcome], 1: ["Completed", completedOutcome], 2: ["Denied", deniedOutcome], 3: ["Failed", failedOutcome] }, @@ -286,49 +307,49 @@ export const outcome = required( ); // node.rs -export const nodeCommon = codecs.slots( - { 0: ["id", string], 1: ["visible", boolSource], 2: ["a11yLabel", nullable(textSource)] }, +export const nodeCommon = present(codecs.slots( + { 0: ["id", text], 1: ["visible", boolSource], 2: ["a11yLabel", nullable(textSourceRaw)] }, named("NodeCommon"), -); +)); // Node closes its own cycle here and nowhere else. export const node: Codec = lazy(() => nodeUnion); -export const boxNode = codecs.slots( - { 0: ["common", nodeCommon], 1: ["style", boxStyle], 2: ["paint", paint], 3: ["role", role], 4: ["children", list(node)] }, +export const boxNode = present(codecs.slots( + { 0: ["common", nodeCommon], 1: ["style", boxStyle], 2: ["paint", paint], 3: ["role", role], 4: ["children", readOnlyList(node)] }, named("BoxNode"), -); -export const textNode = codecs.slots( +)); +export const textNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["content", textSource], - 2: ["styleToken", string], + 2: ["styleToken", text], 3: ["wrap", boolean], 4: ["maxLines", nullable(count)], 5: ["selectable", boolean], }, named("TextNode"), -); -export const imageFit = required( +)); +export const imageFit = present( codecs.union( "ImageFit", { 0: ["Contain", unit], 1: ["Cover", unit], 2: ["Fill", unit], 3: ["Unscaled", unit] }, named("ImageFit"), ), ); -export const imageNode = codecs.slots( - { 0: ["common", nodeCommon], 1: ["catalog", string], 2: ["asset", string], 3: ["fit", imageFit], 4: ["alt", textSource] }, +export const imageNode = present(codecs.slots( + { 0: ["common", nodeCommon], 1: ["catalog", text], 2: ["asset", text], 3: ["fit", imageFit], 4: ["alt", textSource] }, named("ImageNode"), -); -export const buttonNode = codecs.slots( - { 0: ["common", nodeCommon], 1: ["content", list(node)], 2: ["onActivate", commandRef], 3: ["enabled", boolSource] }, +)); +export const buttonNode = present(codecs.slots( + { 0: ["common", nodeCommon], 1: ["content", readOnlyList(node)], 2: ["onActivate", commandRef], 3: ["enabled", boolSource] }, named("ButtonNode"), -); -export const toggleNode = codecs.slots( +)); +export const toggleNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["checked", boolSource], 2: ["onChange", commandRef] }, named("ToggleNode"), -); -export const sliderNode = codecs.slots( +)); +export const sliderNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["min", float64], @@ -338,11 +359,11 @@ export const sliderNode = codecs.slots( 5: ["commit", commandRef], }, named("SliderNode"), -); -export const inputKind = required( +)); +export const inputKind = present( codecs.union("InputKind", { 0: ["Text", unit], 1: ["Number", unit] }, named("InputKind")), ); -export const textInputNode = codecs.slots( +export const textInputNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["multiline", boolean], @@ -352,42 +373,42 @@ export const textInputNode = codecs.slots( 5: ["submit", commandRef], }, named("TextInputNode"), -); -export const selectOption = codecs.slots({ 0: ["value", string], 1: ["label", string] }, named("SelectOption")); -export const literalOptions = codecs.slots({ 0: ["options", list(selectOption)] }, named("LiteralOptions")); -export const boundOptions = codecs.slots( +)); +export const selectOption = present(codecs.slots({ 0: ["value", text], 1: ["label", text] }, named("SelectOption"))); +export const literalOptions = present(codecs.slots({ 0: ["options", readOnlyList(selectOption)] }, named("LiteralOptions"))); +export const boundOptions = present(codecs.slots( { 0: ["collection", collectionSource], 1: ["valueMember", memberPath], 2: ["labelMember", memberPath] }, named("BoundOptions"), -); -export const optionList = required( +)); +export const optionList = present( codecs.union("OptionList", { 0: ["Literal", literalOptions], 1: ["Bound", boundOptions] }, named("OptionList")), ); -export const selectNode = codecs.slots( +export const selectNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["options", optionList], 2: ["value", bind], 3: ["onChange", commandRef] }, named("SelectNode"), -); -export const repeatNode = codecs.slots( +)); +export const repeatNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["collection", collectionSource], 2: ["keyMember", memberPath], 3: ["template", node] }, named("RepeatNode"), -); -export const anchorNode = codecs.slots({ 0: ["node", string] }, named("AnchorNode")); -export const anchor = required( +)); +export const anchorNode = present(codecs.slots({ 0: ["node", text] }, named("AnchorNode"))); +export const anchor = present( codecs.union("Anchor", { 0: ["Viewport", unit], 1: ["Node", anchorNode] }, named("Anchor")), ); -export const overlayNode = codecs.slots( +export const overlayNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["anchor", anchor], 2: ["modal", boolean], 3: ["dismiss", commandRef], - 4: ["children", list(node)], + 4: ["children", readOnlyList(node)], }, named("OverlayNode"), -); -export const plotMark = required( +)); +export const plotMark = present( codecs.union("PlotMark", { 0: ["Line", unit], 1: ["Bar", unit], 2: ["Area", unit] }, named("PlotMark")), ); -export const plotNode = codecs.slots( +export const plotNode = present(codecs.slots( { 0: ["common", nodeCommon], 1: ["series", bind], @@ -398,28 +419,28 @@ export const plotNode = codecs.slots( 6: ["yMax", nullable(float64)], }, named("PlotNode"), -); -export const embedNode = codecs.slots( +)); +export const embedNode = present(codecs.slots( { 0: ["common", nodeCommon], - 1: ["slotKind", string], - 2: ["slotId", string], + 1: ["slotKind", text], + 2: ["slotId", text], 3: ["width", float64], 4: ["height", float64], }, named("EmbedNode"), -); -export const compositionRef = codecs.slots( - { 0: ["publisher", string], 1: ["name", segment], 2: ["version", version] }, +)); +export const compositionRef = present(codecs.slots( + { 0: ["publisher", text], 1: ["name", segment], 2: ["version", version] }, named("CompositionRef"), -); -export const textArg = codecs.slots({ 0: ["value", string] }, named("TextArg")); -export const numberArg = codecs.slots({ 0: ["value", float64] }, named("NumberArg")); -export const boolArg = codecs.slots({ 0: ["value", boolean] }, named("BoolArg")); -export const collectionArg = codecs.slots({ 0: ["source", collectionSource] }, named("CollectionArg")); -export const commandArg = codecs.slots({ 0: ["command", commandRef] }, named("CommandArg")); -export const slotArg = codecs.slots({ 0: ["nodes", list(node)] }, named("SlotArg")); -export const argValue = required( +)); +export const textArg = present(codecs.slots({ 0: ["value", text] }, named("TextArg"))); +export const numberArg = present(codecs.slots({ 0: ["value", float64] }, named("NumberArg"))); +export const boolArg = present(codecs.slots({ 0: ["value", boolean] }, named("BoolArg"))); +export const collectionArg = present(codecs.slots({ 0: ["source", collectionSource] }, named("CollectionArg"))); +export const commandArg = present(codecs.slots({ 0: ["command", commandRef] }, named("CommandArg"))); +export const slotArg = present(codecs.slots({ 0: ["nodes", readOnlyList(node)] }, named("SlotArg"))); +export const argValue = present( codecs.union( "ArgValue", { @@ -434,13 +455,13 @@ export const argValue = required( named("ArgValue"), ), ); -export const arg = codecs.slots({ 0: ["name", string], 1: ["value", argValue] }, named("Arg")); -export const useNode = codecs.slots( - { 0: ["common", nodeCommon], 1: ["composition", compositionRef], 2: ["args", list(arg)] }, +export const arg = present(codecs.slots({ 0: ["name", text], 1: ["value", argValue] }, named("Arg"))); +export const useNode = present(codecs.slots( + { 0: ["common", nodeCommon], 1: ["composition", compositionRef], 2: ["args", readOnlyList(arg)] }, named("UseNode"), -); +)); -const nodeUnion = required( +const nodeUnion = present( codecs.union( "Node", { @@ -462,7 +483,7 @@ const nodeUnion = required( ), ); -export const paramKind = required( +export const paramKind = present( codecs.union( "ParamKind", { @@ -477,35 +498,35 @@ export const paramKind = required( named("ParamKind"), ), ); -export const paramDecl = codecs.slots({ 0: ["name", string], 1: ["kind", paramKind] }, named("ParamDecl")); +export const paramDecl = present(codecs.slots({ 0: ["name", text], 1: ["kind", paramKind] }, named("ParamDecl"))); // The documents' slot records. CommandResult's is in result.ts: it is the one that mints an instance. export const surfaceDocument = codecs.slots( { - 0: ["providerId", string], + 0: ["providerId", text], 1: ["label", segment], 2: ["version", version], - 3: ["title", string], + 3: ["title", text], 4: ["root", node], - 5: ["commands", list(commandDecl)], + 5: ["commands", readOnlyList(commandDecl)], }, named("SurfaceDocument"), ); export const compositionDocument = codecs.slots( { - 0: ["publisher", string], + 0: ["publisher", text], 1: ["name", segment], 2: ["version", version], - 3: ["params", list(paramDecl)], + 3: ["params", readOnlyList(paramDecl)], 4: ["body", node], }, named("CompositionDocument"), ); -export const assetEntry = codecs.slots( - { 0: ["id", string], 1: ["mediaType", string], 2: ["uri", string], 3: ["width", count], 4: ["height", count] }, +export const assetEntry = present(codecs.slots( + { 0: ["id", text], 1: ["mediaType", text], 2: ["uri", text], 3: ["width", count], 4: ["height", count] }, named("AssetEntry"), -); +)); export const assetCatalog = codecs.slots( - { 0: ["providerId", string], 1: ["catalogId", segment], 2: ["version", version], 3: ["assets", list(assetEntry)] }, + { 0: ["providerId", text], 1: ["catalogId", segment], 2: ["version", version], 3: ["assets", readOnlyList(assetEntry)] }, named("AssetCatalog"), ); diff --git a/packages/thing-contract/src/domain.ts b/packages/thing-contract/src/domain.ts index ee53892..f528746 100644 --- a/packages/thing-contract/src/domain.ts +++ b/packages/thing-contract/src/domain.ts @@ -2,7 +2,7 @@ // codec of cultcache-ts with the contract's bound added, so the bound holds on both doors of a document: encode and // decode. A refusal names the domain and its bound, never the value (the leaf's own refusals do not echo one either). import { codecs } from "@gamecult/cultcache-ts"; -import type { Codec } from "@gamecult/cultcache-ts"; +import type { Codec, SlotsCodec } from "@gamecult/cultcache-ts"; // A domain's wire form is its value, so its encode hands the checked value back: a caller that holds a number from // outside (a factory argument, a key part) passes it through `encode` and keeps what comes out. @@ -49,3 +49,34 @@ export const segment: Domain = { /** One colour channel: a byte. */ export const channel = bounded(codecs.int32, (value) => (value >= 0 && value <= 255 ? null : "Rgba channel must be 0 to 255")); + +/** + * A slot the Rust type does not make optional. cultcache-ts reads nil in a string, bytes, record, list or union slot as + * null (the reference's leaf rule), so the slot codec is declared a value type, which makes the library hand it the nil, + * and a nil is refused here on decode and a null or undefined on encode. Typed names and the slots of a record pass + * through. The refusal names the domain, never the value; the library's slot path locates it. + */ +export function present(codec: SlotsCodec): SlotsCodec; +export function present(codec: Codec): Codec; +export function present(codec: Codec): Codec { + const hold = (value: unknown): void => { + if (value === null || value === undefined) throw new Error("Presence: the slot is required"); + }; + const held: Codec = { + get typeName() { + return codec.typeName; + }, + valueType: true, + encode: (value) => (hold(value), codec.encode(value)), + decode: (raw) => (hold(raw), codec.decode(raw)), + }; + if (!("names" in codec)) return held; + const record = codec as SlotsCodec; + return Object.defineProperties(held, { + names: { get: () => record.names, enumerable: true }, + members: { get: () => record.members, enumerable: true }, + }); +} + +/** A required string: the string slot of a record whose Rust member is not an Option. */ +export const text: Codec = present(codecs.string); diff --git a/packages/thing-contract/src/result.ts b/packages/thing-contract/src/result.ts index b87ae6b..d52f2a3 100644 --- a/packages/thing-contract/src/result.ts +++ b/packages/thing-contract/src/result.ts @@ -1,20 +1,30 @@ // The answer to a command invocation. A CommandResult is built by its four factories, each of which copies the -// invocation's id, and by the command_result document codec when it decodes. Decoding is the other door and holds the -// same domain: `seq` is refused below 1 whichever door it enters by. No export takes a state as a string or converts a -// plain object: an object literal, a spread, structuredClone copy or parsed JSON is not a result, and encoding one is -// refused (schema.parse in documents.ts). +// invocation's id, and by the command_result document codec when it decodes. Both doors go through `mint`, which runs +// the slot record on the three fields (presence, Seq, Version, the booleans: every check the decode door runs) and +// builds the instance from the copy that came out, so the value core validates is the value it holds: the outcome and +// its effect are frozen deep, and nothing the caller kept points into them. No export takes a state as a string or +// converts a plain object: an object literal, a spread, structuredClone copy or parsed JSON is not a result, and +// encoding one is refused (schema.parse in documents.ts). // // The copied invocation id is a convenience and not provenance: core binds a result to an invocation it issued. import { codecs } from "@gamecult/cultcache-ts"; import type { SlotsCodec } from "@gamecult/cultcache-ts"; import { outcome } from "./codecs.js"; -import { seq } from "./domain.js"; +import { seq, text } from "./domain.js"; import type { CommandInvocation, Effect, NodeId, Outcome } from "./types.js"; // The one constructor call. The class's static block sets `mint`; the factories and the codec below use it; it is not // exported. The constructor refuses a call that does not carry `door`, so a script that reaches the constructor at run -// time (the TypeScript `private` is compile-time only) builds nothing, and it holds the seq domain for every door. +// time (the TypeScript `private` is compile-time only) builds nothing. +function freezeDeep(value: TValue): TValue { + if (typeof value === "object" && value !== null) { + for (const member of Object.values(value)) freezeDeep(member); + Object.freeze(value); + } + return value; +} + const door: unique symbol = Symbol("CommandResult.door"); let mint: (invocationId: string, position: number, outcome: Outcome) => CommandResult; @@ -27,13 +37,18 @@ export class CommandResult { private constructor(key: typeof door, invocationId: string, position: number, outcome: Outcome) { if (key !== door) throw new Error("a CommandResult is built by its factories"); this.invocationId = invocationId; - this.seq = seq.encode(position); + this.seq = position; this.outcome = outcome; Object.freeze(this); } static { - mint = (invocationId, position, outcome) => new CommandResult(door, invocationId, position, outcome); + // The slot record's wire form is a copy, so what is built is what was checked, and nothing the caller holds points + // into it. + mint = (invocationId, position, answer) => { + const checked = slotRecord.decode(slotRecord.encode({ invocationId, seq: position, outcome: answer })); + return new CommandResult(door, checked.invocationId, checked.seq, freezeDeep(checked.outcome)); + }; } static pending(invocation: CommandInvocation, position: number, message: string): CommandResult { @@ -65,9 +80,9 @@ export class CommandResult { } // The command_result document codec: the slot record, with decode minting an instance. Encode reads the instance's -// fields through the same slot record, so the seq domain is held on both doors. +// fields through the same slot record, so the domains are held on both doors, and so is mint. const slotRecord = codecs.slots<{ invocationId: string; seq: number; outcome: Outcome }>( - { 0: ["invocationId", codecs.string], 1: ["seq", seq], 2: ["outcome", outcome] }, + { 0: ["invocationId", text], 1: ["seq", seq], 2: ["outcome", outcome] }, "GameCult.Thing.Contract.CommandResult", ); diff --git a/packages/thing-contract/src/types.ts b/packages/thing-contract/src/types.ts index 50249d0..57adb24 100644 --- a/packages/thing-contract/src/types.ts +++ b/packages/thing-contract/src/types.ts @@ -244,8 +244,8 @@ export interface SliderNode { } export type InputKind = Arm<"Text"> | Arm<"Number">; /** - * The Rust field is `kind`; here it is `inputKind`, because a TextInput arm carries its payload beside the union's own - * `kind` tag and the two cannot share a name. + * The C# member is InputKind, the camelCase of the Rust field `input_kind`; the name is not a divergence. It could not be + * `kind`, which a TextInput arm's payload would share with the union's own `kind` tag. */ export interface TextInputNode { readonly common: NodeCommon; diff --git a/packages/thing-contract/test/builders.ts b/packages/thing-contract/test/builders.ts index 2bd6e48..f1cd1e1 100644 --- a/packages/thing-contract/test/builders.ts +++ b/packages/thing-contract/test/builders.ts @@ -33,17 +33,28 @@ import type { export const CANARY = "CANARY-7f3a91c2"; export const PINNED_CLOCK = "2026-01-01T00:00:00Z"; -/** The goldens directory, found by walking up from this file (a mutation sandbox sits deeper in the tree). */ -export const goldensDir: string = (() => { +/** The nearest ancestor of this file that holds `relative` (a mutation sandbox sits deeper in the tree). */ +function above(relative: string[], what: string): string { let here = dirname(fileURLToPath(import.meta.url)); for (;;) { - const candidate = join(here, "crates", "thing-contract", "tests", "goldens"); + const candidate = join(here, ...relative); if (existsSync(candidate)) return candidate; const parent = dirname(here); - if (parent === here) throw new Error("the Rust crate's goldens directory is not above this file"); + if (parent === here) throw new Error(`${what} is not above this file`); here = parent; } -})(); +} + +/** The Rust crate's goldens directory. */ +export const goldensDir: string = above(["crates", "thing-contract", "tests", "goldens"], "the Rust crate's goldens directory"); + +/** The C# package's name set and the fixtures each package writes for the other. */ +export const parityDir: string = above(["tests", "thing-contract-parity"], "the parity directory"); + +/** The lines of a file of the C# package's name set, or the rows of a tsv (cells split on tab). */ +export function nonEmptyLines(path: string): string[] { + return readFileSync(path, "utf8").split(/\r?\n/).filter((line) => line.length > 0); +} export function golden(file: string): Uint8Array { return new Uint8Array(readFileSync(join(goldensDir, file))); diff --git a/packages/thing-contract/test/codecs.test.ts b/packages/thing-contract/test/codecs.test.ts index bdb9088..d3eb8d2 100644 --- a/packages/thing-contract/test/codecs.test.ts +++ b/packages/thing-contract/test/codecs.test.ts @@ -1,21 +1,32 @@ -// Every codec of the package is named GameCult.Thing.Contract., the reference's full type name, and every union -// names itself in its refusals. The exports are the lowerCamel of the Rust type names, so the test reads the expected name -// off the export. +// Every codec of the package is named by the C# package's name set (tests/thing-contract-parity/type-names.txt), and +// every union names itself in its refusals. The names are read, never restated here: the C# package owns them. import assert from "node:assert/strict"; +import { join } from "node:path"; import test from "node:test"; import { codecs } from "@gamecult/thing-contract"; -const NS = "GameCult.Thing.Contract."; +import { nonEmptyLines, parityDir } from "./builders.js"; + const entries = Object.entries(codecs) as [string, { typeName?: string; decode(raw: unknown): unknown }][]; const rustName = (key: string) => key[0].toUpperCase() + key.slice(1); +const names = new Set(nonEmptyLines(join(parityDir, "type-names.txt"))); -test("the package exports ninety-five codecs", () => { - assert.equal(entries.length, 95); +test("the package exports one hundred and one codecs", () => { + assert.equal(entries.length, 101); }); -test("every codec carries the reference's full type name", () => { - for (const [key, codec] of entries) assert.equal(codec.typeName, `${NS}${rustName(key)}`, key); +test("every codec's type name is a type of the C# package", () => { + for (const [key, codec] of entries) { + assert.ok(codec.typeName !== undefined && names.has(codec.typeName), `${key}: ${codec.typeName}`); + } + 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", () => { diff --git a/packages/thing-contract/test/definitions.test.ts b/packages/thing-contract/test/definitions.test.ts index 2cc60e2..c41b818 100644 --- a/packages/thing-contract/test/definitions.test.ts +++ b/packages/thing-contract/test/definitions.test.ts @@ -1,6 +1,8 @@ // The five definitions carry the crate's cultcache(type, schema) and, per document slot, the reference's member name -// and C# type name that a store's schema catalog is compared on. +// and C# type name that a store's schema catalog is compared on. The members are read from the C# package's catalog +// (tests/thing-contract-parity/catalog-members.tsv), never restated here. import assert from "node:assert/strict"; +import { join } from "node:path"; import test from "node:test"; import { @@ -12,9 +14,9 @@ import { thingContract, } from "@gamecult/thing-contract"; +import { nonEmptyLines, parityDir } from "./builders.js"; + const NS = "GameCult.Thing.Contract."; -const STRING = "System.String"; -const list = (item: string) => `System.Collections.Generic.List<${NS}${item}>`; const rustName: Record = { "gamecult.thing.surface": "SurfaceDocument", @@ -24,63 +26,50 @@ const rustName: Record = { "gamecult.thing.asset_catalog": "AssetCatalog", }; -const expected = [ - [surfaceDocument, "gamecult.thing.surface", [ - "0:ProviderId:" + STRING, - "1:Label:" + STRING, - "2:Version:System.Int64", - "3:Title:" + STRING, - `4:Root:${NS}Node`, - `5:Commands:${list("CommandDecl")}`, - ]], - [compositionDocument, "gamecult.thing.composition", [ - "0:Publisher:" + STRING, - "1:Name:" + STRING, - "2:Version:System.Int64", - `3:Params:${list("ParamDecl")}`, - `4:Body:${NS}Node`, - ]], - [commandInvocationDocument, "gamecult.thing.command_invocation", [ - "0:InvocationId:" + STRING, - "1:SurfaceKey:" + STRING, - "2:SurfaceVersion:System.Int64", - "3:Command:" + STRING, - `4:Payload:${NS}RecordPayload`, - `5:Captured:${list("CapturedInput")}`, - "6:Client:" + STRING, - "7:IssuedAt:" + STRING, - "8:Delegation:" + STRING, - ]], - [commandResultDocument, "gamecult.thing.command_result", [ - "0:InvocationId:" + STRING, - "1:Seq:System.Int32", - `2:Outcome:${NS}Outcome`, - ]], - [assetCatalogDocument, "gamecult.thing.asset_catalog", [ - "0:ProviderId:" + STRING, - "1:CatalogId:" + STRING, - "2:Version:System.Int64", - `3:Assets:${list("AssetEntry")}`, - ]], +const definitions = [ + [surfaceDocument, "gamecult.thing.surface"], + [compositionDocument, "gamecult.thing.composition"], + [commandInvocationDocument, "gamecult.thing.command_invocation"], + [commandResultDocument, "gamecult.thing.command_result"], + [assetCatalogDocument, "gamecult.thing.asset_catalog"], ] as const; -for (const [definition, type, members] of expected) { +/** The catalog's rows grouped by C# schema id, each group as `slot:Member:TypeName` strings. */ +function catalogGroups(): string[][] { + const groups = new Map(); + for (const row of nonEmptyLines(join(parityDir, "catalog-members.tsv"))) { + const [schemaId, slot, member, typeName] = row.split("\t"); + groups.set(schemaId, [...(groups.get(schemaId) ?? []), `${slot}:${member}:${typeName}`]); + } + return [...groups.values()]; +} + +/** The slot and member names of a group, which tell the five documents apart: the schema id is the C# hash. */ +const shape = (members: readonly string[]): string => members.map((member) => member.split(":").slice(0, 2).join(":")).join(","); + +for (const [definition, type] of definitions) { test(`${type}: type, schema and catalog members`, () => { assert.equal(definition.type, type); assert.equal(definition.schemaName, type); assert.equal(definition.schemaVersion, `${type}.v1`); assert.equal(definition.codec?.typeName, `${NS}${rustName[type]}`); - assert.deepEqual( - definition.members?.map((member) => `${member.slot}:${member.memberName}:${member.typeName}`), - members, - ); + const actual = definition.members?.map((member) => `${member.slot}:${member.memberName}:${member.typeName}`) ?? []; + const rows = catalogGroups().filter((group) => shape(group) === shape(actual)); + assert.equal(rows.length, 1, "exactly one group of the C# catalog has this definition's slots and member names"); + assert.deepEqual(actual, rows[0]); }); } +test("the C# catalog holds the five definitions and nothing else", () => { + const groups = catalogGroups(); + assert.equal(groups.length, 5); + assert.equal(new Set(groups.map(shape)).size, 5); +}); + test("the registry lists the five definitions, in the crate's order", () => { assert.deepEqual( thingContract.definitions.map((definition) => definition.type), - expected.map(([, type]) => type), + definitions.map(([, type]) => type), ); assert.equal(new Set(thingContract.definitions).size, 5); });