Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

7.4 KB
Raw Blame
import type { WidgetButtonSpec, WidgetNode, WidgetRoot } from "./widget.ts";

/** A moment a client words in the reader's language: `clock` "10:30 AM" (marked UTC when there is no zone),
 * `bareClock` the same never marked, `longDate` "Thursday, October 22", `shortDate` "Thu, Oct 22". */
export interface WidgetMoment {
  at: number;
  style: "clock" | "bareClock" | "longDate" | "shortDate";
  zone?: string;
}

export type WidgetTextParam = string | number | WidgetText | WidgetMoment;

/** A server card's words as a `brief.*` or `server.meetings.*` (or a cause's `chat.notice.*`) catalog key and its params, which may name other keys or moments. The node
 * keeps its English beside it, which older clients and every bot widget show. */
export interface WidgetText {
  key: string;
  params?: Record<string, WidgetTextParam>;
}

/** The fields of one widget node a server card names by key. */
export type WidgetTextFields = Partial<Record<"value" | "label" | "title" | "caption", WidgetText>>;

const FIELDS = ["value", "label", "title", "caption"] as const;
const KEY = /^(?:brief|chat\.notice|server\.meetings)\.[\w.]{1,80}$/;
const STYLES = new Set<WidgetMoment["style"]>(["clock", "bareClock", "longDate", "shortDate"]);
const MAX_PARAMS = 8;
const MAX_DEPTH = 3;
const MAX_STRING = 400;
/** The longest readable version of a widget (WIDGET_LIMITS.fallback). */
export const WIDGET_FALLBACK_LIMIT = 1_500;

const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
export const widgetString = (node: WidgetNode, key: string): string | undefined => (typeof node[key] === "string" ? node[key] as string : undefined);
export const widgetNumber = (node: WidgetNode, key: string): number | undefined => (typeof node[key] === "number" ? node[key] as number : undefined);

export function buttonSpecOf(root: WidgetRoot, key: "confirm" | "cancel"): WidgetButtonSpec | undefined {
  const spec = root[key];
  return isRecord(spec) && typeof spec.label === "string" && isRecord(spec.action) ? spec as unknown as WidgetButtonSpec : undefined;
}

function readParam(raw: unknown, depth: number): WidgetTextParam | undefined {
  if (typeof raw === "string") return raw.slice(0, MAX_STRING);
  if (typeof raw === "number") return Number.isFinite(raw) ? raw : undefined;
  if (!isRecord(raw)) return undefined;
  if (typeof raw.at === "number" && Number.isFinite(raw.at) && STYLES.has(raw.style as WidgetMoment["style"])) {
    return { at: raw.at, style: raw.style as WidgetMoment["style"], ...(typeof raw.zone === "string" && raw.zone.length <= 64 ? { zone: raw.zone } : {}) };
  }
  return readText(raw, depth + 1);
}

function readText(raw: unknown, depth: number): WidgetText | undefined {
  if (!isRecord(raw) || typeof raw.key !== "string" || !KEY.test(raw.key) || depth > MAX_DEPTH) return undefined;
  if (raw.params === undefined) return { key: raw.key };
  if (!isRecord(raw.params)) return undefined;
  const entries = Object.entries(raw.params).slice(0, MAX_PARAMS).map(([name, value]) => [name, readParam(value, depth)] as const);
  if (entries.some(([name, value]) => value === undefined || !/^\w{1,32}$/.test(name))) return undefined;
  return { key: raw.key, params: Object.fromEntries(entries) as Record<string, WidgetTextParam> };
}

/** A node's `i18n` as it may be kept: anything malformed is dropped, and the node keeps its English. */
export function readWidgetText(raw: unknown): WidgetTextFields | undefined {
  if (!isRecord(raw)) return undefined;
  const fields: WidgetTextFields = {};
  for (const field of FIELDS) {
    const text = readText(raw[field], 0);
    if (text) fields[field] = text;
  }
  return Object.keys(fields).length ? fields : undefined;
}

