HomeAssistantSessionMapper.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { randomUUID } from "node:crypto";
  2. export type HomeAssistantSessionMapperState = {
  3. activeByChatId: Record<string, string>;
  4. };
  5. export class HomeAssistantSessionMapper {
  6. constructor(
  7. private readonly state: HomeAssistantSessionMapperState = { activeByChatId: {} },
  8. private readonly uuid: () => string = randomUUID,
  9. ) {}
  10. resolve(input: { chatId: string; text: string }): { sessionKey: string; command?: "new"; message: string } {
  11. const trimmed = input.text.trim();
  12. if (trimmed === "/new" || trimmed.startsWith("/new ")) {
  13. const sessionKey = `homeassistant:chat=${input.chatId}:s_${this.uuid()}`;
  14. this.state.activeByChatId[input.chatId] = sessionKey;
  15. return {
  16. sessionKey,
  17. command: "new",
  18. message: trimmed.slice("/new".length).trim(),
  19. };
  20. }
  21. return {
  22. sessionKey: this.state.activeByChatId[input.chatId] ?? `homeassistant:chat=${input.chatId}:general`,
  23. message: trimmed,
  24. };
  25. }
  26. snapshot(): HomeAssistantSessionMapperState {
  27. return { activeByChatId: { ...this.state.activeByChatId } };
  28. }
  29. }