454 lines
14 KiB
TypeScript
454 lines
14 KiB
TypeScript
"use server";
|
|
|
|
import config from "@payload-config";
|
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|
import { getPayload } from "payload";
|
|
import type { User } from "@/payload-types";
|
|
import { emitGameEvent } from "@/utils/event-log/emit";
|
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
|
import { notifyUser } from "@/lib/notifications";
|
|
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
|
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
|
import type {
|
|
DialogueCondition,
|
|
DialogueFlagOp,
|
|
FlowData,
|
|
NpcDialogueEffect,
|
|
} from "@/lib/npc-dialogue/dialogue";
|
|
|
|
interface ActionResult<T = undefined> {
|
|
success: boolean;
|
|
error?: string;
|
|
data?: T;
|
|
}
|
|
|
|
async function authenticate() {
|
|
const payloadConfig = await config;
|
|
const payload = await getPayload({ config: payloadConfig });
|
|
const { headers } = await import("next/headers");
|
|
const hdrs = await headers();
|
|
const { user } = await payload.auth({
|
|
headers: hdrs,
|
|
canSetHeaders: false,
|
|
});
|
|
|
|
if (!isPayloadUser(user)) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
return { payload, user };
|
|
}
|
|
|
|
/**
|
|
* Resolve the effect configured on a dialogue `event` node and run it. The
|
|
* node is looked up server-side from the stored flowchart, so the client can
|
|
* only trigger effects an admin has authored for this conversation.
|
|
*/
|
|
export async function triggerNpcDialogueEvent(
|
|
npcId: number,
|
|
nodeId: string,
|
|
): Promise<ActionResult> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npcId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
|
if (!flowData || !Array.isArray(flowData.nodes)) {
|
|
return { success: false, error: "This contact has no conversation configured." };
|
|
}
|
|
|
|
const node = flowData.nodes.find((n) => n.id === nodeId);
|
|
if (!node || node.type !== "event" || !node.data.effect) {
|
|
// Nothing to trigger (or the node isn't an event): treated as a no-op.
|
|
return { success: true };
|
|
}
|
|
|
|
const effect: NpcDialogueEffect = node.data.effect;
|
|
await runEffect(payload, user.id as number, npcId, effect);
|
|
|
|
return { success: true };
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
if (message === "Unauthorized") {
|
|
return { success: false, error: "You must be logged in." };
|
|
}
|
|
return { success: false, error: message };
|
|
}
|
|
}
|
|
|
|
async function runEffect(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
userId: number,
|
|
npcId: number,
|
|
effect: NpcDialogueEffect,
|
|
): Promise<void> {
|
|
switch (effect.type) {
|
|
case "notify": {
|
|
await notifyUser(payload, {
|
|
userId,
|
|
type: "npc:dialogue",
|
|
title: effect.title ?? "Conversation",
|
|
message: effect.message,
|
|
});
|
|
break;
|
|
}
|
|
case "emit": {
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.NpcDialogue,
|
|
message: effect.message ?? "NPC dialogue event",
|
|
actor: userId,
|
|
targetCollection: "game-npcs",
|
|
targetId: npcId,
|
|
data: { effect: "emit" },
|
|
});
|
|
break;
|
|
}
|
|
case "reward": {
|
|
// LLM/reward seam intentionally left unconfigured (see Phase 5).
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.NpcDialogue,
|
|
message: effect.message ?? "NPC dialogue reward (unconfigured)",
|
|
actor: userId,
|
|
targetCollection: "game-npcs",
|
|
targetId: npcId,
|
|
data: { effect: "reward", unconfigured: true },
|
|
});
|
|
break;
|
|
}
|
|
case "flag": {
|
|
const key = effect.flagKey?.trim();
|
|
if (!key) break;
|
|
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
|
|
const amount = effect.flagAmount ?? 0;
|
|
await applyFlagEffect(payload, userId, key, op, amount, effect.flagText);
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.NpcDialogue,
|
|
message: `Conversation set flag "${key}" (${op}).`,
|
|
actor: userId,
|
|
targetCollection: "game-npcs",
|
|
targetId: npcId,
|
|
data: { effect: "flag", key, op, amount },
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Effective value of a flag: player-specific entry takes priority; if absent,
|
|
* fall back to the global entry (user is null). Missing flags read false / 0 /
|
|
* empty. `text` is the string the flag contributes to interpolated dialogue
|
|
* (booleans render "true"/"false", numbers their digits, text flags verbatim).
|
|
*/
|
|
async function readFlag(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
userId: number,
|
|
key: string,
|
|
): Promise<{ bool: boolean; num: number; text: string }> {
|
|
// Player-specific flag (priority).
|
|
const playerRes = await payload.find({
|
|
collection: "player-flags",
|
|
where: {
|
|
user: { equals: userId },
|
|
key: { equals: key },
|
|
},
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const playerDoc = playerRes.docs[0];
|
|
if (playerDoc) return flagValues(playerDoc);
|
|
|
|
// Global fallback (user is null).
|
|
const globalRes = await payload.find({
|
|
collection: "player-flags",
|
|
where: {
|
|
user: { equals: null },
|
|
key: { equals: key },
|
|
},
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const globalDoc = globalRes.docs[0];
|
|
if (!globalDoc) return { bool: false, num: 0, text: "" };
|
|
return flagValues(globalDoc);
|
|
}
|
|
|
|
/** Reads a stored flag doc into its condition + interpolation values. */
|
|
function flagValues(doc: {
|
|
flagType: "boolean" | "number" | "text";
|
|
boolValue?: boolean | null;
|
|
numberValue?: number | null;
|
|
textValue?: string | null;
|
|
}): { bool: boolean; num: number; text: string } {
|
|
if (doc.flagType === "number") {
|
|
const num = doc.numberValue ?? 0;
|
|
return { bool: num !== 0, num, text: String(num) };
|
|
}
|
|
if (doc.flagType === "text") {
|
|
const text = doc.textValue ?? "";
|
|
return { bool: text.trim().length > 0, num: 0, text };
|
|
}
|
|
const bool = doc.boolValue === true;
|
|
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false" };
|
|
}
|
|
|
|
/** Create-or-update a player flag according to the effect's write mode. */
|
|
async function applyFlagEffect(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
userId: number,
|
|
key: string,
|
|
op: DialogueFlagOp,
|
|
amount: number,
|
|
effectText?: string,
|
|
): Promise<void> {
|
|
const existing = await payload.find({
|
|
collection: "player-flags",
|
|
where: {
|
|
user: { equals: userId },
|
|
key: { equals: key },
|
|
},
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const doc = existing.docs[0];
|
|
|
|
if (op === "set_true" || op === "set_false") {
|
|
const boolValue = op === "set_true";
|
|
if (doc) {
|
|
await payload.update({
|
|
collection: "player-flags",
|
|
id: doc.id,
|
|
data: { flagType: "boolean", boolValue },
|
|
overrideAccess: true,
|
|
});
|
|
} else {
|
|
await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: userId, key, flagType: "boolean", boolValue },
|
|
overrideAccess: true,
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (op === "set_number") {
|
|
if (doc) {
|
|
await payload.update({
|
|
collection: "player-flags",
|
|
id: doc.id,
|
|
data: { flagType: "number", numberValue: amount },
|
|
overrideAccess: true,
|
|
});
|
|
} else {
|
|
await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: userId, key, flagType: "number", numberValue: amount },
|
|
overrideAccess: true,
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (op === "set_text") {
|
|
const textValue = effectText ?? "";
|
|
if (doc) {
|
|
await payload.update({
|
|
collection: "player-flags",
|
|
id: doc.id,
|
|
data: { flagType: "text", textValue },
|
|
overrideAccess: true,
|
|
});
|
|
} else {
|
|
await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: userId, key, flagType: "text", textValue },
|
|
overrideAccess: true,
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
// add: numeric flags accumulate; boolean flags convert (true = 1).
|
|
const current = doc
|
|
? doc.flagType === "number"
|
|
? doc.numberValue ?? 0
|
|
: doc.boolValue
|
|
? 1
|
|
: 0
|
|
: 0;
|
|
const numberValue = current + amount;
|
|
if (doc) {
|
|
await payload.update({
|
|
collection: "player-flags",
|
|
id: doc.id,
|
|
data: { flagType: "number", numberValue },
|
|
overrideAccess: true,
|
|
});
|
|
} else {
|
|
await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: userId, key, flagType: "number", numberValue },
|
|
overrideAccess: true,
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Evaluate a dialogue `condition` node against the reading user's live
|
|
* web-app state (player flags). The node is looked up server-side from the
|
|
* stored flowchart, so the client can only evaluate conditions an admin
|
|
* authored for this conversation.
|
|
*/
|
|
export async function evaluateNpcDialogueCondition(
|
|
npcId: number,
|
|
nodeId: string,
|
|
): Promise<ActionResult<boolean>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npcId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
|
if (!node || node.type !== "condition" || !node.data.condition) {
|
|
// Not a condition node: nothing to branch on.
|
|
return { success: true, data: false };
|
|
}
|
|
|
|
const value = await evaluateCondition(payload, user.id as number, node.data.condition);
|
|
return { success: true, data: value };
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
if (message === "Unauthorized") {
|
|
return { success: false, error: "You must be logged in." };
|
|
}
|
|
return { success: false, error: message };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Evaluate every choice's visibility gate for a `choice` node in one round
|
|
* trip. Ungated choices are always visible; gated ones appear only while the
|
|
* reading user's flags satisfy their condition. The node is looked up
|
|
* server-side from the stored flowchart, so clients never see gate config
|
|
* for conversations an admin has not authored.
|
|
*/
|
|
export async function evaluateNpcDialogueChoices(
|
|
npcId: number,
|
|
nodeId: string,
|
|
): Promise<ActionResult<boolean[]>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npcId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
|
if (!node || node.type !== "choice") {
|
|
// Not a choice node: nothing to gate.
|
|
return { success: true, data: [] };
|
|
}
|
|
|
|
const visible: boolean[] = [];
|
|
for (const choice of node.data.choices ?? []) {
|
|
if (!choice.condition?.key?.trim()) {
|
|
visible.push(true);
|
|
continue;
|
|
}
|
|
visible.push(await evaluateCondition(payload, user.id as number, choice.condition));
|
|
}
|
|
return { success: true, data: visible };
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
if (message === "Unauthorized") {
|
|
return { success: false, error: "You must be logged in." };
|
|
}
|
|
return { success: false, error: message };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolve every interpolatable display string of one node against the reading
|
|
* user's live flags. Tokens (`{{key}}`) are replaced server-side at render
|
|
* time, so interpolated values may contain dialogue markup (colors) and stay
|
|
* fresh when flags change mid-conversation. Only the flag keys a node actually
|
|
* references are read; substituted values are never re-scanned for tokens.
|
|
*/
|
|
export async function resolveNpcDialogueTexts(
|
|
npcId: number,
|
|
nodeId: string,
|
|
): Promise<ActionResult<ResolvedNodeTexts>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npcId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
|
if (!node) return { success: true, data: {} };
|
|
|
|
const keys = collectNodeTokens(node);
|
|
const values: Record<string, string> = {};
|
|
for (const key of keys) {
|
|
const flag = await readFlag(payload, user.id as number, key);
|
|
values[key] = flag.text;
|
|
}
|
|
return { success: true, data: resolveNodeTexts(node, values) };
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
if (message === "Unauthorized") {
|
|
return { success: false, error: "You must be logged in." };
|
|
}
|
|
return { success: false, error: message };
|
|
}
|
|
}
|
|
|
|
async function evaluateCondition(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
userId: number,
|
|
condition: DialogueCondition,
|
|
): Promise<boolean> {
|
|
const flag = await readFlag(payload, userId, condition.key);
|
|
const amount = condition.amount ?? 0;
|
|
switch (condition.op) {
|
|
case "is_true":
|
|
return flag.bool;
|
|
case "is_false":
|
|
return !flag.bool;
|
|
case "gte":
|
|
return flag.num >= amount;
|
|
case "lte":
|
|
return flag.num <= amount;
|
|
case "gt":
|
|
return flag.num > amount;
|
|
case "lt":
|
|
return flag.num < amount;
|
|
case "eq":
|
|
return flag.num === amount;
|
|
}
|
|
}
|
|
|