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

60 lines
1.9 KiB
TypeScript

import {
$claimNick,
$joinedUser,
$says,
$user,
Join,
NickConflict,
UserId,
UserInfo,
asNickClaim,
fromJoin,
fromNickConflict,
fromUserInfo,
} from "./gen/secure-chat-protocol.js";
import { Assertion, Handle, Ref, Turn } from "./actor.js";
import { observe, during, $Observe, asObserve } from "./dataspace.js";
import { attenuate, rfilter, pRec, pPointer, pString, pLit } from "./rewrite.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: attenuate(ds, rfilter(
pRec($Observe, pLit($user), pPointer()),
pRec($Observe, pLit($says), pPointer()),
pRec($claimNick, pLit(uid), pString(), pPointer()),
pRec($says, pLit(uid), pString()))),
})));
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);
}));
}