Skip to content

Commit

Permalink
fix signature of MachineEvent.Factory.parse
Browse files Browse the repository at this point in the history
  • Loading branch information
rkuhn committed Jan 25, 2024
1 parent f743b62 commit fff8f8e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
2 changes: 1 addition & 1 deletion machine-runner/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@actyx/machine-runner",
"version": "0.5.5",
"version": "0.5.6",
"description": "asymmetric replicated state machines: runtime support",
"type": "module",
"types": "./lib/esm/index.d.ts",
Expand Down
18 changes: 10 additions & 8 deletions machine-runner/src/design/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,32 @@ export namespace MachineEvent {
key: Key,
zodDefinition?: z.ZodType<Payload>,
) => {
const defaultParser: (event: MachineEvent<Key, Payload>) => ParseResult<Payload> = (event) => {
const defaultParser: (event: unknown) => ParseResult<MachineEvent<Key, Payload>> = (event) => {
if (typeof event !== 'object' || event === null) {
return { success: false, error: `Event ${event} is not an object` }
}

if (event.type !== key) {
const type = (event as any).type
if (type !== key) {
return {
success: false,
error: `Event type ${event.type} does not match expected type ${key}`,
error: `Event type ${type} does not match expected type ${key}`,
}
}

return { success: true, event }
return { success: true, event: event as MachineEvent<Key, Payload> }
}

if (!zodDefinition) {
return defaultParser
} else {
const [zod, fromZodError] = (() => {
const { z, fromZodError } = getZod()
const zod = z.intersection(zodDefinition, z.object({ type: z.string() }))
const zod = z.intersection(zodDefinition, z.object({ type: z.literal<Key>(key) }))
return [zod, fromZodError] as const
})()

return (event: MachineEvent<Key, Payload>): ParseResult<Payload> => {
return (event: unknown): ParseResult<MachineEvent<Key, Payload>> => {
const defaultParserResult = defaultParser(event)
if (!defaultParserResult.success) return defaultParserResult

Expand All @@ -86,7 +87,8 @@ export namespace MachineEvent {
return { success: false, error: fromZodError(result.error).toString() }
}

return { success: true, event: result.data }
// something is wrong with z.literal(), the resulting type doesn’t unify with Key
return { success: true, event: Object.assign(result.data, { type: key }) }
}
}
}
Expand Down Expand Up @@ -222,7 +224,7 @@ export namespace MachineEvent {
* used, this method will only check whether the given event has the correct
* type field.
*/
parse: (event: MachineEvent<Key, Payload>) => ParseResult<Payload>
parse: (event: unknown) => ParseResult<MachineEvent<Key, Payload>>
/**
* Contains Zod definition. Also serves to differentiate Event from
* Event.Factory when evaluated with Payload.Of
Expand Down

0 comments on commit fff8f8e

Please sign in to comment.