novy-syndicate/src/secure-chat-moderator.ts

39 lines
1.5 KiB
TypeScript
Raw Normal View History

import { $claimNick, $joinedUser, asNickClaim, fromJoin, fromNickConflict, fromUserInfo, Join, NickConflict, UserId, UserInfo } from "./gen/secure-chat-protocol.js";
import { Assertion, Handle, Ref, Turn } from "./actor.js";
import { observe, during, $Observe, asObserve } from "./dataspace.js";
export default function (t: Turn, ds: Ref) {
let nextUserId: UserId = 0;
const nicks = new Map<string, UserId>();
observe(t, ds, $Observe, during((t, o0) => {
const o = asObserve(o0);
if (o.label !== $joinedUser) return null;
const uid: UserId = nextUserId++;
const f = t.facet(t => {
t.assert(o.observer, fromJoin(Join({ uid, handle: ds })));
let infoHandle: Handle | undefined;
let nick: string | undefined;
observe(t, ds, $claimNick, {
assert(t: Turn, c0: Assertion): void {
const c = asNickClaim(c0);
if (c.uid !== uid) return;
if (nicks.has(c.name)) {
t.message(c.k, fromNickConflict(NickConflict()));
} else {
t.message(c.k, true);
if (nick !== void 0) nicks.delete(nick);
infoHandle = t.replace(ds, infoHandle, fromUserInfo(UserInfo(c)));
nick = c.name;
nicks.set(nick, uid);
}
}
});
});
return t => t.stop(f);
}));
}