Skip to content
1        10        20        30        40        50        60        70        80        90        100       1101(() => {2  "use strict";34  const MAX_HISTORY_TURNS = 10;5  const SQL_PREFIX = "/sql ";6  const SUGGESTIONS = [7    "Who are the top players on the leaderboard?",8    "Which heroes win the most games?",9    "How many players are on the leaderboard?",10  ];1112  const state = {13    authEnabled: false,14    user: null,15    history: [],16    busy: false,17    chatWired: false,18  };1920  const ui = {21    authView: document.getElementById("auth-view"),22    app: document.getElementById("app"),23    log: document.getElementById("log"),24    form: document.getElementById("composer"),25    input: document.getElementById("input"),26    send: document.getElementById("send"),27    suggestions: document.getElementById("suggestions"),28    newChat: document.getElementById("new-chat"),29    currentUser: document.getElementById("current-user"),30    invitesButton: document.getElementById("invites-button"),31    logoutButton: document.getElementById("logout-button"),32    invitesDialog: document.getElementById("invites-dialog"),33  };3435  function el(tag, className, text) {36    const node = document.createElement(tag);37    if (className) node.className = className;38    if (text !== undefined) node.textContent = text;39    return node;40  }4142  function textInput(type, name, label, autocomplete) {43    const input = el("input");44    input.type = type;45    input.name = name;46    input.required = true;47    input.autocomplete = autocomplete || "off";48    return { input, label };49  }5051  function field(labelText, input) {52    const wrap = el("label", "field");53    wrap.append(el("span", null, labelText), input);54    return wrap;55  }5657  function link(href, text) {58    const a = el("a", null, text);59    a.href = href;60    return a;61  }6263  function setError(node, message) {64    node.textContent = message || "";65    node.classList.toggle("hidden", !message);66  }6768  function formatDate(seconds) {69    return new Date(seconds * 1000).toLocaleString(undefined, {70      year: "numeric",71      month: "short",72      day: "numeric",73      hour: "2-digit",74      minute: "2-digit",75    });76  }7778  async function api(path, options = {}) {79    const response = await fetch(path, {80      credentials: "same-origin",81      ...options,82      headers: { "content-type": "application/json", ...(options.headers || {}) },83    });84    const data = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));85    if (!response.ok) {86      const error = new Error(data.error || `HTTP ${response.status}`);87      error.status = response.status;88      throw error;89    }90    return data;91  }9293  // ---- App shell -----------------------------------------------------------9495  function enterApp(user) {96    state.user = user;97    ui.authView.classList.add("hidden");98    ui.app.classList.remove("hidden");99100    const signedIn = Boolean(user);101    ui.currentUser.textContent = signedIn ? user.username : "";102    ui.currentUser.classList.toggle("hidden", !signedIn);103    ui.logoutButton.classList.toggle("hidden", !state.authEnabled);104    ui.invitesButton.classList.toggle("hidden", !(signedIn && user.is_admin));105106    if (!state.chatWired) {107      wireChat();108      state.chatWired = true;109    }110    if (window.location.pathname !== "/" || window.location.search) {111      window.history.replaceState({}, "", "/");112    }113    ui.input.focus();114  }115116  function showAuth() {117    ui.app.classList.add("hidden");118    ui.authView.classList.remove("hidden");119  }120121  // ---- Login and signup ----------------------------------------------------122123  function authCard(title, subtitle) {124    const card = el("section", "auth-card");125    card.append(el("p", "auth-sigil", "☠"), el("h2", null, title), el("p", "auth-subtitle", subtitle));126    return card;127  }128129  function showLogin(message) {130    showAuth();131    const card = authCard("Sign in", "Totenschloss is invite-only. Sign in to continue.");132    const form = el("form", "auth-form");133134    const username = textInput("text", "username", "Username", "username");135    const password = textInput("password", "password", "Password", "current-password");136    username.input.maxLength = 32;137    password.input.maxLength = 128;138139    const error = el("p", "form-error hidden");140    setError(error, message);141142    const submit = el("button", "primary", "Sign in");143    submit.type = "submit";144145    form.append(146      field("Username", username.input),147      field("Password", password.input),148      error,149      submit,150    );151152    form.addEventListener("submit", async (event) => {153      event.preventDefault();154      setError(error, "");155      submit.disabled = true;156      submit.textContent = "Signing in…";157      try {158        const result = await api("/api/auth/login", {159          method: "POST",160          body: JSON.stringify({161            username: username.input.value.trim(),162            password: password.input.value,163          }),164        });165        enterApp(result.user);166      } catch (err) {167        setError(error, err.message);168      } finally {169        submit.disabled = false;170        submit.textContent = "Sign in";171      }172    });173174    const hint = el("p", "auth-hint");175    hint.append("Have an invite? ", link("/signup", "Create an account"), ".");176    card.append(form, hint);177    ui.authView.replaceChildren(card);178    username.input.focus();179  }180181  function showSignup(inviteCode) {182    showAuth();183    const card = authCard("Create your account", "Use the single-use invite link an admin shared with you.");184    const form = el("form", "auth-form");185186    const invite = textInput("text", "invite", "Invite code", "off");187    invite.input.value = inviteCode || "";188    invite.input.maxLength = 128;189190    const username = textInput("text", "username", "Username", "username");191    username.input.maxLength = 32;192    const password = textInput("password", "password", "Password", "new-password");193    password.input.maxLength = 128;194    password.input.minLength = 8;195    const confirm = textInput("password", "confirm", "Confirm password", "new-password");196    confirm.input.maxLength = 128;197198    username.input.placeholder = "3-32 letters, digits, dots, dashes or underscores";199200    const error = el("p", "form-error hidden");201    const submit = el("button", "primary", "Create account");202    submit.type = "submit";203204    form.append(205      field("Invite code", invite.input),206      field("Username", username.input),207      field("Password", password.input),208      field("Confirm password", confirm.input),209      error,210      submit,211    );212213    form.addEventListener("submit", async (event) => {214      event.preventDefault();215      setError(error, "");216      if (password.input.value !== confirm.input.value) {217        setError(error, "The passwords do not match.");218        return;219      }220      submit.disabled = true;221      submit.textContent = "Creating…";222      try {223        const result = await api("/api/auth/signup", {224          method: "POST",225          body: JSON.stringify({226            invite: invite.input.value.trim(),227            username: username.input.value.trim(),228            password: password.input.value,229          }),230        });231        enterApp(result.user);232      } catch (err) {233        setError(error, err.message);234      } finally {235        submit.disabled = false;236        submit.textContent = "Create account";237      }238    });239240    const hint = el("p", "auth-hint");241    hint.append("Already have an account? ", link("/login", "Sign in"), ".");242    card.append(form, hint);243    ui.authView.replaceChildren(card);244    (inviteCode ? username.input : invite.input).focus();245  }246247  // ---- Invites (admin) -----------------------------------------------------248249  async function openInvites() {250    if (!ui.invitesDialog.open) ui.invitesDialog.showModal();251    ui.invitesDialog.replaceChildren(el("p", "muted", "Loading invites…"));252    try {253      const data = await api("/api/invites");254      renderInvitesDialog(data.invites || []);255    } catch (err) {256      renderInvitesDialog([], err.message);257    }258  }259260  function renderInvitesDialog(invites, loadError) {261    const dialog = ui.invitesDialog;262263    const close = el("button", "ghost", "Close");264    close.type = "button";265    close.addEventListener("click", () => dialog.close());266267    const header = el("header", "dialog-head");268    header.append(el("h2", null, "Invites"), close);269270    const form = el("form", "invite-form");271    form.append(el("p", "muted", "Invites are single-use. Share the link with one person."));272273    const select = el("select");274    [275      ["24", "1 day"],276      ["168", "7 days"],277      ["720", "30 days"],278    ].forEach(([value, label]) => {279      const option = el("option", null, label);280      option.value = value;281      select.append(option);282    });283    select.value = "168";284285    const createButton = el("button", "primary", "Create invite");286    createButton.type = "submit";287    const createError = el("p", "form-error hidden");288    setError(createError, loadError);289    const result = el("div", "invite-result hidden");290291    const list = el("div", "invite-list");292    renderInviteList(list, invites, createError);293294    form.append(field("Expires", select), createButton, createError, result);295    form.addEventListener("submit", async (event) => {296      event.preventDefault();297      setError(createError, "");298      result.classList.add("hidden");299      createButton.disabled = true;300      createButton.textContent = "Creating…";301      try {302        const created = await api("/api/invites", {303          method: "POST",304          body: JSON.stringify({ expires_in_hours: Number(select.value) }),305        });306        const url = new URL(created.path, window.location.origin).href;307        result.replaceChildren(308          el("p", "muted", `Link for one person (expires ${formatDate(created.expires_at)}):`),309        );310        const row = el("div", "copy-row");311        const linkInput = el("input", "invite-link");312        linkInput.type = "text";313        linkInput.readOnly = true;314        linkInput.value = url;315        const copy = el("button", "ghost", "Copy");316        copy.type = "button";317        copy.addEventListener("click", async () => {318          try {319            await navigator.clipboard.writeText(url);320            copy.textContent = "Copied";321          } catch {322            linkInput.select();323            document.execCommand("copy");324            copy.textContent = "Copied";325          }326          setTimeout(() => {327            copy.textContent = "Copy";328          }, 1500);329        });330        row.append(linkInput, copy);331        result.append(row);332        result.classList.remove("hidden");333334        const refreshed = await api("/api/invites");335        renderInviteList(list, refreshed.invites || [], createError);336      } catch (err) {337        setError(createError, err.message);338      } finally {339        createButton.disabled = false;340        createButton.textContent = "Create invite";341      }342    });343344    dialog.replaceChildren(header, form, el("h3", null, "Recent invites"), list);345  }346347  function renderInviteList(container, invites, errorNode) {348    container.replaceChildren();349    if (invites.length === 0) {350      container.append(el("p", "muted", "No invites yet."));351      return;352    }353354    invites355      .slice()356      .reverse()357      .forEach((invite) => {358        const row = el("div", "invite-row");359        const info = el("div", "invite-info");360        info.append(el("span", `badge ${invite.status}`, invite.status));361362        const detail = el("span", "muted");363        if (invite.status === "used") {364          detail.textContent = `created ${formatDate(invite.created_at)} · used by ${invite.used_by}`;365        } else if (invite.status === "expired") {366          detail.textContent = `created ${formatDate(invite.created_at)} · expired ${formatDate(invite.expires_at)}`;367        } else {368          detail.textContent = `created ${formatDate(invite.created_at)} · expires ${formatDate(invite.expires_at)}`;369        }370        info.append(detail);371        row.append(info);372373        if (invite.status === "active") {374          const revoke = el("button", "ghost", "Revoke");375          revoke.type = "button";376          revoke.addEventListener("click", async () => {377            if (!window.confirm("Revoke this invite? The link will stop working.")) return;378            revoke.disabled = true;379            try {380              await api("/api/invites/revoke", {381                method: "POST",382                body: JSON.stringify({ id: invite.id }),383              });384              const refreshed = await api("/api/invites");385              renderInviteList(container, refreshed.invites || [], errorNode);386            } catch (err) {387              setError(errorNode, err.message);388              revoke.disabled = false;389            }390          });391          row.append(revoke);392        }393394        container.append(row);395      });396  }397398  // ---- Chat ----------------------------------------------------------------399400  function scrollToEnd() {401    ui.log.scrollTop = ui.log.scrollHeight;402  }403404  function addMessage(role, text) {405    const message = el("article", `msg ${role}`);406    message.append(el("div", "bubble", text));407    ui.log.append(message);408    scrollToEnd();409    return message;410  }411412  const PREVIEW_ROWS = 10;413414  function renderTable(query, preview) {415    const wrap = el("div", "table-wrap");416    const table = el("table");417418    const head = el("thead");419    const headRow = el("tr");420    query.columns.forEach((name) => headRow.append(el("th", null, name)));421    head.append(headRow);422423    const body = el("tbody");424    query.rows.forEach((row, index) => {425      const tr = el("tr");426      if (preview && index >= preview) tr.className = "extra";427      row.forEach((cell) => {428        tr.append(cell === null ? el("td", "null", "NULL") : el("td", null, cell));429      });430      body.append(tr);431    });432433    table.append(head, body);434    wrap.append(table);435436    if (preview && query.rows.length > preview) {437      const note = el("p", "note preview-note", `Showing ${preview} of ${query.rows.length} rows`);438      wrap.append(note);439    } else if (query.total_rows > query.rows.length) {440      wrap.append(el("p", "note", `Showing ${query.rows.length} of ${query.total_rows} rows`));441    }442    return wrap;443  }444445  function renderQuery(query, open) {446    const details = el("details", "query");447    details.open = open;448449    const summary = el(450      "summary",451      null,452      query.error_message ? "Query failed" : `${query.total_rows} row${query.total_rows === 1 ? "" : "s"}`,453    );454    details.append(summary, el("pre", "sql", query.sql));455456    if (query.error_message) {457      details.append(el("p", "error-text", query.error_message));458    } else if (query.columns.length > 0) {459      details.append(renderTable(query));460    }461    return details;462  }463464  // The reply itself should read like a conversation. The result stays visible, but465  // only the first rows: SQL and the rest of the rows wait behind one quiet expander.466  function renderData(queries) {467    const usable = queries.filter((query) => !query.error_message && query.columns.length > 0);468    if (usable.length === 0) return null;469470    const panel = el("div", "chat-data");471    usable.forEach((query) => {472      const lookup = el("div", "lookup");473      const table = renderTable(query, PREVIEW_ROWS);474      lookup.append(table);475476      const hidden = query.rows.length - PREVIEW_ROWS;477      const details = el("details", "query-more");478      details.append(479        el("summary", null, hidden > 0 ? `Show SQL and ${hidden} more rows` : "Show SQL"),480        el("pre", "sql", query.sql),481      );482      details.addEventListener("toggle", () => {483        lookup.classList.toggle("expanded", details.open);484        const note = table.querySelector(".preview-note");485        if (!note) return;486        note.textContent = details.open487          ? `Showing ${query.rows.length} of ${query.total_rows} rows`488          : `Showing ${PREVIEW_ROWS} of ${query.rows.length} rows`;489      });490      lookup.append(details);491      panel.append(lookup);492    });493    return panel;494  }495496  async function send(text) {497    state.busy = true;498    ui.send.disabled = true;499    addMessage("user", text);500    const pending = addMessage("assistant pending", "Thinking…");501502    const isDirectSql = text.startsWith(SQL_PREFIX);503    try {504      const response = await fetch("/api/chat", {505        method: "POST",506        credentials: "same-origin",507        headers: { "content-type": "application/json" },508        body: JSON.stringify({509          message: text,510          history: isDirectSql ? [] : state.history.slice(-MAX_HISTORY_TURNS),511        }),512      });513      if (response.status === 401) {514        window.location.href = "/login";515        return;516      }517      const data = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));518      pending.remove();519      if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);520521      const reply = addMessage("assistant", data.answer || "");522      if (!data.answer) reply.classList.add("no-text");523      const queries = data.queries || [];524      if (isDirectSql) {525        // A /sql request asked for the query, so its result is the answer.526        queries.forEach((query) => reply.append(renderQuery(query, true)));527      } else {528        const panel = renderData(queries);529        if (panel) reply.append(panel);530      }531      if (!isDirectSql && data.answer) {532        state.history.push({ role: "user", content: text }, { role: "assistant", content: data.answer });533      }534    } catch (error) {535      pending.remove();536      addMessage("assistant error", error.message || String(error));537    } finally {538      state.busy = false;539      ui.send.disabled = false;540      ui.input.focus();541      scrollToEnd();542    }543  }544545  function resize() {546    ui.input.style.height = "auto";547    ui.input.style.height = `${Math.min(ui.input.scrollHeight, 180)}px`;548  }549550  function buildIntro() {551    const intro = el("section", "intro");552    intro.append(el("p", null, "Conversation cleared. Ask a new question."));553    return intro;554  }555556  function wireChat() {557    ui.form.addEventListener("submit", (event) => {558      event.preventDefault();559      const text = ui.input.value.trim();560      if (!text || state.busy) return;561      ui.input.value = "";562      resize();563      send(text);564    });565566    ui.input.addEventListener("keydown", (event) => {567      if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {568        event.preventDefault();569        ui.form.requestSubmit();570      }571    });572    ui.input.addEventListener("input", resize);573574    ui.newChat.addEventListener("click", () => {575      if (state.busy) return;576      state.history = [];577      ui.log.replaceChildren(buildIntro());578      ui.input.focus();579    });580581    ui.logoutButton.addEventListener("click", async () => {582      try {583        await api("/api/auth/logout", { method: "POST", body: "{}" });584      } catch {585        // Signing out is best-effort; reloading still clears the local view.586      }587      window.location.href = "/login";588    });589590    ui.invitesButton.addEventListener("click", openInvites);591592    SUGGESTIONS.forEach((text) => {593      const chip = el("button", "chip", text);594      chip.type = "button";595      chip.addEventListener("click", () => {596        if (state.busy) return;597        send(text);598      });599      ui.suggestions.append(chip);600    });601  }602603  // ---- Boot ----------------------------------------------------------------604605  async function boot() {606    let me;607    try {608      me = await api("/api/auth/me");609    } catch (err) {610      showLogin(`Could not reach the server: ${err.message}`);611      return;612    }613614    state.authEnabled = Boolean(me.auth_enabled);615    if (!state.authEnabled) {616      enterApp(null);617      return;618    }619    if (me.authenticated && me.user) {620      enterApp(me.user);621      return;622    }623624    const params = new URLSearchParams(window.location.search);625    const invite = params.get("invite") || "";626    if (window.location.pathname === "/signup" || invite) {627      showSignup(invite);628    } else {629      showLogin();630    }631  }632633  boot();634})();