- npc-dialogues gains priority + entryGate (flag key/op/amount) fields - contact page offers the highest-priority conversation whose gate passes (ungated = fallback, ties by oldest); only the winner's flow leaves the server so locked story content never reaches clients - extract shared flag reads (readFlag/evaluateCondition) to lib/npc-dialogue/flags and pure selection to lib/npc-dialogue/selection - migration 20261006_203217_add_dialogue_entry_gate; spec covers ordering, gating, fallback, and storage round-trip
312 lines
11 KiB
TypeScript
312 lines
11 KiB
TypeScript
import { getPayload, Payload } from "payload";
|
|
import config from "@/payload.config";
|
|
import { createElement } from "react";
|
|
import { renderToStaticMarkup } from "react-dom/server";
|
|
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
|
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
|
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
|
import {
|
|
collectNodeTokens,
|
|
extractFlagTokens,
|
|
formatFlagValue,
|
|
hasFlagTokens,
|
|
interpolateFlags,
|
|
resolveNodeTexts,
|
|
} from "@/lib/npc-dialogue/interpolate";
|
|
|
|
let payload: Payload;
|
|
|
|
const RUN = `dlg_${Date.now().toString(36)}`;
|
|
const TIMEOUT = 30_000;
|
|
|
|
describe("flag token extraction + interpolation (pure)", () => {
|
|
it("extracts distinct lowercased keys and ignores single-brace markup", () => {
|
|
expect(extractFlagTokens("Status: {{network_status}}. {{NETWORK_STATUS}} again")).toEqual([
|
|
"network_status",
|
|
]);
|
|
expect(extractFlagTokens("{green}no tokens here{/} **bold**")).toEqual([]);
|
|
expect(extractFlagTokens(undefined)).toEqual([]);
|
|
expect(hasFlagTokens("a {{x}} b")).toBe(true);
|
|
expect(hasFlagTokens("{red}x{/}")).toBe(false);
|
|
});
|
|
|
|
it("substitutes values, resolves missing keys to empty, keeps markup intact", () => {
|
|
const out = interpolateFlags("Link {{network_status}}, rep {{rep_merchants}}", {
|
|
network_status: "{green}NOMINAL{/}",
|
|
});
|
|
expect(out).toBe("Link {green}NOMINAL{/}, rep ");
|
|
});
|
|
|
|
it("is case-insensitive on keys and never re-scans substituted values", () => {
|
|
const out = interpolateFlags("{{Key}} says {{key}}", {
|
|
key: "{{key}}",
|
|
});
|
|
// Single pass: the injected token must survive literally, not expand.
|
|
expect(out).toBe("{{key}} says {{key}}");
|
|
});
|
|
|
|
it("formats flag values per type for interpolation", () => {
|
|
expect(formatFlagValue({ flagType: "text", textValue: "{green}OK{/}" })).toBe("{green}OK{/}");
|
|
expect(formatFlagValue({ flagType: "text" })).toBe("");
|
|
expect(formatFlagValue({ flagType: "number", numberValue: 7 })).toBe("7");
|
|
expect(formatFlagValue({ flagType: "number" })).toBe("0");
|
|
expect(formatFlagValue({ flagType: "boolean", boolValue: true })).toBe("true");
|
|
expect(formatFlagValue({ flagType: "boolean", boolValue: false })).toBe("false");
|
|
});
|
|
|
|
it("collects node tokens across body, lead-in, closing, effect message, labels", () => {
|
|
const node: DialogueNode = {
|
|
id: "n1",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
leadIn: "Ops report: {{ops_status}}",
|
|
choices: [
|
|
{ label: "Ack ({{clearance_level}})", target: "a" },
|
|
{ label: "No tokens", target: "b" },
|
|
],
|
|
},
|
|
};
|
|
expect(new Set(collectNodeTokens(node))).toEqual(new Set(["ops_status", "clearance_level"]));
|
|
});
|
|
|
|
it("resolves only the fields a node defines, index-aligning labels", () => {
|
|
const node: DialogueNode = {
|
|
id: "n1",
|
|
type: "dialogue",
|
|
position: { x: 0, y: 0 },
|
|
data: { body: "Status {{network_status}}", next: { target: "x" } },
|
|
};
|
|
const resolved = resolveNodeTexts(node, { network_status: "{red}DOWN{/}" });
|
|
expect(resolved).toEqual({ body: "Status {red}DOWN{/}" });
|
|
|
|
const choice: DialogueNode = {
|
|
id: "n2",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
leadIn: "{{greeting}}",
|
|
choices: [
|
|
{ label: "{{a}}", target: "t" },
|
|
{ label: "plain", target: "u" },
|
|
],
|
|
},
|
|
};
|
|
const r2 = resolveNodeTexts(choice, { greeting: "Hi", a: "1" });
|
|
expect(r2.leadIn).toBe("Hi");
|
|
expect(r2.labels).toEqual(["1", "plain"]);
|
|
expect(r2.body).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("text flags (player-flags collection)", () => {
|
|
beforeAll(async () => {
|
|
payload = await getPayload({ config });
|
|
}, TIMEOUT);
|
|
|
|
afterAll(async () => {
|
|
const res = await payload.find({
|
|
collection: "player-flags",
|
|
where: { key: { like: `${RUN}%` } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const doc of res.docs) {
|
|
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
|
}
|
|
});
|
|
|
|
it("stores and reads a global text flag with markup", async () => {
|
|
const created = await payload.create({
|
|
collection: "player-flags",
|
|
data: {
|
|
user: null,
|
|
key: `${RUN}_network_status`,
|
|
flagType: "text",
|
|
textValue: "{green}NOMINAL{/}",
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
expect(created.flagType).toBe("text");
|
|
expect(created.textValue).toBe("{green}NOMINAL{/}");
|
|
|
|
const fetched = await payload.findByID({
|
|
collection: "player-flags",
|
|
id: created.id,
|
|
overrideAccess: true,
|
|
});
|
|
expect(fetched.textValue).toBe("{green}NOMINAL{/}");
|
|
|
|
// Interpolates into dialogue text exactly as authored.
|
|
const values = { [`${RUN}_network_status`]: formatFlagValue(fetched) };
|
|
const line = interpolateFlags(`Grid says {{${RUN}_network_status}}`, values);
|
|
expect(line).toBe(`Grid says {green}NOMINAL{/}`);
|
|
});
|
|
|
|
it("converts an existing boolean flag to text via update (set_text semantics)", async () => {
|
|
const created = await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: null, key: `${RUN}_converted`, flagType: "boolean", boolValue: true },
|
|
overrideAccess: true,
|
|
});
|
|
const updated = await payload.update({
|
|
collection: "player-flags",
|
|
id: created.id,
|
|
data: { flagType: "text", textValue: "{amber}REDACTED{/}" },
|
|
overrideAccess: true,
|
|
});
|
|
expect(updated.flagType).toBe("text");
|
|
expect(updated.textValue).toBe("{amber}REDACTED{/}");
|
|
expect(formatFlagValue(updated)).toBe("{amber}REDACTED{/}");
|
|
});
|
|
|
|
it("stores conversation priority + entry gate and drives selection", async () => {
|
|
const npc = await payload.create({
|
|
collection: "game-npcs",
|
|
data: { name: `${RUN}_gate_npc`, canMessage: true },
|
|
overrideAccess: true,
|
|
});
|
|
const flow = { nodes: [], edges: [] };
|
|
const gated = await payload.create({
|
|
collection: "npc-dialogues",
|
|
data: {
|
|
name: `${RUN}_gated`,
|
|
npc: npc.id,
|
|
flowData: flow,
|
|
priority: 10,
|
|
entryGate: { key: `${RUN}_met`, op: "is_true" },
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
const fallback = await payload.create({
|
|
collection: "npc-dialogues",
|
|
data: { name: `${RUN}_fallback`, npc: npc.id, flowData: flow },
|
|
overrideAccess: true,
|
|
});
|
|
try {
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npc.id } },
|
|
limit: 10,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
expect(res.docs).toHaveLength(2);
|
|
|
|
const unlocked = new Set([`${RUN}_met`]);
|
|
const chosen = await selectDialogueForUser(res.docs, async (c) => unlocked.has(c.key));
|
|
expect(chosen?.id).toBe(gated.id);
|
|
|
|
const fallen = await selectDialogueForUser(res.docs, async () => false);
|
|
expect(fallen?.id).toBe(fallback.id);
|
|
} finally {
|
|
for (const doc of [gated, fallback]) {
|
|
await payload.delete({ collection: "npc-dialogues", id: doc.id, overrideAccess: true });
|
|
}
|
|
await payload.delete({ collection: "game-npcs", id: npc.id, overrideAccess: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("inline images in dialogue markup", () => {
|
|
const render = (text: string) =>
|
|
renderToStaticMarkup(createElement(DialogueText, { text }));
|
|
|
|
it("renders site-relative and absolute-http images as inline icons", () => {
|
|
const html = render("Pay 5  now");
|
|
expect(html).toContain('<img src="/api/media/file/coin.png" alt="coin"');
|
|
expect(render("")).toContain("<img");
|
|
});
|
|
|
|
it("leaves unsafe or malformed image URLs literal", () => {
|
|
// Protocol-relative and scheme-less/bad URLs never become <img>.
|
|
expect(render("")).not.toContain("<img");
|
|
expect(render("")).not.toContain("<img");
|
|
expect(render("")).not.toContain("<img");
|
|
});
|
|
|
|
it("keeps existing markup working alongside images", () => {
|
|
const html = render("**b** {green}g{/}  `code`");
|
|
expect(html).toContain("<strong");
|
|
expect(html).toContain("text-green-400");
|
|
expect(html).toContain("<img");
|
|
expect(html).toContain("<code");
|
|
});
|
|
});
|
|
|
|
describe("conversation selection (entry gates + priority)", () => {
|
|
const pass = async () => true;
|
|
const fail = async () => false;
|
|
|
|
it("prefers higher priority regardless of input order", async () => {
|
|
const docs = [
|
|
{ id: 1, priority: 0 },
|
|
{ id: 2, priority: 10 },
|
|
{ id: 3, priority: 5 },
|
|
];
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(2);
|
|
});
|
|
|
|
it("breaks ties by oldest id", async () => {
|
|
const docs = [{ id: 7 }, { id: 3, priority: 0 }];
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(3);
|
|
});
|
|
|
|
it("skips gated conversations whose condition fails, falling back to ungated", async () => {
|
|
const docs = [
|
|
{ id: 1, priority: 10, entryGate: { key: "met_fixer", op: "is_true" as const } },
|
|
{ id: 2, priority: 0 },
|
|
];
|
|
expect((await selectDialogueForUser(docs, fail))?.id).toBe(2);
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(1);
|
|
});
|
|
|
|
it("returns null when every candidate is gated shut", async () => {
|
|
const docs = [{ id: 1, entryGate: { key: "secret", op: "is_true" as const } }];
|
|
expect(await selectDialogueForUser(docs, fail)).toBeNull();
|
|
});
|
|
|
|
it("treats blank gate keys as ungated and defaults the op", () => {
|
|
expect(gateCondition({ key: " " })).toBeNull();
|
|
expect(gateCondition(null)).toBeNull();
|
|
expect(gateCondition({ key: "x" })).toEqual({
|
|
kind: "flag",
|
|
key: "x",
|
|
op: "is_true",
|
|
amount: 0,
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("choice tooltip interpolation", () => {
|
|
it("collects tokens from tooltips and resolves them index-aligned", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
choices: [
|
|
{ label: "A", target: "t", tooltip: "Cost {{cost}} " },
|
|
{ label: "B", target: "u" },
|
|
],
|
|
},
|
|
};
|
|
expect(collectNodeTokens(node)).toContain("cost");
|
|
const resolved = resolveNodeTexts(node, { cost: "5" });
|
|
expect(resolved.tooltips?.[0]).toBe("Cost 5 ");
|
|
expect(resolved.tooltips?.[1]).toBe("");
|
|
});
|
|
|
|
it("omits the tooltips array when no choice has a tooltip", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: { choices: [{ label: "A", target: "t" }] },
|
|
};
|
|
expect(resolveNodeTexts(node, {}).tooltips).toBeUndefined();
|
|
});
|
|
});
|