atagen

malice

public
Star0
Watch0
77eddb6b710ffe2b884b8bdf7b0611041f7358e6
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/commands.tsTypescript74 lines2.1 KB
1
import type { Person } from './types';
2
3
export interface ParsedCommand {
4
  name: string;
5
  args: string;
6
}
7
8
export const COMMANDS = [
9
  'me',
10
  'notice',
11
  'msg',
12
  'join',
13
  'leave',
14
  'invite',
15
  'disinvite',
16
  'kick',
17
  'ban',
18
  'unban',
19
  'powerlevel',
20
  'mute',
21
  'unmute',
22
  'ignore',
23
  'unignore',
24
  'delete',
25
  'roomnick',
26
  'globalnick',
27
  'roomavatar',
28
  'globalavatar'
29
] as const;
30
export type CommandName = (typeof COMMANDS)[number];
31
32
/** A leading `/word`, or null for plain text. `//text` sends `/text` as a message. */
33
export function parseCommand(text: string): ParsedCommand | null {
34
  const match = /^\/([a-z]+)(?:\s+([\s\S]*))?$/i.exec(text.trim());
35
  if (!match) return null;
36
  return { name: match[1].toLowerCase(), args: (match[2] ?? '').trim() };
37
}
38
39
export function isKnownCommand(name: string): name is CommandName {
40
  return (COMMANDS as readonly string[]).includes(name);
41
}
42
43
export function unescapeCommand(text: string): string {
44
  return text.startsWith('//') ? text.slice(1) : text;
45
}
46
47
export type Target = { user_id: string; rest: string } | { error: string };
48
49
/** The user an argument string starts with, by matrix id or by a known display name. */
50
export function splitTarget(args: string, people: Person[]): Target {
51
  if (!args) return { error: 'Name someone' };
52
  if (args.startsWith('@')) {
53
    const [id, ...rest] = args.split(/\s+/);
54
    if (/^@[^:\s]+:\S+$/.test(id)) return { user_id: id, rest: rest.join(' ') };
55
  }
56
  const lower = args.toLowerCase();
57
  let best: Person[] = [];
58
  let bestLength = 0;
59
  for (const person of people) {
60
    const name = person.name.toLowerCase();
61
    if (!name || name.length < bestLength) continue;
62
    if (lower !== name && !lower.startsWith(`${name} `)) continue;
63
    if (name.length > bestLength) {
64
      best = [person];
65
      bestLength = name.length;
66
    } else {
67
      best.push(person);
68
    }
69
  }
70
  const ids = [...new Set(best.map((p) => p.user_id))];
71
  if (ids.length === 0) return { error: `No one here is called ${args.split(/\s+/)[0]}` };
72
  if (ids.length > 1) return { error: `Several people are called ${best[0].name}, use their @id` };
73
  return { user_id: ids[0], rest: args.slice(bestLength).trim() };
74
}