bus-event.ts 984 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import z from "zod"
  2. import type { ZodType } from "zod"
  3. import { Log } from "../util/log"
  4. export namespace BusEvent {
  5. const log = Log.create({ service: "event" })
  6. export type Definition = ReturnType<typeof define>
  7. const registry = new Map<string, Definition>()
  8. export function define<Type extends string, Properties extends ZodType>(type: Type, properties: Properties) {
  9. const result = {
  10. type,
  11. properties,
  12. }
  13. registry.set(type, result)
  14. return result
  15. }
  16. export function payloads() {
  17. return z
  18. .discriminatedUnion(
  19. "type",
  20. registry
  21. .entries()
  22. .map(([type, def]) => {
  23. return z
  24. .object({
  25. type: z.literal(type),
  26. properties: def.properties,
  27. })
  28. .meta({
  29. ref: "Event" + "." + def.type,
  30. })
  31. })
  32. .toArray() as any,
  33. )
  34. .meta({
  35. ref: "Event",
  36. })
  37. }
  38. }