From f3da73553c45f17e04b1e77cb13eb0fca714d1bd Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 30 May 2025 20:47:56 -0400 Subject: sync --- js/src/bus/index.ts | 101 ---------------------------------------------------- 1 file changed, 101 deletions(-) delete mode 100644 js/src/bus/index.ts (limited to 'js/src/bus') diff --git a/js/src/bus/index.ts b/js/src/bus/index.ts deleted file mode 100644 index 342d82b6d..000000000 --- a/js/src/bus/index.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { z, type ZodType } from "zod"; -import { App } from "../app/app"; -import { Log } from "../util/log"; - -export namespace Bus { - const log = Log.create({ service: "bus" }); - type Subscription = (event: any) => void; - - const state = App.state("bus", () => { - const subscriptions = new Map(); - - return { - subscriptions, - }; - }); - - export type EventDefinition = ReturnType; - - const registry = new Map(); - - export function event( - type: Type, - properties: Properties, - ) { - const result = { - type, - properties, - }; - registry.set(type, result); - return result; - } - - export function payloads() { - return z.discriminatedUnion( - "type", - registry - .entries() - .map(([type, def]) => - z - .object({ - type: z.literal(type), - properties: def.properties, - }) - .openapi({ - ref: "Event" + "." + def.type, - }), - ) - .toArray() as any, - ); - } - - export function publish( - def: Definition, - properties: z.output, - ) { - const payload = { - type: def.type, - properties, - }; - log.info("publishing", { - type: def.type, - }); - for (const key of [def.type, "*"]) { - const match = state().subscriptions.get(key); - for (const sub of match ?? []) { - sub(payload); - } - } - } - - export function subscribe( - def: Definition, - callback: (event: { - type: Definition["type"]; - properties: z.infer; - }) => void, - ) { - return raw(def.type, callback); - } - - export function subscribeAll(callback: (event: any) => void) { - return raw("*", callback); - } - - function raw(type: string, callback: (event: any) => void) { - log.info("subscribing", { type }); - const subscriptions = state().subscriptions; - let match = subscriptions.get(type) ?? []; - match.push(callback); - subscriptions.set(type, match); - - return () => { - log.info("unsubscribing", { type }); - const match = subscriptions.get(type); - if (!match) return; - const index = match.indexOf(callback); - if (index === -1) return; - match.splice(index, 1); - }; - } -} -- cgit v1.2.3