- 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
53 lines
1.9 KiB
TypeScript
53 lines
1.9 KiB
TypeScript
/**
|
|
* Conversation selection when an NPC has multiple conversations.
|
|
*
|
|
* Each conversation may declare an entry gate (a flag condition evaluated
|
|
* against the reading player) and a priority. The offer order is priority
|
|
* descending, oldest first; the first conversation whose gate passes wins.
|
|
* An empty gate key always passes, which makes ungated conversations the
|
|
* natural fallback. Pure module: the caller injects the condition evaluator
|
|
* so this stays testable and client-safe.
|
|
*/
|
|
|
|
import type { DialogueCondition } from "./dialogue";
|
|
|
|
/** The stored entry gate shape on an npc-dialogues document. */
|
|
export interface DialogueEntryGate {
|
|
key?: string | null;
|
|
op?: DialogueCondition["op"] | null;
|
|
amount?: number | null;
|
|
}
|
|
|
|
/** Minimal candidate shape the selector reads from a conversation doc. */
|
|
export interface GateCandidate {
|
|
id: number;
|
|
priority?: number | null;
|
|
entryGate?: DialogueEntryGate | null;
|
|
}
|
|
|
|
/** Turns a stored gate into a runtime condition; null when ungated. */
|
|
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
|
|
const key = gate?.key?.trim();
|
|
if (!key || !gate) return null;
|
|
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
|
|
}
|
|
|
|
/**
|
|
* Picks the conversation to offer: highest priority first (ties break by
|
|
* oldest id), gated conversations skipped unless `evaluate` passes their
|
|
* condition. Returns null when every candidate is gated shut.
|
|
*/
|
|
export async function selectDialogueForUser<T extends GateCandidate>(
|
|
docs: readonly T[],
|
|
evaluate: (condition: DialogueCondition) => Promise<boolean>,
|
|
): Promise<T | null> {
|
|
const ordered = [...docs].sort(
|
|
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,
|
|
);
|
|
for (const doc of ordered) {
|
|
const condition = gateCondition(doc.entryGate);
|
|
if (!condition) return doc;
|
|
if (await evaluate(condition)) return doc;
|
|
}
|
|
return null;
|
|
}
|