All files / core/src campfire.ts

0% Statements 0/45
0% Branches 0/14
0% Functions 0/9
0% Lines 0/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138                                                                                                                                                                                                                                                                                   
import { FlarieServerContext, type FlarieMessage, type Platform, FlarieMessageEphemeral } from './types';
import { cyan, magenta, bold, italic } from 'chalk';
import * as readline from 'node:readline/promises';
import { userInfo } from 'node:os';
import { EventEmitter } from 'node:events';
import { FlarieCommand } from './types/command';
import { FlarieError } from './types/error';
import { Logger } from './logger';
 
export class CampfirePlatform extends EventEmitter implements Platform {
  public static readonly NAME = 'campfire';
  static readonly #BOT_USERNAME = 'flarie';
  #rl: readline.Interface;
  #username: string;
  #commands: Map<string, FlarieCommand>;
 
  constructor() {
    super();
 
    this.#commands = new Map();
 
    this.#rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });
 
    this.#username = userInfo().username;
  }
 
  #log(name: string, message: FlarieMessageEphemeral) {
    if (message.ephemeral) {
      console.log(magenta(italic(`[${name}][e]: ${message.content}`)));
    } else {
      console.log(cyan(`${bold(`[${name}]:`)} ${message.content}`));
    }
  }
 
  async send(serverId: string, channelId: string, message: string | FlarieMessage): Promise<void> {
    this.#log(
      CampfirePlatform.#BOT_USERNAME,
      typeof message === 'string'
        ? {
            content: message,
          }
        : message
    );
  }
 
  async #send(message: string | FlarieMessage): Promise<void> {
    this.send('campfire', 'campfire', message);
  }
 
  async #requestInput() {
    this.emit('ready');
 
    while (true) {
      const message = await this.#rl.question('> ');
 
      process.stdout.clearLine(0);
      process.stdout.moveCursor(0, -1);
      process.stdout.clearLine(0);
      process.stdout.cursorTo(0);
 
      if (['exit', 'quit'].includes(message)) {
        process.exit(0);
      } else if (message.startsWith('/')) {
        const [name] = message.replace('/', '').split(' ');
 
        if (!name) return;
 
        const command = this.#commands.get(name);
 
        if (!command) return;
 
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        const self = this;
 
        try {
          await command.invoke({
            async reply(message) {
              self.#send(message);
              this.replied = true;
            },
            replied: false,
            context: new FlarieServerContext({
              server: {
                id: 'server-id',
                name: 'server-name',
              },
              channel: {
                id: 'channel-id',
                name: 'channel-name',
              },
              user: {
                id: this.#username,
                username: this.#username,
                displayName: this.#username,
                bot: false,
              },
            }),
          });
        } catch (error) {
          if (error instanceof FlarieError) {
            Logger.log(error.level, error.message);
            await this.#send(error.toFlarieMessage());
          } else {
            Logger.error(error?.toString());
            await this.#send('There was an error while executing this command!');
          }
        }
      } else {
        this.#log(this.#username, {
          content: message,
        });
        this.emit('message', {
          id: this.#username,
          username: this.#username,
          message: message,
        });
      }
    }
  }
 
  async authenticate(): Promise<void> {
    await new Promise((resolve) => setTimeout(resolve));
 
    this.#send(`Welcome ${this.#username}!`);
 
    this.#requestInput();
  }
 
  async register(commands: FlarieCommand[]): Promise<void> {
    for (const command of commands) {
      this.#commands.set(command.name, command);
    }
  }
}