/** Days as a person says them: "Every day", "Weekdays", "Weekends", or the names. */
export function dayList(days: string): string {
  const picked = days.split(",").filter(Boolean);
  if (picked.length === 7) return "Every day";
  if (picked.join(",") === "mon,tue,wed,thu,fri") return "Weekdays";
  if (picked.join(",") === "sat,sun") return "Weekends";
  const names: Record<string, string> = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };
  return picked.map((day) => names[day] ?? day).join(", ");
}

function inlineText(node: WidgetNode): string {
  switch (node.type) {
    case "Text": case "Title": case "Caption": case "Label":
      return widgetString(node, "value") ?? "";
    case "Markdown":
      return (widgetString(node, "value") ?? "").replace(/\s+/g, " ");
    case "Badge":
      return widgetString(node, "label") ?? "";
    case "Button":
      return node.label ? `[${String(node.label)}]` : "";
    case "Image":
      return node.alt ? `[image: ${String(node.alt)}]` : "[image]";
    case "Progress":
      return [widgetString(node, "label"), `${Math.round((widgetNumber(node, "value") ?? 0) * 100)}%`].filter(Boolean).join(" ");
    case "Chart":
      return `[chart: ${(Array.isArray(node.series) ? node.series as Array<{ label?: string; dataKey: string }> : []).map((series) => series.label ?? series.dataKey).join(", ")}]`;
    case "Checkbox":
      return `[ ] ${widgetString(node, "label") ?? String(node.name)}`;
    case "Select": case "RadioGroup":
      return `(${(Array.isArray(node.options) ? node.options as Array<{ label: string }> : []).slice(0, 6).map((option) => option.label).join(" / ")})`;
    case "DayPicker":
      return `[${typeof node.defaultValue === "string" ? dayList(node.defaultValue) : "days"}]`;
    case "Input": case "Textarea": case "DatePicker": case "TimePicker":
      return `[${widgetString(node, "placeholder") ?? String(node.name)}]`;
    default:
      return (Array.isArray(node.children) ? node.children : []).map(inlineText).filter(Boolean).join(" · ");
  }
}

function blockLines(node: WidgetNode): string[] {
  const children = Array.isArray(node.children) ? node.children : [];
  if (node.type === "ListViewItem") return [`- ${inlineText(node)}`];
  if (node.type === "Table") return children.map((row) => (Array.isArray(row.children) ? row.children : []).map(inlineText).join(" | "));
  if (node.type === "Markdown") return [widgetString(node, "value") ?? ""];
  const stacked = node.type === "Col" || node.type === "Form" || node.type === "Transition" || (node.type === "Box" && node.direction !== "row");
  return stacked ? children.flatMap(blockLines) : [inlineText(node)];
}

/** The readable version of a widget: the message `text`, read by previews,
 * notifications, exports, replayed history and clients that do not know the kind. */
export function widgetToText(root: WidgetRoot): string {
  const lines: string[] = [];
  const statusText = isRecord(root.status) && typeof root.status.text === "string" ? root.status.text : "";
  if (statusText) lines.push(statusText);
  const title = widgetString(root, "title");
  const head = [title ? `**${title}**` : "", widgetString(root, "caption"), widgetString(root, "meta")].filter(Boolean).join(" · ");
  if (head) lines.push(head);
  for (const child of Array.isArray(root.children) ? root.children : []) lines.push(...blockLines(child));
  const buttons = (["confirm", "cancel"] as const).map((key) => buttonSpecOf(root, key)?.label).filter(Boolean).map((label) => `[${label}]`).join(" ");
  if (buttons) lines.push(buttons);
  const out = lines.map((line) => line.trimEnd()).filter(Boolean).join("\n");
  return out.length <= WIDGET_FALLBACK_LIMIT ? out : `${out.slice(0, WIDGET_FALLBACK_LIMIT - 1).trimEnd()}…`;
}